private ISelection restoreSelectionState(IMemento memento) { if (memento == null) return null; IMemento childMem; childMem = memento.getChild(TAG_SELECTED_ELEMENTS); if (childMem != null) { ArrayList list = new ArrayList(); IMemento[] elementMem = childMem.getChildren(TAG_SELECTED_ELEMENT); for (int i = 0; i < elementMem.length; i++) { String javaElementHandle = elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH); if (javaElementHandle == null) { // logical package IMemento[] packagesMem = elementMem[i].getChildren(TAG_LOGICAL_PACKAGE); LogicalPackage lp = null; for (int j = 0; j < packagesMem.length; j++) { javaElementHandle = packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH); Object pack = DLTKCore.create(javaElementHandle); if (pack instanceof IScriptFolder && ((IScriptFolder) pack).exists()) { if (lp == null) lp = new LogicalPackage((IScriptFolder) pack); else lp.add((IScriptFolder) pack); } } if (lp != null) list.add(lp); } else { IModelElement element = DLTKCore.create(javaElementHandle); if (element != null && element.exists()) list.add(element); } } return new StructuredSelection(list); } return null; }
/* * (non-Javadoc) Method declared on IContentProvider. */ public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { super.inputChanged(viewer, oldInput, newInput); fViewer = (TreeViewer) viewer; if (oldInput == null && newInput != null) { DLTKCore.addElementChangedListener(this); } else if (oldInput != null && newInput == null) { DLTKCore.removeElementChangedListener(this); } fInput = newInput; }
/** * @param element * @param iBuildpathEntry * @return the name of the container description */ private String getEntryDescription(Object element, IBuildpathEntry iBuildpathEntry) { IProject project = ((IncludePath) element).getProject(); IScriptProject scriptProject = DLTKCore.create(project); IBuildpathContainer buildpathContainer = null; try { buildpathContainer = DLTKCore.getBuildpathContainer(iBuildpathEntry.getPath(), scriptProject); } catch (ModelException e) { // no matching container - return the path } if (buildpathContainer != null) { return buildpathContainer.getDescription(); } return iBuildpathEntry.getPath().toOSString(); }
public IRuntimeBuildpathEntry[] getRuntimeBuildpathEntries(ILaunchConfiguration configuration) throws CoreException { IBuildpathEntry entry = DLTKCore.newProjectEntry(getScriptProject().getProject().getFullPath()); List buildpathEntries = new ArrayList(5); List expanding = new ArrayList(5); expandProject(entry, buildpathEntries, expanding); IRuntimeBuildpathEntry[] runtimeEntries = new IRuntimeBuildpathEntry[buildpathEntries.size()]; for (int i = 0; i < runtimeEntries.length; i++) { Object e = buildpathEntries.get(i); if (e instanceof IBuildpathEntry) { IBuildpathEntry cpe = (IBuildpathEntry) e; runtimeEntries[i] = new RuntimeBuildpathEntry(cpe); } else { runtimeEntries[i] = (IRuntimeBuildpathEntry) e; } } // remove bootpath entries - this is a default user buildpath List ordered = new ArrayList(runtimeEntries.length); for (int i = 0; i < runtimeEntries.length; i++) { if (runtimeEntries[i].getBuildpathProperty() == IRuntimeBuildpathEntry.USER_ENTRY) { ordered.add(runtimeEntries[i]); } } return (IRuntimeBuildpathEntry[]) ordered.toArray(new IRuntimeBuildpathEntry[ordered.size()]); }
/** * @param scriptFile * @param position */ private FunctionStatement getFunctionStatement(final IFile scriptFile, final int position) { Script script = JavaScriptParserUtil.parse(DLTKCore.createSourceModuleFrom(scriptFile)); final ASTNode[] closestValue = new ASTNode[1]; ASTVisitor finder = new ASTVisitor() { @Override public boolean visitGeneral(ASTNode node) throws Exception { if (node.sourceStart() > position) return false; if (node.sourceEnd() >= position) { closestValue[0] = node; } return true; }; }; try { script.traverse(finder); } catch (Exception e) { e.printStackTrace(); } ASTNode node = closestValue[0]; while (node instanceof JSNode) { if (node instanceof FunctionStatement) { return (FunctionStatement) node; } node = ((JSNode) node).getParent(); } return null; }
/* * Refreshes the external folders referenced on the buildpath of the given * source project */ public void refreshReferences(IProject source, IProgressMonitor monitor) { IProject externalProject = getExternalFoldersProject(); if (source.equals(externalProject)) return; if (!ScriptProject.hasScriptNature(source)) return; try { HashSet externalFolders = getExternalFolders(((ScriptProject) DLTKCore.create(source)).getResolvedBuildpath()); if (externalFolders == null) return; final Iterator iterator = externalFolders.iterator(); Job refreshJob = new Job(Messages.refreshing_external_folders) { public boolean belongsTo(Object family) { return family == ResourcesPlugin.FAMILY_MANUAL_REFRESH; } protected IStatus run(IProgressMonitor pm) { try { while (iterator.hasNext()) { IPath externalPath = (IPath) iterator.next(); IFolder folder = getFolder(externalPath); if (folder != null) folder.refreshLocal(IResource.DEPTH_INFINITE, pm); } } catch (CoreException e) { return e.getStatus(); } return Status.OK_STATUS; } }; refreshJob.schedule(); } catch (CoreException e) { Util.log(e, "Exception while refreshing external project"); // $NON-NLS-1$ } return; }
/** * @param matchList a List of SearchMatch * @param status the status to report errors. * @return a SearchResultGroup[], grouped by SearchMatch#getResource() */ public static SearchResultGroup[] groupByCu( List<SearchMatch> matchList, RefactoringStatus status) { Map<IResource, List<SearchMatch>> grouped = new HashMap<IResource, List<SearchMatch>>(); boolean hasPotentialMatches = false; boolean hasNonCuMatches = false; for (SearchMatch searchMatch : matchList) { if (searchMatch.getAccuracy() == SearchMatch.A_INACCURATE) hasPotentialMatches = true; if (!grouped.containsKey(searchMatch.getResource())) grouped.put(searchMatch.getResource(), new ArrayList<SearchMatch>(1)); grouped.get(searchMatch.getResource()).add(searchMatch); } for (Iterator<IResource> iter = grouped.keySet().iterator(); iter.hasNext(); ) { IResource resource = iter.next(); IModelElement element = DLTKCore.create(resource); if (!(element instanceof ISourceModule)) { iter.remove(); hasNonCuMatches = true; } } SearchResultGroup[] result = new SearchResultGroup[grouped.keySet().size()]; int i = 0; for (IResource resource : grouped.keySet()) { List<SearchMatch> searchMatches = grouped.get(resource); SearchMatch[] matchArray = searchMatches.toArray(new SearchMatch[searchMatches.size()]); result[i] = new SearchResultGroup(resource, matchArray); i++; } addStatusErrors(status, hasPotentialMatches, hasNonCuMatches); return result; }
/** @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); } }
private void importFile(File file, IProject project, List<IBuildpathEntry> entries) { try { level++; // handle windows path separators String path = file.getAbsolutePath().replace("\\", "/").replace(symfonyPath, ""); // import the directory if (file.isDirectory() && !file.isHidden()) { IFolder folder = project.getFolder(path); if (!folder.exists()) { folder.create(true, true, null); } // add root folders to buildpath if (level == 1 && !folder.getFullPath().toString().endsWith("bin")) { IPath[] exclusion = {}; if (folder.getName().equals(SymfonyCoreConstants.APP_PATH)) { exclusion = new IPath[] { new Path(SymfonyCoreConstants.CACHE_PATH), new Path(SymfonyCoreConstants.LOG_PATH) }; } else if (folder.getName().equals(SymfonyCoreConstants.VENDOR_PATH)) { exclusion = new IPath[] {new Path(SymfonyCoreConstants.SKELETON_PATH)}; } IBuildpathEntry entry = DLTKCore.newSourceEntry(folder.getFullPath(), exclusion); entries.add(entry); } // now import recursively for (File f : file.listFiles()) { importFile(f, project, entries); } // create the project file } else if (file.isFile() && ".gitkeep".equals(file.getName()) == false) { FileInputStream fis = new FileInputStream(file); IFile iFile = project.getFile(path); iFile.create(fis, true, null); } level--; } catch (CoreException e) { e.printStackTrace(); Logger.logException(e); } catch (FileNotFoundException e) { e.printStackTrace(); Logger.logException(e); } }
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 static ISourceModule resolveSourceModule(FileStoreEditorInput input) { final ISourceModule[] modules = new ISourceModule[1]; final IPath filePath = URIUtil.toPath(input.getURI()); IScriptModel scriptModel = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { scriptModel.accept( new IModelElementVisitor() { public boolean visit(IModelElement element) { boolean shouldDescend = (modules[0] == null); if (shouldDescend == true) { if (element instanceof ExternalProjectFragment) { ExternalProjectFragment fragment = (ExternalProjectFragment) element; try { if (filePath .removeLastSegments(1) .toFile() .getCanonicalPath() .startsWith(fragment.getPath().toFile().getCanonicalPath()) == true) { IPath folderPath = new Path(filePath.removeLastSegments(1).toFile().getCanonicalPath()); folderPath = folderPath.removeFirstSegments( new Path(fragment.getPath().toFile().getCanonicalPath()) .segmentCount()); IScriptFolder folder = fragment.getScriptFolder(folderPath); if ((folder != null) && (folder.exists() == true)) { ISourceModule module = folder.getSourceModule(filePath.lastSegment()); if (module != null) { modules[0] = module; } } } } catch (IOException ixcn) { ixcn.printStackTrace(); } shouldDescend = false; } else { shouldDescend = ((element instanceof IScriptProject) || (element instanceof IScriptModel)); } } return shouldDescend; } }); } catch (ModelException mxcn) { mxcn.printStackTrace(); } return modules[0]; }
private static ImageDescriptor getFolderBaseImage(IResource resource) { IModelElement modelElement = DLTKCore.create(resource); if (null != modelElement) { if (modelElement instanceof IScriptFolder) return PHPPluginImages.DESC_OBJS_PHPFOLDER_ROOT; } else { return PlatformUI.getWorkbench() .getSharedImages() .getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); } return null; }
public void installSymfony(IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); SymfonyProjectWizardFirstPage firstPage = (SymfonyProjectWizardFirstPage) fFirstPage; monitor.beginTask("Installing symfony...", 100); monitor.worked(10); IProject projectHandle = fFirstPage.getProjectHandle(); final IScriptProject scriptProject = DLTKCore.create(projectHandle); File file = null; final List<IBuildpathEntry> entries = new ArrayList<IBuildpathEntry>(); level = 0; try { file = new File(firstPage.getLibraryPath()); symfonyPath = new Path(firstPage.getLibraryPath()).toString(); if (file.isDirectory()) { final File[] files = file.listFiles(); if (!scriptProject.isOpen()) { scriptProject.open(monitor); } if (files != null && scriptProject != null && scriptProject.isOpen()) { for (File f : files) { importFile(f, scriptProject.getProject(), entries); } BuildPathUtils.addEntriesToBuildPath(scriptProject, entries); monitor.worked(90); } } } catch (ModelException e) { e.printStackTrace(); Logger.logException(e); } catch (Exception e) { e.printStackTrace(); Logger.logException(e); } finally { monitor.worked(100); monitor.done(); } }
@Test public void test(String fileName) { PdttFileExt testFile = filesMap.get(fileName); IFile file = project.findFile(testFile.getTestFiles().get(0).getName()); IStructuredModel model = null; try { model = createUnManagedStructuredModelFor(file); } catch (IOException e) { fail(e.getMessage()); } catch (CoreException e) { fail(e.getMessage()); } assertNotNull(model); IStructuredDocument structuredDocument = model.getStructuredDocument(); assertNotNull(structuredDocument); int start = Integer.valueOf(testFile.getConfig().get("start")); int length = Integer.valueOf(testFile.getConfig().get("length")); String visibility = testFile.getConfig().get("visibility"); ExtractFunctionRefactoring processor = new ExtractFunctionRefactoring( DLTKCore.createSourceModuleFrom(file), structuredDocument, start, length); if ("default".equals(visibility)) { processor.setVisibility(Modifiers.AccDefault); } if ("public".equals(visibility)) { processor.setVisibility(Modifiers.AccPublic); } if ("prvate".equals(visibility)) { processor.setVisibility(Modifiers.AccPrivate); } if ("protected".equals(visibility)) { processor.setVisibility(Modifiers.AccProtected); } processor.setNewFunctionName(testFile.getConfig().get("newName")); checkInitCondition(processor); performChange(processor); checkTestResult(testFile, structuredDocument); }
public void initializeFrom(Element memento) throws CoreException { String name = memento.getAttribute("project"); // $NON-NLS-1$ if (name == null) { abort(LaunchingMessages.DefaultProjectBuildpathEntry_3, null); } IScriptProject project = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(name)); setScriptProject(project); name = memento.getAttribute("exportedEntriesOnly"); // $NON-NLS-1$ if (name == null) { fExportedEntriesOnly = false; } else { fExportedEntriesOnly = Boolean.valueOf(name).booleanValue(); } }
@Override public Set<IScriptProject> collectProjects() { final Set<IScriptProject> projects = new HashSet<IScriptProject>(); final IScriptModel model = DLTKCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { for (IScriptProject project : model.getScriptProjects(TclNature.NATURE_ID)) { InstrumentationUtils.collectProjects(model, projects, project); } } catch (CoreException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } return projects; }
public void executeInBackground(final IExecutableOperation operation) { if (!isRunningInUIThread()) { operation.execute(new NullProgressMonitor()); } else if (DLTKUI.isStarted()) { if (active) { return; } final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null) { @Override protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(operation.getOperationName()); } }; active = true; try { dialog.run( true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { if (!isRunningInUIThread()) { operation.execute(monitor); } } }); } catch (InvocationTargetException e) { DLTKCore.error(e.getMessage(), e); } catch (InterruptedException e) { DLTKCore.error(e.getMessage(), e); } finally { active = false; } } }
@Override public void initialize(IPath containerPath, IScriptProject scriptProject) throws CoreException { if (containerPath.segmentCount() > 0 && containerPath.segment(0).equals(CONTAINER_PATH)) { try { if (isPHPProject(scriptProject)) { DLTKCore.setBuildpathContainer( containerPath, new IScriptProject[] {scriptProject}, new IBuildpathContainer[] {new LanguageModelContainer(containerPath, scriptProject)}, null); } } catch (final Exception e) { GeneratorBeautifierPlugin.log(e); } } }
/** * Heavily based on RemoteScriptSourceLookupDirector#getSourceElement(Object) but adds {@link * IStorage} support and checks that URI actually contains something (case of unreachable stack * levels) * * @see * org.eclipse.debug.core.sourcelookup.AbstractSourceLookupDirector#getSourceElement(java.lang.Object) * @see * org.eclipse.dltk.launching.sourcelookup.RemoteScriptSourceLookupDirector#getSourceElement(Object) */ @Override public Object getSourceElement(Object element) { // if the element is an unreachable stack frame we don't need to search trough the source path // computer. if (element instanceof IScriptStackFrame) { IScriptStackFrame frame = (ScriptStackFrame) element; UnreachableStackFrame unreachableStackFrame = UnreachableStackFrame.checkReachable(frame); if (unreachableStackFrame != null) { return unreachableStackFrame; } } // search in all container of the source path computer. Object o = super.getSourceElement(element); // a file or a IStorage was found, we return it, we can display it. if (o instanceof IFile || o instanceof IStorage) { return o; } // at this time, if we still have a ScriptStackFrame // we could have a fallback and create a DBGPSourceModule // (the source code will be return by the DBGP client via the command "source" if (element instanceof ScriptStackFrame) { ScriptStackFrame frame = (ScriptStackFrame) element; URI uri = frame.getSourceURI(); String path = uri.getPath(); IProject project = LaunchConfigurationUtils.getProject(getLaunchConfiguration()); if (project == null) { return null; } IScriptProject scriptProject = DLTKCore.create(project); /* * XXX: this should probably use some kind of IStorable implementation instead of directly relying on the stack frame - that allows for * re-use of the ExternalStorageEditorInput object */ return new DBGPSourceModule( (ScriptProject) scriptProject, path, DefaultWorkingCopyOwner.PRIMARY, frame); } // we not managed the other case, so return null return null; }
public String getDescription() { FunctionStatement f = getFunctionStatement(getScriptFile(), getProblemStartIdx()); ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(getScriptFile()); try { String functionString = sourceModule.getBuffer().getText(f.sourceStart(), f.sourceEnd() - f.sourceStart()); int lineEnd = functionString.indexOf('\n'); StringBuilder sb = new StringBuilder(lineEnd + 100); sb.append("<html><body> *<b>"); sb.append(getAnnotation()); sb.append("</b><br/> */<br/>"); sb.append(functionString.substring(0, lineEnd)); sb.append("</body></html>"); return sb.toString(); } catch (ModelException e) { } return getLabel(); }
private Map<IFile, Program> collectReferencingFiles(IFile sourceFile, IProgressMonitor pm) { ISourceModule sourceModule = DLTKCore.createSourceModuleFrom(sourceFile); Map<IFile, Program> participantFiles = new HashMap<IFile, Program>(); Collection<Node> references = MoveUtils.getReferencingFiles(sourceModule); if (references != null) { for (Iterator<Node> it = references.iterator(); it.hasNext(); ) { Node node = it.next(); IFile file = (IFile) node.getFile().getResource(); try { participantFiles.put(file, RefactoringUtility.getProgramForFile(file)); } catch (Exception e) { } } } return participantFiles; }
/** * 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); } } } }
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 static ISourceModule[] findAffectedCompilationUnits( SearchPattern pattern, IDLTKSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws CoreException { boolean hasNonCuMatches = false; class ResourceSearchRequestor extends SearchRequestor { boolean hasPotentialMatches = false; Set<IResource> resources = new HashSet<IResource>(5); private IResource fLastResource; public void acceptSearchMatch(SearchMatch match) { if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) { hasPotentialMatches = true; } if (fLastResource != match.getResource()) { fLastResource = match.getResource(); resources.add(fLastResource); } } } ResourceSearchRequestor requestor = new ResourceSearchRequestor(); new SearchEngine() .search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm); List<ISourceModule> result = new ArrayList<ISourceModule>(requestor.resources.size()); for (IResource resource : requestor.resources) { IModelElement element = DLTKCore.create(resource); if (element instanceof ISourceModule) { result.add((ISourceModule) element); } else { hasNonCuMatches = true; } } addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches); return (ISourceModule[]) result.toArray(new ISourceModule[result.size()]); }
/** * 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); } }
/* * 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); }
public CompletionEngine_Test() { String filePath = ITestResourcesConstants.TR_CA + "/" + "testCodeCompletion.d"; IFile file = SampleMainProject.scriptProject.getProject().getFile(filePath); this.srcModule = DLTKCore.createSourceModuleFrom(file); }
@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; }