private String handleBrowse(String filter) { IJavaSearchScope scope = null; if (_project == null) { scope = SearchEngine.createWorkspaceScope(); } else { scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {_project}); } try { SelectionDialog dialog = JavaUI.createTypeDialog( Display.getCurrent().getActiveShell(), null, scope, IJavaElementSearchConstants.CONSIDER_CLASSES, false, filter.isEmpty() ? "* " : filter); if (dialog.open() == SelectionDialog.OK) { Object[] result = dialog.getResult(); if (result.length > 0 && result[0] instanceof IType) { return ((IType) result[0]).getFullyQualifiedName(); } } } catch (JavaModelException e) { e.printStackTrace(); } return null; }
protected List<String> getSourceFolders(IProject project) { List<String> result = new ArrayList<String>(); IJavaProject javaProject = JavaCore.create(project); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); try { for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) { if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { IPath path = packageFragmentRoot.getPath(); IFolder folder = root.getFolder(path); String location = folder.getLocation().toString(); if (!location.contains("src-gen")) { result.add(location); } } } for (IProject referencedProject : javaProject.getProject().getReferencedProjects()) { if (referencedProject.isAccessible() && referencedProject.hasNature(JavaCore.NATURE_ID)) { result.addAll(getSourceFolders(referencedProject)); } } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) { IPackageFragmentRoot initRoot = null; if (elem != null) { initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); try { if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) { IJavaProject jproject = elem.getJavaProject(); if (jproject != null) { initRoot = null; if (jproject.exists()) { IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { initRoot = roots[i]; break; } } } if (initRoot == null) { initRoot = jproject.getPackageFragmentRoot(jproject.getResource()); } } } } catch (JavaModelException e) { // TODO e.printStackTrace(); } } return initRoot; }
private static void getOpenTabs(IWorkbenchWindow window) { openTabs.clear(); WorkbenchPage activePage = (WorkbenchPage) window.getActivePage(); IEditorReference[] editorRefs = ((WorkbenchPage) activePage).getSortedEditors(); // WorkbenchPage.getSortedEditors() returns the editors in activation order (oldest // first). We want most recently activated to be first, so reverse the list. List<IEditorReference> editorRefsAsList = Arrays.asList(editorRefs); Collections.reverse(editorRefsAsList); try { for (IEditorReference ref : editorRefsAsList) { if (ref.getEditorInput() instanceof FileEditorInput) { IFile file = ((FileEditorInput) ref.getEditorInput()).getFile(); IJavaElement editorElt = JavaCore.create(file); if (editorElt instanceof ICompilationUnit) { openTabs.addAll(Arrays.asList(((ICompilationUnit) editorElt).getAllTypes())); } } } } catch (PartInitException e) { System.out.print("Exception while getting all open tabs. " + e.getMessage()); e.printStackTrace(); } catch (JavaModelException e) { System.out.print("Exception while getting all open tabs. " + e.getMessage()); e.printStackTrace(); } }
/** * The default implementation recursively traverses the folders of the imported projects and * copies all contents into a feature folder with the imported projects name in {@code * newProject}. Can be overwritten by extending classes to accomodate {@link * IComposerExtensionBase Composers} needs. */ protected void migrateProjects() { for (IProject project : projects) { IPath destinationPath = new Path(configurationData.sourcePath); assert newProject.getFolder(destinationPath).isAccessible() : DESTINATIONFOLDER_NOT_ACCESSIBLE_OR_WRONG_PATH; assert project.isOpen() : PROJECT + project.getName() + IS_NOT_OPEN_; IPath featureFolderPath = SPLMigrationUtils.setupFolder( newProject.getFolder(destinationPath).getFolder(project.getName())); try { migrateClassPathDependentContent(project, featureFolderPath); } catch (JavaModelException e) { e.printStackTrace(); } // try // { // if(project.hasNature(ANDROID_NATURE)) // copyProjectProperties(project, featureFolderPath); // } catch (CoreException e) // { // e.printStackTrace(); // } } }
/** @see edu.buffalo.cse.green.editor.model.commands.DeleteCommand#doDelete() */ public void doDelete() { RootModel root = _typeModel.getRootModel(); // Remove relationships first List<RelationshipModel> rels = root.getRelationships(); // No iterators here due to CME's (ConcurrentModificationException) // Removal of relationships causes modifications to the rels list. for (int i = 0; i < rels.size(); i++) { IType t = _typeModel.getType(); RelationshipModel r = rels.get(i); if (r.getSourceType() == t || r.getTargetType() == t) { DeleteCommand drc = r.getDeleteCommand(DiagramEditor.findProjectEditor(root.getProject())); drc.suppressMessage(true); drc.execute(); } } _typeModel.removeChildren(); // remove fields/methods _typeModel.removeFromParent(); try { IType type = _typeModel.getType(); ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT); if (type.equals(cu.findPrimaryType())) { cu.delete(true, PlugIn.getEmptyProgressMonitor()); } else { type.delete(true, PlugIn.getEmptyProgressMonitor()); } } catch (JavaModelException e) { e.printStackTrace(); } root.updateRelationships(); }
public ASTReader(IJavaProject iJavaProject, IProgressMonitor monitor) { if (monitor != null) monitor.beginTask("Parsing selected Java Project", getNumberOfCompilationUnits(iJavaProject)); systemObject = new SystemObject(); examinedProject = iJavaProject; try { IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots(); for (IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) { IJavaElement[] children = iPackageFragmentRoot.getChildren(); for (IJavaElement child : children) { if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { IPackageFragment iPackageFragment = (IPackageFragment) child; ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits(); for (ICompilationUnit iCompilationUnit : iCompilationUnits) { if (monitor != null && monitor.isCanceled()) throw new OperationCanceledException(); systemObject.addClasses(parseAST(iCompilationUnit)); if (monitor != null) monitor.worked(1); } } } } } catch (JavaModelException e) { e.printStackTrace(); } if (monitor != null) monitor.done(); }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement) */ public void handleMove(RootModel root, E sourceElement, E targetElement) { root.changeProjectElement(sourceElement, targetElement); try { List<IJavaElement> packages = root.getElementsOfKind(PACKAGE_FRAGMENT); // look through packages to match up source and destination elements for (IJavaElement packElement : packages) { IPackageFragment packFrag = (IPackageFragment) packElement; if (JavaModelListener.sameElements( packFrag.getAncestor(JAVA_PROJECT), sourceElement.getPrimaryElement())) { for (IPackageFragment packFrags : targetElement.getPackageFragments()) { // check for the same name of the two packages if (packFrag.getElementName().equals(packFrags.getElementName())) { PackageRefactorHandler.instance().handleMove(root, packFrag, packFrags); } } } } root.dispose(); } catch (JavaModelException e) { e.printStackTrace(); } }
public static String getType(final IField field) { try { return Signature.toString(field.getTypeSignature()); } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final JavaModelException e) { e.printStackTrace(); } return null; }
private IType getJDTType(JvmType jvmTypeRef) { try { IJavaProject javaProject = javaProjectProvider.getJavaProject(jvmTypeRef.eResource().getResourceSet()); return javaProject.findType(jvmTypeRef.getQualifiedName()); } catch (JavaModelException e) { // TODO Logging e.printStackTrace(); } return null; }
public void generate( ICompilationUnit compilationUnit, boolean createPrivateConstructor, boolean formatSource, List<IField> selectedFields) { try { System.out.println(compilationUnit.getSource()); } catch (JavaModelException e) { e.printStackTrace(); } }
public static List<IField> findAllFields(final IType clazz) { final List<IField> fields = new ArrayList<IField>(); try { for (final IField field : clazz.getFields()) { final int flags = field.getFlags(); final boolean notStatic = !Flags.isStatic(flags); if (notStatic) fields.add(field); } } catch (final JavaModelException e) { e.printStackTrace(); } return fields; }
private IJavaElement visit(IParent parent) { try { for (IJavaElement child : parent.getChildren()) { IJavaElement elementFound = visit(child); if (elementFound != null) { return elementFound; } } } catch (JavaModelException e) { e.printStackTrace(); } return null; }
public String getCuttedSourceCode(ICompilationUnit unit) { int[] offsets = getSelectionStartAndEnd(unit); String source; String cutted; try { source = unit.getSource(); cutted = source.substring(offsets[0], offsets[1] + 1); return cutted; } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
private static PackageFragment defaultPackage(IProject proj) { IJavaProject jp = JavaCore.create(proj); try { IPackageFragment[] packageFragments = jp.getPackageFragments(); for (IPackageFragment frag : packageFragments) { if (frag.getElementName().equals(DEFAULT_PACKAGE_NAME)) return (PackageFragment) frag; } return null; } catch (JavaModelException e) { e.printStackTrace(); System.out.printf("Yikes!%n"); return null; } }
/** * Gets the classpath. * * @param project the project * @return the classpath * @see * net.kbserve.pyjdt.properties.models.ICPEType#getClasspath(org.eclipse.core.resources.IProject) */ @Override public IClasspathEntry getClasspath(IProject project) { IJavaProject javaProject = JavaCore.create(project); try { for (IClasspathEntry icp : javaProject.getRawClasspath()) { if (makeStringPath(icp).equals(getPath())) { return icp; } } } catch (JavaModelException e) { e.printStackTrace(); } return null; }
/** Tests if the current workbench selection is a suitable container to use. */ private void initialize() { if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; Object obj = ssel.getFirstElement(); if (obj instanceof IPackageFragmentRoot) { try { obj = ((IPackageFragmentRoot) obj).getCorrespondingResource(); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (obj instanceof IPackageFragment) { try { obj = ((IPackageFragment) obj).getCorrespondingResource(); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if ((obj instanceof IResource) || (obj instanceof IContainer)) { IContainer container; if (obj instanceof IContainer) container = (IContainer) obj; else container = ((IResource) obj).getParent(); containerText.setText(container.getFullPath().toString()); } } // passwordText.setText(""); }
public void initialize(String variable) { IPreferenceStore preferenceStore = GradlePlugin.getPlugin().getPreferenceStore(); String gradleCache = preferenceStore.getString(IGradlePreferenceConstants.GRADLE_CACHE); // create directory if it not already exists File gradleCacheDir = new File(gradleCache); gradleCacheDir.mkdirs(); try { JavaCore.setClasspathVariable(variable, new Path(gradleCacheDir.getAbsolutePath()), null); } catch (JavaModelException e) { // TODO FIX ERROR HANDLING !!! e.printStackTrace(); } }
private void setContentsToCU(ICompilationUnit unit, String value) { if (unit == null) { return; } synchronized (unit) { IBuffer buffer; try { buffer = unit.getBuffer(); if (buffer != null) { buffer.setContents(value); } } catch (JavaModelException e) { e.printStackTrace(); } } }
/** Tests if the current workbench selection is a suitable container to use. */ private void initialize() { if (selection != null && selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection ssel = (IStructuredSelection) selection; if (ssel.size() > 1) return; Object obj = ssel.getFirstElement(); IJavaElement element = JavaExt.as(obj); if (element != null) { try { containerText.setText(JDTUtils.getIJavaElementPath(element)); } catch (JavaModelException jme) { jme.printStackTrace(); } } } fileText.setText("new.jaml"); }
/** * @see * edu.buffalo.cse.green.RefactorHandler#handleMove(edu.buffalo.cse.green.editor.model.RootModel, * org.eclipse.jdt.core.IJavaElement, org.eclipse.jdt.core.IJavaElement) */ public void handleMove(RootModel root, E sourceElement, E targetElement) { try { List<IJavaElement> cus = root.getElementsOfKind(COMPILATION_UNIT); ICompilationUnit[] newCUs = targetElement.getCompilationUnits(); for (IJavaElement cuElement : cus) { ICompilationUnit iCU = (ICompilationUnit) cuElement; if (JavaModelListener.sameElements(iCU.getAncestor(PACKAGE_FRAGMENT), sourceElement)) { for (ICompilationUnit cu : newCUs) { if (cu.getElementName().equals(iCU.getElementName())) { CompilationUnitRefactorHandler.instance().handleMove(root, iCU, cu); } } } } } catch (JavaModelException e) { e.printStackTrace(); } }
public static int getNumberOfCompilationUnits(IJavaProject iJavaProject) { int numberOfCompilationUnits = 0; try { IPackageFragmentRoot[] iPackageFragmentRoots = iJavaProject.getPackageFragmentRoots(); for (IPackageFragmentRoot iPackageFragmentRoot : iPackageFragmentRoots) { IJavaElement[] children = iPackageFragmentRoot.getChildren(); for (IJavaElement child : children) { if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { IPackageFragment iPackageFragment = (IPackageFragment) child; ICompilationUnit[] iCompilationUnits = iPackageFragment.getCompilationUnits(); numberOfCompilationUnits += iCompilationUnits.length; } } } } catch (JavaModelException e) { e.printStackTrace(); } return numberOfCompilationUnits; }
@Test public void test0d() { try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); IProject project = root.getProject("TestProject"); IJavaProject javaProject = JavaCore.create(project); IPackageFragment mypackage = javaProject.findPackageFragment(new Path("/TestProject/src/be/ac/ua/test/pack")); if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) { ICompilationUnit cu = mypackage.getCompilationUnits()[0]; IType[] types = cu.getAllTypes(); ClassRecorder recorder = new ClassRecorder(types[0]); Field uniqueNameField = ClassRecorder.class.getDeclaredField("uniqueName"); uniqueNameField.setAccessible(true); String fieldValue = (String) uniqueNameField.get(recorder); assertEquals(fieldValue, packname + "." + classname); /*Field parentField = ClassRecorder.class.getDeclaredField("parent"); parentField.setAccessible(true); FamixEntity fieldValue2 = (FamixEntity)parentField.get(recorder); assertEquals(packname, fieldValue2.getUniqueName());*/ } } catch (JavaModelException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (SecurityException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IllegalArgumentException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (NoSuchFieldException e) { e.printStackTrace(); fail("Unexpected exception"); } catch (IllegalAccessException e) { e.printStackTrace(); fail("Unexpected exception"); } }
@Override public void resourceChanged(IResourceChangeEvent event) { IPath path = BMClasspathContainer.PATH; try { IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); for (IJavaProject javaProject : model.getJavaProjects()) { for (IClasspathEntry rawEntry : javaProject.readRawClasspath()) { if (rawEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { IPath entryPath = rawEntry.getPath(); if (path.isPrefixOf(entryPath)) { this.initialize(entryPath, javaProject); return; } } } } } catch (JavaModelException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } }
private void process() { try { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); String basepackage = preferenceStore.getString(JsfcaPerferenceConstants.PROP_KEY_BASE_PACKAGE); String regEx = preferenceStore.getString(JsfcaPerferenceConstants.PROP_KEY_FILE_PATTERN); if (basepackage == null || basepackage.isEmpty()) { return; } if (regEx == null || regEx.isEmpty()) { return; } Pattern classPattern = Pattern.compile(regEx); IPackageFragment[] packageFragments = javaProject.getPackageFragments(); for (IPackageFragment packageFragment : packageFragments) { if (packageFragment.getElementName().startsWith(basepackage.toLowerCase())) { if (packageFragment.containsJavaResources()) { ICompilationUnit[] compilationUnits = packageFragment.getCompilationUnits(); for (ICompilationUnit compUnit : compilationUnits) { IType primaryType = compUnit.findPrimaryType(); if (primaryType != null && classPattern.matcher(primaryType.getElementName()).matches()) { createSymbol(primaryType); } } } } } } catch (JavaModelException e) { e.printStackTrace(); } }
/** Makes the fix */ public boolean fix() { IResource source = marker.getResource(); IJavaElement javaElem = JavaCore.create(source); ICompilationUnit compUnit = (ICompilationUnit) javaElem; IProgressMonitor pm = new NullProgressMonitor(); try { // create move policy and processor for the compilation unit IMovePolicy movePolicy = ReorgPolicyFactory.createMovePolicy( new IResource[] {compUnit.getResource()}, new IJavaElement[] {compUnit}); JavaMoveProcessor processor = new JavaMoveProcessor(movePolicy); if (newSource == null) return false; processor.setDestination(ReorgDestinationFactory.createDestination(newSource)); // the refactoring object Refactoring refactoring = new ProcessorBasedRefactoring(processor); // set a refactoring wizard RefactoringWizard wizard = new ReorgMoveWizard(processor, refactoring); Shell activeShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); wizard.setContainer(new RefactoringWizardDialog(activeShell, wizard)); // set reorg queries (no idea what it is used for, but doesn't work without it) processor.setCreateTargetQueries(new CreateTargetQueries(wizard)); processor.setReorgQueries(new ReorgQueries(activeShell)); // perform the refactoring and return its success result performRefactoring(refactoring); boolean status = wizard.getChange() != null; System.out.println(status); return status; } catch (JavaModelException e) { e.printStackTrace(); return false; } catch (OperationCanceledException e) { e.printStackTrace(); return false; } finally { pm.done(); } }
/** * Constructor * * @param marker the marker to be fixed */ public Fixer(IMarker marker) { super(); this.marker = marker; IResource source = marker.getResource(); IProject project = source.getProject(); IJavaProject javaProject = JavaCore.create(project); IPackageFragment[] packageFragments; try { packageFragments = javaProject.getPackageFragments(); String newSourceName; newSourceName = (String) marker.getAttribute(QuickFix.ATTRIBUTE_NEWSOURCE); for (IPackageFragment pckgFrg : packageFragments) { if (pckgFrg.getElementName().equals(newSourceName)) { newSource = pckgFrg; break; } } } catch (JavaModelException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } }
protected String chooseSuperclass() { Set<String> superclasses = new HashSet<String>(); try { IProject actualProject = ResourcesPlugin.getWorkspace().getRoot().getProject(getContainerFullPath().segment(0)); IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(actualProject); TypeNameCollector typeNameCollector = new TypeNameCollector(javaProject, false); BindingReflectionUtils.findMatchingElementClassNames( "", SearchPattern.R_PREFIX_MATCH, typeNameCollector, new NullProgressMonitor()); for (String typeName : typeNameCollector.getTypeNames()) { // int dotIndex = typeName.lastIndexOf('.'); // if (dotIndex != -1) { // typeName = typeName.substring(dotIndex + 1); // } // validValues.add("\"" + typeName + "\""); superclasses.add(typeName); } } catch (JavaModelException e) { // JTourBusPlugin.log(e); e.printStackTrace(); } ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), new StringLabelProvider()); dialog.setIgnoreCase(true); dialog.setTitle(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_title); dialog.setMessage(NewWizardMessages.NewTypeWizardPage_SuperClassDialog_message); // dialog.setEmptyListMessage(NewWizardMessages.NewTypeWiz); dialog.setFilter(_superclassDialogField.getText()); dialog.setElements(superclasses.toArray()); if (dialog.open() == Window.OK) { return (String) dialog.getFirstResult(); } return null; }
protected IPackageFragment choosePackage() { List<IJavaElement> packagesList = new LinkedList<IJavaElement>(); try { IProject actualProject = ResourcesPlugin.getWorkspace().getRoot().getProject(getContainerFullPath().segment(0)); IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProject(actualProject); IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (int k = 0; k < roots.length; k++) { if (roots[k].getKind() == IPackageFragmentRoot.K_SOURCE) { IJavaElement[] children = roots[k].getChildren(); for (int i = 0; i < children.length; i++) { packagesList.add(children[i]); } } } } catch (JavaModelException e) { // JTourBusPlugin.log(e); e.printStackTrace(); } IJavaElement[] packages = packagesList.toArray(new IJavaElement[packagesList.size()]); ElementListSelectionDialog dialog = new ElementListSelectionDialog( getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_title); dialog.setMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_description); dialog.setEmptyListMessage(NewWizardMessages.NewTypeWizardPage_ChoosePackageDialog_empty); dialog.setFilter(_packageDialogField.getText()); dialog.setElements(packages); if (dialog.open() == Window.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; }
private String getTypeParam(ITypeParameter typeParam) { try { StringBuilder builder = new StringBuilder(); builder.append('<').append(typeParam.getElementName()); boolean first = true; for (String bound : typeParam.getBounds()) { if (first) { first = false; builder.append('+'); } else { builder.append('&'); } builder.append(bound.replace(" extends ", "+")); } builder.append('>'); return builder.toString(); } catch (JavaModelException e) { e.printStackTrace(); System.out.println("bad"); return null; } }