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)); }
/** * 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 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)); }
public boolean isOnClasspath(String fullyQualifiedName, IJavaProject project) { if (fullyQualifiedName.indexOf('$') != -1) fullyQualifiedName = fullyQualifiedName.replace('$', '.'); try { IType type = project.findType(fullyQualifiedName); return type != null && type.exists(); } catch (JavaModelException e) { } return false; }
public static byte[] getClassContent(IJavaProject javaProject, String className) { if (javaProject == null || !javaProject.exists()) return null; String resourceName = className.replace('.', '/') + ".class"; try { IPath outPath = javaProject .getProject() .getLocation() .removeLastSegments(1) .append(javaProject.getOutputLocation()); outPath = outPath.addTrailingSeparator(); { URL url = toURL(outPath.append(resourceName)); if (url != null) { InputStream inputStream = url.openStream(); byte[] content = new byte[inputStream.available()]; inputStream.read(content); return content; } for (IProject project : javaProject.getProject().getReferencedProjects()) { if (!project.isOpen()) { continue; } IJavaProject javaReferencedProject = JavaCore.create(project); if (javaReferencedProject.exists()) { byte[] content = getClassContent(javaReferencedProject, className); if (content != null) { return content; } } } } IType type = javaProject.findType(className); if (type != null && type.exists()) { if (type.isBinary()) { return type.getClassFile().getBytes(); } else { IJavaProject typeProject = type.getJavaProject(); if (!javaProject.equals(typeProject)) { return getClassContent(typeProject, className); } } } } catch (Exception e) { e.printStackTrace(); } return null; }
public static IType[] getMemberTypes(IType type, String[] names) { if (names == null) return new IType[0]; Set memberTypes = new HashSet(); for (int i = 0; i < names.length; i++) { IType memberType; if (names[i].indexOf('.') != -1) { String[] path = names[i].split("\\."); memberType = type.getType(path[0]); for (int j = 1; j < path.length; j++) { memberType = memberType.getType(path[j]); } } else memberType = type.getType(names[i]); assertTrue( "member type " + memberType.getElementName() + " does not exist", memberType.exists()); memberTypes.add(memberType); } return (IType[]) memberTypes.toArray(new IType[memberTypes.size()]); }
private static IStatus validateDestinationType(IType type, String typeName) { if (type == null || !type.exists()) return new Status( IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, Messages.format( RefactoringMessages.MoveMembersInputPage_not_found, BasicElementLabels.getJavaElementName(typeName)), null); if (type.isBinary()) return new Status( IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, RefactoringMessages.MoveMembersInputPage_no_binary, null); return Status.OK_STATUS; }
/** * Determines is the java element contains a main method. * * @param element the element to check for the method * @return true if the method is found in the element, false otherwise */ private boolean hasMain(IJavaElement element) { try { IType type = getType(element); if (type != null && type.exists()) { if (hasMainMethod(type)) { return true; } // failed to find in public type, check static inner types IJavaElement[] children = type.getChildren(); for (int i = 0; i < children.length; i++) { if (hasMainInChildren(getType(children[i]))) { return true; } } } } catch (JavaModelException e) { } catch (CoreException ce) { } return false; }
/** * 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); } }
private static void checkTypeInType(IType destinationType, RefactoringStatus result, IType type) throws JavaModelException { String typeName = type.getElementName(); IType destinationTypeType = destinationType.getType(typeName); if (destinationTypeType.exists()) { String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_type_name_conflict0, new String[] { BasicElementLabels.getJavaElementName(typeName), getQualifiedLabel(destinationType) }); RefactoringStatusContext context = JavaStatusContext.create( destinationType.getCompilationUnit(), destinationTypeType.getNameRange()); result.addError(message, context); } else { // need to check the hierarchy of enclosing and enclosed types if (destinationType.getElementName().equals(typeName)) { String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_type_name_conflict1, getQualifiedLabel(type)); RefactoringStatusContext context = JavaStatusContext.create( destinationType.getCompilationUnit(), destinationType.getNameRange()); result.addError(message, context); } if (typeNameExistsInEnclosingTypeChain(destinationType, typeName)) { String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_type_name_conflict2, getQualifiedLabel(type)); RefactoringStatusContext context = JavaStatusContext.create( destinationType.getCompilationUnit(), destinationType.getNameRange()); result.addError(message, context); } checkHierarchyOfEnclosedTypes(destinationType, result, type); } }
public void testFinderWithSuite() throws Exception { IPath projectPath = createGenericProject(); IPath root = projectPath.append("src"); env.addGroovyClass( root, "p2", "Hello", "package p2;\n" + "import junit.framework.Test;\n" + "public class Hello {\n" + " public static Test suite() throws Exception { }\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", new JUnit4TestFinder().isTest(type)); }
private synchronized void internalCheckConsistency(IProgressMonitor monitor) throws OperationCanceledException { // Setting fNeedsConsistencyCheck is necessary here since // markAsInconsistent isn't synchronized. fNeedsConsistencyCheck = true; List typesToCheck = new ArrayList(getKeys()); monitor.beginTask(CorextMessages.TypeInfoHistory_consistency_check, typesToCheck.size()); monitor.setTaskName(CorextMessages.TypeInfoHistory_consistency_check); for (Iterator iter = typesToCheck.iterator(); iter.hasNext(); ) { TypeNameMatch type = (TypeNameMatch) iter.next(); long currentTimestamp = getContainerTimestamp(type); Long lastTested = (Long) fTimestampMapping.get(type); if (lastTested != null && currentTimestamp != IResource.NULL_STAMP && currentTimestamp == lastTested.longValue() && !isContainerDirty(type)) continue; try { IType jType = type.getType(); if (jType == null || !jType.exists()) { remove(type); } else { // copy over the modifiers since they may have changed int modifiers = jType.getFlags(); if (modifiers != type.getModifiers()) { replace(type, SearchEngine.createTypeNameMatch(jType, modifiers)); } else { fTimestampMapping.put(type, new Long(currentTimestamp)); } } } catch (JavaModelException e) { remove(type); } if (monitor.isCanceled()) throw new OperationCanceledException(); monitor.worked(1); } monitor.done(); fNeedsConsistencyCheck = false; }
/** * Determines is the java element contains a specific method. * * <p>The syntax for the property tester is of the form: methodname, signature, modifiers. * * <ol> * <li>methodname - case sensitive method name, required. For example, <code>toString</code>. * <li>signature - JLS style method signature, required. For example, <code>(QString;)V</code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </code>. * </ol> * * @param element the element to check for the method * @param args first arg is method name, secondary args are parameter types signatures * @return true if the method is found in the element, false otherwise */ private boolean hasMethod(IJavaElement element, Object[] args) { try { if (args.length > 1) { IType type = getType(element); if (type != null && type.exists()) { String name = (String) args[0]; String signature = (String) args[1]; String[] parms = Signature.getParameterTypes(signature); String returnType = Signature.getReturnType(signature); IMethod candidate = type.getMethod(name, parms); if (candidate.exists()) { // check return type if (candidate.getReturnType().equals(returnType)) { // check modifiers if (args.length > 2) { String modifierText = (String) args[2]; String[] modifiers = modifierText.split(" "); // $NON-NLS-1$ int flags = 0; for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } if (candidate.getFlags() == flags) { return true; } } } } } } } catch (JavaModelException e) { } return false; }
/** * Returns the primary type of a class file. * * @param classFile the class file * @return returns the primary type of the class file, or <code>null</code> if is does not have * one */ private IType getMainType(IClassFile classFile) { IType type = classFile.getType(); return type != null && type.exists() ? type : null; }
/** * Initializes the refactoring from scripting arguments. Used by {@link * RenameVirtualMethodProcessor} and {@link RenameNonVirtualMethodProcessor} * * @param extended the arguments * @return the resulting status */ protected final RefactoringStatus initialize(JavaRefactoringArguments extended) { fInitialized = true; final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT); if (handle != null) { final IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false); final String refactoring = getProcessorName(); if (element instanceof IMethod) { final IMethod method = (IMethod) element; final IType declaring = method.getDeclaringType(); if (declaring != null && declaring.exists()) { final IMethod[] methods = declaring.findMethods(method); if (methods != null && methods.length == 1 && methods[0] != null) { if (!methods[0].exists()) return JavaRefactoringDescriptorUtil.createInputFatalStatus( methods[0], refactoring, IJavaRefactorings.RENAME_METHOD); fMethod = methods[0]; initializeWorkingCopyOwner(); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( null, refactoring, IJavaRefactorings.RENAME_METHOD); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( element, refactoring, IJavaRefactorings.RENAME_METHOD); } else return JavaRefactoringDescriptorUtil.createInputFatalStatus( element, refactoring, IJavaRefactorings.RENAME_METHOD); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT)); final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME); if (name != null && !"".equals(name)) // $NON-NLS-1$ setNewElementName(name); else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME)); final String references = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES); if (references != null) { fUpdateReferences = Boolean.valueOf(references).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES)); final String delegate = extended.getAttribute(ATTRIBUTE_DELEGATE); if (delegate != null) { fDelegateUpdating = Boolean.valueOf(delegate).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DELEGATE)); final String deprecate = extended.getAttribute(ATTRIBUTE_DEPRECATE); if (deprecate != null) { fDelegateDeprecation = Boolean.valueOf(deprecate).booleanValue(); } else return RefactoringStatus.createFatalErrorStatus( Messages.format( RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_DEPRECATE)); return new RefactoringStatus(); }
/** * @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);*/ }
/** * Determines is the java element contains a method with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name, * modifiers * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </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 method is found in the element, false otherwise */ private boolean hasMethodWithAnnotation(IJavaElement element, Object[] args) { try { String annotationType = (String) args[0]; int flags = 0; if (args.length > 1) { String[] modifiers = ((String) args[1]).split(" "); // $NON-NLS-1$ for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } } else { flags = -1; } IType type = getType(element); if (type == null || !type.exists()) { return false; } IMethod[] methods = type.getMethods(); if (methods.length == 0) { 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; } IScanner scanner = null; // delay initialization for (int i = 0; i < methods.length; i++) { IMethod curr = methods[i]; if (curr.isConstructor() || (flags != -1 && flags != (curr.getFlags() & FLAGS_MASK))) { continue; } ISourceRange sourceRange = curr.getSourceRange(); ISourceRange nameRange = curr.getNameRange(); if (sourceRange != null && nameRange != null) { if (scanner == null) { 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; }
@Override public Action populateTagAction( final TemplateTag tagFound, final String tagBody, final String insideTagBody, final ICompilationUnit compUnit, final boolean hasSubAction1, final Map<String, Object> placeHolders, final Map<String, Object> contextMap, final String spacesBeforeCursor, final Map<String, String> attributes, final StringBuilder existingMembersBuilder, final List<Action> actionList) throws Exception { String memberName = null; boolean optional = false; final ACTION_TYPE actionType = ACTION_TYPE.Create; String typeToCreate = null; String delimiter = null; if (tagFound == TemplateTag.CLASS) { memberName = attributes.containsKey(PLACEHOLDER_NAME) ? attributes.get(PLACEHOLDER_NAME) : null; } else if (tagFound == TemplateTag.CLASSES) { memberName = attributes.containsKey(NAMES) ? attributes.get(NAMES) : null; } final String pkg = attributes.containsKey(PLACEHOLDER_PACKAGE) ? attributes.get(PLACEHOLDER_PACKAGE) : EMPTY_STR; final String project = attributes.containsKey(PLACEHOLDER_PROJECT) ? attributes.get(PLACEHOLDER_PROJECT) : null; typeToCreate = attributes.containsKey(TYPE) ? attributes.get(TYPE) : PLACEHOLDER_CLASS; optional = attributes.containsKey(OPTIONAL) ? Boolean.valueOf(attributes.get(OPTIONAL)) : false; delimiter = attributes.containsKey(DELIMITER) ? attributes.get(DELIMITER) : SPACE; final boolean overrideMethods = attributes.containsKey("override_methods") ? Boolean.valueOf(attributes.get("override_methods")) : false; /* * IJavaProject prj = getJavaProject(project); if (prj == null) { * prj = getJavaProject((String) * placeHolders.get(PLACEHOLDER_PROJECT)); } if * (prj.getProject().isSynchronized(0)) { throw new * Exception("Project: " + prj.getProject().getName() + * " is not synchronized ,Please refresh and try again."); } */ if (memberName == null || memberName.equals(EMPTY_STR)) { if (tagFound == TemplateTag.CLASS) { throw new Exception( "Please provide attribute \"name\" for <fc:class> tag in the XML and try again"); } else if (tagFound == TemplateTag.CLASSES) { throw new Exception( "Please provide attribute \"names\" for <fc:classes> tag in the XML and try again"); } } /*if (pkg == null) { throw new Exception("Please provide attribute \"package\" for <fc:" + tagFound.toString().toLowerCase() + "> tag in the XML and try again"); }*/ if (!isEmpty(insideTagBody) && insideTagBody.contains(XML_START + TEMPLATE_TAG_PREFIX + COLON)) { throw new Exception( "There should not be any other tags inside <fc:" + tagFound.toString().toLowerCase() + ">, exiting...."); } IJavaProject javaProject = null; if (!isEmpty(project) && project.startsWith(HASH)) { final Object projct = placeHolders.get(project.replace(HASH, EMPTY_STR).trim()); if (projct instanceof FastCodeProject) { javaProject = ((FastCodeProject) projct).getJavaProject(); if (javaProject == null) { javaProject = getJavaProject(((FastCodeProject) projct).getProject()); } } else { javaProject = getJavaProject((String) projct); } } else { javaProject = getJavaProject(project); // getJavaProject(attributes.get(PLACEHOLDER_PROJECT)); } boolean createProject = false; if (javaProject == null) { for (final Action action : actionList) { if (action.getEntity() == ACTION_ENTITY.Project) { if (action.getEntityName().equals(project)) { javaProject = null; createProject = true; } } } if (!createProject) { javaProject = getJavaProject( placeHolders.get(PLACEHOLDER_PROJECT) instanceof FastCodeProject ? ((FastCodeProject) placeHolders.get(PLACEHOLDER_PROJECT)).getName() : (String) placeHolders.get(PLACEHOLDER_PROJECT)); } } IPackageFragment pkgFrgmt = null; if (!createProject) { if (javaProject == null) { javaProject = getWorkingJavaProjectFromUser(); // did for j2ee base } final String defaultPath = typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? getDefaultPathFromProject(javaProject, typeToCreate, EMPTY_STR) : getDefaultPathFromProject(javaProject, "source", EMPTY_STR); final TemplateTagsProcessor templateTagsProcessor = new TemplateTagsProcessor(); pkgFrgmt = pkg.startsWith(HASH) ? ((FastCodePackage) placeHolders.get(pkg.replace(HASH, EMPTY_STR).trim())) .getPackageFragment() : templateTagsProcessor.getPackageFragment( javaProject, defaultPath, pkg, typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? typeToCreate : "source"); } String labelMsg = null; final String labelMsgPart1 = pkgFrgmt != null ? EMPTY_STR : isEmpty(pkg) ? "default " : "new "; boolean isClassExist = false; if (tagFound == TemplateTag.CLASS) { if (isJavaReservedWord(memberName) || !isValidVariableName(memberName)) { throw new Exception( "Attribute \"name\" contains either java reserved word or not valid for class name ,Please provide correct one for <fc:class> tag in the XML and try again"); } if (!isEmpty(insideTagBody)) { final String classNameInsideTagBody = parseClassName(replaceSpecialChars(insideTagBody.trim())); if (!memberName.equals(classNameInsideTagBody)) { // System.out.println(classNameInsideTagBody); throw new Exception( "Attribute \"name\" value " + memberName + " and class name inside <fc:class> tag body " + classNameInsideTagBody + " does not match, Please provide same name in both the places for <fc:class> tag in the XML and try again"); } } // if (pkgFrgmt != null) { final String fullClassName = pkgFrgmt != null ? pkgFrgmt.getElementName() + DOT + memberName.trim() : isEmpty(pkg) ? memberName.trim() : pkg + DOT + memberName; // if (compUnit != null) { if (javaProject != null) { final IType type3 = javaProject.findType(fullClassName); if (type3 != null && type3.exists()) { isClassExist = true; /*this.existingMembersBuilder.append("Class with Name: " + fullClassName); this.existingMembersBuilder.append(SPACE + COMMA + SPACE); return null;*/ } } // } // } final String pkgNme = pkgFrgmt != null ? pkgFrgmt.getElementName() : pkg; final String msg3 = isClassExist ? " (Class already exists.)" : EMPTY_STR; final String actionTypeClassLbl = isClassExist ? "Overwrite " : actionType.toString(); labelMsg = typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? actionTypeClassLbl + SPACE + typeToCreate + SPACE + "class" + SPACE + memberName + " in " + labelMsgPart1 + "package " + pkg + msg3 : actionTypeClassLbl + SPACE + typeToCreate + SPACE + memberName + " in " + labelMsgPart1 + "package " + pkgNme + msg3; // + msg3; } else if (tagFound == TemplateTag.CLASSES) { final String[] namesarr = memberName.split(delimiter); boolean duplicate = false; for (int j = 0; j < namesarr.length; j++) { for (int k = j + 1; k < namesarr.length; k++) { if (namesarr[k].equals(namesarr[j])) { duplicate = true; break; } if (duplicate) { break; } } } if (duplicate) { throw new Exception( "Attribute \"names\" contains duplicate class name,Please provide correct attribute \"names\" for <fc:classes> tag in the XML and try again"); } // StringBuilder existingClassName = new StringBuilder(); final List<String> classNamesList = new ArrayList<String>(); for (final String className : memberName.split(delimiter)) { if (isJavaReservedWord(className) || !isValidVariableName(className)) { throw new Exception( "Attribute \"names\" contains either java reserved word or not valid for class name ,Please provide correct one for <fc:classes> tag in the XML and try again"); } classNamesList.add(className); // if (pkgFrgmt != null) { final String fullClassName = pkgFrgmt != null ? pkgFrgmt.getElementName() + DOT + className.trim() : isEmpty(pkg) ? className.trim() : pkg + DOT + className.trim(); // if (compUnit != null) { if (javaProject != null) { final IType type4 = javaProject.findType(fullClassName); if (type4 != null && type4.exists()) { existingMembersBuilder.append("Class with Name: " + fullClassName); existingMembersBuilder.append(SPACE + COMMA + SPACE); classNamesList.remove(className); continue; } } // } // } } String classNames = EMPTY_STR; if (!classNamesList.isEmpty()) { for (final String className : classNamesList) { classNames = classNames + className + delimiter; } } memberName = classNames; if (isEmpty(memberName)) { return null; } labelMsg = typeToCreate.equals(ACTION_ENTITY.Test.getValue()) ? actionType.toString() + SPACE + typeToCreate + SPACE + "classes" + SPACE + classNames.replace(delimiter, COMMA + SPACE) + " in " + labelMsgPart1 + " package " + pkg : actionType.toString() + SPACE + "classes" + SPACE + classNames.replace(delimiter, COMMA + SPACE) + " in " + labelMsgPart1 + " package " + pkg; } final Action actionClass = new Action.Builder() .withEntity(tagFound == TemplateTag.CLASS ? ACTION_ENTITY.Class : ACTION_ENTITY.Classes) .withType(actionType) .withEntityName(memberName) .withPackge(pkgFrgmt == null ? pkg : pkgFrgmt) .withProject(createProject ? project : javaProject) .withSource(isEmpty(insideTagBody) ? insideTagBody : insideTagBody.trim()) .withLabelMsg(labelMsg) .withOptional(optional) .withTypeToCreate(typeToCreate) .withDelimiter(delimiter) .withOverrideMethods(overrideMethods) .withExist(isClassExist) .build(); return actionClass; // break; }
/** * Creates a qualified class name from a class name which doesn't contain package name. * * @param parent a full qualified class name of the class which uses this variable * @param type a class name which doesn't contain package name * @return full a created qualified class name */ public static String getFullQName(IType parent, String type) { if (type.indexOf('.') >= 0) { return type; } if (isPrimitive(type)) { return type; } IJavaProject project = parent.getJavaProject(); try { IType javaType = project.findType("java.lang." + type); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { ex.printStackTrace(); } while (true) { try { IType javaType = project.findType(parent.getFullyQualifiedName() + "." + type); if (javaType != null && javaType.exists()) { return parent.getFullyQualifiedName() + "." + type; } } catch (Exception ex) { ex.printStackTrace(); } try { IType javaType = project.findType(parent.getPackageFragment().getElementName() + "." + type); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { ex.printStackTrace(); } try { IImportDeclaration[] imports = parent.getCompilationUnit().getImports(); for (int i = 0; i < imports.length; i++) { String importName = imports[i].getElementName(); if (importName.endsWith("." + type)) { return importName; } if (importName.endsWith(".*")) { try { IType javaType = project.findType(importName.replaceFirst("\\*$", type)); if (javaType != null && javaType.exists()) { return javaType.getFullyQualifiedName(); } } catch (Exception ex) { } } } } catch (Exception ex) { ex.printStackTrace(); } try { // スーパークラス if (parent.getSuperclassTypeSignature() == null) { break; } String superClass = JavaUtil.getFullQName(parent, Signature.toString(parent.getSuperclassTypeSignature())); if (superClass.startsWith("java.lang.")) { break; } parent = parent.getJavaProject().findType(superClass); } catch (JavaModelException ex) { } } return type; }