private static void populateClasses( final Shell shell, final IParent parent, final List<IType> types, final Filter filter) { try { for (final IJavaElement element : parent.getChildren()) { if (element instanceof IType) { final IType type = (IType) element; if (type.isClass() && type.isStructureKnown() && !type.isAnonymous() && !type.isLocal() && !Flags.isAbstract(type.getFlags()) && Flags.isPublic(type.getFlags()) && (filter == null || filter.accept(type))) { types.add(type); } } else if (element instanceof IParent && !element.getPath().toString().contains("/test/") && (!(element instanceof IPackageFragmentRoot) || !((IPackageFragmentRoot) element).isExternal())) { populateClasses(shell, (IParent) element, types, filter); } } } catch (final JavaModelException e) { Activator.error(e); } }
/* * @see TypeHierarchyContentProvider.getTypesInHierarchy */ @Override protected final void getTypesInHierarchy(IType type, List<IType> res) { ITypeHierarchy hierarchy = getHierarchy(); if (hierarchy != null) { IType[] types = hierarchy.getSubtypes(type); if (isObject(type)) { for (int i = 0; i < types.length; i++) { IType curr = types[i]; if (!isAnonymousFromInterface( curr)) { // no anonymous classes on 'Object' -> will be children of interface res.add(curr); } } } else { boolean isHierarchyOnType = (hierarchy.getType() != null); boolean isClass = !Flags.isInterface(hierarchy.getCachedFlags(type)); if (isClass || isHierarchyOnType) { for (int i = 0; i < types.length; i++) { res.add(types[i]); } } else { for (int i = 0; i < types.length; i++) { IType curr = types[i]; // no classes implementing interfaces, only if anonymous if (Flags.isInterface(hierarchy.getCachedFlags(curr)) || isAnonymous(curr)) { res.add(curr); } } } } } }
private boolean isVisible(TypeNameMatch curr, ICompilationUnit cu) { int flags = curr.getModifiers(); if (Flags.isPrivate(flags)) { return false; } if (Flags.isPublic(flags) || Flags.isProtected(flags)) { return true; } return curr.getPackageName().equals(cu.getParent().getElementName()); }
private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) { int flags = curr.getModifiers(); if (Flags.isAnnotation(flags)) { return is50OrHigher && ((typeKinds & SimilarElementsRequestor.ANNOTATIONS) != 0); } if (Flags.isEnum(flags)) { return is50OrHigher && ((typeKinds & SimilarElementsRequestor.ENUMS) != 0); } if (Flags.isInterface(flags)) { return (typeKinds & SimilarElementsRequestor.INTERFACES) != 0; } return (typeKinds & SimilarElementsRequestor.CLASSES) != 0; }
public void testCustomPreferences() throws Exception { DiaGenSource s = createLibraryGen(false); final GenDiagram gd = s.getGenDiagram(); GenCustomPreferencePage pp = GMFGenFactory.eINSTANCE.createGenCustomPreferencePage(); if (gd.getPreferencePages().isEmpty()) { gd.getPreferencePages().add(pp); } else { gd.getPreferencePages().get(0).getChildren().add(pp); } pp.setGenerateBoilerplate(true); pp.setName("Page Name"); pp.setQualifiedClassName( gd.getEditorGen().getEditor().getPackageName() + ".CustomPreferencePage"); GenPreference p1 = GMFGenFactory.eINSTANCE.createGenPreference(); p1.setName("PREF_XXX_ONE"); p1.setDefaultValue("\"XXX_ONE_DEFAULT\""); GenPreference p2 = GMFGenFactory.eINSTANCE.createGenPreference(); p2.setName("NO_PREFIX_XXX_TWO"); p2.setKey("KEY.XXX.TWO"); pp.getPreferences().add(p1); pp.getPreferences().add(p2); // generateAndCompile(s); // IProject generatedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(gd.getEditorGen().getPlugin().getID()); IFile file_pp = generatedProject.getFile("/src/" + pp.getQualifiedClassName().replace('.', '/') + ".java"); assertTrue(file_pp.exists()); ICompilationUnit cuPage = (ICompilationUnit) JavaCore.create(file_pp); assertNotNull(cuPage); IType mainClass = cuPage.getTypes()[0]; assertNotNull(mainClass); assertEquals(2, mainClass.getFields().length); final IField p1field = mainClass.getField(p1.getName()); final IField p2field = mainClass.getField(p2.getName()); assertTrue(Flags.isPublic(p1field.getFlags())); assertTrue(Flags.isStatic(p1field.getFlags())); assertTrue(Flags.isPublic(p2field.getFlags())); assertTrue(Flags.isStatic(p2field.getFlags())); assertEquals('"' + p1.getKey() + '"', p1field.getConstant()); assertEquals('"' + p2.getKey() + '"', p2field.getConstant()); IMethod initMethod = mainClass.getMethod( "initDefaults", new String[] {"Q" + IPreferenceStore.class.getSimpleName() + ";"}); assertNotNull(initMethod); String methodText = initMethod.getSource(); assertTrue(methodText.indexOf(p1.getName()) != -1); assertTrue(methodText.indexOf(p1.getDefaultValue()) != -1); assertTrue(methodText.indexOf(p2.getName()) == -1); }
/* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyContentProvider#getRootTypes(java.util.List) */ @Override protected final void getRootTypes(List<IType> res) { ITypeHierarchy hierarchy = getHierarchy(); if (hierarchy != null) { IType input = hierarchy.getType(); if (input == null) { IType[] classes = hierarchy.getRootClasses(); for (int i = 0; i < classes.length; i++) { res.add(classes[i]); } IType[] interfaces = hierarchy.getRootInterfaces(); for (int i = 0; i < interfaces.length; i++) { res.add(interfaces[i]); } } else { if (Flags.isInterface(hierarchy.getCachedFlags(input))) { res.add(input); } else if (isAnonymousFromInterface(input)) { res.add(hierarchy.getSuperInterfaces(input)[0]); } else { IType[] roots = hierarchy.getRootClasses(); for (int i = 0; i < roots.length; i++) { if (isObject(roots[i])) { res.add(roots[i]); return; } } res.addAll(Arrays.asList(roots)); // something wrong with the hierarchy } } } }
/** * 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; }
@Override public boolean isPublic() { try { return Flags.isPublic(((IMember) tm).getFlags()); } catch (JavaModelException e) { return false; } }
@Override public Change createChange(IProgressMonitor monitor) throws CoreException { try { final TextChange[] changes = fChangeManager.getAllChanges(); final List<TextChange> list = new ArrayList<>(changes.length); list.addAll(Arrays.asList(changes)); String project = null; IJavaProject javaProject = fMethod.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE; try { if (!Flags.isPrivate(fMethod.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final IType declaring = fMethod.getDeclaringType(); try { if (declaring.isAnonymous() || declaring.isLocal()) flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final String description = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fMethod.getElementName())); final String header = Messages.format( RefactoringCoreMessages.RenameMethodProcessor_descriptor_description, new String[] { JavaElementLabels.getTextLabel(fMethod, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(getNewElementName()) }); final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString(); final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor( IJavaRefactorings.RENAME_METHOD); descriptor.setProject(project); descriptor.setDescription(description); descriptor.setComment(comment); descriptor.setFlags(flags); descriptor.setJavaElement(fMethod); descriptor.setNewName(getNewElementName()); descriptor.setUpdateReferences(fUpdateReferences); descriptor.setKeepOriginal(fDelegateUpdating); descriptor.setDeprecateDelegate(fDelegateDeprecation); return new DynamicValidationRefactoringChange( descriptor, RefactoringCoreMessages.RenameMethodProcessor_change_name, list.toArray(new Change[list.size()])); } finally { monitor.done(); } }
/** * Overridden by subclasses. * * @return return the refactoring descriptor for this refactoring */ protected RenameJavaElementDescriptor createRefactoringDescriptor() { String project = null; IJavaProject javaProject = fField.getJavaProject(); if (javaProject != null) project = javaProject.getElementName(); int flags = JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE; try { if (!Flags.isPrivate(fField.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final IType declaring = fField.getDeclaringType(); try { if (declaring.isAnonymous() || declaring.isLocal()) flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT; } catch (JavaModelException exception) { JavaPlugin.log(exception); } final String description = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fField.getElementName())); final String header = Messages.format( RefactoringCoreMessages.RenameFieldProcessor_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), JavaElementLabels.getElementLabel( fField.getParent(), JavaElementLabels.ALL_FULLY_QUALIFIED), getNewElementName() }); final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header); if (fRenameGetter) comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_getter); if (fRenameSetter) comment.addSetting(RefactoringCoreMessages.RenameFieldRefactoring_setting_rename_settter); final RenameJavaElementDescriptor descriptor = RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor( IJavaRefactorings.RENAME_FIELD); descriptor.setProject(project); descriptor.setDescription(description); descriptor.setComment(comment.asString()); descriptor.setFlags(flags); descriptor.setJavaElement(fField); descriptor.setNewName(getNewElementName()); descriptor.setUpdateReferences(fUpdateReferences); descriptor.setUpdateTextualOccurrences(fUpdateTextualMatches); descriptor.setRenameGetters(fRenameGetter); descriptor.setRenameSetters(fRenameSetter); descriptor.setKeepOriginal(fDelegateUpdating); descriptor.setDeprecateDelegate(fDelegateDeprecation); return descriptor; }
/** * We don't include nested types because structural changes of nested types should not affect * Xtend classes which use top level types. * * @deprecated This method is not used anymore. */ @Deprecated protected void traverseType(IType type, NameBasedEObjectDescriptionBuilder acceptor) { try { if (type.exists()) { for (IField field : type.getFields()) { if (!Flags.isSynthetic(field.getFlags())) { String fieldName = field.getElementName(); acceptor.accept(fieldName); } } for (IMethod method : type.getMethods()) { if (!Flags.isSynthetic(method.getFlags())) { String methodName = method.getElementName(); acceptor.accept(methodName); } } } } catch (JavaModelException e) { if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e); } }
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; }
/** * Method to post process returned flags from the {@link * org.eclipse.pde.api.tools.internal.JavadocTagManager} * * @param tag the tag to process * @param element the {@link IJavaElement} the tag will appear on * @return true if the tag should be included in completion proposals, false otherwise */ private boolean acceptTag(IApiJavadocTag tag, IJavaElement element) throws JavaModelException { if (fExistingTags != null) { Boolean fragments = fExistingTags.get(tag.getTagName()); // if the tag has a fragment don't overwrite / propose again if (fragments != null && Boolean.FALSE.equals(fragments)) { return false; } } switch (element.getElementType()) { case IJavaElement.TYPE: { IType type = (IType) element; int flags = type.getFlags(); String tagname = tag.getTagName(); if (Flags.isAbstract(flags)) { return !tagname.equals(JavadocTagManager.TAG_NOINSTANTIATE); } if (Flags.isFinal(flags)) { return !tagname.equals(JavadocTagManager.TAG_NOEXTEND); } break; } case IJavaElement.METHOD: { IMethod method = (IMethod) element; if (Flags.isFinal(method.getFlags()) || Flags.isStatic(method.getFlags())) { return !tag.getTagName().equals(JavadocTagManager.TAG_NOOVERRIDE); } IType type = method.getDeclaringType(); if (type != null && Flags.isFinal(type.getFlags())) { return !tag.getTagName().equals(JavadocTagManager.TAG_NOOVERRIDE); } break; } default: break; } return true; }
/** * This method asks the specified <code>IType</code> if it has a main method, if not it recurses * through all of its children When recursing we only care about child <code>IType</code>s that * are static. * * @param type the <code>IType</code> to inspect for a main method * @return true if a main method was found in specified <code>IType</code>, false otherwise * @throws CoreException * @since 3.3 */ private boolean hasMainInChildren(IType type) throws CoreException { if (type.isClass() & Flags.isStatic(type.getFlags())) { if (hasMainMethod(type)) { return true; } else { IJavaElement[] children = type.getChildren(); for (int i = 0; i < children.length; i++) { if (children[i].getElementType() == IJavaElement.TYPE) { return hasMainInChildren((IType) children[i]); } } } } return false; }
protected void setUp() throws Exception { super.setUp(); fProject = new SWTTestProject(); IType control = fProject.getProject().findType("org.eclipse.swt.widgets.Control"); ExtractInterfaceProcessor processor = new ExtractInterfaceProcessor( control, JavaPreferencesSettings.getCodeGenerationSettings(fProject.getProject())); fRefactoring = new ProcessorBasedRefactoring(processor); IMethod[] methods = control.getMethods(); List extractedMembers = new ArrayList(); for (int i = 0; i < methods.length; i++) { IMethod method = methods[i]; int flags = method.getFlags(); if (Flags.isPublic(flags) && !Flags.isStatic(flags) && !method.isConstructor()) { extractedMembers.add(method); } } processor.setTypeName("IControl"); processor.setExtractedMembers( (IMember[]) extractedMembers.toArray(new IMember[extractedMembers.size()])); processor.setReplace(true); }
/** * @since 2.3 * @deprecated This method is not used anymore. */ @Deprecated protected IType getPrimaryTypeFrom(ICompilationUnit cu) { try { if (cu.exists()) { IType primaryType = cu.findPrimaryType(); if (primaryType != null) return primaryType; // if no exact match is found, return the first public type in CU (if any) for (IType type : cu.getTypes()) { if (Flags.isPublic(type.getFlags())) return type; } } } catch (JavaModelException e) { if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e); } return null; }
/** * Returns if the given {@link IJavaElement} is externally visible <br> * <br> * Changes to the logic here must also be made in the {@link TagValidator} to ensure the * visibility is computed equally. * * @see TagValidator * @param element * @return <code>true</code> if the given element is visible <code>false</code> otherwise * @throws JavaModelException if a model lookup fails */ boolean isVisible(IJavaElement element) throws JavaModelException { if (element != null) { switch (element.getElementType()) { case IJavaElement.FIELD: case IJavaElement.METHOD: { IMember member = (IMember) element; int flags = member.getFlags(); IType type = member.getDeclaringType(); if (Flags.isPublic(flags) || Flags.isProtected(flags) || (type != null && type.isInterface())) { return isVisible(type); } break; } case IJavaElement.TYPE: { IType type = (IType) element; int flags = type.getFlags(); if (type.isLocal() && !type.isAnonymous() || Flags.isPrivate(flags)) { return false; } if (type.isMember()) { if ((Flags.isPublic(flags) && Flags.isStatic(flags)) || Flags.isPublic(flags) || Flags.isProtected(flags) || type.isInterface()) { return isVisible(type.getDeclaringType()); } } else { return Flags.isPublic(flags) || type.isInterface(); } break; } default: { break; } } } return false; }
private void checkOverridden(RefactoringStatus status, IProgressMonitor pm) throws JavaModelException { pm.beginTask("", 9); // $NON-NLS-1$ pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden); MethodDeclaration decl = fSourceProvider.getDeclaration(); IMethod method = (IMethod) decl.resolveBinding().getJavaElement(); if (method == null || Flags.isPrivate(method.getFlags())) { pm.worked(8); return; } IType type = method.getDeclaringType(); ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6)); checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1)); checkSuperClasses( status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1)); checkSuperInterfaces( status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1)); pm.setTaskName(""); // $NON-NLS-1$ }
/** * Finds a method declaration in a type's hierarchy. The search is top down, so this returns the * first declaration of the method in the hierarchy. This searches for a method with a name and * signature. Parameter types are only compared by the simple name, no resolving for the fully * qualified type name is done. Constructors are only compared by parameters, not the name. * * @param type Searches in this type's supertypes. * @param name The name of the method to find * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> * @param isConstructor If the method is a constructor * @return The first method found or null, if nothing found */ private static IMethod findMethodDeclarationInHierarchy( ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { IType[] superTypes = hierarchy.getAllSupertypes(type); for (int i = superTypes.length - 1; i >= 0; i--) { IMethod first = JavaModelUtil.findMethod(name, paramTypes, isConstructor, superTypes[i]); if (first != null && !Flags.isPrivate(first.getFlags())) { // the order getAllSupertypes does make assumptions of the order of inner elements -> search // recursively IMethod res = findMethodDeclarationInHierarchy( hierarchy, first.getDeclaringType(), name, paramTypes, isConstructor); if (res != null) { return res; } return first; } } return null; }
private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException { buf.append(meth.getElementName()); /* * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs. * This breaks all clients that directly create such URLs. * We can't know what format is required, so we just guess by the project's compiler compliance. */ boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject()); buf.append(is18OrHigher ? '-' : '('); String[] params = meth.getParameterTypes(); IType declaringType = meth.getDeclaringType(); boolean isVararg = Flags.isVarargs(meth.getFlags()); int lastParam = params.length - 1; for (int i = 0; i <= lastParam; i++) { if (i != 0) { buf.append(is18OrHigher ? "-" : ", "); // $NON-NLS-1$ //$NON-NLS-2$ } String curr = Signature.getTypeErasure(params[i]); String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType); if (fullName == null) { // e.g. a type parameter "QE;" fullName = Signature.toString(Signature.getElementType(curr)); } if (fullName != null) { buf.append(fullName); int dim = Signature.getArrayCount(curr); if (i == lastParam && isVararg) { dim--; } while (dim > 0) { buf.append(is18OrHigher ? ":A" : "[]"); // $NON-NLS-1$ //$NON-NLS-2$ dim--; } if (i == lastParam && isVararg) { buf.append("..."); // $NON-NLS-1$ } } } buf.append(is18OrHigher ? '-' : ')'); }
/** * Method to post process returned flags from the {@link Javadoc} node of the element * * @param tags the tags to process * @param element the {@link ASTNode} the tag appears on * @return the list of valid tags to process restrictions for */ private List pruneTags(final List tags, ASTNode node) { ArrayList pruned = new ArrayList(tags.size()); TagElement tag = null; switch (node.getNodeType()) { case ASTNode.TYPE_DECLARATION: { TypeDeclaration type = (TypeDeclaration) node; int flags = type.getModifiers(); for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) { tag = (TagElement) iterator.next(); String tagname = tag.getTagName(); if (type.isInterface() && ("@noextend".equals(tagname) || //$NON-NLS-1$ "@noimplement".equals(tagname))) { // $NON-NLS-1$ pruned.add(tag); } else { if ("@noextend".equals(tagname)) { // $NON-NLS-1$ if (!Flags.isFinal(flags)) { pruned.add(tag); continue; } } if ("@noinstantiate".equals(tagname)) { // $NON-NLS-1$ if (!Flags.isAbstract(flags)) { pruned.add(tag); continue; } } } } break; } case ASTNode.METHOD_DECLARATION: { MethodDeclaration method = (MethodDeclaration) node; int flags = method.getModifiers(); for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) { tag = (TagElement) iterator.next(); if ("@noreference".equals(tag.getTagName())) { // $NON-NLS-1$ pruned.add(tag); continue; } if ("@nooverride".equals(tag.getTagName())) { // $NON-NLS-1$ ASTNode parent = method.getParent(); int pflags = 0; if (parent instanceof BodyDeclaration) { pflags = ((BodyDeclaration) parent).getModifiers(); } if (!Flags.isFinal(flags) && !Flags.isStatic(flags) && !Flags.isFinal(pflags)) { pruned.add(tag); continue; } } } break; } case ASTNode.FIELD_DECLARATION: { FieldDeclaration field = (FieldDeclaration) node; for (Iterator iterator = tags.iterator(); iterator.hasNext(); ) { tag = (TagElement) iterator.next(); boolean isfinal = Flags.isFinal(field.getModifiers()); if (isfinal || (isfinal && Flags.isStatic(field.getModifiers()))) { break; } if ("@noreference".equals(tag.getTagName())) { // $NON-NLS-1$ pruned.add(tag); break; } } break; } } return pruned; }
private boolean isCacheableRHS(IType type) throws JavaModelException { return !type.isInterface() && !Flags.isAbstract(type.getFlags()); }
/** * Determines whether the given member is a valid android.view.View to be added to the list of * custom views or third party views. It checks that the view is public and not abstract for * example. */ private static boolean isValidView(IType type, boolean layoutsOnly) throws JavaModelException { // Skip anonymous classes if (type.isAnonymous()) { return false; } int flags = type.getFlags(); if (Flags.isAbstract(flags) || !Flags.isPublic(flags)) { return false; } // TODO: if (layoutsOnly) perhaps try to filter out AdapterViews and other ViewGroups // not willing to accept children via XML // See if the class has one of the acceptable constructors // needed for XML instantiation: // View(Context context) // View(Context context, AttributeSet attrs) // View(Context context, AttributeSet attrs, int defStyle) // We don't simply do three direct checks via type.getMethod() because the types // are not resolved, so we don't know for each parameter if we will get the // fully qualified or the unqualified class names. // Instead, iterate over the methods and look for a match. String typeName = type.getElementName(); for (IMethod method : type.getMethods()) { // Only care about constructors if (!method.getElementName().equals(typeName)) { continue; } String[] parameterTypes = method.getParameterTypes(); if (parameterTypes == null || parameterTypes.length < 1 || parameterTypes.length > 3) { continue; } String first = parameterTypes[0]; // Look for the parameter type signatures -- produced by // JDT's Signature.createTypeSignature("Context", false /*isResolved*/);. // This is not a typo; they were copy/pasted from the actual parameter names // observed in the debugger examining these data structures. if (first.equals("QContext;") // $NON-NLS-1$ || first.equals("Qandroid.content.Context;")) { // $NON-NLS-1$ if (parameterTypes.length == 1) { return true; } String second = parameterTypes[1]; if (second.equals("QAttributeSet;") // $NON-NLS-1$ || second.equals("Qandroid.util.AttributeSet;")) { // $NON-NLS-1$ if (parameterTypes.length == 2) { return true; } String third = parameterTypes[2]; if (third.equals("I")) { // $NON-NLS-1$ if (parameterTypes.length == 3) { return true; } } } } } return false; }
/** * @param insideTagBody * @param tagBody * @param templateTag * @param contextMap * @param placeHolders * @param spacesBeforeCursor * @param overrideMethods * @param exist * @param overWrite * @param type * @throws JavaModelException * @throws Exception */ public void createClassFromTag( final String className, final Object packge, final Object project, String insideTagBody, final Map<String, Object> contextMap, final Map<String, Object> placeHolders, final ICompilationUnit compUnit, final String typeToCreate, final String spacesBeforeCursor, boolean overrideMethods, final boolean exist, final boolean overWrite) throws JavaModelException, Exception { final VersionControlPreferences versionControlPreferences = VersionControlPreferences.getInstance(); if (typeToCreate.equals(ACTION_ENTITY.Innerclass.getValue())) { compUnit.becomeWorkingCopy(null); final File newFileObj = new File(compUnit.getResource().getLocationURI().toString()); /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));*/ try { // addOrUpdateFileStatusInCache(newFileObj); final IType innerClassType = SourceUtil.createInnerClass(insideTagBody, compUnit); /*final boolean prjShared = !isEmpty(compUnit.getResource().getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(compUnit.getResource().getProject().getName()));*/ if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(newFileObj, compUnit.getResource().getProject())) { final IFile file = (IFile) innerClassType.getResource(); // .getLocationURI()); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .get(file); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); final List<Object> innerClassList = new ArrayList<Object>(); innerClassList.add(new FastCodeType(innerClassType)); chngsForType.add(new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, innerClassList)); } else { boolean isNew = true; Object fastCodeFieldList = null; for (final FastCodeEntityHolder fcEntityHolder : chngsForType) { if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_INNERCLASSES)) { fastCodeFieldList = fcEntityHolder.getFastCodeEntity(); isNew = false; break; } } if (isNew) { fastCodeFieldList = new ArrayList<Object>(); ((List<Object>) fastCodeFieldList).add(innerClassType); chngsForType.add( new FastCodeEntityHolder(PLACEHOLDER_INNERCLASSES, fastCodeFieldList)); } else { ((List<Object>) fastCodeFieldList).add(innerClassType); } /*Object innerClassList = chngsForType.get("innerClasses"); if (innerClassList == null) { innerClassList = new ArrayList<Object>(); } ((List<Object>) innerClassList).add(new FastCodeType(innerClassType)); chngsForType.put("innerClasses", innerClassList);*/ } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(file, chngsForType); } } } catch (final FastCodeRepositoryException ex) { ex.printStackTrace(); } compUnit.commitWorkingCopy(false, null); compUnit.discardWorkingCopy(); return; } final IJavaProject prj = project instanceof String ? getJavaProject((String) project) : (IJavaProject) project; /*IJavaProject prj = getJavaProject(project);// getJavaProject(attributes.get(PLACEHOLDER_PROJECT)); if (prj == null) { prj = getJavaProject(placeHolders.get(PLACEHOLDER_PROJECT) instanceof FastCodeProject ? ((FastCodeProject) placeHolders .get(PLACEHOLDER_PROJECT)).getName() : (String) placeHolders.get(PLACEHOLDER_PROJECT)); } if (prj == null) { prj = this.javaProject = this.javaProject == null ? getWorkingJavaProjectFromUser() : this.javaProject;//did for j2ee base }*/ if (prj == null) { throw new Exception("Can not continue without java project."); } final String srcPath = typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? getDefaultPathFromProject(prj, typeToCreate, EMPTY_STR) : getDefaultPathFromProject(prj, "source", EMPTY_STR); IPackageFragment pkgFrgmt = null; final TemplateTagsProcessor templateTagsProcessor = new TemplateTagsProcessor(); if (packge instanceof String && !isEmpty((String) packge) || packge instanceof IPackageFragment) { pkgFrgmt = packge instanceof String ? templateTagsProcessor.getPackageFragment( prj, srcPath, (String) packge, typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? typeToCreate : "source") : (IPackageFragment) packge; } if (pkgFrgmt == null) { /*final boolean prjShared = !isEmpty(prj.getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(prj.getProject().getName()));*/ File file = null; if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(file, prj.getProject())) { final String prjURI = prj.getResource().getLocationURI().toString(); final String path = prjURI.substring(prjURI.indexOf(COLON) + 1); final String newPackURL = path + srcPath + FILE_SEPARATOR + ((String) packge).replace(DOT, FILE_SEPARATOR); file = new File(newPackURL); // final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); addOrUpdateFileStatusInCache(file); // checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, // file.getAbsolutePath())); } } pkgFrgmt = templateTagsProcessor.createPackage( prj, (String) packge, typeToCreate, contextMap); // createPackage(prj, // attributes.get(PLACEHOLDER_PACKAGE)); if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { if (proceedWithAutoCheckin(null, prj.getProject())) { final IFile ifile = getIFileFromFile(file); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(ifile); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); chngsForType.add( new FastCodeEntityHolder(PLACEHOLDER_PACKAGE, new FastCodePackage(pkgFrgmt))); } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(ifile, chngsForType); } } } boolean createFileAlone = true; if ((Boolean) placeHolders.get(AUTO_CHECKIN)) { String path; try { final boolean prjShared = !isEmpty(pkgFrgmt.getResource().getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty(isPrjConfigured(pkgFrgmt.getResource().getProject().getName())); createFileAlone = !(versionControlPreferences.isEnable() && prjShared && prjConfigured); final String prjURI = pkgFrgmt.getResource().getLocationURI().toString(); path = prjURI.substring(prjURI.indexOf(COLON) + 1); final File newFileObj = new File(path + FORWARD_SLASH + className + DOT + JAVA_EXTENSION); if (versionControlPreferences.isEnable() && prjShared && prjConfigured) { final RepositoryService repositoryService = getRepositoryServiceClass(); try { if (repositoryService.isFileInRepository( newFileObj)) { // && !MessageDialog.openQuestion(new Shell(), "File present in // repository", "File already present in repository. Click yes to // overwrite")) { /*MessageDialog.openWarning(new Shell(), "File present in repository", className + " is already present in repository. Please synchronise and try again."); return;*/ createFileAlone = MessageDialog.openQuestion( new Shell(), "File present in repository", "File " + newFileObj.getName() + " already present in repository. Click yes to just create the file, No to return without any action."); if (!createFileAlone) { return; } } } catch (final Throwable th) { th.printStackTrace(); createFileAlone = true; } } final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache .getFilesToCheckIn() .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath())); } catch (final FastCodeRepositoryException ex) { ex.printStackTrace(); } } /*if (parseClassName(insideTagBody) == null) { insideTagBody = MODIFIER_PUBLIC + SPACE + typeToCreate + SPACE + className + SPACE + LEFT_CURL + NEWLINE + insideTagBody + NEWLINE + RIGHT_CURL; }*/ final Object codeFormatter = createCodeFormatter(prj.getProject()); if (!isEmpty(insideTagBody)) { insideTagBody = formatCode(insideTagBody.trim(), codeFormatter); } ICompilationUnit compilationUnit = null; if (exist) { if (overWrite) { final IType type = prj.findType(pkgFrgmt.getElementName() + DOT + className.trim()); if (type.getCompilationUnit().hasUnsavedChanges()) { type.getCompilationUnit().save(new NullProgressMonitor(), true); } // type.getCompilationUnit().delete(true, new NullProgressMonitor()); insideTagBody = buildClass(insideTagBody, pkgFrgmt, prj, className); // type.getCompilationUnit().getBuffer().setContents(insideTagBody); final ReplaceEdit replaceEdit = new ReplaceEdit(0, type.getCompilationUnit().getSource().length(), insideTagBody); type.getCompilationUnit().applyTextEdit(replaceEdit, new NullProgressMonitor()); compilationUnit = type.getCompilationUnit(); compilationUnit.becomeWorkingCopy(null); compilationUnit.commitWorkingCopy(false, null); compilationUnit.discardWorkingCopy(); // refreshProject(prj.getElementName()); } else { return; } } else { compilationUnit = SourceUtil.createClass(insideTagBody, pkgFrgmt, prj, className); } if (compilationUnit == null) { return; } if (!typeToCreate.equals(ACTION_ENTITY.Interface.getValue())) { if (compilationUnit.findPrimaryType().getSuperclassName() != null) { final IType superClassType = prj.findType( getFQNameFromFieldTypeName( compilationUnit.findPrimaryType().getSuperclassName(), compilationUnit)); if (superClassType != null && superClassType.exists()) { if (Flags.isAbstract( superClassType .getFlags()) /*Modifier.isAbstract(Class.forName(superClassType.getFullyQualifiedName()).getModifiers())*/) { overrideMethods = true; } } } if (overrideMethods) { final String superInterfaces[] = compilationUnit.findPrimaryType().getSuperInterfaceNames(); if (superInterfaces != null) { for (final String superInertafce : superInterfaces) { final IType superIntType = prj.findType(getFQNameFromFieldTypeName(superInertafce, compilationUnit)); final FastCodeContext fastCodeContext = new FastCodeContext(superIntType); final CreateSimilarDescriptorClass createSimilarDescriptorClass = new CreateSimilarDescriptorClass.Builder().withClassType(CLASS_TYPE.CLASS).build(); implementInterfaceMethods( superIntType, fastCodeContext, compilationUnit.findPrimaryType(), null, createSimilarDescriptorClass); final IType[] superInterfaceType = getSuperInterfacesType(superIntType); if (superInterfaceType != null) { for (final IType type : superInterfaceType) { if (type == null || !type.exists()) { continue; } final FastCodeContext context = new FastCodeContext(type); implementInterfaceMethods( type, context, compilationUnit.findPrimaryType(), null, createSimilarDescriptorClass); } } } } overrideBaseClassMethods(compilationUnit); } } /* * final IType newType = compilationUnit.findPrimaryType(); String * superClassName = newType.getSuperclassName(); if * (!isEmpty(superClassName)) { final IType superClassType = * prj.findType(getFQNameFromFieldTypeName(newType.getSuperclassName(), * newType.getCompilationUnit())); final FastCodeContext fastCodeContext * = new FastCodeContext(superClassType); final * CreateSimilarDescriptorClass createSimilarDescriptorClass = new * CreateSimilarDescriptorClass.Builder().withClassType( * CLASS_TYPE.CLASS).build(); for (final IMethod method : * superClassType.getMethods()) { if (method.isConstructor()) { * overrideConstructor(method, newType); final MethodBuilder * methodBuilder = new SimilarMethodBuilder(fastCodeContext); * methodBuilder.buildMethod(method, newType, null, * createSimilarDescriptorClass); } } } */ contextMap.put( "Class_" + compilationUnit.getElementName(), new FastCodeObject(compilationUnit, ACTION_ENTITY.Class.getValue())); if (!createFileAlone) { final IFile fileObj = (IFile) compilationUnit.findPrimaryType().getResource(); // .getLocationURI()); List<FastCodeEntityHolder> chngsForType = ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)).get(fileObj); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); chngsForType.add( new FastCodeEntityHolder( PLACEHOLDER_CLASS, new FastCodeType(compilationUnit.findPrimaryType()))); } ((Map<Object, List<FastCodeEntityHolder>>) contextMap.get(FC_OBJ_CREATED)) .put(fileObj, chngsForType); } /*final Map<String, Object> listofChange = ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).get(file); if (chngsForType == null) { chngsForType = new HashMap<String, Object>(); chngsForType.put("class", CREATE_CLASS); //fastCodeCache.getCommentKey().get(fastCodeCache.getCommentKey().indexOf("create.class.field")) } ((Map<Object, Map<String, Object>>) contextMap.get("changes_for_File")).put(file, listofChange);*/ }
/** * @see * org.eclipse.jdt.internal.core.search.matching.PatternLocator#matchReportReference(org.eclipse.jdt.internal.compiler.ast.ASTNode, * org.eclipse.jdt.core.IJavaElement, Binding, int, * org.eclipse.jdt.internal.core.search.matching.MatchLocator) */ protected void matchReportReference( ASTNode reference, IJavaElement element, IJavaElement localElement, IJavaElement[] otherElements, Binding elementBinding, int accuracy, MatchLocator locator) throws CoreException { MethodBinding methodBinding = (reference instanceof MessageSend) ? ((MessageSend) reference).binding : ((elementBinding instanceof MethodBinding) ? (MethodBinding) elementBinding : null); if (this.isDeclarationOfReferencedMethodsPattern) { if (methodBinding == null) return; // need exact match to be able to open on type ref if (accuracy != SearchMatch.A_ACCURATE) return; // element that references the method must be included in the enclosing element DeclarationOfReferencedMethodsPattern declPattern = (DeclarationOfReferencedMethodsPattern) this.pattern; while (element != null && !declPattern.enclosingElement.equals(element)) element = element.getParent(); if (element != null) { reportDeclaration(methodBinding, locator, declPattern.knownMethods); } } else { MethodReferenceMatch methodReferenceMatch = locator.newMethodReferenceMatch( element, elementBinding, accuracy, -1, -1, false /*not constructor*/, false /*not synthetic*/, reference); methodReferenceMatch.setLocalElement(localElement); this.match = methodReferenceMatch; if (this.pattern.findReferences && reference instanceof MessageSend) { IJavaElement focus = this.pattern.focus; // verify closest match if pattern was bound // (see bug 70827) if (focus != null && focus.getElementType() == IJavaElement.METHOD) { if (methodBinding != null && methodBinding.declaringClass != null) { boolean isPrivate = Flags.isPrivate(((IMethod) focus).getFlags()); if (isPrivate && !CharOperation.equals( methodBinding.declaringClass.sourceName, focus.getParent().getElementName().toCharArray())) { return; // finally the match was not possible } } } matchReportReference((MessageSend) reference, locator, ((MessageSend) reference).binding); } else { if (reference instanceof SingleMemberAnnotation) { reference = ((SingleMemberAnnotation) reference).memberValuePairs()[0]; this.match.setImplicit(true); } int offset = reference.sourceStart; int length = reference.sourceEnd - offset + 1; this.match.setOffset(offset); this.match.setLength(length); locator.report(this.match); } } }
private boolean isPrivate(int flags) { return Flags.isPrivate(flags); }
/* * (non-Javadoc) * @see * org.eclipse.pde.api.tools.internal.search.AbstractTypeLeakDetector#isProblem * (org.eclipse.pde.api.tools.internal.provisional.model.IReference) */ @Override public boolean isProblem(IReference reference) { if (super.isProblem(reference)) { // check the use restrictions on the API type (can be extended or // not) IApiType type = (IApiType) reference.getMember(); IApiComponent component = type.getApiComponent(); try { if (type.isClass()) { int modifiers = 0; IApiAnnotations annotations = component.getApiDescription().resolveAnnotations(type.getHandle()); if (annotations != null) { // if annotations are null, the reference should not // have been retained // as it indicates a reference from a top level non // public type if (RestrictionModifiers.isExtendRestriction(annotations.getRestrictions())) { // The no extend restriction means only public // members can be seen modifiers = Flags.AccPublic; } else { if (Flags.isFinal(type.getModifiers())) { // if final then only public members can be seen modifiers = Flags.AccPublic; } else { // public and protected members can be seen modifiers = Flags.AccPublic | Flags.AccProtected; } } IApiType nonApiSuper = type.getSuperclass(); // collect all visible methods in non-API types Set<MethodKey> methods = new HashSet<MethodKey>(); while (!isAPIType(nonApiSuper)) { if (hasVisibleField(nonApiSuper, modifiers)) { // a visible field in a non-API type is a // definite leak return true; } gatherVisibleMethods(nonApiSuper, methods, modifiers); nonApiSuper = nonApiSuper.getSuperclass(); } if (methods.size() > 0) { // check if the visible members are part of an API // interface/class List<IApiType> apiTypes = new LinkedList<IApiType>(); apiTypes.add(type); gatherAPISuperTypes(apiTypes, type); for (IApiType t2 : apiTypes) { Set<MethodKey> apiMembers = new HashSet<MethodKey>(); gatherVisibleMethods(t2, apiMembers, modifiers); methods.removeAll(apiMembers); if (methods.size() == 0) { // there are no visible methods left that // are not part of an API type/interface return false; } } if (methods.size() > 0) { // there are visible members that are not part // of an API type/interface return true; } } } } else { // don't process interfaces, enums, annotations return true; } } catch (CoreException ce) { if (ApiPlugin.DEBUG_PROBLEM_DETECTOR) { ApiPlugin.log(ce); } return true; } } return false; }
protected static final boolean isStatic(IMember member) throws JavaModelException { return Flags.isStatic(member.getFlags()); }
/** * Create a stub for a getter of the given field using getter/setter templates. The resulting code * has to be formatted and indented. * * @param field The field to create a getter for * @param getterName The chosen name for the getter * @param addComments If <code>true</code>, comments will be added. * @param flags The flags signaling visibility, if static, synchronized or final * @return Returns the generated stub. * @throws CoreException when stub creation failed */ public static String getGetterStub( IField field, String getterName, boolean addComments, int flags) throws CoreException { String fieldName = field.getElementName(); IType parentType = field.getDeclaringType(); boolean isStatic = Flags.isStatic(flags); boolean isSync = Flags.isSynchronized(flags); boolean isFinal = Flags.isFinal(flags); String typeName = Signature.toString(field.getTypeSignature()); String accessorName = StubUtility.getBaseName(field); String lineDelim = "\n"; // Use default line delimiter, as generated stub has to be formatted anyway // //$NON-NLS-1$ StringBuffer buf = new StringBuffer(); if (addComments) { String comment = CodeGeneration.getGetterComment( field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), getterName, field.getElementName(), typeName, accessorName, lineDelim); if (comment != null) { buf.append(comment); buf.append(lineDelim); } } buf.append(JdtFlags.getVisibilityString(flags)); buf.append(' '); if (isStatic) buf.append("static "); // $NON-NLS-1$ if (isSync) buf.append("synchronized "); // $NON-NLS-1$ if (isFinal) buf.append("final "); // $NON-NLS-1$ buf.append(typeName); buf.append(' '); buf.append(getterName); buf.append("() {"); // $NON-NLS-1$ buf.append(lineDelim); boolean useThis = StubUtility.useThisForFieldAccess(field.getJavaProject()); if (useThis && !isStatic) { fieldName = "this." + fieldName; // $NON-NLS-1$ } String body = CodeGeneration.getGetterMethodBodyContent( field.getCompilationUnit(), parentType.getTypeQualifiedName('.'), getterName, fieldName, lineDelim); if (body != null) { buf.append(body); } buf.append("}"); // $NON-NLS-1$ buf.append(lineDelim); return buf.toString(); }
private void extractIType(IType type) { try { String fqn = type.getFullyQualifiedName(); // Write the entity if (type.isClass()) { entityWriter.writeClass(fqn, type.getFlags(), path); // Write the superclass String superSig = type.getSuperclassTypeSignature(); if (superSig != null) { relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path); } } else if (type.isAnnotation()) { entityWriter.writeAnnotation(fqn, type.getFlags(), path); } else if (type.isInterface()) { entityWriter.writeInterface(fqn, type.getFlags(), path); } else if (type.isEnum()) { entityWriter.writeEnum(fqn, type.getFlags(), path); } // Write the superinterfaces for (String superIntSig : type.getSuperInterfaceTypeSignatures()) { relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path); } if (!fqnStack.isEmpty()) { relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path); } fqnStack.push(type.getFullyQualifiedName()); for (IType child : type.getTypes()) { extractIType(child); } for (IField field : type.getFields()) { if (!Flags.isSynthetic(field.getFlags())) { extractIField(field); } } for (IMethod method : type.getMethods()) { if (!Flags.isSynthetic(method.getFlags()) || (Flags.isSynthetic(method.getFlags()) && method.isConstructor() && method.getParameterTypes().length == 0)) { extractIMethod(method, type.isAnnotation()); } } int pos = 0; for (ITypeParameter param : type.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } fqnStack.pop(); } catch (Exception e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }