/** * @return an empty optional if the given package binding is not the top * package of a JtxtUML model; otherwise an optional of the name of * the model (the name is the name of the package if not specified) */ public static Optional<String> findModelNameInTopPackage(IPackageBinding packageBinding) { List<IAnnotationBinding> annots = Stream.of(packageBinding.getAnnotations()) .filter(a -> a.getAnnotationType().getQualifiedName().equals(Model.class.getCanonicalName())) .collect(Collectors.toList()); if (annots.size() == 1) { Optional<String> name = Stream.of(annots.get(0).getDeclaredMemberValuePairs()) .filter(p -> p.getName().equals("value")).map(p -> (String) p.getValue()).findAny(); if (name.isPresent()) { return name; } else { return Optional.of(packageBinding.getName()); } } return Optional.empty(); }
private static void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet<ITypeBinding> visited, ArrayList<IMethodBinding> allMethods, IPackageBinding currPack, ArrayList<IMethodBinding> toImplement) { if (visited.add(typeBinding)) { IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods(); for (int i= 0; i < typeMethods.length; i++) { IMethodBinding curr= typeMethods[i]; IMethodBinding impl= findMethodBinding(curr, allMethods); if (impl == null || !Bindings.isVisibleInHierarchy(impl, currPack)) { if (impl != null) allMethods.remove(impl); toImplement.add(curr); allMethods.add(curr); } } ITypeBinding[] superInterfaces= typeBinding.getInterfaces(); for (int i= 0; i < superInterfaces.length; i++) findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, currPack, toImplement); } }
private Binding getBinding(final IBinding binding) { Binding result = null; if (binding instanceof IMethodBinding) { result = getMethodBinding((IMethodBinding) binding); } else if (binding instanceof ITypeBinding) { result = getClassBinding((ITypeBinding) binding, false); } else if (binding instanceof IPackageBinding) { result = getPackageBinding((IPackageBinding) binding); } else if (binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) { result = getFieldBinding((IVariableBinding) binding); } else if (binding instanceof IVariableBinding && !((IVariableBinding) binding).isField()) { result = getVariableBinding((IVariableBinding) binding); } return result; }
public static boolean isVisibleInHierarchy(IMethodBinding member, IPackageBinding pack) { int otherflags= member.getModifiers(); ITypeBinding declaringType= member.getDeclaringClass(); if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags) || (declaringType != null && declaringType.isInterface())) { return true; } else if (Modifier.isPrivate(otherflags)) { return false; } return declaringType != null && pack == declaringType.getPackage(); }
public GeneratedTypeBinding( String name, IPackageBinding packageBinding, ITypeBinding superClass, boolean isInterface, ITypeBinding componentType, ITypeBinding declaringClass) { this.name = name; this.packageBinding = packageBinding; this.superClass = superClass; this.isInterface = isInterface; this.componentType = componentType; this.declaringClass = declaringClass; }
/** * Creates a new non-array type, extracting the package from the provided name. */ public static GeneratedTypeBinding newTypeBinding( String name, ITypeBinding superClass, boolean isInterface) { int idx = name.lastIndexOf('.'); IPackageBinding packageBinding = null; if (idx >= 0) { packageBinding = new GeneratedPackageBinding(name.substring(0, idx)); name = name.substring(idx + 1); } return new GeneratedTypeBinding(name, packageBinding, superClass, isInterface, null); }
private static String getFullNameInner(ITypeBinding binding) { binding = Types.mapType(binding.getErasure()); // Make sure type variables aren't included. ITypeBinding outerBinding = binding.getDeclaringClass(); if (binding.isLocal() && !binding.isAnonymous()) { String binaryName = binding.getBinaryName(); int innerClassIndex = binaryName.lastIndexOf(binding.getName()); while (innerClassIndex > 0 && binaryName.charAt(innerClassIndex - 1) != '$') { --innerClassIndex; } return getFullNameInner(outerBinding) + '_' + binaryName.substring(innerClassIndex); } if (outerBinding != null) { String baseName = getFullNameInner(outerBinding) + '_' + getName(binding); return (outerBinding.isEnum() && binding.isAnonymous()) ? baseName : baseName; } String name = binding.getQualifiedName(); // Use ObjectiveCType annotation, if it exists. IAnnotationBinding annotation = BindingUtil.getAnnotation(binding, ObjectiveCName.class); if (annotation != null) { return (String) BindingUtil.getAnnotationValue(annotation, "value"); } // Use mapping file entry, if it exists. if (Options.getClassMappings().containsKey(name)) { return Options.getClassMappings().get(name); } // Annotation-based mapping String annoName = BindingUtil.extractMappingName(binding); if (annoName != null) { return annoName; } // Use camel-cased package+class name. IPackageBinding pkg = binding.getPackage(); String pkgName = pkg != null ? getPrefix(pkg) : ""; return pkgName + binding.getName(); }
public static boolean isVisibleInHierarchy(IMethodBinding member, IPackageBinding pack) { int otherflags = member.getModifiers(); ITypeBinding declaringType = member.getDeclaringClass(); if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags) || (declaringType != null && declaringType.isInterface())) { return true; } else if (Modifier.isPrivate(otherflags)) { return false; } return declaringType != null && pack == declaringType.getPackage(); }
private static IPackageBinding getPackageBinding(CompilationUnit cu) { try { return cu.getPackage().resolveBinding(); } catch (NullPointerException e) { return null; } }
@Override public ModelId getModelOf(Class<?> element, ElementExporter elementExporter) throws ElementExportationException { try { Package ownPackage = element.getPackage(); if (ownPackage.getAnnotation(Model.class) != null) { return new ModelIdImpl(ownPackage.getName()); } String ownPackageName = ownPackage.getName(); IJavaProject javaProject = ProjectUtils.findJavaProject(elementExporter.getSourceProjectName()); Stream<ICompilationUnit> stream = PackageUtils.findAllPackageFragmentsAsStream(javaProject) .filter(p -> ownPackageName.startsWith(p.getElementName() + ".")) .map(pf -> pf.getCompilationUnit(PackageUtils.PACKAGE_INFO)).filter(ICompilationUnit::exists); String topPackageName = Stream.of(SharedUtils.parseICompilationUnitStream(stream, javaProject)) .map(CompilationUnit::getPackage).filter(Objects::nonNull).map(PackageDeclaration::resolveBinding) .filter(Objects::nonNull).filter(pb -> ModelUtils.findModelNameInTopPackage(pb).isPresent()) .map(IPackageBinding::getName).findFirst().get(); return new ModelIdImpl(topPackageName); } catch (NotFoundException | JavaModelException | IOException | NoSuchElementException e) { e.printStackTrace(); throw new ElementExportationException(); } }
private void rewriteName(Name name, ITypeBinding type) { AST creator= name.getAST(); boolean fullyQualified= false; if (name instanceof QualifiedName) { SimpleName left= ASTNodes.getLeftMostSimpleName(name); if (left.resolveBinding() instanceof IPackageBinding) fullyQualified= true; } if (fullyQualified) { fCuRewrite.getASTRewrite().replace( name, ASTNodeFactory.newName(creator, type.getQualifiedName()), fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fCuRewrite.getImportRemover().registerRemovedNode(name); } else { ImportRewriteContext context= new ContextSensitiveImportRewriteContext(name, fCuRewrite.getImportRewrite()); Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context); fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName()); Name n= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result)); fCuRewrite.getASTRewrite().replace( name, n, fCuRewrite.createGroupDescription(REFERENCE_UPDATE)); fCuRewrite.getImportRemover().registerRemovedNode(name); fNeedsImport= true; } }
@Override public boolean visit(CompilationUnit node) { if(node.getPackage() != null && node.getPackage().getName() != null) { this.currentPackageName = node.getPackage().getName().getFullyQualifiedName(); } else { this.currentPackageName = ""; } // Prefills the list with the imports that already exist in the list. for (Object o : node.imports()) { ImportDeclaration declaration = (ImportDeclaration) o; IBinding resolvedBinding = declaration.resolveBinding(); if (resolvedBinding instanceof ITypeBinding) { ITypeBinding resolvedTypeBinding = (ITypeBinding) resolvedBinding; if (resolvedTypeBinding != null && !resolvedTypeBinding.isRecovered()) { resolvedTypeBinding = resolvedTypeBinding.getErasure(); String typeName = resolvedTypeBinding.getName(); IPackageBinding packageBinding = resolvedTypeBinding.getPackage(); if (packageBinding != null) { String packageName = packageBinding.getName(); this.typesToPackageBinding.put(typeName, packageName); } } } } return true; }
private static void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet<ITypeBinding> visited, ArrayList<IMethodBinding> allMethods, IPackageBinding currPack, ArrayList<IMethodBinding> toImplement) { if (visited.add(typeBinding)) { IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods(); nextMethod: for (int i= 0; i < typeMethods.length; i++) { IMethodBinding curr= typeMethods[i]; for (Iterator<IMethodBinding> allIter= allMethods.iterator(); allIter.hasNext();) { IMethodBinding oneMethod= allIter.next(); if (Bindings.isSubsignature(oneMethod, curr)) { // We've already seen a method that is a subsignature of curr. if (!Bindings.isSubsignature(curr, oneMethod)) { // oneMethod is a true subsignature of curr; let's go with oneMethod continue nextMethod; } // Subsignatures are equivalent. // Check visibility and return types ('getErasure()' tries to achieve effect of "rename type variables") if (Bindings.isVisibleInHierarchy(oneMethod, currPack) && oneMethod.getReturnType().getErasure().isSubTypeCompatible(curr.getReturnType().getErasure())) { // oneMethod is visible and curr doesn't have a stricter return type; let's go with oneMethod continue nextMethod; } // curr is stricter than oneMethod, so let's remove oneMethod allIter.remove(); toImplement.remove(oneMethod); } else if (Bindings.isSubsignature(curr, oneMethod)) { // curr is a true subsignature of oneMethod. Let's remove oneMethod. allIter.remove(); toImplement.remove(oneMethod); } } int modifiers= curr.getModifiers(); if (!Modifier.isStatic(modifiers)) { allMethods.add(curr); if (Modifier.isAbstract(modifiers)) { toImplement.add(curr); } } } ITypeBinding[] superInterfaces= typeBinding.getInterfaces(); for (int i= 0; i < superInterfaces.length; i++) { findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, currPack, toImplement); } } }
public IPackageBinding getPackageBinding() { return packageBinding; }
public GeneratedTypeBinding( String name, IPackageBinding packageBinding, ITypeBinding superClass, boolean isInterface, ITypeBinding componentType) { this(name, packageBinding, superClass, isInterface, componentType, null); }
@Override public IPackageBinding getPackage() { return packageBinding; }
@Override public IPackageBinding getPackage() { return new GeneratedPackageBinding(clazz.getPackage().getName()); }
@Override public IPackageBinding getPackage() { return null; }
private static void findUnimplementedInterfaceMethods( ITypeBinding typeBinding, HashSet<ITypeBinding> visited, ArrayList<IMethodBinding> allMethods, IPackageBinding currPack, ArrayList<IMethodBinding> toImplement) { if (visited.add(typeBinding)) { IMethodBinding[] typeMethods = typeBinding.getDeclaredMethods(); nextMethod: for (int i = 0; i < typeMethods.length; i++) { IMethodBinding curr = typeMethods[i]; for (Iterator<IMethodBinding> allIter = allMethods.iterator(); allIter.hasNext(); ) { IMethodBinding oneMethod = allIter.next(); if (Bindings.isSubsignature(oneMethod, curr)) { // We've already seen a method that is a subsignature of curr. if (!Bindings.isSubsignature(curr, oneMethod)) { // oneMethod is a true subsignature of curr; let's go with oneMethod continue nextMethod; } // Subsignatures are equivalent. // Check visibility and return types ('getErasure()' tries to achieve effect of "rename // type variables") if (Bindings.isVisibleInHierarchy(oneMethod, currPack) && oneMethod .getReturnType() .getErasure() .isSubTypeCompatible(curr.getReturnType().getErasure())) { // oneMethod is visible and curr doesn't have a stricter return type; let's go with // oneMethod continue nextMethod; } // curr is stricter than oneMethod, so let's remove oneMethod allIter.remove(); toImplement.remove(oneMethod); } else if (Bindings.isSubsignature(curr, oneMethod)) { // curr is a true subsignature of oneMethod. Let's remove oneMethod. allIter.remove(); toImplement.remove(oneMethod); } } if (Modifier.isAbstract(curr.getModifiers())) { toImplement.add(curr); allMethods.add(curr); } } ITypeBinding[] superInterfaces = typeBinding.getInterfaces(); for (int i = 0; i < superInterfaces.length; i++) findUnimplementedInterfaceMethods( superInterfaces[i], visited, allMethods, currPack, toImplement); } }
public Namespace ensureNamespaceFromPackageBinding(IPackageBinding binding) { return ensureNamespaceNamed(binding.getName()); }
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException { fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit()); SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange()); TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION); ASTRewrite rewrite= fBaseCURewrite.getASTRewrite(); int modifier= Modifier.PRIVATE; TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field); FieldDeclaration lastField= null; initializeDeclaration(typeNode); for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) { FieldInfo pi= iter.next(); if (isCreateField(pi)) { VariableDeclarationFragment vdf= pi.declaration; FieldDeclaration parent= (FieldDeclaration) vdf.getParent(); if (lastField == null) lastField= parent; else if (lastField.getStartPosition() < parent.getStartPosition()) lastField= parent; ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY); removeNode(vdf, removeFieldGroup, fBaseCURewrite); if (listRewrite.getRewrittenList().size() == 0) { removeNode(parent, removeFieldGroup, fBaseCURewrite); } if (fDescriptor.isCreateTopLevel()) { IVariableBinding binding= vdf.resolveBinding(); ITypeRoot typeRoot= fBaseCURewrite.getCu(); if (binding == null || binding.getType() == null){ status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf)); } else { ITypeBinding typeBinding= binding.getType(); if (Modifier.isPrivate(typeBinding.getModifiers())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf)); } else if (Modifier.isProtected(typeBinding.getModifiers())){ ITypeBinding declaringClass= typeBinding.getDeclaringClass(); if (declaringClass != null) { IPackageBinding package1= declaringClass.getPackage(); if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf)); } } } } } Expression initializer= vdf.getInitializer(); if (initializer != null) pi.initializer= initializer; int modifiers= parent.getModifiers(); if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){ modifier= modifiers; } } } FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier); ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); if (lastField != null) bodyDeclList.insertAfter(fieldDeclaration, lastField, null); else bodyDeclList.insertFirst(fieldDeclaration, null); return fieldDeclaration; }
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException { Assert.isNotNull(delegate); Assert.isNotNull(delegatingField); Assert.isNotNull(settings); AST ast= rewrite.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE)); decl.setName(ast.newSimpleName(delegate.getName())); decl.setConstructor(false); createTypeParameters(imports, context, ast, delegate, decl); decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context)); List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl); createThrownExceptions(decl, delegate, imports, context, ast); Block body= ast.newBlock(); decl.setBody(body); String delimiter= StubUtility.getLineDelimiterUsed(unit); Statement statement= null; MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(delegate.getName())); List<Expression> arguments= invocation.arguments(); for (int i= 0; i < params.size(); i++) arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier())); if (settings.useKeywordThis) { FieldAccess access= ast.newFieldAccess(); access.setExpression(ast.newThisExpression()); access.setName(ast.newSimpleName(delegatingField.getName())); invocation.setExpression(access); } else invocation.setExpression(ast.newSimpleName(delegatingField.getName())); if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$ statement= ast.newExpressionStatement(invocation); } else { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(invocation); statement= returnStatement; } body.statements().add(statement); ITypeBinding declaringType= delegatingField.getDeclaringClass(); if (declaringType == null) { // can be null for return decl; } String qualifiedName= declaringType.getQualifiedName(); IPackageBinding packageBinding= declaringType.getPackage(); if (packageBinding != null) { if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName())) qualifiedName= qualifiedName.substring(packageBinding.getName().length()); } if (settings.createComments) { /* * TODO: have API for delegate method comments This is an inlined * version of * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)} */ delegate= delegate.getMethodDeclaration(); String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName(); String linkToMethodName= delegate.getName(); String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate); String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter); if (string != null) { Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC); decl.setJavadoc(javadoc); } } return decl; }
private static void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet<ITypeBinding> visited, ArrayList<IMethodBinding> allMethods, IPackageBinding currPack, ArrayList<IMethodBinding> toImplement) { if (visited.add(typeBinding)) { IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods(); nextMethod: for (int i= 0; i < typeMethods.length; i++) { IMethodBinding curr= typeMethods[i]; for (Iterator<IMethodBinding> allIter= allMethods.iterator(); allIter.hasNext();) { IMethodBinding oneMethod= allIter.next(); if (Bindings.isSubsignature(oneMethod, curr)) { // We've already seen a method that is a subsignature of curr. if (!Bindings.isSubsignature(curr, oneMethod)) { // oneMethod is a true subsignature of curr; let's go with oneMethod continue nextMethod; } // Subsignatures are equivalent. // Check visibility and return types ('getErasure()' tries to achieve effect of "rename type variables") if (Bindings.isVisibleInHierarchy(oneMethod, currPack) && oneMethod.getReturnType().getErasure().isSubTypeCompatible(curr.getReturnType().getErasure())) { // oneMethod is visible and curr doesn't have a stricter return type; let's go with oneMethod continue nextMethod; } // curr is stricter than oneMethod, so let's remove oneMethod allIter.remove(); toImplement.remove(oneMethod); } else if (Bindings.isSubsignature(curr, oneMethod)) { // curr is a true subsignature of oneMethod. Let's remove oneMethod. allIter.remove(); toImplement.remove(oneMethod); } } if (Modifier.isAbstract(curr.getModifiers())) { toImplement.add(curr); allMethods.add(curr); } } ITypeBinding[] superInterfaces= typeBinding.getInterfaces(); for (int i= 0; i < superInterfaces.length; i++) findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, currPack, toImplement); } }
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException { fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit()); SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange()); TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION); ASTRewrite rewrite= fBaseCURewrite.getASTRewrite(); int modifier= Modifier.PRIVATE; TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field); FieldDeclaration lastField= null; initializeDeclaration(typeNode); for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) { FieldInfo pi= iter.next(); if (isCreateField(pi)) { VariableDeclarationFragment vdf= pi.declaration; FieldDeclaration parent= (FieldDeclaration) vdf.getParent(); if (lastField == null) lastField= parent; else if (lastField.getStartPosition() < parent.getStartPosition()) lastField= parent; ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY); removeNode(vdf, removeFieldGroup, fBaseCURewrite); if (listRewrite.getRewrittenList().size() == 0) { removeNode(parent, removeFieldGroup, fBaseCURewrite); } if (fDescriptor.isCreateTopLevel()) { IVariableBinding binding= vdf.resolveBinding(); ITypeRoot typeRoot= fBaseCURewrite.getCu(); if (binding == null || binding.getType() == null){ status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf)); } else { ITypeBinding typeBinding= binding.getType(); if (Modifier.isPrivate(typeBinding.getDeclaredModifiers())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf)); } else if (Modifier.isProtected(typeBinding.getDeclaredModifiers())){ ITypeBinding declaringClass= typeBinding.getDeclaringClass(); if (declaringClass != null) { IPackageBinding package1= declaringClass.getPackage(); if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){ status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf)); } } } } } Expression initializer= vdf.getInitializer(); if (initializer != null) pi.initializer= initializer; int modifiers= parent.getModifiers(); if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){ modifier= modifiers; } } } FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier); ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); if (lastField != null) bodyDeclList.insertAfter(fieldDeclaration, lastField, null); else bodyDeclList.insertFirst(fieldDeclaration, null); return fieldDeclaration; }
public ApiDescriptor(MethodInvocation method) { IMethodBinding methodBinding = method.resolveMethodBinding(); if (methodBinding != null) { mMethodName = methodBinding.getName(); ITypeBinding[] argMethods = methodBinding.getParameterTypes(); ITypeBinding retMethod = methodBinding.getReturnType(); boolean isConstructor = methodBinding.isConstructor(); ITypeBinding declaringClass = methodBinding.getDeclaringClass(); MethodType methodType = MethodType.NORMAL; if (isConstructor) { methodType = MethodType.CONSTRUCTOR; } mMethodType = methodType; if (declaringClass != null) { mClassName = declaringClass.getName(); IPackageBinding pckg = declaringClass.getPackage(); if (pckg != null) { mPackageName = pckg.getName(); } else { System.out.println(">>inf: package is not specified."); } } else { System.out.println(">>inf: class is not specified."); } if (retMethod != null) { mReturnType = retMethod.getName(); } else { System.out.println(">>inf: return type is not specified."); } if (argMethods != null) { mParams = new ArrayList<ParameterDescriptor>(argMethods.length); int pos = 1; for (ITypeBinding param : argMethods) { if (param != null) { String paramName = param.getName(); ITypeBinding paramType = param.getTypeDeclaration(); String paramTypeName = null; if (paramType != null) { paramTypeName = paramType.getName(); } mParams.add(new ParameterDescriptor(paramName, paramTypeName, pos)); pos++; } else { System.out.println(">>error: parameter is NULL."); } } } else { System.out.println(">>inf: method parameters are not specified."); } } else { System.out.println(">>warning: method binding can't be resolved."); } }
private boolean compareAttributes(String name, ITypeBinding declaringClass, ITypeBinding[] args, ITypeBinding ret, boolean isConstructor) { boolean matched = false; if (mMethodName != null) { if (mMethodName.equals(name)) { matched = true; } else { System.out.println(">>inf: method names are not matched."); return false; } } else { System.out.println(">>inf: method name is not specified."); } MethodType methodType = MethodType.NORMAL; if (isConstructor) { methodType = MethodType.CONSTRUCTOR; } if (mMethodType.equals(methodType)) { matched = true; } else { System.out.println(">>inf: method type is not matched."); return false; } if ((mClassName != null) && declaringClass != null) { if (mClassName.equals(declaringClass.getName())) { matched = true; } else { System.out.println(">>inf: class names are not matched."); return false; } IPackageBinding pckg = declaringClass.getPackage(); if ((mPackageName != null) && pckg != null) { if (mPackageName.equals(pckg.getName())) { matched = true; } else { System.out.println(">>inf: package names are not matched."); return false; } } else { System.out.println(">>inf: package is not specified."); } } else { System.out.println(">>inf: class is not specified."); } if ((mReturnType != null) && (ret != null)) { if (mReturnType.equals(ret.getName())) { matched = true; } else { System.out.println(">>inf: return types are not matched."); return false; } } else { System.out.println(">>inf: return type is not specified."); } if ((mParams != null) && (args != null)) { for (ParameterDescriptor param : mParams) { if ((param != null) && (param.getPos() >= 0) && (param.getPos() < args.length)) { String paramName = param.getName(); if ((paramName != null) && paramName.equals(args[param.getPos()].getName())) { matched = true; } else { System.out.println(">>inf: parameters are not matched."); return false; } } else { System.out.println(">>error: bad configuration of parameters."); } } } else { System.out.println(">>inf: method parameters are not specified."); } return matched; }
private static PackageBinding getPackageBinding(final IPackageBinding binding) { PackageBinding result = new PackageBinding(); result.setName(binding.getName()); return result; }
/** * Checks Qualified Type, represented by its use in parent node, its name, * and its type binding. * * @param node * : Parent Node * @param qualifiedName * : Qualified Name * @param typeBinding * : Type Binding */ @SuppressWarnings("unchecked") private void checkQualifiedType(ASTNode node, QualifiedName qualifiedName, ITypeBinding typeBinding) { // At first we extract package name & type for Type, by : // - Splitting the String if Type Binding has been deduced (recovered) // - Taking it from Binding otherwise String fullyQualifiedName = qualifiedName.getFullyQualifiedName(); String typeName = null; String packageName = null; if (typeBinding == null || typeBinding.isRecovered()) { typeName = qualifiedName.getFullyQualifiedName().substring( qualifiedName.getFullyQualifiedName().lastIndexOf(".") + 1); packageName = qualifiedName.getFullyQualifiedName().substring(0, qualifiedName.getFullyQualifiedName().lastIndexOf(".")); } else { typeBinding = typeBinding.getErasure(); typeName = typeBinding.getName(); IPackageBinding packageBinding = typeBinding.getPackage(); if (packageBinding == null) return; packageName = packageBinding.getName(); } // Checks if name should be trimmed (if class with same name but // different package has already been registered), and trims it if // needed if (shouldTrimName(packageName, typeName)) { StructuralPropertyDescriptor locationInParent = qualifiedName.getLocationInParent(); if (locationInParent == null) return; if (locationInParent.isChildListProperty()) { ChildListPropertyDescriptor clpd = (ChildListPropertyDescriptor) locationInParent; List<ASTNode> astNodes = (List<ASTNode>) node.getStructuralProperty(clpd); astNodes.remove(qualifiedName); astNodes.add(node.getAST().newName(typeName)); } else { node.setStructuralProperty(locationInParent, node.getAST().newName(typeName)); } hasModifications = true; } // Checks if import should be added (e.g. package is not java.lang) and // does it if needed if (shouldAddImport(node, typeName, packageName, fullyQualifiedName)) { this.tryAddImport(node.getAST(), fullyQualifiedName); if (!typesToPackageBinding.containsKey(typeName)) typesToPackageBinding.put(typeName, packageName); } else if (this.currentPackageName.equals(packageName)) if (!typesToPackageBinding.containsKey(typeName)) typesToPackageBinding.put(typeName, packageName); }