private IProject getProject() {
   IScriptProject scriptProject = getScriptProject();
   if (scriptProject != null) {
     return scriptProject.getProject();
   }
   return null;
 }
 private boolean isOnClassPath(final ISourceModule element) {
   IScriptProject project = element.getScriptProject();
   if (project == null || !project.exists()) {
     return false;
   }
   return project.isOnBuildpath(element);
 }
 /** @since 2.0 */
 @Override
 public void delete(boolean force, IProgressMonitor monitor) {
   // Remove correction for this module from all places.
   final IScriptProject scriptProject = getScriptProject();
   final IEnvironment environment = EnvironmentManager.getEnvironment(scriptProject);
   TclProjectInfo project = TclPackagesManager.getTclProject(scriptProject.getElementName());
   EList<TclModuleInfo> modules = project.getModules();
   String path = environment.convertPathToString(getFullPath()).toString();
   for (TclModuleInfo tclModuleInfo : modules) {
     EList<UserCorrection> corrections = tclModuleInfo.getSourceCorrections();
     EList<TclSourceEntry> sourced = tclModuleInfo.getSourced();
     EList<UserCorrection> sourceCorrections = tclModuleInfo.getSourceCorrections();
     for (TclSourceEntry tclSourceEntry : sourced) {
       String value = tclSourceEntry.getValue();
       if (value.contains("$") && value.equals(getOriginalName())) {
         for (UserCorrection userCorrection : sourceCorrections) {
           if (userCorrection.getOriginalValue().equals(value)) {
             userCorrection.getUserValue().remove(path);
           }
         }
       }
     }
   }
   TclPackagesManager.save();
   // Do delta refresh
   try {
     ModelManager.getModelManager()
         .getDeltaProcessor()
         .checkExternalChanges(
             new IModelElement[] {getScriptProject()}, new NullProgressMonitor());
   } catch (ModelException e) {
     DLTKCore.error("Failed to call for model update:", e);
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.jdt.ui.StandardJavaElementContentProvider#getPackageFragmentRoots
   * (org.eclipse.jdt.core.IJavaProject)
   */
  protected Object[] getProjectFragments(final IScriptProject project) throws ModelException {
    if (!project.getProject().isOpen()) {
      return StandardModelElementContentProvider.NO_CHILDREN;
    }

    List<Object> result = new ArrayList<Object>();

    boolean addZIPContainer = false;

    IProjectFragment[] roots = project.getProjectFragments();
    for (int i = 0; i < roots.length; i++) {
      IProjectFragment root = roots[i];
      IBuildpathEntry classpathEntry = root.getRawBuildpathEntry();
      if (classpathEntry == null) {
        continue;
      }
      int entryKind = classpathEntry.getEntryKind();
      if (entryKind == IBuildpathEntry.BPE_CONTAINER) {
        // all ClassPathContainers are added later
      } else if (fShowLibrariesNode && (entryKind == IBuildpathEntry.BPE_LIBRARY /*
																 * || entryKind
																 * ==
																 * IBuildpathEntry
																 * .BPE_VARIABLE
																 */)) {
        addZIPContainer = true;
      } else {
        if (isProjectProjectFragment(root)) {
          // filter out package fragments that correspond to projects
          // and
          // replace them with the package fragments directly
          Object[] fragments = getProjectFragmentContent(root);
          for (int j = 0; j < fragments.length; j++) {
            result.add(fragments[j]);
          }
        } else {
          result.add(root);
        }
      }
    }

    if (addZIPContainer) {
      result.add(new LibraryContainer(project));
    }

    // separate loop to make sure all containers are on the classpath
    IBuildpathEntry[] rawBuidspath = project.getRawBuildpath();
    for (int i = 0; i < rawBuidspath.length; i++) {
      IBuildpathEntry classpathEntry = rawBuidspath[i];
      if (classpathEntry.getEntryKind() == IBuildpathEntry.BPE_CONTAINER) {
        result.add(new BuildPathContainer(project, classpathEntry));
      }
    }
    Object[] resources = project.getForeignResources();
    for (int i = 0; i < resources.length; i++) {
      result.add(resources[i]);
    }
    return result.toArray();
  }
Example #5
0
  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);
      }
    }
  }
 public boolean isModelChangesProvidedFor(IModelElement modelElement, String name) {
   IScriptProject project = modelElement.getScriptProject();
   if (!"ModelMembersq".equals(project.getElementName())) {
     return false;
   }
   if (modelElement.getElementType() == IModelElement.PROJECT_FRAGMENT) {
     return true;
   }
   return false;
 }
Example #7
0
 /**
  * Answers if the given <code>element</code> is a valid input for this part.
  *
  * @param element the object to test
  * @return <true> if the given element is a valid input
  */
 protected boolean isValidInput(Object element) {
   if (element instanceof IScriptProject
       || (element instanceof IProjectFragment
           && ((IModelElement) element).getElementName()
               != IProjectFragment.DEFAULT_PACKAGE_ROOT)) {
     IScriptProject jProject = ((IModelElement) element).getScriptProject();
     if (jProject != null) return DLTKLanguageManager.hasScriptNature(jProject.getProject());
   }
   return false;
 }
  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();
    }
  }
Example #9
0
    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);
        }
      }
    }
 public void provideModelChanges(IModelElement parentElement, List children) {
   IScriptProject project = parentElement.getScriptProject();
   if (!"ModelMembersq".equals(project.getElementName())) {
     return;
   }
   switch (parentElement.getElementType()) {
     case IModelElement.PROJECT_FRAGMENT:
       List addon = new ArrayList();
       for (Iterator iterator = children.iterator(); iterator.hasNext(); ) {
         IModelElement el = (IModelElement) iterator.next();
         if (el.getElementType() == IModelElement.SCRIPT_FOLDER) {
           addon.add(
               new TestFolder(
                   (ModelElement) parentElement,
                   el.getPath().removeFirstSegments(el.getParent().getPath().segmentCount())));
         }
       }
       children.addAll(addon);
       break;
     case IModelElement.SCRIPT_FOLDER:
       break;
   }
 }
  /**
   * Modifies PHP project buildpath so it will contain path to the language model library
   *
   * @param project Project handle
   * @throws ModelException
   */
  public static void enableLanguageModelFor(IScriptProject project) throws ModelException {
    if (!isPHPProject(project)) {
      return;
    }

    boolean found = false;
    final IBuildpathEntry[] rawBuildpath = project.getRawBuildpath();
    for (final IBuildpathEntry entry : rawBuildpath) {
      if (entry.isContainerEntry() && entry.getPath().equals(LANGUAGE_CONTAINER_PATH)) {
        found = true;
        break;
      }
    }

    if (!found) {
      final IBuildpathEntry containerEntry = DLTKCore.newContainerEntry(LANGUAGE_CONTAINER_PATH);
      final int newSize = rawBuildpath.length + 1;
      final List<IBuildpathEntry> newRawBuildpath = new ArrayList<IBuildpathEntry>(newSize);
      newRawBuildpath.addAll(Arrays.asList(rawBuildpath));
      newRawBuildpath.add(containerEntry);
      project.setRawBuildpath(newRawBuildpath.toArray(new IBuildpathEntry[newSize]), null);
    }
  }
Example #12
0
  /*
   * 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 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);
  }
  @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;
  }
  /**
   * 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;
  }
  /**
   * Processes a delta recursively. When more than two children are affected the tree is fully
   * refreshed starting at this node.
   *
   * @param delta the delta to process
   * @param runnables the resulting view changes as runnables (type {@link Runnable} )
   * @return true is returned if the conclusion is to refresh a parent of an element. In that case
   *     no siblings need to be processed
   * @throws JavaModelException thrown when the access to an element failed
   */
  private boolean processDelta(final IModelElementDelta delta, final Collection<Runnable> runnables)
      throws ModelException {

    int kind = delta.getKind();
    int flags = delta.getFlags();
    IModelElement element = delta.getElement();
    int elementType = element.getElementType();

    if (elementType != IModelElement.SCRIPT_MODEL && elementType != IModelElement.SCRIPT_PROJECT) {
      IScriptProject proj = element.getScriptProject();
      if (proj == null || !proj.getProject().isOpen()) {
        // TODO: Not needed if parent already did the 'open' check!
        return false;
      }
    }

    if (elementType == IModelElement.SCRIPT_FOLDER) {
      if ((flags & (IModelElementDelta.F_CONTENT | IModelElementDelta.F_CHILDREN))
          == IModelElementDelta.F_CONTENT) {
        if (!fIsFlatLayout) {
          Object parent = getHierarchicalPackageParent((IScriptFolder) element);
          if (!(parent instanceof IProjectFragment)) {
            postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
            return true;
          }
        }
        // content change, without children info (for example resource
        // added/removed to class folder package)
        postRefresh(internalGetParent(element), PARENT, element, runnables);
        return true;
      }

      if (!fIsFlatLayout) {
        if (kind == IModelElementDelta.REMOVED) {
          final Object parent = getHierarchicalPackageParent((IScriptFolder) element);
          if (parent instanceof IProjectFragment) {
            postRemove(element, runnables);
            return false;
          } else {
            postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
            return true;
          }
        } else if (kind == IModelElementDelta.ADDED) {
          final Object parent = getHierarchicalPackageParent((IScriptFolder) element);
          if (parent instanceof IProjectFragment) {
            if (fFoldPackages) {
              postRefresh(parent, PARENT, element, runnables);
              return true;
            } else {
              postAdd(parent, element, runnables);
              return false;
            }
          } else {
            postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
            return true;
          }
        }
        handleAffectedChildren(delta, element, runnables);
        return false;
      }
    }

    if (elementType == IModelElement.SOURCE_MODULE) {
      ISourceModule cu = (ISourceModule) element;
      if (!ScriptModelUtil.isPrimary(cu)) {
        return false;
      }

      if (!getProvideMembers() && cu.isWorkingCopy() && kind == IModelElementDelta.CHANGED) {
        return false;
      }

      if (kind == IModelElementDelta.CHANGED && !isStructuralCUChange(flags)) {
        return false; // test moved ahead
      }

      if (!isOnClassPath(cu)) { // TODO: isOnClassPath expensive! Should
        // be put after all cheap tests
        return false;
      }
    }

    if (elementType == IModelElement.SCRIPT_PROJECT) {
      // handle open and closing of a project
      if ((flags & (IModelElementDelta.F_CLOSED | IModelElementDelta.F_OPENED)) != 0) {
        postRefresh(element, ORIGINAL, element, runnables);
        return false;
      }
      // if the class path has changed we refresh the entire project
      if ((flags & IModelElementDelta.F_BUILDPATH_CHANGED) != 0) {
        postRefresh(element, ORIGINAL, element, runnables);
        return false;
      }
      // if added it could be that the corresponding IProject is already
      // shown. Remove it first.
      // bug 184296
      if (kind == IModelElementDelta.ADDED) {
        postRemove(element.getResource(), runnables);
        postAdd(element.getParent(), element, runnables);
        return false;
      }
    }

    if (kind == IModelElementDelta.REMOVED) {
      Object parent = internalGetParent(element);
      if (element instanceof IScriptFolder) {
        // refresh package fragment root to allow filtering empty
        // (parent) packages: bug 72923
        if (fViewer.testFindItem(parent) != null) {
          postRefresh(parent, PARENT, element, runnables);
        }
        return true;

      } else if (element instanceof IProjectFragment
          && ((IProjectFragment) element).getKind() != IProjectFragment.K_SOURCE) {
        // libs and class folders can show up twice (in library
        // container and as resource at original location)
        IResource resource = element.getResource();
        if (resource != null) postRemove(resource, runnables);
      }

      postRemove(element, runnables);
      if (parent instanceof IScriptFolder) {
        postUpdateIcon((IScriptFolder) parent, runnables);
      }
      // we are filtering out empty subpackages, so we
      // a package becomes empty we remove it from the viewer.
      if (isScriptFolderEmpty(element.getParent())) {
        if (fViewer.testFindItem(parent) != null) {
          postRefresh(internalGetParent(parent), GRANT_PARENT, element, runnables);
        }
        return true;
      }
      return false;
    }

    if (kind == IModelElementDelta.ADDED) {
      Object parent = internalGetParent(element);
      // we are filtering out empty subpackages, so we
      // have to handle additions to them specially.
      if (parent instanceof IScriptFolder) {
        Object grandparent = internalGetParent(parent);
        // 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
        // avoid posting a refresh to an invisible parent
        if (parent.equals(fInput)) {
          postRefresh(parent, PARENT, element, runnables);
        } else {
          // refresh from grandparent if parent isn't visible yet
          if (fViewer.testFindItem(parent) == null) {
            postRefresh(grandparent, GRANT_PARENT, element, runnables);
          } else {
            postRefresh(parent, PARENT, element, runnables);
          }
        }
        return true;
      } else {
        postAdd(parent, element, runnables);
      }
    }

    if (elementType == IModelElement.SOURCE_MODULE || elementType == IModelElement.BINARY_MODULE) {
      if (kind == IModelElementDelta.CHANGED) {
        // isStructuralCUChange already performed above
        postRefresh(element, ORIGINAL, element, runnables);
      }
      return false;
    }

    if (elementType == IModelElement.PROJECT_FRAGMENT) {
      // the contents of an external JAR or class folder has changed
      if ((flags & IModelElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) {
        postRefresh(element, ORIGINAL, element, runnables);
        return false;
      }
      if ((flags & (IModelElementDelta.F_CONTENT | IModelElementDelta.F_CHILDREN))
          == IModelElementDelta.F_CONTENT) {
        // content change, without children info (for example resource
        // added/removed to class folder package)
        postRefresh(internalGetParent(element), PARENT, element, runnables);
        return true;
      }
      // the source attachment of a JAR has changed
      // if ((flags & ( | IModelElementDelta.F_SOURCEDETACHED)) != 0) {
      // postUpdateIcon(element, runnables);
      // }

      if (isBuildPathChange(delta)) {
        // throw the towel and do a full refresh of the affected java
        // project.
        postRefresh(element.getScriptProject(), PROJECT, element, runnables);
        return true;
      }
    }

    handleAffectedChildren(delta, element, runnables);
    return false;
  }
Example #17
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;
 }
  public TestRunSession(ILaunch launch, IScriptProject project, ITestRunnerClient runnerClient) {
    Assert.isNotNull(launch);
    Assert.isNotNull(runnerClient);

    fLaunch = launch;
    fProject = project;

    ILaunchConfiguration launchConfiguration = launch.getLaunchConfiguration();
    if (launchConfiguration != null) {
      fTestRunName = launchConfiguration.getName();
      fTestingEngine = DLTKTestingConstants.getTestingEngine(launchConfiguration);
      testRunnerUI = fTestingEngine.getTestRunnerUI(project, launchConfiguration);
      categoryEngines = TestCategoryEngineManager.getCategoryEngines(testRunnerUI);
    } else {
      fTestRunName = project.getElementName();
      fTestingEngine = NullTestingEngine.getInstance();
      testRunnerUI = NullTestRunnerUI.getInstance();
      categoryEngines = null;
    }

    fTestRoot = new TestRoot(this);
    fIdToTest = new HashMap<String, TestElement>();
    fCategoryMap = new HashMap<String, TestCategoryElement>();

    fTestRunnerClient = runnerClient;
    fTestRunnerClient.startListening(new TestSessionNotifier());

    final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
    launchManager.addLaunchListener(
        new ILaunchesListener2() {
          public void launchesTerminated(ILaunch[] launches) {
            if (Arrays.asList(launches).contains(fLaunch)) {
              if (fTestRunnerClient != null) {
                fTestRunnerClient.stopWaiting();
              }
              launchManager.removeLaunchListener(this);
              scheduleTestRunTerminated();
            }
          }

          public void launchesRemoved(ILaunch[] launches) {
            if (Arrays.asList(launches).contains(fLaunch)) {
              if (fTestRunnerClient != null) {
                fTestRunnerClient.stopWaiting();
              }
              launchManager.removeLaunchListener(this);
              scheduleTestRunTerminated();
            }
          }

          public void launchesChanged(ILaunch[] launches) {}

          public void launchesAdded(ILaunch[] launches) {}

          private void scheduleTestRunTerminated() {
            if (!fIsRunning) return;
            final Job job = new Job("TestRunSession - notify launch terminated") { // $NON-NLS-1$
                  @Override
                  protected IStatus run(IProgressMonitor monitor) {
                    testRunTerminated();
                    return org.eclipse.core.runtime.Status.OK_STATUS;
                  }
                };
            job.setSystem(true);
            // small delay, giving a chance for the client to notify in a
            // normal way.
            job.schedule(750);
          }
        });

    fSessionListeners = new ListenerList();
    addTestSessionListener(new TestRunListenerAdapter(this));
  }