コード例 #1
0
  private ISelection restoreSelectionState(IMemento memento) {
    if (memento == null) return null;

    IMemento childMem;
    childMem = memento.getChild(TAG_SELECTED_ELEMENTS);
    if (childMem != null) {
      ArrayList list = new ArrayList();
      IMemento[] elementMem = childMem.getChildren(TAG_SELECTED_ELEMENT);
      for (int i = 0; i < elementMem.length; i++) {
        String javaElementHandle = elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
        if (javaElementHandle == null) {
          // logical package
          IMemento[] packagesMem = elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
          LogicalPackage lp = null;
          for (int j = 0; j < packagesMem.length; j++) {
            javaElementHandle = packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
            Object pack = DLTKCore.create(javaElementHandle);
            if (pack instanceof IScriptFolder && ((IScriptFolder) pack).exists()) {
              if (lp == null) lp = new LogicalPackage((IScriptFolder) pack);
              else lp.add((IScriptFolder) pack);
            }
          }
          if (lp != null) list.add(lp);
        } else {
          IModelElement element = DLTKCore.create(javaElementHandle);
          if (element != null && element.exists()) list.add(element);
        }
      }
      return new StructuredSelection(list);
    }
    return null;
  }
コード例 #2
0
  /**
   * @param matchList a List of SearchMatch
   * @param status the status to report errors.
   * @return a SearchResultGroup[], grouped by SearchMatch#getResource()
   */
  public static SearchResultGroup[] groupByCu(
      List<SearchMatch> matchList, RefactoringStatus status) {
    Map<IResource, List<SearchMatch>> grouped = new HashMap<IResource, List<SearchMatch>>();
    boolean hasPotentialMatches = false;
    boolean hasNonCuMatches = false;

    for (SearchMatch searchMatch : matchList) {
      if (searchMatch.getAccuracy() == SearchMatch.A_INACCURATE) hasPotentialMatches = true;
      if (!grouped.containsKey(searchMatch.getResource()))
        grouped.put(searchMatch.getResource(), new ArrayList<SearchMatch>(1));
      grouped.get(searchMatch.getResource()).add(searchMatch);
    }

    for (Iterator<IResource> iter = grouped.keySet().iterator(); iter.hasNext(); ) {
      IResource resource = iter.next();
      IModelElement element = DLTKCore.create(resource);
      if (!(element instanceof ISourceModule)) {
        iter.remove();
        hasNonCuMatches = true;
      }
    }

    SearchResultGroup[] result = new SearchResultGroup[grouped.keySet().size()];
    int i = 0;
    for (IResource resource : grouped.keySet()) {
      List<SearchMatch> searchMatches = grouped.get(resource);
      SearchMatch[] matchArray = searchMatches.toArray(new SearchMatch[searchMatches.size()]);
      result[i] = new SearchResultGroup(resource, matchArray);
      i++;
    }
    addStatusErrors(status, hasPotentialMatches, hasNonCuMatches);
    return result;
  }
コード例 #3
0
  /*
   * Refreshes the external folders referenced on the buildpath of the given
   * source project
   */
  public void refreshReferences(IProject source, IProgressMonitor monitor) {
    IProject externalProject = getExternalFoldersProject();
    if (source.equals(externalProject)) return;
    if (!ScriptProject.hasScriptNature(source)) return;
    try {
      HashSet externalFolders =
          getExternalFolders(((ScriptProject) DLTKCore.create(source)).getResolvedBuildpath());
      if (externalFolders == null) return;
      final Iterator iterator = externalFolders.iterator();
      Job refreshJob =
          new Job(Messages.refreshing_external_folders) {
            public boolean belongsTo(Object family) {
              return family == ResourcesPlugin.FAMILY_MANUAL_REFRESH;
            }

            protected IStatus run(IProgressMonitor pm) {
              try {
                while (iterator.hasNext()) {
                  IPath externalPath = (IPath) iterator.next();
                  IFolder folder = getFolder(externalPath);
                  if (folder != null) folder.refreshLocal(IResource.DEPTH_INFINITE, pm);
                }
              } catch (CoreException e) {
                return e.getStatus();
              }
              return Status.OK_STATUS;
            }
          };
      refreshJob.schedule();
    } catch (CoreException e) {
      Util.log(e, "Exception while refreshing external project"); // $NON-NLS-1$
    }
    return;
  }
コード例 #4
0
ファイル: MoveDelegate.java プロジェクト: spiritman1990/pdt
  private void removeBuildPath(IResource resource, IProject project) {

    IScriptProject projrct = DLTKCore.create(project);
    IPath filePath = resource.getFullPath();

    oldBuildEntries = Arrays.asList(projrct.readRawBuildpath());

    newBuildEntries = new ArrayList<IBuildpathEntry>();

    newBuildEntries.addAll(oldBuildEntries);

    for (int i = 0; i < oldBuildEntries.size(); i++) {
      IBuildpathEntry fEntryToChange = oldBuildEntries.get(i);
      IPath entryPath = fEntryToChange.getPath();

      int mattchedPath = entryPath.matchingFirstSegments(filePath);

      if (mattchedPath == filePath.segmentCount()) {
        newBuildEntries.remove(fEntryToChange);
      } else {
        IBuildpathEntry newEntry =
            RefactoringUtility.createNewBuildpathEntry(
                fEntryToChange, fEntryToChange.getPath(), filePath, ""); // $NON-NLS-1$
        newBuildEntries.remove(fEntryToChange);
        newBuildEntries.add(newEntry);
      }
    }

    oldIncludePath = new ArrayList<IBuildpathEntry>();

    newIncludePathEntries = new ArrayList<IBuildpathEntry>();
    List<IncludePath> includePathEntries =
        Arrays.asList(IncludePathManager.getInstance().getIncludePaths(project));

    for (IncludePath entry : includePathEntries) {
      Object includePathEntry = entry.getEntry();
      IResource includeResource = null;
      if (!(includePathEntry instanceof IBuildpathEntry)) {
        includeResource = (IResource) includePathEntry;
        IPath entryPath = includeResource.getFullPath();

        IBuildpathEntry oldEntry =
            RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
        oldIncludePath.add((IBuildpathEntry) oldEntry);

        if (filePath.isPrefixOf(entryPath) || entryPath.equals(filePath)) {
        } else {
          IBuildpathEntry newEntry =
              RefactoringUtility.createNewBuildpathEntry(IBuildpathEntry.BPE_SOURCE, entryPath);
          newIncludePathEntries.add(newEntry);
        }
      } else {
        newIncludePathEntries.add((IBuildpathEntry) includePathEntry);
        oldIncludePath.add((IBuildpathEntry) includePathEntry);
      }
    }
  }
コード例 #5
0
ファイル: DLTKUIPlugin.java プロジェクト: earlyster/dltk.core
  public static ISourceModule resolveSourceModule(FileStoreEditorInput input) {
    final ISourceModule[] modules = new ISourceModule[1];
    final IPath filePath = URIUtil.toPath(input.getURI());
    IScriptModel scriptModel = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot());
    try {
      scriptModel.accept(
          new IModelElementVisitor() {

            public boolean visit(IModelElement element) {
              boolean shouldDescend = (modules[0] == null);

              if (shouldDescend == true) {
                if (element instanceof ExternalProjectFragment) {
                  ExternalProjectFragment fragment = (ExternalProjectFragment) element;

                  try {
                    if (filePath
                            .removeLastSegments(1)
                            .toFile()
                            .getCanonicalPath()
                            .startsWith(fragment.getPath().toFile().getCanonicalPath())
                        == true) {
                      IPath folderPath =
                          new Path(filePath.removeLastSegments(1).toFile().getCanonicalPath());
                      folderPath =
                          folderPath.removeFirstSegments(
                              new Path(fragment.getPath().toFile().getCanonicalPath())
                                  .segmentCount());
                      IScriptFolder folder = fragment.getScriptFolder(folderPath);
                      if ((folder != null) && (folder.exists() == true)) {
                        ISourceModule module = folder.getSourceModule(filePath.lastSegment());
                        if (module != null) {
                          modules[0] = module;
                        }
                      }
                    }
                  } catch (IOException ixcn) {
                    ixcn.printStackTrace();
                  }

                  shouldDescend = false;
                } else {
                  shouldDescend =
                      ((element instanceof IScriptProject) || (element instanceof IScriptModel));
                }
              }

              return shouldDescend;
            }
          });
    } catch (ModelException mxcn) {
      mxcn.printStackTrace();
    }

    return modules[0];
  }
コード例 #6
0
  private static ImageDescriptor getFolderBaseImage(IResource resource) {
    IModelElement modelElement = DLTKCore.create(resource);

    if (null != modelElement) {
      if (modelElement instanceof IScriptFolder) return PHPPluginImages.DESC_OBJS_PHPFOLDER_ROOT;
    } else {
      return PlatformUI.getWorkbench()
          .getSharedImages()
          .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER);
    }
    return null;
  }
  public void installSymfony(IProgressMonitor monitor) {

    if (monitor == null) monitor = new NullProgressMonitor();

    SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;
    monitor.beginTask("Installing symfony...", 100);
    monitor.worked(10);

    IProject projectHandle = fFirstPage.getProjectHandle();
    final IScriptProject scriptProject = DLTKCore.create(projectHandle);

    File file = null;
    final List<IBuildpathEntry> entries = new ArrayList<IBuildpathEntry>();

    level = 0;

    try {

      file = new File(firstPage.getLibraryPath());
      symfonyPath = new Path(firstPage.getLibraryPath()).toString();

      if (file.isDirectory()) {

        final File[] files = file.listFiles();

        if (!scriptProject.isOpen()) {
          scriptProject.open(monitor);
        }

        if (files != null && scriptProject != null && scriptProject.isOpen()) {

          for (File f : files) {
            importFile(f, scriptProject.getProject(), entries);
          }

          BuildPathUtils.addEntriesToBuildPath(scriptProject, entries);
          monitor.worked(90);
        }
      }
    } catch (ModelException e) {
      e.printStackTrace();
      Logger.logException(e);
    } catch (Exception e) {
      e.printStackTrace();
      Logger.logException(e);
    } finally {

      monitor.worked(100);
      monitor.done();
    }
  }
コード例 #8
0
 /**
  * @param element
  * @param iBuildpathEntry
  * @return the name of the container description
  */
 private String getEntryDescription(Object element, IBuildpathEntry iBuildpathEntry) {
   IProject project = ((IncludePath) element).getProject();
   IScriptProject scriptProject = DLTKCore.create(project);
   IBuildpathContainer buildpathContainer = null;
   try {
     buildpathContainer = DLTKCore.getBuildpathContainer(iBuildpathEntry.getPath(), scriptProject);
   } catch (ModelException e) {
     // no matching container - return the path
   }
   if (buildpathContainer != null) {
     return buildpathContainer.getDescription();
   }
   return iBuildpathEntry.getPath().toOSString();
 }
コード例 #9
0
 public void initializeFrom(Element memento) throws CoreException {
   String name = memento.getAttribute("project"); // $NON-NLS-1$
   if (name == null) {
     abort(LaunchingMessages.DefaultProjectBuildpathEntry_3, null);
   }
   IScriptProject project =
       DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(name));
   setScriptProject(project);
   name = memento.getAttribute("exportedEntriesOnly"); // $NON-NLS-1$
   if (name == null) {
     fExportedEntriesOnly = false;
   } else {
     fExportedEntriesOnly = Boolean.valueOf(name).booleanValue();
   }
 }
コード例 #10
0
 @Override
 public Set<IScriptProject> collectProjects() {
   final Set<IScriptProject> projects = new HashSet<IScriptProject>();
   final IScriptModel model = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot());
   try {
     for (IScriptProject project : model.getScriptProjects(TclNature.NATURE_ID)) {
       InstrumentationUtils.collectProjects(model, projects, project);
     }
   } catch (CoreException e) {
     if (DLTKCore.DEBUG) {
       e.printStackTrace();
     }
   }
   return projects;
 }
コード例 #11
0
  /**
   * Heavily based on RemoteScriptSourceLookupDirector#getSourceElement(Object) but adds {@link
   * IStorage} support and checks that URI actually contains something (case of unreachable stack
   * levels)
   *
   * @see
   *     org.eclipse.debug.core.sourcelookup.AbstractSourceLookupDirector#getSourceElement(java.lang.Object)
   * @see
   *     org.eclipse.dltk.launching.sourcelookup.RemoteScriptSourceLookupDirector#getSourceElement(Object)
   */
  @Override
  public Object getSourceElement(Object element) {
    // if the element is an unreachable stack frame we don't need to search trough the source path
    // computer.
    if (element instanceof IScriptStackFrame) {
      IScriptStackFrame frame = (ScriptStackFrame) element;
      UnreachableStackFrame unreachableStackFrame = UnreachableStackFrame.checkReachable(frame);
      if (unreachableStackFrame != null) {
        return unreachableStackFrame;
      }
    }

    // search in all container of the source path computer.
    Object o = super.getSourceElement(element);

    // a file or a IStorage was found, we return it, we can display it.
    if (o instanceof IFile || o instanceof IStorage) {
      return o;
    }

    // at this time, if we still have a ScriptStackFrame
    // we could have a fallback and create a DBGPSourceModule
    // (the source code will be return by the DBGP client via the command "source"
    if (element instanceof ScriptStackFrame) {
      ScriptStackFrame frame = (ScriptStackFrame) element;

      URI uri = frame.getSourceURI();
      String path = uri.getPath();
      IProject project = LaunchConfigurationUtils.getProject(getLaunchConfiguration());
      if (project == null) {
        return null;
      }
      IScriptProject scriptProject = DLTKCore.create(project);

      /*
       * XXX: this should probably use some kind of IStorable implementation instead of directly relying on the stack frame - that allows for
       * re-use of the ExternalStorageEditorInput object
       */
      return new DBGPSourceModule(
          (ScriptProject) scriptProject, path, DefaultWorkingCopyOwner.PRIMARY, frame);
    }

    // we not managed the other case, so return null
    return null;
  }
コード例 #12
0
 /**
  * Returns the hierarchical packages inside a given folder.
  *
  * @param folder The parent folder
  * @param result Collection where the resulting elements are added
  * @throws CoreException thrown when elements could not be accessed
  */
 private void getHierarchicalPackagesInFolder(
     final IFolder folder, final Collection<Object> result) throws CoreException {
   IResource[] resources = folder.members();
   for (int i = 0; i < resources.length; i++) {
     IResource resource = resources[i];
     if (resource instanceof IFolder) {
       IFolder curr = (IFolder) resource;
       IModelElement element = DLTKCore.create(curr);
       if (element instanceof IScriptFolder) {
         if (fFoldPackages) {
           IScriptFolder fragment = (IScriptFolder) element;
           IProjectFragment root = (IProjectFragment) fragment.getParent();
           element = ScriptExplorerContentProvider.getFolded(root.getChildren(), fragment);
         }
         result.add(element);
       }
     }
   }
 }
コード例 #13
0
ファイル: PHPCorePlugin.java プロジェクト: KopjeKoffie/pdt
    public void resourceChanged(IResourceChangeEvent event) {
      if (event.getBuildKind() == IncrementalProjectBuilder.CLEAN_BUILD) {
        Object source = event.getSource();
        try {
          if (source instanceof IProject) {
            IProject project = (IProject) source;
            ProjectIndexerManager.removeProject(project.getFullPath());
            ProjectIndexerManager.indexProject(project);

          } else if (source instanceof IWorkspace) {
            IWorkspace workspace = (IWorkspace) source;
            IProject[] projects = workspace.getRoot().getProjects();

            // remove from index:
            for (IProject project : projects) {
              if (!project.isAccessible()) {
                continue;
              }
              IScriptProject scriptProject = DLTKCore.create(project);
              if (scriptProject.isOpen()) {
                IProjectFragment[] projectFragments = scriptProject.getProjectFragments();
                for (IProjectFragment projectFragment : projectFragments) {
                  ProjectIndexerManager.removeProjectFragment(
                      scriptProject, projectFragment.getPath());
                }
                ProjectIndexerManager.removeProject(project.getFullPath());
              }
            }

            // add to index:
            for (IProject project : projects) {
              if (!project.isAccessible()) {
                continue;
              }
              ProjectIndexerManager.indexProject(project);
            }
          }
        } catch (CoreException e) {
          Logger.logException(e);
        }
      }
    }
コード例 #14
0
  public static ISourceModule[] findAffectedCompilationUnits(
      SearchPattern pattern,
      IDLTKSearchScope scope,
      final IProgressMonitor pm,
      RefactoringStatus status,
      final boolean tolerateInAccurateMatches)
      throws CoreException {

    boolean hasNonCuMatches = false;

    class ResourceSearchRequestor extends SearchRequestor {
      boolean hasPotentialMatches = false;
      Set<IResource> resources = new HashSet<IResource>(5);
      private IResource fLastResource;

      public void acceptSearchMatch(SearchMatch match) {
        if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) {
          hasPotentialMatches = true;
        }
        if (fLastResource != match.getResource()) {
          fLastResource = match.getResource();
          resources.add(fLastResource);
        }
      }
    }
    ResourceSearchRequestor requestor = new ResourceSearchRequestor();
    new SearchEngine()
        .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
    List<ISourceModule> result = new ArrayList<ISourceModule>(requestor.resources.size());
    for (IResource resource : requestor.resources) {
      IModelElement element = DLTKCore.create(resource);
      if (element instanceof ISourceModule) {
        result.add((ISourceModule) element);
      } else {
        hasNonCuMatches = true;
      }
    }
    addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches);
    return (ISourceModule[]) result.toArray(new ISourceModule[result.size()]);
  }
コード例 #15
0
ファイル: PHPCorePlugin.java プロジェクト: KopjeKoffie/pdt
  /*
   * Do the actual modifications on the project
   */
  private void modifyProject(IProject project) throws CoreException, ModelException {
    final PHPNature phpNature = new PHPNature();

    // add the required builders and build paths as defined in the new PHP
    // nature
    phpNature.setProject(project);
    phpNature.configure();

    IScriptProject scriptProject = DLTKCore.create(project);
    // merge the project build path with the old include path
    IBuildpathEntry[] existingPath = scriptProject.getRawBuildpath();

    ArrayList<IBuildpathEntry> newPath = new ArrayList<IBuildpathEntry>();
    if (existingPath != null) {
      newPath.addAll(Arrays.asList(existingPath));
    }
    ProjectBackwardCompatibilityUtil unit = new ProjectBackwardCompatibilityUtil();
    IBuildpathEntry[] oldIncludePath = unit.convertIncludePathForProject(project);
    if (oldIncludePath != null) {
      newPath.addAll(Arrays.asList(oldIncludePath));
    }
    scriptProject.setRawBuildpath(
        newPath.toArray(new IBuildpathEntry[newPath.size()]), new NullProgressMonitor());
  }
  @Override
  public Object execute(ExecutionEvent event) {

    //	Plugin.isManuallyStarted = true;

    System.out.println("ASIDECodeAnnotateHandler.java is ran ---first line");
    targetPart = HandlerUtil.getActivePart(event);

    IWorkbenchPartSite site = targetPart.getSite();
    ISelectionProvider selectionProvider = site.getSelectionProvider();
    if (selectionProvider == null) {
      return null;
    }
    ISelection selection = selectionProvider.getSelection();
    if (selection == null) {
      System.out.println("selectProject = ");
      return null;
    }
    IResource iRes = extractSelection(selection);
    if (iRes == null) {
      System.out.println("test == null");
      return null;
    }
    selectProject = iRes.getProject();
    if (selectProject == null) {
      System.out.println("selectProject == null");
      return null;
    }
    System.out.println("selectProject = " + selectProject.getName());

    // the following is temporarily added here
    pathCollector = ModelRegistry.getPathCollectorForProject(selectProject);

    if (pathCollector == null) {
      pathCollector = new PathCollector(selectProject);
    }

    paths = pathCollector.getAllPaths();

    if (paths == null) paths = Collections.synchronizedList(new ArrayList<Path>());

    System.out.println(
        "ASIDECodeAnnotateHandler.java is ran -- start iterating files of the project");
    IScriptProject scriptProject = DLTKCore.create(selectProject);
    if (scriptProject == null) {
      System.out.println("scirpt project == null");
      return null;
    }
    int count = 1;

    // gather statistics
    // GatherStatistics.NumOfWarningsInEachFile();
    // while tablename = ...

    Utils.removeAllQuestionMarkers(iRes);
    Plugin.projectResource = iRes;
    Iterator ite = Plugin.sensitive_DB_Tables.iterator();
    String currentSensitiveTableName = null;
    // commented out Nov. 27
    /*while(ite.hasNext()){
    currentSensitiveTableName = (String) ite.next();
    Plugin.CurrentSensitiveDBTable = currentSensitiveTableName;
    System.out.println("Current Table is=" + Plugin.CurrentSensitiveDBTable);*/

    String currentTableName;

    while (!Plugin.sensitive_DB_Tables_AlphRanked
        .isEmpty()) { // collect the warnings that comes from one table, one throughout iteration
                      // for each table, and put the results into the

      currentTableName = Plugin.sensitive_DB_Tables_AlphRanked.first();
      count = 1;
      Plugin.allMarkerRecords.clear();

      while (Plugin.sensitiveOperationsForCurrentIteration != null
          && Plugin.sensitiveOperationsForCurrentIteration.size() != 0) {
        count++;
        System.out.println("-----------------begin round " + count);
        System.out.println(
            "Plugin.sensitiveOperationsForCurrentIteration size =!!!"
                + Plugin.sensitiveOperationsForCurrentIteration.size());
        IScriptFolder[] folders = null;
        try {
          folders = scriptProject.getScriptFolders();
        } catch (ModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println("number of folders ==" + folders.length);

        /*String pattern = "Exec";
        process(selectProject, pattern);*/

        ////////////////
        Plugin.sensitiveOperationsForAnotherIteration.clear();
        Plugin.sensitiveOperationsForAnotherIteration = new HashSet();
        //	System.out.println("at the begining point: size of current " +
        // Plugin.sensitiveOperationsForCurrentIteration.size());
        int numOfFiles = 0;
        for (IScriptFolder folder : folders) {
          String folderName = folder.getElementName();
          if (!Constants.PHPLibraryFolders.contains(folderName)) {

            ISourceModule[] sourceModules = null;
            try {
              sourceModules = folder.getSourceModules();
            } catch (ModelException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
            numOfFiles += sourceModules.length;
          }
        }
        /*    for(int i = 0; i < 20; i++)
        System.out.println("files num = " + numOfFiles);*/
        System.out.println("sum of folders =" + folders.length);
        int currentFolderNum = 1;
        for (IScriptFolder folder : folders) {
          System.out.println("folder scanning = " + currentFolderNum + "/" + folders.length);
          String folderName = folder.getElementName();
          System.out.println("folder name = " + folderName);

          if (!Constants.PHPLibraryFolders.contains(folderName)) {

            ISourceModule[] sourceModules = null;
            try {
              sourceModules = folder.getSourceModules();
            } catch (ModelException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            for (ISourceModule tmpSourceModule : sourceModules) {
              System.out.println("scanning " + tmpSourceModule.getElementName());
              // if it is not the first time to run CodeAnnotate on this project, then disable the
              // scan function,
              // we have already pop the marker records from the file and displayed in Eclipse
              // already.
              if (false) {
              } // temporarily testing
              /*		if(Plugin.FIRST_TIME_RUN == false){
              	//simply display the markers based on the marker records in the file
              	String fileDir = tmpSourceModule.getResource().getFullPath().toString();
              	System.out.println("all markers size = " + Plugin.allMarkerRecords.size());
              	HashSet<MarkerRecord> markerRecordsInSingleFile = Utils.getMarkerRecordsForSingleFile(Plugin.allMarkerRecords, fileDir);
              	Utils.createMarkersForSingleFile(markerRecordsInSingleFile, tmpSourceModule);

              	HashSet<AnnotationRecord> annotationRecordsInSingleFile = Utils.getAnnotationRecordsForSingleFile(Plugin.allAnnotationRecords, fileDir);
              	Utils.createAnnotationsForSingleFile(annotationRecordsInSingleFile, tmpSourceModule);

              	System.out.println("finished creating markers for fileDir = " + fileDir + ", markerRecordsInSingleFile size = " + markerRecordsInSingleFile.size());
              }*/
              else { // start scanning the files for sensitive operations

                //			System.out.println("isourcemodule being built = " +
                // tmpSourceModule.getElementName().toLowerCase());
                //				System.out.println("full path of the source module is ---" +
                // tmpSourceModule.getResource().getFullPath().toString());

                SensitiveOperationVisitor visitor =
                    new SensitiveOperationVisitor(
                        tmpSourceModule,
                        Plugin.sensitiveOperationsForCurrentIteration,
                        Plugin.sensitiveOperationsForAnotherIteration,
                        Plugin.sensitiveOperations);
                Program root = null;
                try {
                  root = Utils.getCompilationUnit(tmpSourceModule);
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  System.err.println("root = util.getcompilationUnit() throws exception!");
                  e.printStackTrace();
                }
                //		System.out.println("begin of traverseTopDown");
                if (root == null) {
                  System.err.println(
                      "tmpSourceModule name = "
                          + tmpSourceModule.getElementName()
                          + " in "
                          + tmpSourceModule.getPath().toString());
                  System.err.println("root == null");
                  // return null;
                }
                root.traverseTopDown(visitor);

                Plugin.sensitiveOperations = visitor.getSensitiveOperations();
                Plugin.sensitiveOperationsForAnotherIteration =
                    visitor.getSensitiveOperationsForAnotherIteration();
              }
            }
          }
          currentFolderNum++;
        }
        Plugin.sensitiveOperationsForCurrentIteration.clear();
        Plugin.sensitiveOperationsForCurrentIteration = new HashSet();

        //	System.out.println("Plugin.sensitiveOperationsForAnotherIteration size after iteration ="
        // + Plugin.sensitiveOperationsForAnotherIteration.size());
        Plugin.sensitiveOperationsForCurrentIteration =
            (HashSet<SensitiveMethod>) Plugin.sensitiveOperationsForAnotherIteration.clone();
        //	System.out.println("after assignment, Plugin.sensitiveOperationsForCurrentIteratio size =
        // " + Plugin.sensitiveOperationsForCurrentIteration.size());

        /*String newRuleFileName = "newRulesForIteration" + count + "th.txt";
        InRunPluginDataSave.writeNewSensitiveRulesIntoFile(newRuleFileName, Plugin.sensitiveOperationsForCurrentIteration);

        String mappingFileName = "numOfWarningsInEachFileInIteration" + (count-1) + "th.txt";;
        InRunPluginDataSave.writeMappingBetweenWarningsAndFiles(mappingFileName, Plugin.numberOfWarningsInEachFile);

        if(count == 2){
        String newTableNamesFileName = "tableNamesEncounteredInIteration" + (count-1) + "th.txt";
        InRunPluginDataSave.writeTableNamesIntoFile(newTableNamesFileName, Plugin.allTableNames);

        String mappingFileName2 = "numOfWarningsRelatedToEachTableForIteration" + (count-1) + "th.txt";
        InRunPluginDataSave.writeMappingBetweenWarningsAndFiles(mappingFileName2, Plugin.numberOfWarningsRelatedToEachTable);
        }*/

        PostRunPluginConfig.writeMarkerRecordIntoFile(
            Plugin.allMarkerRecords, count, currentTableName);
      }

      //// newly added
      // remove the first table name in the treeset so that we focus on the next table in the next
      // iteration.
      Plugin.sensitive_DB_Tables_AlphRanked.pollFirst();
      Plugin.sensitiveOperationsForCurrentIteration = RulesUtils.getSensitiveOperations();
    }

    // commented out Nov. 27
    /*GatherStatistics.writeMarkersForEachTable(Plugin.allMarkerRecords, Plugin.CurrentSensitiveDBTable);
    Plugin.allMarkerRecords.clear();
    Plugin.allMarkerRecords = new HashSet();
    count = 1;
    Plugin.sensitiveOperationsForCurrentIteration.clear();
    Plugin.sensitiveOperationsForCurrentIteration = new HashSet();
    Plugin.sensitiveOperationsForCurrentIteration = (HashSet<SensitiveMethod>) Plugin.sensitiveOperationsForCurrentIteration_backup.clone();
    Plugin.sensitiveOperations.clear();
    Plugin.sensitiveOperations = new HashSet();
    Plugin.sensitiveOperations = (HashSet<SensitiveMethod>)Plugin.sensitiveOperations_backup.clone();
    }*/
    // above is temporarily added.

    // below are temporarily added for the analysis use
    //		GatherStatistics.filesWithoutRequiredAccessControls(Plugin.numberOfWarningsInEachFile,
    // Plugin.numberOfAccessControlsInEachFile);

    /*
     * Use a Job to attach a {@link CodeAnnotateDocumentEditListener} to
     * each and every IDocument that is related to a ICompilationUnit in the
     * selected project
     */
    /*
     * Job job = new MountListenerJob("Mount listener to Java file",
     * JavaCore.create(selectProject)); job.setPriority(Job.INTERACTIVE);
     * job.schedule();
     */

    /* Delegates all heavy lifting to {@link PathFinder} */
    /*Job heavy_job = new Job("Finding paths in Project: "
    				+ selectProject.getName()) {

    			@Override
    			protected IStatus run(final IProgressMonitor monitor) {
    				try {
    					Plugin.getDefault().getWorkbench().getDisplay()
    							.asyncExec(new Runnable() {

    								@Override
    								public void run() {
    									// PathFinder.getInstance(selectProject).run(monitor);

    								}

    							});

    				} finally {
    					monitor.done();
    				}
    				return Status.OK_STATUS;
    			}

    		};
    		heavy_job.setPriority(Job.LONG);
    		heavy_job.schedule();
    */
    System.out.println("finished scanning, marker records saved");
    // PostRunPluginConfig.config(Plugin.allMarkerRecords, Plugin.allAnnotationRecords);
    //	PostRunPluginConfig.writeMarkerRecordIntoFile(Plugin.allMarkerRecords, count);
    //		GatherStatistics.readWarningStatistics(Plugin.sensitive_DB_Tables_AlphRanked,
    // "Update_Level5.txt");
    return null;
  }
コード例 #17
0
  /**
   * Returns the transitive closure of buildpath entries for the given project entry.
   *
   * @param projectEntry project buildpath entry
   * @param expandedPath a list of entries already expanded, should be empty to begin, and contains
   *     the result
   * @param expanding a list of projects that have been or are currently being expanded (to detect
   *     cycles)
   * @exception CoreException if unable to expand the buildpath
   */
  private void expandProject(IBuildpathEntry projectEntry, List expandedPath, List expanding)
      throws CoreException {
    expanding.add(projectEntry);
    // 1. Get the raw buildpath
    // 2. Replace source folder entries with a project entry
    IPath projectPath = projectEntry.getPath();
    IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment());
    if (res == null) {
      // add project entry and return
      expandedPath.add(projectEntry);
      return;
    }
    IScriptProject project = (IScriptProject) DLTKCore.create(res);
    if (project == null || !project.getProject().isOpen() || !project.exists()) {
      // add project entry and return
      expandedPath.add(projectEntry);
      return;
    }

    IBuildpathEntry[] buildPath = project.getRawBuildpath();
    List unexpandedPath = new ArrayList(buildPath.length);
    // boolean projectAdded = false;
    for (int i = 0; i < buildPath.length; i++) {
      IBuildpathEntry buildpathEntry = buildPath[i];
      if (buildpathEntry.getEntryKind() == IBuildpathEntry.BPE_SOURCE) { // sources
        // are
        // always
        // added
        unexpandedPath.add(buildpathEntry);
      } else {
        // add exported entires, as configured
        if (buildpathEntry.isExported()) {
          unexpandedPath.add(buildpathEntry);
        } else if (!isExportedEntriesOnly() || project.equals(getScriptProject())) {
          // add non exported entries from root project or if we are
          // including all entries
          unexpandedPath.add(buildpathEntry);
        }
      }
    }
    // 3. expand each project entry (except for the root project)
    // 4. replace each container entry with a runtime entry associated with
    // the project
    Iterator iter = unexpandedPath.iterator();
    while (iter.hasNext()) {
      IBuildpathEntry entry = (IBuildpathEntry) iter.next();
      if (entry == projectEntry) {
        expandedPath.add(entry);
      } else {
        switch (entry.getEntryKind()) {
          case IBuildpathEntry.BPE_PROJECT:
            if (!expanding.contains(entry)) {
              expandProject(entry, expandedPath, expanding);
            }
            break;
          case IBuildpathEntry.BPE_CONTAINER:
            IBuildpathContainer container =
                DLTKCore.getBuildpathContainer(entry.getPath(), project);
            int property = -1;
            if (container != null) {
              switch (container.getKind()) {
                case IBuildpathContainer.K_APPLICATION:
                  property = IRuntimeBuildpathEntry.USER_ENTRY;
                  break;
                case IBuildpathContainer.K_DEFAULT_SYSTEM:
                  property = IRuntimeBuildpathEntry.STANDARD_ENTRY;
                  break;
                case IBuildpathContainer.K_SYSTEM:
                  property = IRuntimeBuildpathEntry.BOOTSTRAP_ENTRY;
                  break;
              }
              IRuntimeBuildpathEntry r =
                  ScriptRuntime.newRuntimeContainerBuildpathEntry(
                      entry.getPath(), property, project);
              // check for duplicate/redundant entries
              boolean duplicate = false;
              BuildpathContainerInitializer initializer =
                  DLTKCore.getBuildpathContainerInitializer(r.getPath().segment(0));
              for (int i = 0; i < expandedPath.size(); i++) {
                Object o = expandedPath.get(i);
                if (o instanceof IRuntimeBuildpathEntry) {
                  IRuntimeBuildpathEntry re = (IRuntimeBuildpathEntry) o;
                  if (re.getType() == IRuntimeBuildpathEntry.CONTAINER) {
                    BuildpathContainerInitializer initializer2 =
                        DLTKCore.getBuildpathContainerInitializer(re.getPath().segment(0));
                    Object id1 = null;
                    Object id2 = null;
                    if (initializer == null) {
                      id1 = r.getPath().segment(0);
                    } else {
                      id1 = initializer.getComparisonID(r.getPath(), project);
                    }
                    if (initializer2 == null) {
                      id2 = re.getPath().segment(0);
                    } else {
                      IScriptProject context = re.getScriptProject();
                      if (context == null) {
                        context = project;
                      }
                      id2 = initializer2.getComparisonID(re.getPath(), context);
                    }
                    if (id1 == null) {
                      duplicate = id2 == null;
                    } else {
                      duplicate = id1.equals(id2);
                    }
                    if (duplicate) {
                      break;
                    }
                  }
                }
              }
              if (!duplicate) {
                expandedPath.add(r);
              }
            }
            break;
          default:
            if (!expandedPath.contains(entry)) {
              expandedPath.add(entry);
            }
            break;
        }
      }
    }
    return;
  }
  @Override
  protected void updateProject(IProgressMonitor monitor)
      throws CoreException, InterruptedException {

    IProject projectHandle = fFirstPage.getProjectHandle();
    IScriptProject create = DLTKCore.create(projectHandle);
    super.init(create, null, false);
    fCurrProjectLocation = getProjectLocationURI();

    boolean installSymfony = true;

    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    try {
      monitor.beginTask(NewWizardMessages.ScriptProjectWizardSecondPage_operation_initialize, 70);
      if (monitor.isCanceled()) {
        throw new OperationCanceledException();
      }

      URI realLocation = fCurrProjectLocation;
      if (fCurrProjectLocation == null) { // inside workspace
        try {
          URI rootLocation = ResourcesPlugin.getWorkspace().getRoot().getLocationURI();
          realLocation =
              new URI(
                  rootLocation.getScheme(),
                  null,
                  Path.fromPortableString(rootLocation.getPath())
                      .append(getProject().getName())
                      .toString(),
                  null);
        } catch (URISyntaxException e) {
          Assert.isTrue(false, "Can't happen"); // $NON-NLS-1$
        }
      }

      rememberExistingFiles(realLocation);

      createProject(getProject(), fCurrProjectLocation, new SubProgressMonitor(monitor, 20));

      IBuildpathEntry[] buildpathEntries = null;
      IncludePath[] includepathEntries = null;

      SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage;

      if (firstPage.getDetect()) {

        installSymfony = false;
        includepathEntries = setProjectBaseIncludepath();
        if (!getProject().getFile(FILENAME_BUILDPATH).exists()) {

          IDLTKLanguageToolkit toolkit = DLTKLanguageManager.getLanguageToolkit(getScriptNature());
          final BuildpathDetector detector = createBuildpathDetector(monitor, toolkit);
          buildpathEntries = detector.getBuildpath();

        } else {
          monitor.worked(20);
        }
      } else if (firstPage.hasSymfonyStandardEdition()) {

        // flat project layout
        IPath projectPath = getProject().getFullPath();
        List cpEntries = new ArrayList();
        cpEntries.add(DLTKCore.newSourceEntry(projectPath));

        //				buildpathEntries = (IBuildpathEntry[]) cpEntries
        //						.toArray(new IBuildpathEntry[cpEntries.size()]);
        //				includepathEntries = setProjectBaseIncludepath();

        buildpathEntries = new IBuildpathEntry[0];
        includepathEntries = new IncludePath[0];

        monitor.worked(20);

      } else {
        // flat project layout
        IPath projectPath = getProject().getFullPath();
        List cpEntries = new ArrayList();
        cpEntries.add(DLTKCore.newSourceEntry(projectPath));

        //				buildpathEntries = (IBuildpathEntry[]) cpEntries
        //						.toArray(new IBuildpathEntry[cpEntries.size()]);
        //				includepathEntries = setProjectBaseIncludepath();

        buildpathEntries = new IBuildpathEntry[0];
        includepathEntries = new IncludePath[0];

        monitor.worked(20);
      }
      if (monitor.isCanceled()) {
        throw new OperationCanceledException();
      }

      init(DLTKCore.create(getProject()), buildpathEntries, false);

      // setting PHP4/5 and ASP-Tags :
      setPhpLangOptions();

      configureScriptProject(new SubProgressMonitor(monitor, 30));

      SymfonyProjectWizardFirstPage p = (SymfonyProjectWizardFirstPage) getFirstPage();

      // checking and adding JS nature,libs, include path if needed
      if (p.shouldSupportJavaScript()) {
        addJavaScriptNature(monitor);
      }

      // adding build paths, and language-Container:
      getScriptProject().setRawBuildpath(buildpathEntries, new NullProgressMonitor());
      LanguageModelInitializer.enableLanguageModelFor(getScriptProject());

      // init, and adding include paths:
      getBuildPathsBlock().init(getScriptProject(), new IBuildpathEntry[] {});
      IncludePathManager.getInstance().setIncludePath(getProject(), includepathEntries);

      if (installSymfony) installSymfony(new SubProgressMonitor(monitor, 50));

    } finally {
      monitor.done();
    }
  }
コード例 #19
0
  @Override
  public Image getImage(Object element) {
    IModelElement modelElement = null;
    if (element instanceof ExternalProjectFragment) {
      return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
    }

    if (element instanceof IncludePath) {
      Object entry = ((IncludePath) element).getEntry();

      // An included PHP project
      if (entry instanceof IBuildpathEntry) {
        int entryKind = ((IBuildpathEntry) entry).getEntryKind();
        if (entryKind == IBuildpathEntry.BPE_PROJECT) {
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHP_PROJECT);
        }
        // A library
        if (entryKind == IBuildpathEntry.BPE_LIBRARY
            || entryKind == IBuildpathEntry.BPE_CONTAINER) {
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
        }
      }

      if (entry instanceof ExternalProjectFragment) {
        return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_LIBRARY);
      }

      // Folder in the include path, should have same image as in the PHP
      // Explorer .
      if (entry instanceof IFolder) {
        IModelElement createdScriptFolder = DLTKCore.create((IFolder) entry);
        if (null == createdScriptFolder) return getImage(entry);
        return getImage(createdScriptFolder);
      }

      if (entry instanceof IResource) {
        return (getImage((IResource) entry));
      }
      return null;
    }

    if (element instanceof IResource) {
      modelElement = DLTKCore.create((IResource) element);
    } else if (element instanceof IModelElement) {
      modelElement = (IModelElement) element;
    }

    if (modelElement != null) {
      IScriptProject project = modelElement.getScriptProject();
      if (!project.isOnBuildpath(modelElement)) { // not in build path,
        // hence: hollow,
        // non-pakg icons
        if (modelElement.getElementType() == IModelElement.SOURCE_MODULE)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_CUNIT_RESOURCE);
        if (modelElement.getElementType() == IModelElement.PROJECT_FRAGMENT
            || modelElement.getElementType() == IModelElement.SCRIPT_FOLDER)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHP_FOLDER);
      } else { // in build path ...
        if (modelElement.getElementType() == IModelElement.SCRIPT_FOLDER
            || element instanceof IFolder)
          return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_PHPFOLDER_ROOT);
      }
    }
    try {
      if (element instanceof IType && PHPFlags.isTrait(((IType) element).getFlags())) {
        return PHPPluginImages.get(PHPPluginImages.IMG_OBJS_TRAIT);
      }
    } catch (ModelException e) {
    }

    if (element != null) {
      for (ILabelProvider provider :
          TreeContentProviderRegistry.getInstance().getLabelProviders()) {
        Image image = provider.getImage(element);

        if (image != null) {
          return image;
        }
      }
    }

    return super.getImage(element);
  }
コード例 #20
0
 /**
  * Returns the package fragment root corresponding to a given resource path.
  *
  * @param resourcePathString path of expected package fragment root.
  * @return the {@link IProjectFragment package fragment root} which path match the given one or
  *     <code>null</code> if none was found.
  */
 public IProjectFragment projectFragment(String resourcePathString) {
   int index = -1;
   int separatorIndex = resourcePathString.indexOf(FILE_ENTRY_SEPARATOR);
   boolean isZIPFile = separatorIndex != -1;
   boolean isSpecial = resourcePathString.startsWith(IBuildpathEntry.BUILDPATH_SPECIAL);
   if (isZIPFile) {
     // internal or external jar (case 3, 4, or 5)
     String zipPath = resourcePathString.substring(0, separatorIndex);
     String relativePath = resourcePathString.substring(separatorIndex + 1);
     index = indexOf(zipPath, relativePath);
   } else {
     // resource in workspace (case 1 or 2)
     index = indexOf(resourcePathString);
   }
   if (index >= 0) {
     int idx = projectIndexes[index];
     String projectPath = idx == -1 ? null : (String) this.projectPaths.get(idx);
     if (projectPath != null) {
       IScriptProject project =
           DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(projectPath));
       if (isZIPFile) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       if (isSpecial) {
         return project.getProjectFragment(this.containerPaths[index]);
       }
       Object target =
           Model.getTarget(
               ResourcesPlugin.getWorkspace().getRoot(),
               Path.fromPortableString(
                   this.containerPaths[index] + '/' + this.relativePaths[index]),
               false);
       if (target instanceof IProject) {
         return project.getProjectFragment((IProject) target);
       }
       if (target instanceof IResource) {
         IModelElement element = DLTKCore.create((IResource) target);
         return (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
       }
       if (target instanceof IFileHandle) {
         try {
           IProjectFragment[] fragments = project.getProjectFragments();
           IFileHandle t = (IFileHandle) target;
           IPath absPath = t.getFullPath();
           for (int i = 0; i < fragments.length; ++i) {
             IProjectFragment f = fragments[i];
             if (f.isExternal()) {
               IPath pPath = f.getPath();
               if (pPath.isPrefixOf(absPath) && !Util.isExcluded(absPath, f, t.isDirectory())) {
                 return f;
               }
             }
           }
         } catch (ModelException e) {
           e.printStackTrace();
           return null;
         }
       }
     }
   }
   return null;
 }
  /**
   * @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();
    }
  }