/** * Tries to find the given {@link IApiMethod} in the given {@link IType}. If a matching method is * not found <code>null</code> is returned * * @param type the type top look in for the given {@link IApiMethod} * @param method the {@link IApiMethod} to look for * @return the {@link IMethod} from the given {@link IType} that matches the given {@link * IApiMethod} or <code>null</code> if no matching method is found * @throws JavaModelException * @throws CoreException */ protected IMethod findMethodInType(IType type, IApiMethod method) throws JavaModelException, CoreException { String[] parameterTypes = Signature.getParameterTypes(method.getSignature()); for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = parameterTypes[i].replace('/', '.'); } String methodname = method.getName(); if (method.isConstructor()) { IApiType enclosingType = method.getEnclosingType(); if (enclosingType.isMemberType() && !Flags.isStatic(enclosingType.getModifiers())) { // remove the synthetic argument that corresponds to the enclosing type int length = parameterTypes.length - 1; System.arraycopy(parameterTypes, 1, (parameterTypes = new String[length]), 0, length); } methodname = enclosingType.getSimpleName(); } IMethod Qmethod = type.getMethod(methodname, parameterTypes); IMethod[] methods = type.getMethods(); IMethod match = null; for (int i = 0; i < methods.length; i++) { IMethod m = methods[i]; if (m.isSimilar(Qmethod)) { match = m; break; } } return match; }
public void testMissingType() { try { IType type = fProject.findType("tests.apiusescan.coretestproject.IConstants"); type.rename("IConstants1", true, null); IProject project = fProject.getProject(); ExternalDependencyTestUtils.waitForBuild(); IMarker[] markers = project.findMarkers( IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); assertEquals( "No API Use Scan problem marker found for missing type IConstants", 1, markers.length); String typeName = markers[0].getAttribute(IApiMarkerConstants.API_USESCAN_TYPE, null); assertEquals( "Marker for missing type IConstants not found", "tests.apiusescan.coretestproject.IConstants", typeName); type = fProject.findType("tests.apiusescan.coretestproject.IConstants1"); type.rename("IConstants", true, null); ExternalDependencyTestUtils.waitForBuild(); markers = project.findMarkers( IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); assertEquals( "API Use Scan problem marker for missing type IConstants did not clear", 0, markers.length); } catch (JavaModelException e) { fail(e.getMessage()); } catch (CoreException e) { fail(e.getMessage()); } }
/** Returns a flat list of all interfaces and super types for the given {@link IType}. */ public static List<String> getFlatListOfClassAndInterfaceNames(IType parameterType, IType type) { List<String> requiredTypes = new ArrayList<String>(); if (parameterType != null) { do { try { requiredTypes.add(parameterType.getFullyQualifiedName()); String[] interfaceNames = parameterType.getSuperInterfaceNames(); for (String interfaceName : interfaceNames) { if (interfaceName != null) { if (type.isBinary()) { requiredTypes.add(interfaceName); } String resolvedName = resolveClassName(interfaceName, type); if (resolvedName != null) { requiredTypes.add(resolvedName); } } } parameterType = Introspector.getSuperType(parameterType); } catch (JavaModelException e) { } } while (parameterType != null && !parameterType.getFullyQualifiedName().equals(Object.class.getName())); } return requiredTypes; }
/** Calculate the number of methods. */ public void calculateNumberOfMethods() { if (resource.isAccessible()) { // we need to change the Resource into a Java-File final IJavaElement element = JavaCore.create(resource); final List<Object> methods = new ArrayList<Object>(); if (element instanceof ICompilationUnit) { try { // ITypes can be Package Declarations or other Java Stuff too IType[] types = ((ICompilationUnit) element).getTypes(); for (IType type : types) { // only if it is an IType itself, it's a Class // from which we can get its Methods methods.addAll(Arrays.asList(type.getMethods())); } } catch (JavaModelException jme) { PMDPlugin.getDefault().logError(StringKeys.ERROR_JAVAMODEL_EXCEPTION + toString(), jme); } } if (!methods.isEmpty()) { numberOfMethods = methods.size(); } } }
public static IWorkspaceRoot setupWorkspace() throws CoreException, IOException, InvocationTargetException, InterruptedException { if (isSetup) { clearDoiModel(); return workspaceRoot; } taskscape = new InteractionContext(HELPER_CONTEXT_ID, new InteractionContextScaling()); workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); project1 = ContextTestUtil.createJavaPluginProjectFromZip("project1", "project1.zip"); project2 = ContextTestUtil.createJavaPluginProjectFromZip("project2", "project2.zip"); jdtCoreDomProject = new TestJavaProject("workspace-helper-project"); IPackageFragment jdtCoreDomPkg = jdtCoreDomProject.createPackage("org.eclipse.jdt.core.dom"); IType astNodeType = jdtCoreDomProject.createType(jdtCoreDomPkg, "ASTNode.java", "public class ASTNode { }"); astNodeType.createMethod( "public final void setSourceRange(int startPosition, int length) { }", null, false, null); isSetup = true; project1.open(new NullProgressMonitor()); project2.open(new NullProgressMonitor()); jdtCoreDomProject.getJavaProject().open(new NullProgressMonitor()); return workspaceRoot; }
protected TestNGMethodWizardPage(List<JavaElement> elements) { super(ResourceUtil.getString("NewTestNGClassWizardPage.title")); setTitle(ResourceUtil.getString("NewTestNGClassWizardPage.title")); setDescription(ResourceUtil.getString("TestNGMethodWizardPage.description")); for (JavaElement je : elements) { if (je.compilationUnit != null) { try { for (IType type : je.compilationUnit.getTypes()) { for (IMethod method : type.getMethods()) { m_elements.add(method); } } } catch (JavaModelException ex) { // ignore } } } Collections.sort( m_elements, new Comparator<IMethod>() { public int compare(IMethod o1, IMethod o2) { return o1.getElementName().compareTo(o2.getElementName()); } }); }
private char[][][] getQualifiedNames(ObjectVector types) { final int size = types.size; char[][][] focusQualifiedNames = null; IJavaElement javaElement = this.pattern.focus; int index = 0; while (javaElement != null && !(javaElement instanceof ITypeRoot)) { javaElement = javaElement.getParent(); } if (javaElement != null) { IType primaryType = ((ITypeRoot) javaElement).findPrimaryType(); if (primaryType != null) { focusQualifiedNames = new char[size + 1][][]; focusQualifiedNames[index++] = CharOperation.splitOn('.', primaryType.getFullyQualifiedName().toCharArray()); } } if (focusQualifiedNames == null) { focusQualifiedNames = new char[size][][]; } for (int i = 0; i < size; i++) { focusQualifiedNames[index++] = CharOperation.splitOn( '.', ((IType) (types.elementAt(i))).getFullyQualifiedName().toCharArray()); } return focusQualifiedNames.length == 0 ? null : ReferenceCollection.internQualifiedNames(focusQualifiedNames, true); }
@Test public void testDownloadedSourcesShouldAttachToPackageFragmentRoot() throws Exception { String pom = "<groupId>test</groupId>" + "<artifactId>testArtifact</artifactId>" + "<version>42</version>" + "<dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.12</version>" + " </dependency>" + "</dependencies>"; createTestProject("test2", pom); IProject test = ResourcesPlugin.getWorkspace().getRoot().getProject("test2"); mavenWorkspace.update(Collections.singletonList(test)); mavenWorkspace.waitForUpdate(); IJavaProject javaProject = JavaCore.create(test); IType type = javaProject.findType("org.junit.Test"); assertNull(type.getClassFile().getSourceRange()); boolean downloadSources = classpathManager.downloadSources(test.getFullPath().toOSString(), "org.junit.Test"); assertTrue(downloadSources); IType type2 = javaProject.findType("org.junit.Test"); assertNotNull(type2.getClassFile().getSourceRange()); }
public CodeInsertionDialog(Shell shell, IType type) throws JavaModelException { super(shell); insertPositions = new ArrayList<IJavaElement>(); fLabels = new ArrayList<String>(); System.out.println(type.getElementName() + type.getElementType()); IJavaElement[] members = type.getChildren(); insertPositions.add(members.length > 0 ? members[0] : null); // first insertPositions.add(null); // last fLabels.add(CodeInsertionDialog.firstElement); fLabels.add(CodeInsertionDialog.secondElement); for (int i = 0; i < members.length; i++) { IJavaElement curr = members[i]; String methodLabel = JavaElementLabels.getElementLabel(curr, JavaElementLabels.M_PARAMETER_TYPES); // System.out.println(MessageFormat.format(afterElement, methodLabel)); fLabels.add(MessageFormat.format(afterElement, methodLabel)); insertPositions.add(findSibling(curr, members)); } insertPositions.add(null); // null indicate we want to insert into the last position }
/** Create & return a new configuration based on the specified <code>IType</code>. */ protected ILaunchConfiguration createConfiguration(IType type) { String launcherName = MainLauncher.this.getLauncherName(); ILaunchConfigurationType configType = MainLauncher.this.getLaunchConfigurationType(); ILaunchConfigurationWorkingCopy wc = null; try { wc = configType.newInstance(null, launcherName); } catch (CoreException exception) { JDIDebugUIPlugin.log(exception); return null; } wc.setAttribute( IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName()); wc.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type.getJavaProject().getElementName()); MainLauncher.this.setAdditionalAttributes(wc); ILaunchConfiguration config = null; try { config = wc.doSave(); } catch (CoreException exception) { JDIDebugUIPlugin.log(exception); } return config; }
public void setApiMissingForElementType(boolean missing, IType type) { if (missing) { _elementTypeToApiMissingCache.put(type.getFullyQualifiedName(), Boolean.TRUE); } else { _elementTypeToApiMissingCache.put(type.getFullyQualifiedName(), Boolean.FALSE); } }
public String getContainingPackageName() { IType containingType = getContainingType(); if (containingType == null) { return ""; } return containingType.getPackageFragment().getElementName(); }
/** @see ITypeRoot#findPrimaryType() */ public IType findPrimaryType() { IType primaryType = getType(); if (primaryType.exists()) { return primaryType; } return null; }
public void testUsingRunWithAnnotation() throws Exception { IPath projectPath = createGenericProject(); IPath root = projectPath.append("src"); env.addGroovyClass( root, "", "T3", "" + "import org.junit.runner.RunWith\n" + "@RunWith(org.junit.runners.Suite.class)\n" + "public class T3 {\n" + "def void t() {\n" + "return;\n" + "}\n" + "}\n"); incrementalBuild(projectPath); expectingNoProblems(); IFile file = getFile(projectPath, "src/T3.groovy"); ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file); IType type = unit.getType("T3"); assertTrue("Groovy type T3 should exist.", type.exists()); assertTrue("Groovy type T3 should be a test suite", new JUnit4TestFinder().isTest(type)); }
private long getContainerTimestamp(TypeNameMatch match) { try { IType type = match.getType(); IResource resource = type.getResource(); if (resource != null) { URI location = resource.getLocationURI(); if (location != null) { IFileInfo info = EFS.getStore(location).fetchInfo(); if (info.exists()) { // The element could be removed from the build path. So check // if the Java element still exists. IJavaElement element = JavaCore.create(resource); if (element != null && element.exists()) return info.getLastModified(); } } } else { // external JAR IPackageFragmentRoot root = match.getPackageFragmentRoot(); if (root.exists()) { IFileInfo info = EFS.getLocalFileSystem().getStore(root.getPath()).fetchInfo(); if (info.exists()) { return info.getLastModified(); } } } } catch (CoreException e) { // Fall through } return IResource.NULL_STAMP; }
/** {@inheritDoc} */ public Object[] getChildren(Object element) { // AspectJ Change begin if (element instanceof ICompilationUnit) { element = AJCompilationUnitManager.mapToAJCompilationUnit((ICompilationUnit) element); } // AspectJ Change end if (fShowOnlyMainType) { if (element instanceof ICompilationUnit) { element = getMainType((ICompilationUnit) element); } else if (element instanceof IClassFile) { element = getMainType((IClassFile) element); } if (element == null) return NO_CHILDREN; } if (fShowInheritedMembers && element instanceof IType) { IType type = (IType) element; if (type.getDeclaringType() == null) { ITypeHierarchy th = getSuperTypeHierarchy(type); if (th != null) { List children = new ArrayList(); IType[] superClasses = th.getAllSupertypes(type); children.addAll(Arrays.asList(super.getChildren(type))); for (int i = 0, scLength = superClasses.length; i < scLength; i++) children.addAll(Arrays.asList(super.getChildren(superClasses[i]))); return children.toArray(); } } } return super.getChildren(element); }
@Override protected IStatus superClassChanged() { final IStatus status = super.superClassChanged(); // if there's already an error, let's go with it if (status.getSeverity() == IStatus.ERROR) { return status; } if (getJavaProject() != null && getSuperClass() != null && !getSuperClass().isEmpty()) { // check if the selected superclass is a subclass of // 'javax.ws.rs.core.Application' try { final IType selectedSuperClass = getJavaProject().findType(getSuperClass()); final List<IType> selectedSuperClassHierarchy = JdtUtils.findSupertypes(selectedSuperClass); if (selectedSuperClassHierarchy != null) { for (IType type : selectedSuperClassHierarchy) { if (type.getFullyQualifiedName().equals(JaxrsClassnames.APPLICATION)) { return status; } } // no match for 'javax.ws.rs.core.Application', in the // hierarchy, let's raise an error return new Status( IStatus.ERROR, JBossJaxrsUIPlugin.PLUGIN_ID, JaxrsApplicationCreationMessages .JaxrsApplicationCreationWizardPage_IllegalTypeHierarchy); } } catch (CoreException e) { Logger.error("Failed to retrieve type hierarchy for '" + getSuperClass() + "'", e); } } // return the status from the parent class return status; }
private static void checkMethodInType( IType destinationType, RefactoringStatus result, IMethod method) throws JavaModelException { IMethod[] destinationTypeMethods = destinationType.getMethods(); IMethod found = findMethod(method, destinationTypeMethods); if (found != null) { RefactoringStatusContext context = JavaStatusContext.create(destinationType.getCompilationUnit(), found.getSourceRange()); String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_signature_exists, new String[] { BasicElementLabels.getJavaElementName(method.getElementName()), getQualifiedLabel(destinationType) }); result.addError(message, context); } else { IMethod similar = Checks.findMethod(method, destinationType); if (similar != null) { String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_same_param_count, new String[] { BasicElementLabels.getJavaElementName(method.getElementName()), getQualifiedLabel(destinationType) }); RefactoringStatusContext context = JavaStatusContext.create( destinationType.getCompilationUnit(), similar.getSourceRange()); result.addWarning(message, context); } } }
/** * Determines if the supplied src file contains an import for the supplied type (including * wildcard .* imports). * * @param src The compilation unit. * @param type The type. * @return true if the src file has a qualifying import. */ public static boolean containsImport(ICompilationUnit src, IType type) throws Exception { String typePkg = type.getPackageFragment().getElementName(); IPackageDeclaration[] packages = src.getPackageDeclarations(); String pkg = packages.length > 0 ? packages[0].getElementName() : null; // classes in same package are auto imported. if ((pkg == null && typePkg == null) || (pkg != null && pkg.equals(typePkg))) { return true; } // java.lang is auto imported. if (JAVA_LANG.equals(typePkg)) { return true; } typePkg = typePkg + ".*"; String typeName = type.getFullyQualifiedName().replace('$', '.'); IImportDeclaration[] imports = src.getImports(); for (int ii = 0; ii < imports.length; ii++) { String name = imports[ii].getElementName(); if (name.equals(typeName) || name.equals(typePkg)) { return true; } } return false; }
/** * Determines is the java element contains a type with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * </ol> * * @param element the element to check for the method * @param annotationName the qualified or unqualified name of the annotation to look for * @return true if the type is found in the element, false otherwise */ private boolean hasTypeWithAnnotation(IJavaElement element, String annotationType) { try { IType type = getType(element); if (type == null || !type.exists()) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } ISourceRange sourceRange = type.getSourceRange(); ISourceRange nameRange = type.getNameRange(); if (sourceRange != null && nameRange != null) { IScanner scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); if (findAnnotation(scanner, annotationType)) { return true; } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
/** @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 String getContainingTypename() { IType containingType = getContainingType(); if (containingType == null) { return ""; } return containingType.getFullyQualifiedName(); }
/* (non-Javadoc) * @see org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#createConfiguration(org.eclipse.jdt.core.IType) */ @Override protected ILaunchConfiguration createConfiguration(IType type) { ILaunchConfiguration config = null; ILaunchConfigurationWorkingCopy wc = null; try { ILaunchConfigurationType configType = getConfigurationType(); wc = configType.newInstance( null, getLaunchManager().generateLaunchConfigurationName(type.getTypeQualifiedName('.'))); // wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, // type.getFullyQualifiedName()); wc.setAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, type.getJavaProject().getElementName()); wc.setMappedResources(new IResource[] {type.getUnderlyingResource()}); config = wc.doSave(); } catch (CoreException exception) { MessageDialog.openError( JDIDebugUIPlugin.getActiveWorkbenchShell(), LauncherMessages.JavaLaunchShortcut_3, exception.getStatus().getMessage()); } return config; }
public ITypeModel getBodyType() { IMethod iMethod = (IMethod) tm; try { String[] parameterTypes = iMethod.getParameterTypes(); for (String s : parameterTypes) { if (s.contains("java")) // $NON-NLS-1$ { continue; } String returnType = s; if (returnType.startsWith("Q") && returnType.endsWith(";")) { // $NON-NLS-1$ //$NON-NLS-2$ IType ownerType = (IType) iMethod.getAncestor(IJavaElement.TYPE); String[][] resolveType = ownerType.resolveType(returnType.substring(1, returnType.length() - 1)); if (resolveType.length == 1) { IType findType = ownerType.getJavaProject().findType(resolveType[0][0] + '.' + resolveType[0][1]); if (findType != null && findType instanceof SourceType) { return new JDTType(findType); } } } } } catch (Exception e) { throw new IllegalStateException(e); } return null; }
private StringBuffer composeTypeReference(IType type) { StringBuffer buffer = new StringBuffer(); buffer.append(type.getJavaProject().getElementName()); buffer.append(PROJECT_END_CHAR); buffer.append(type.getFullyQualifiedName()); return buffer; }
protected void handleSelectServiceButton(Text text) { PortalServiceSearchScope scope = new PortalServiceSearchScope(); scope.setResourcePattern(new String[] {".*Service.class$"}); // $NON-NLS-1$ IProject project = ProjectUtil.getProject(model); ILiferayProject liferayProject = LiferayCore.create(project); IPath serviceJarPath = liferayProject.getLibraryPath("portal-service"); scope.setEnclosingJarPaths(new IPath[] {serviceJarPath}); FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialogEx( getShell(), false, null, scope, IJavaSearchConstants.INTERFACE); dialog.setTitle(J2EEUIMessages.SUPERCLASS_SELECTION_DIALOG_TITLE); dialog.setMessage(J2EEUIMessages.SUPERCLASS_SELECTION_DIALOG_DESC); if (dialog.open() == Window.OK) { IType type = (IType) dialog.getFirstResult(); String classFullPath = J2EEUIMessages.EMPTY_STRING; if (type != null) { classFullPath = type.getFullyQualifiedName(); } text.setText(classFullPath); } }
public void testFinderOfNonPublicSubclass() throws Exception { IPath projectPath = createGenericProject(); IPath root = projectPath.append("src"); env.addGroovyClass( root, "p2", "Hello", "package p2;\n" + "class Hello extends Tester {\n" + "}\n"); env.addGroovyClass( root, "p2", "Tester", "package p2;\n" + "import junit.framework.TestCase\n" + "abstract class Tester extends TestCase {\n" + "}\n"); incrementalBuild(projectPath); expectingNoProblems(); IFile file = getFile(projectPath, "src/p2/Hello.groovy"); ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file); IType type = unit.getType("Hello"); assertTrue("Groovy type Hello should exist.", type.exists()); assertTrue( "Groovy type Hello should be a test suite (even though it is non-public)", new JUnit4TestFinder().isTest(type)); file = getFile(projectPath, "src/p2/Tester.groovy"); unit = JavaCore.createCompilationUnitFrom(file); type = unit.getType("Tester"); assertTrue("Groovy type Tester should exist.", type.exists()); assertFalse( "Groovy type Tester should not be a test suite (it is abstract)", new JUnit4TestFinder().isTest(type)); }
/** @since 2.8 */ protected void convertChangedType( URI topLevelUri, IType type, List<IResourceDescription.Delta> result) { TypeResourceDescription newDescription = createTypeResourceDescription(topLevelUri, type.getFullyQualifiedName()); IResourceDescription oldDescription = createTypeResourceDescription(newDescription.getURI(), type.getFullyQualifiedName()); result.add(createStructureChangeDelta(type, oldDescription, newDescription)); }
private static boolean typeNameExistsInEnclosingTypeChain(IType type, String typeName) { IType enclosing = type.getDeclaringType(); while (enclosing != null) { if (enclosing.getElementName().equals(typeName)) return true; enclosing = enclosing.getDeclaringType(); } return false; }
private IField getFieldInWorkingCopy( ICompilationUnit newWorkingCopyOfDeclaringCu, String elementName) { IType type = fField.getDeclaringType(); IType typeWc = (IType) JavaModelUtil.findInCompilationUnit(newWorkingCopyOfDeclaringCu, type); if (typeWc == null) return null; return typeWc.getField(elementName); }