Esempio n. 1
0
 private String formatLogicalPackageMessage(LogicalPackage logicalPackage) {
   IScriptFolder[] fragments = logicalPackage.getScriptFolders();
   StringBuffer buf = new StringBuffer(logicalPackage.getElementName());
   buf.append(ScriptElementLabels.CONCAT_STRING);
   String message = ""; // $NON-NLS-1$
   boolean firstTime = true;
   for (int i = 0; i < fragments.length; i++) {
     IScriptFolder fragment = fragments[i];
     IModelElement element = fragment.getParent();
     if (element instanceof IProjectFragment) {
       IProjectFragment root = (IProjectFragment) element;
       String label =
           ScriptElementLabels.getDefault()
               .getElementLabel(
                   root,
                   ScriptElementLabels.DEFAULT_QUALIFIED | ScriptElementLabels.ROOT_QUALIFIED);
       if (firstTime) {
         buf.append(label);
         firstTime = false;
       } else
         message =
             Messages.format(
                 ScriptBrowsingMessages.StatusBar_concat, new String[] {message, label});
     }
   }
   buf.append(message);
   return buf.toString();
 }
  private IHyperlink getTemplateLink(ViewPath viewPath, IRegion wordRegion) {

    IScriptFolder folder =
        SymfonyModelAccess.getDefault()
            .findBundleFolder(viewPath.getBundle(), input.getScriptProject());

    if (folder == null) {
      Logger.debugMSG("Unable to resolve template link: " + viewPath);
      return null;
    }

    String path = "Resources/views/";

    if (viewPath.getController() != null) {
      path += viewPath.getController() + "/";
    }

    path += viewPath.getTemplate();
    ISourceModule module = folder.getSourceModule(path);

    if (module != null) {
      return new ModelElementHyperlink(wordRegion, module, new OpenAction(editor));
    }

    return null;
  }
 public Object getHierarchicalPackageParent(final IScriptFolder child) {
   String name = child.getElementName();
   IProjectFragment parent = (IProjectFragment) child.getParent();
   int index = name.lastIndexOf(IScriptFolder.PACKAGE_DELIMITER);
   if (index != -1) {
     String realParentName = name.substring(0, index);
     IScriptFolder element = parent.getScriptFolder(realParentName);
     if (element != null && element.exists()) {
       try {
         if (fFoldPackages
             && ScriptExplorerContentProvider.isEmpty(element)
             && ScriptExplorerContentProvider.findSinglePackageChild(element, parent.getChildren())
                 != null) {
           return getHierarchicalPackageParent(element);
         }
       } catch (ModelException e) {
         // ignore
       }
       return element;
     } else if (element != null) { // bug 65240
       IResource resource = element.getResource();
       if (resource != null) {
         return resource;
       }
     }
   }
   if (parent.getResource() instanceof IProject) {
     return parent.getScriptProject();
   }
   return parent;
 }
 private String getNameDelta(IScriptFolder parent, IScriptFolder fragment) {
   String prefix = parent.getElementName() + IScriptFolder.PACKAGE_DELIMITER;
   String fullName = fragment.getElementName();
   if (fullName.startsWith(prefix)) {
     return fullName.substring(prefix.length());
   }
   return fullName;
 }
 private String getNameDelta(IFolder parent, IScriptFolder fragment) {
   IPath prefix = parent.getFullPath();
   IPath fullPath = fragment.getPath();
   if (prefix.isPrefixOf(fullPath)) {
     StringBuffer buf = new StringBuffer();
     for (int i = prefix.segmentCount(); i < fullPath.segmentCount(); i++) {
       if (buf.length() > 0) buf.append(IScriptFolder.PACKAGE_DELIMITER);
       buf.append(fullPath.segment(i));
     }
     return buf.toString();
   }
   return fragment.getElementName();
 }
  private static boolean hasReadOnlyResourcesAndSubResources(IModelElement modelElement)
      throws CoreException {
    switch (modelElement.getElementType()) {
      case IModelElement.SOURCE_MODULE:
        IResource resource = ReorgUtils.getResource(modelElement);
        return (resource != null && Resources.isReadOnly(resource));
      case IModelElement.SCRIPT_FOLDER:
        IResource packResource = ReorgUtils.getResource(modelElement);
        if (packResource == null) return false;
        IScriptFolder pack = (IScriptFolder) modelElement;
        if (Resources.isReadOnly(packResource)) return true;
        Object[] nonScript = pack.getForeignResources();
        for (int i = 0; i < nonScript.length; i++) {
          Object object = nonScript[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(pack.getChildren());
      case IModelElement.PROJECT_FRAGMENT:
        IProjectFragment root = (IProjectFragment) modelElement;
        if (root.isArchive()) return false;
        IResource pfrResource = ReorgUtils.getResource(modelElement);
        if (pfrResource == null) return false;
        if (Resources.isReadOnly(pfrResource)) return true;
        Object[] nonScript1 = root.getForeignResources();
        for (int i = 0; i < nonScript1.length; i++) {
          Object object = nonScript1[i];
          if (object instanceof IResource
              && hasReadOnlyResourcesAndSubResources((IResource) object)) return true;
        }
        return hasReadOnlyResourcesAndSubResources(root.getChildren());

      case IModelElement.FIELD:
        //			case IModelElement.IMPORT_CONTAINER:
        //			case IModelElement.IMPORT_DECLARATION:
        //			case IModelElement.INITIALIZER:
      case IModelElement.METHOD:
        //			case IModelElement.PACKAGE_DECLARATION:
      case IModelElement.TYPE:
        return false;
      default:
        Assert.isTrue(false); // not handled here
        return false;
    }
  }
  /** Adds all of the openables defined within this package fragment to the list. */
  private void injectAllOpenablesForPackageFragment(IScriptFolder packFrag, ArrayList openables) {

    try {
      IProjectFragment root = (IProjectFragment) packFrag.getParent();
      int kind = root.getKind();
      if (kind != 0) {
        boolean isSourcePackageFragment = (kind == IProjectFragment.K_SOURCE);
        if (isSourcePackageFragment) {
          ISourceModule[] cus = packFrag.getSourceModules();
          for (int i = 0; i < cus.length; i++) {
            openables.add(cus[i]);
          }
        }
      }
    } catch (ModelException e) {
      // ignore
    }
  }
 /**
  * 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);
       }
     }
   }
 }
  @Override
  public String resolve(IScriptFolder container) {

    if (container == null) {
      Logger.log(Logger.WARNING, "Unable to resolve namespace, no container available");
      return null;
    }

    // Try composer first - Symfony 2.1
    try {
      IPath path = ModelAccess.getInstance().resolve(container.getResource());
      if (path != null) {
        return path.toString().replace("/", "\\");
      }
    } catch (Exception e) {
      Logger.logException(e);
    }

    // fallback to Symfony 2.0
    return SymfonyModelAccess.getDefault()
        .findNameSpace(container.getScriptProject(), container.getPath());
  }
  /**
   * Returns the hierarchical packages inside a given fragment or root.
   *
   * @param parent The parent package fragment root
   * @param fragment The package to get the children for or 'null' to get the children of the root.
   * @param result Collection where the resulting elements are added
   * @throws JavaModelException
   */
  private void getHierarchicalPackageChildren(
      final IProjectFragment parent, final IScriptFolder fragment, final Collection<Object> result)
      throws ModelException {
    IModelElement[] children = parent.getChildren();

    if (fragment == null || fragment.isRootFolder()) {
      List<IModelElement> newElements = new ArrayList<IModelElement>();
      for (int i = 0; i < children.length; ++i) {
        if (children[i] instanceof IScriptFolder) {
          IScriptFolder scriptFolder = (IScriptFolder) children[i];
          if (scriptFolder.isRootFolder()) {
            IModelElement[] members = scriptFolder.getChildren();
            for (int j = 0; j < members.length; ++j) {
              newElements.add(members[j]);
            }
            continue;
          }
        }
        newElements.add(children[i]);
      }
      children = newElements.toArray(new IModelElement[newElements.size()]);
    }

    String prefix =
        fragment != null
            ? fragment.getElementName() + IScriptFolder.PACKAGE_DELIMETER_STR
            : ""; //$NON-NLS-1$
    int prefixLen = prefix.length();
    for (int i = 0; i < children.length; i++) {
      if (children[i] instanceof IScriptFolder) {
        IScriptFolder curr = (IScriptFolder) children[i];
        String name = curr.getElementName();
        if (name.startsWith(prefix)
            && name.length() > prefixLen
            && name.indexOf(IScriptFolder.PACKAGE_DELIMITER, prefixLen) == -1) {
          if (fFoldPackages) {
            curr = ScriptExplorerContentProvider.getFolded(children, curr);
          }
          result.add(curr);
        } /*
           * else if (fragment == null && curr.isRootFolder()) {
           * result.add(curr); }
           */
      } else {
        result.add(children[i]);
      }
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.jdt.ui.StandardJavaElementContentProvider#getPackageContent
   * (org.eclipse.jdt.core.IPackageFragment)
   */
  protected Object[] getScriptFolderContent(final IScriptFolder fragment) throws ModelException {
    if (fIsFlatLayout) {
      return super.getScriptFolderContent(fragment);
    }

    // hierarchical package mode
    ArrayList<Object> result = new ArrayList<Object>();

    getHierarchicalPackageChildren((IProjectFragment) fragment.getParent(), fragment, result);
    Object[] nonPackages = super.getScriptFolderContent(fragment);
    if (result.isEmpty()) {
      return nonPackages;
    }
    for (int i = 0; i < nonPackages.length; i++) {
      result.add(nonPackages[i]);
    }
    return result.toArray();
  }
 private static IScriptFolder findSinglePackageChild(
     final IScriptFolder fragment, final IModelElement[] children) {
   String prefix = fragment.getElementName() + IScriptFolder.PACKAGE_DELIMITER;
   int prefixLen = prefix.length();
   IScriptFolder found = null;
   for (int i = 0; i < children.length; i++) {
     IModelElement element = children[i];
     String name = element.getElementName();
     if (name.startsWith(prefix)
         && name.length() > prefixLen
         && name.indexOf(IScriptFolder.PACKAGE_DELIMITER, prefixLen) == -1) {
       if (found == null) {
         found = (IScriptFolder) element;
       } else {
         return null;
       }
     }
   }
   return found;
 }
  @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 static boolean isEmpty(final IScriptFolder fragment) throws ModelException {
   return !fragment.containsScriptResources() && fragment.getForeignResources().length == 0;
 }