예제 #1
0
  /**
   * Performs the reconcile and returns the AST if it was computed.
   *
   * @param unit the compilation unit
   * @param initialReconcile <code>true</code> if this is the initial reconcile
   * @return the AST or <code>null</code> if none
   * @throws JavaModelException if the original Java element does not exist
   * @since 3.4
   */
  private Program reconcile(ISourceModule unit, boolean initialReconcile) throws ModelException {
    /* fix for missing cancel flag communication */
    IProblemRequestorExtension extension = getProblemRequestorExtension();
    if (extension != null) {
      extension.setProgressMonitor(fProgressMonitor);
      extension.setIsActive(true);
    }

    try {
      final ASTProvider astProvider = PHPUiPlugin.getDefault().getASTProvider();

      synchronized (unit) {
        unit.reconcile(true, null, fProgressMonitor);
      }

      // read DOM AST from provider if avaiable
      Program createdAST = astProvider.getAST(unit, SharedASTProvider.WAIT_NO, fProgressMonitor);
      if (astProvider.isActive(unit) && createdAST != null) {
        return createdAST;
      }

      if (initialReconcile || astProvider.isActive(unit)) {
        PHPVersion phpVersion = ProjectOptions.getPhpVersion(unit.getScriptProject().getProject());
        ASTParser newParser = ASTParser.newParser(phpVersion, unit);
        createdAST = newParser.createAST(null);
        if (createdAST != null && document != null) {
          createdAST.setSourceModule(unit);
          createdAST.setSourceRange(0, document.getLength());
          createdAST.setLineEndTable(Util.lineEndTable(document));
        }
        return createdAST;
      }

    } catch (OperationCanceledException ex) {
      Assert.isTrue(fProgressMonitor == null || fProgressMonitor.isCanceled());

    } catch (Exception e) {
      throw new ModelException(e, IStatus.ERROR);

    } finally {
      /* fix for missing cancel flag communication */
      if (extension != null) {
        extension.setProgressMonitor(null);
        extension.setIsActive(false);
      }
    }

    return null;
  }
예제 #2
0
  /**
   * @param path
   * @return true if the given path indicates a global variable
   */
  public static boolean globalVariableAlreadyExists(Program program, final String name) {
    assert program != null && name != null;

    final GlobalVariableSearcher checkGlobalVisitor = new GlobalVariableSearcher(name);
    program.accept(checkGlobalVisitor);

    return checkGlobalVisitor.globalVariableAlreadyExists();
  }
예제 #3
0
  /**
   * @param path
   * @return true if the given path indicates a global variable
   */
  public static boolean functionAlreadyExists(Program program, final String name) {
    assert program != null && name != null;

    final FunctionSearcher checkFunctionVisitor = new FunctionSearcher(name);
    program.accept(checkFunctionVisitor);

    return checkFunctionVisitor.functionAlreadyExists();
  }
예제 #4
0
  /**
   * @param program
   * @param name
   * @return true - if the program has a class name already
   */
  public static boolean classNameAlreadyExists(Program program, final String name) {
    assert program != null && name != null;

    final ClassSearcher checkClassVisitor = new ClassSearcher(name);
    program.accept(checkClassVisitor);

    return checkClassVisitor.classNameAlreadyExists();
  }
예제 #5
0
  /**
   * @param program
   * @param name
   * @return true - if the program has this constant already
   */
  public static boolean constantAlreadyExists(Program program, final String name) {
    assert program != null && name != null;

    final DefinedSearcher checkConstantVisitor = new DefinedSearcher(name);
    program.accept(checkConstantVisitor);

    return checkConstantVisitor.constantAlreadyExists();
  }
  @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;
  }
  private void generate(
      final List<GetterSetterEntry> entries, final int modifier, final boolean generateComments)
      throws Exception {

    ISourceModule source = type.getSourceModule();
    String name = type.getElementName().replace("$", "");
    StringBuffer buffer = new StringBuffer(name);
    buffer.replace(0, 1, Character.toString(Character.toUpperCase(name.charAt(0))));
    name = buffer.toString();

    ASTParser parser = ASTParser.newParser(source);
    parser.setSource(document.get().toCharArray());

    Program program = parser.createAST(new NullProgressMonitor());
    //		program.recordModifications();
    //		AST ast = program.getAST();

    ISourceRange range = type.getSourceRange();
    ASTNode node = program.getElementAt(range.getOffset());

    if (!(node instanceof ClassDeclaration)) {
      return;
    }

    char indentChar = FormatPreferencesSupport.getInstance().getIndentationChar(document);
    String indent = String.valueOf(indentChar);

    ClassDeclaration clazz = (ClassDeclaration) node;
    Block body = clazz.getBody();
    List<Statement> bodyStatements = body.statements();

    int end = bodyStatements.get(bodyStatements.size() - 1).getEnd();

    if (insertFirst) {
      end = bodyStatements.get(0).getStart() - 1;
    } else if (insertAfter != null) {

      boolean found = false;

      for (IMethod method : type.getMethods()) {
        if (method == insertAfter) {
          ISourceRange r = method.getSourceRange();
          end = r.getOffset() + r.getLength();
          found = true;
        }
      }

      if (!found) {
        for (IField field : type.getFields()) {
          ISourceRange r = field.getSourceRange();
          end = r.getOffset() + r.getLength() + 1;
        }
      }
    }

    lineDelim = TextUtilities.getDefaultLineDelimiter(document);
    String methods = "";

    int i = 0;
    for (GetterSetterEntry entry : entries) {

      String code = "";

      if (!entry.isGetter) {
        code =
            GetterSetterUtil.getSetterStub(
                entry.field,
                entry.getIdentifier(),
                entry.getType(),
                generateComments,
                modifier,
                indent);

      } else {
        code =
            GetterSetterUtil.getGetterStub(
                entry.field, entry.getIdentifier(), generateComments, modifier, indent);
      }

      code = lineDelim + code;
      String formatted = indentPattern(code, indent, lineDelim);

      if (i++ == 0) {
        formatted = lineDelim + formatted;
      }

      methods += formatted;
    }

    document.replace(end, 0, methods);

    Formatter formatter = new Formatter();
    Region region = new Region(end, methods.length());
    formatter.format(document, region);
  }
예제 #8
0
  /**
   * Creates the text changes for all the affected files. Updates all the include statements in the
   * current file and all the includes in the "including " files. In case of folders, creates the
   * changes recursively
   *
   * @param pm - progress monitor
   * @param rootChange - the root change that the new changes are added to
   * @param sourceResources
   * @return the root change after the additions
   * @throws CoreException
   */
  private Change createTextChanges(
      IProgressMonitor pm,
      CompositeChange rootChange,
      Set<IFile> phpFiles,
      IResource[] sourceResources)
      throws CoreException {
    List<ProgramFileChange> changes = new ArrayList<ProgramFileChange>();
    try {
      pm.beginTask(PhpRefactoringCoreMessages.getString("MoveDelegate.1"), 100); // $NON-NLS-1$

      // creat text changes:
      // for each file that will be moved, update its includes
      // and update all the files that include it,

      IResource[] uniqueSourceResources = removeDuplicateResources(sourceResources);

      for (Iterator<IFile> it = phpFiles.iterator(); it.hasNext(); ) {
        IFile currentMovedResource = it.next();

        Map<IFile, Program> participantFiles = collectReferencingFiles(currentMovedResource, pm);

        for (Entry<IFile, Program> entry : participantFiles.entrySet()) {
          final IFile file = entry.getKey();
          if (phpFiles.contains(file)) {
            continue;
          }
          final Program program = entry.getValue();

          final ChangeIncludePath rename =
              new ChangeIncludePath(
                  currentMovedResource, file, fMainDestinationPath, false, uniqueSourceResources);
          // aggregate the changes identifiers
          program.accept(rename);

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

          pm.worked(1);

          if (rename.hasChanges()) {
            ProgramFileChange change = new ProgramFileChange(file.getName(), file, program);
            change.setEdit(new MultiTextEdit());
            change.setTextType("php"); // $NON-NLS-1$

            changes.add(change);
            rename.updateChange(change);
          }
        }

        ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(currentMovedResource);

        if (sourceModule instanceof ISourceModule) {

          Program program = null;
          try {
            program = ASTUtils.createProgramFromSource(sourceModule);
          } catch (Exception e) {
          }

          if (program != null) {
            final ChangeIncludePath rename =
                new ChangeIncludePath(
                    currentMovedResource,
                    currentMovedResource,
                    fMainDestinationPath,
                    true,
                    uniqueSourceResources);

            // aggregate the changes identifiers
            program.accept(rename);

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

            pm.worked(1);

            if (rename.hasChanges()) {
              ProgramFileChange change =
                  new ProgramFileChange(
                      currentMovedResource.getName(), currentMovedResource, program);
              change.setEdit(new MultiTextEdit());
              change.setTextType("php"); // $NON-NLS-1$

              changes.add(change);
              rename.updateChange(change);
            }
          }
        }
      }
      pm.worked(70);

    } finally {
      pm.done();
    } // getChildren()

    Map<IFile, List<TextEdit>> changeMap = new HashMap<IFile, List<TextEdit>>();
    Map<IFile, ProgramFileChange> fileMap = new HashMap<IFile, ProgramFileChange>();
    for (ProgramFileChange programFileChange : changes) {
      List<TextEdit> list = changeMap.get(programFileChange.getFile());
      if (list == null) {
        list = new ArrayList<TextEdit>();
        changeMap.put(programFileChange.getFile(), list);
        fileMap.put(programFileChange.getFile(), programFileChange);
      } else {

      }
      list.addAll(Arrays.asList(programFileChange.getEdit().getChildren()));
    }
    for (IFile file : changeMap.keySet()) {
      ProgramFileChange change =
          new ProgramFileChange(file.getName(), file, fileMap.get(file).getProgram());
      change.setEdit(new MultiTextEdit());
      change.setTextType("php"); // $NON-NLS-1$

      List<TextEdit> list = changeMap.get(file);
      Collections.sort(
          list,
          new Comparator<TextEdit>() {
            public int compare(TextEdit o1, TextEdit o2) {
              return o2.getOffset() - o1.getOffset();
            }
          });

      for (TextEdit textEdit : list) {
        if (textEdit instanceof ReplaceEdit) {
          ReplaceEdit replaceEdit = (ReplaceEdit) textEdit;
          change.addEdit(
              new ReplaceEdit(
                  replaceEdit.getOffset(), replaceEdit.getLength(), replaceEdit.getText()));
        }
      }
      rootChange.add(change);
    }
    return rootChange;
  }