List of usage examples for org.eclipse.jdt.core IJavaElement METHOD
int METHOD
To view the source code for org.eclipse.jdt.core IJavaElement METHOD.
Click Source Link
From source file:org.eclipse.xtext.common.types.ui.refactoring.participant.JdtRenameParticipant.java
License:Open Source License
protected EClass getExpectedJvmType(IJavaElement javaElement) { try {/*w w w . j a v a 2 s .c om*/ switch (javaElement.getElementType()) { case IJavaElement.TYPE: if (((IType) javaElement).isEnum()) return TypesPackage.Literals.JVM_ENUMERATION_TYPE; else return TypesPackage.Literals.JVM_TYPE; case IJavaElement.METHOD: if (((IMethod) javaElement).isConstructor()) return TypesPackage.Literals.JVM_CONSTRUCTOR; else return TypesPackage.Literals.JVM_OPERATION; case IJavaElement.FIELD: if (((IField) javaElement).isEnumConstant()) return TypesPackage.Literals.JVM_ENUMERATION_LITERAL; else return TypesPackage.Literals.JVM_FIELD; default: return null; } } catch (JavaModelException exc) { throw new WrappedException(exc); } }
From source file:org.eclipse.xtext.common.types.util.jdt.JavaElementFinderTest.java
License:Open Source License
protected void doTestFindMethod(Class<?> declaringType, String methodName, int numberOfParameters) { JvmOperation foundOperation = findOperation(declaringType, methodName, numberOfParameters); assertNotNull(foundOperation);/*w ww .j ava2s .co m*/ IJavaElement found = elementFinder.findElementFor(foundOperation); assertEquals(IJavaElement.METHOD, found.getElementType()); assertEquals(methodName, found.getElementName()); IMethod foundMethod = (IMethod) found; assertEquals(numberOfParameters, foundMethod.getNumberOfParameters()); }
From source file:org.eclipse.xtext.xbase.ui.navigation.XbaseHyperLinkHelper.java
License:Open Source License
protected void createHyperlinksForCrossRef(XtextResource resource, INode crossRefNode, final IHyperlinkAcceptor acceptor) { EObject containedElementAt = getEObjectAtOffsetHelper().resolveContainedElementAt(resource, crossRefNode.getOffset());/*from www .ja va 2s .c om*/ if (containedElementAt instanceof XAbstractFeatureCall) { IResolvedTypes resolveTypes = typeResolver.resolveTypes(resource); XAbstractFeatureCall featureCall = (XAbstractFeatureCall) containedElementAt; final JvmIdentifiableElement targetElement = featureCall.getFeature(); if (targetElement instanceof JvmType || featureCall.getFeature() instanceof JvmEnumerationLiteral) { return; } IJavaElement javaElement = javaElementFinder.findExactElementFor(targetElement); if (sourceViewer != null && javaElement != null && (javaElement.getElementType() == IJavaElement.METHOD && canBeOverridden((IMethod) javaElement))) { acceptor.accept(new XbaseImplementatorsHyperlink(javaElement, new Region(crossRefNode.getOffset(), crossRefNode.getLength()), sourceViewer, implOpener)); } LightweightTypeReference typeReference = resolveTypes.getActualType(featureCall); if (typeReference == null || typeReference.isPrimitive() || typeReference.isPrimitiveVoid()) { return; } final JvmType type = typeReference.getType(); if (type != null) createHyperlinksTo(resource, crossRefNode, type, new IHyperlinkAcceptor() { @Override public void accept(IHyperlink hyperlink) { if (hyperlink instanceof AbstractHyperlink) { String target = labelForTargetElement(targetElement); ((AbstractHyperlink) hyperlink) .setHyperlinkText("Open " + target + " Type - " + type.getSimpleName()); } acceptor.accept(hyperlink); } private String labelForTargetElement(final JvmIdentifiableElement targetElement) { String target = "Return"; if (targetElement instanceof JvmField) { target = "Field"; } else if (targetElement instanceof JvmFormalParameter) { // special case for variables in switch and for loops if (targetElement.eContainer() instanceof XSwitchExpression || targetElement.eContainer() instanceof XForLoopExpression) { target = "Variable"; } else { target = "Parameter"; } } else if (targetElement instanceof XVariableDeclaration) { target = "Variable"; } return target; } }); } }
From source file:org.eclipselabs.stlipse.javaeditor.JavaCompletionProposalComputer.java
License:Open Source License
private StringBuilder resolveBeanPropertyName(IJavaElement element) throws JavaModelException { StringBuilder result = new StringBuilder(); int elementType = element.getElementType(); String elementName = element.getElementName(); if (elementType == IJavaElement.FIELD) { result.append(elementName);/*from w w w . j a va2 s. com*/ } else if (elementType == IJavaElement.METHOD) { IMethod method = (IMethod) element; if (Flags.isPublic(method.getFlags()) && (isSetter(method) || isGetter(method))) { result.append(BeanPropertyVisitor.getFieldNameFromAccessor(elementName)); } } return result; }
From source file:org.evosuite.eclipse.popup.actions.ExtendSuiteEditorAction.java
License:Open Source License
@Override public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); ISelection selection = HandlerUtil.getActiveMenuSelection(event); String SUT = ""; IResource target = null;//w w w .jav a2 s .c o m System.out.println("Current selection of type " + selection.getClass().getName() + ": " + selection); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; IAdaptable firstElement = (IAdaptable) treeSelection.getFirstElement(); // Relies on an internal API, bad juju if (firstElement instanceof org.eclipse.jdt.internal.core.CompilationUnit) { try { org.eclipse.jdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.jdt.internal.core.CompilationUnit) firstElement; String packageName = ""; if (compilationUnit.getPackageDeclarations().length > 0) { System.out.println( "Package: " + compilationUnit.getPackageDeclarations()[0].getElementName()); packageName = compilationUnit.getPackageDeclarations()[0].getElementName(); } String targetSuite = compilationUnit.getElementName().replace(".java", ""); if (!packageName.isEmpty()) targetSuite = packageName + "." + targetSuite; System.out.println("Selected class: " + targetSuite); SUT = targetSuite; target = compilationUnit.getResource(); } catch (JavaModelException e) { } } } else if (activeEditor instanceof JavaEditor) { ITypeRoot root = EditorUtility.getEditorInputJavaElement(activeEditor, false); ITextSelection sel = (ITextSelection) ((JavaEditor) activeEditor).getSelectionProvider().getSelection(); int offset = sel.getOffset(); IJavaElement element; try { element = root.getElementAt(offset); if (element.getElementType() == IJavaElement.METHOD) { IJavaElement pDeclaration = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IPackageFragment pFragment = (IPackageFragment) pDeclaration; String packageName = ""; if (pFragment.getCompilationUnits()[0].getPackageDeclarations().length > 0) { System.out.println("Package: " + pFragment.getCompilationUnits()[0].getPackageDeclarations()[0].getElementName()); packageName = pFragment.getCompilationUnits()[0].getPackageDeclarations()[0] .getElementName(); } String targetSuite = element.getParent().getElementName(); if (!packageName.isEmpty()) targetSuite = packageName + "." + targetSuite; System.out.println("Selected class: " + targetSuite); SUT = targetSuite; } else if (element.getElementType() == IJavaElement.TYPE) { IType type = ((IType) element); System.out.println("Selected class: " + type.getFullyQualifiedName()); SUT = type.getFullyQualifiedName(); } IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot(); target = wroot.findMember(root.getPath()); } catch (JavaModelException e) { } } if (!SUT.isEmpty() && target != null) { IProject proj = target.getProject(); fixJUnitClassPath(JavaCore.create(proj)); generateTests(target); } return null; }
From source file:org.evosuite.eclipse.popup.actions.GenerateTestsEditorAction.java
License:Open Source License
@Override public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart activeEditor = HandlerUtil.getActiveEditor(event); // ISelection selection = HandlerUtil.getCurrentSelection(event); ISelection selection = HandlerUtil.getActiveMenuSelection(event); String SUT = ""; IResource target = null;//from ww w . j a v a2s .co m System.out.println("Current selection of type " + selection.getClass().getName() + ": " + selection); if (selection instanceof TreeSelection) { TreeSelection treeSelection = (TreeSelection) selection; IAdaptable firstElement = (IAdaptable) treeSelection.getFirstElement(); // Relies on an internal API, bad juju if (firstElement instanceof org.eclipse.jdt.internal.core.CompilationUnit) { try { org.eclipse.jdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.jdt.internal.core.CompilationUnit) firstElement; String packageName = ""; if (compilationUnit.getPackageDeclarations().length > 0) { System.out.println( "Package: " + compilationUnit.getPackageDeclarations()[0].getElementName()); packageName = compilationUnit.getPackageDeclarations()[0].getElementName(); } String targetSuite = compilationUnit.getElementName().replace(".java", ""); if (!packageName.isEmpty()) targetSuite = packageName + "." + targetSuite; System.out.println("Selected class: " + targetSuite); SUT = targetSuite; target = compilationUnit.getResource(); } catch (JavaModelException e) { } } } else if (activeEditor instanceof JavaEditor) { ITypeRoot root = EditorUtility.getEditorInputJavaElement(activeEditor, false); ITextSelection sel = (ITextSelection) ((JavaEditor) activeEditor).getSelectionProvider().getSelection(); int offset = sel.getOffset(); IJavaElement element; try { element = root.getElementAt(offset); if (element == null) { ISelection sel2 = HandlerUtil.getCurrentSelection(event); System.out.println( "Selected element of type " + sel2.getClass().getName() + ": " + sel2.toString()); } else if (element.getElementType() == IJavaElement.METHOD) { IJavaElement pDeclaration = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IPackageFragment pFragment = (IPackageFragment) pDeclaration; String packageName = ""; if (pFragment.getCompilationUnits()[0].getPackageDeclarations().length > 0) { System.out.println("Package: " + pFragment.getCompilationUnits()[0].getPackageDeclarations()[0].getElementName()); packageName = pFragment.getCompilationUnits()[0].getPackageDeclarations()[0] .getElementName(); } String targetSuite = element.getParent().getElementName(); if (!packageName.isEmpty()) targetSuite = packageName + "." + targetSuite; System.out.println("Selected class: " + targetSuite); SUT = targetSuite; } else if (element.getElementType() == IJavaElement.TYPE) { IType type = ((IType) element); System.out.println("Selected class: " + type.getFullyQualifiedName()); SUT = type.getFullyQualifiedName(); } IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot(); target = wroot.findMember(EditorUtility.getEditorInputJavaElement(activeEditor, false).getPath()); } catch (JavaModelException e) { } } if (!SUT.isEmpty() && target != null) { IProject proj = target.getProject(); fixJUnitClassPath(JavaCore.create(proj)); generateTests(target); } return null; }
From source file:org.evosuite.eclipse.quickfixes.MarkerWriter.java
License:Open Source License
public IJavaElement getMethod(IJavaElement e) { IJavaElement method = e;/*from ww w. j a va 2 s. c o m*/ while (method != null && method.getElementType() != IJavaElement.METHOD) { method = method.getParent(); } return method; }
From source file:org.fastcode.popup.actions.easycreate.CopyMemberAction.java
License:Open Source License
/** * This method is used by both copying from existing member or creating new * member.// w w w .ja v a 2 s . co m * * @param type * @param newField * @throws Exception * */ protected void copySelectedMember(final IType type, final IJavaElement element, String newField) throws Exception { final GlobalSettings globalSettings = GlobalSettings.getInstance(); if (element == null) { openError(this.editorPart.getSite().getShell(), "Selection Error", "Please select some field and try again."); return; } switch (element.getElementType()) { case IJavaElement.TYPE: if (!isMemberNameSelected(type, (ITextSelection) this.selection)) { openError(this.editorPart.getSite().getShell(), "Selection Error", "Please select part or whole name of a method/field/type and try again."); return; } if (!element.equals(type)) { openError(this.editorPart.getSite().getShell(), "Selection Error", "Please select part or whole name of primary type and try again."); return; } final InputDialog typeInputDialog = new InputDialog(this.editorPart.getSite().getShell(), "New Name", "Enter a new name for class or names (space separated)", EMPTY_STR, null); if (typeInputDialog.open() == Window.CANCEL) { return; } final String newTypeName = typeInputDialog.getValue(); final ICompilationUnit retCompUnit = copyType(type, newTypeName, (ITextSelection) this.selection); if (retCompUnit != null) { final IEditorPart javaEditor = JavaUI.openInEditor(retCompUnit); JavaUI.revealInEditor(javaEditor, (IJavaElement) retCompUnit.findPrimaryType()); } break; case IJavaElement.IMPORT_DECLARATION: final IImportDeclaration importDeclaration = (IImportDeclaration) element; copyImport(type, importDeclaration, (ITextSelection) this.selection); break; case IJavaElement.FIELD: final IField field = (IField) element; if (!isMemberNameSelected(field, (ITextSelection) this.selection)) { openError(this.editorPart.getSite().getShell(), "Selection Error", "Please select part or whole name of a method/field and try again."); return; } //final boolean createGetterSetter = globalSettings.isGetterSetterForPrivateFields(); if (isEmpty(newField) && (isPrivate(field.getFlags()) || isProtected(field.getFlags())) || this.allowMultiple || doesGetterSetterExist(field) != GETTER_SETTER.NONE) { final InputDialog fieldInputDialog = new InputDialog(this.editorPart.getSite().getShell(), "New Name", "Enter a new name for field or names (space separated)", EMPTY_STR, null); if (fieldInputDialog.open() == Window.CANCEL) { return; } newField = fieldInputDialog.getValue(); } else if (isEmpty(newField)) { newField = "copyOf"; } copyField(type, field, newField, (ITextSelection) this.selection); break; case IJavaElement.METHOD: if (!isMemberNameSelected((IMethod) element, (ITextSelection) this.selection)) { MessageDialog.openError(this.editorPart.getSite().getShell(), "Selection Error", "Please select part or whole name of a method/field and try again."); return; } boolean copyBody = true; if (type.isClass()) { if (globalSettings.getCopyMethodBody() == CREATE_OPTIONS_CHOICE.NEVER_CREATE) { copyBody = false; } else if (globalSettings.getCopyMethodBody() == CREATE_OPTIONS_CHOICE.ASK_TO_CREATE) { final MessageDialogWithToggle dialogWithToggle = MessageDialogWithToggle.openYesNoQuestion( this.editorPart.getSite().getShell(), "Copy Method Body", "Would you like to copy method's body as well?", "Remember Decision", false, Activator.getDefault().getPreferenceStore(), P_ASK_FOR_COPY_METHOD_BODY); if (dialogWithToggle.getReturnCode() != MESSAGE_DIALOG_RETURN_YES) { copyBody = false; } } } copyMethod(type, (IMethod) element, (ITextSelection) this.selection, copyBody); break; default: break; } }
From source file:org.fastcode.popup.actions.easycreate.CopyMemberAction.java
License:Open Source License
/** * * @param type/* w w w . j av a 2s . co m*/ * @param member * @param newMemberName * @param newFieldPart * @param selectedText * @param copyBody * @return * @throws Exception */ private IMember copyMemberAndSelect(final IType type, final IMember member, final IMember sibling, final String newMemberName, final String newFieldPart, final String selectedText, final boolean copyBody) throws Exception { final IJavaElement nextElement = findNextElement(type, sibling); IMember newMember = null; final GlobalSettings globalSettings = getInstance(); if (member.getElementType() != IJavaElement.METHOD || copyBody) { member.copy(type, nextElement, newMemberName, false, null); } else { // Create a new method signature manually final IMethod method = (IMethod) member; int count = 0; final StringBuilder methodSrc = new StringBuilder(); if (isJunitTest(type)) { final StringBuilder methAnnotations = new StringBuilder(); final IPreferenceStore preferences = new ScopedPreferenceStore(new InstanceScope(), FAST_CODE_PLUGIN_ID); final String methodAnnotations = preferences.getString(P_JUNIT_METHOD_ANNOTATIONS); if (methodAnnotations != null) { for (String methodAnnotation : methodAnnotations.split(NEWLINE)) { methodAnnotation = replacePlaceHolder(methodAnnotation, "user", globalSettings.getUser()); final String currDate = computeDate(globalSettings.getDateFormat()); methodAnnotation = replacePlaceHolder(methodAnnotation, "curr_date", currDate); methodAnnotation = replacePlaceHolder(methodAnnotation, "today", currDate); methAnnotations.append(methodAnnotation + NEWLINE); } } methodSrc.append(methAnnotations.toString()); } else { for (final IAnnotation annotation : method.getAnnotations()) { methodSrc.append("@" + annotation.getSource() + NEWLINE); } } if (isPrivate(method.getFlags())) { methodSrc.append("private"); } else if (isProtected(method.getFlags())) { methodSrc.append("protected"); } else if (isPublic(method.getFlags())) { methodSrc.append("public"); } if (isStatic(method.getFlags())) { methodSrc.append(SPACE + "static"); } methodSrc.append(SPACE + Signature.getSignatureSimpleName(method.getReturnType())); methodSrc.append(SPACE + newMemberName); methodSrc.append(LEFT_PAREN); for (final String paramName : method.getParameterNames()) { final String paramType = method.getParameterTypes()[count]; methodSrc.append(Signature.getSignatureSimpleName(paramType) + SPACE + paramName); if (count < method.getParameterNames().length - 1) { methodSrc.append(COMMA + SPACE); } count++; } methodSrc.append(") {\n"); methodSrc.append("}\n"); newMember = type.createMethod(methodSrc.toString(), nextElement, false, null); } if (newMember == null || !newMember.exists()) { if (member instanceof IField) { newMember = type.getField(newMemberName); } else if (member instanceof IMethod) { newMember = type.getMethod(newMemberName, ((IMethod) member).getParameterTypes()); } } ITextSelection sel = null; if (member.getElementName().equals(selectedText)) { sel = new TextSelection(newMember.getNameRange().getOffset(), newMember.getNameRange().getLength()); } else { final String textToSelect = isEmpty(newFieldPart) ? COPYOF : newFieldPart; sel = new TextSelection( newMember.getNameRange().getOffset() + newMember.getElementName().indexOf(textToSelect), textToSelect.length()); } this.editorPart.getEditorSite().getSelectionProvider().setSelection(sel); return newMember; }
From source file:org.fastcode.util.JUnitCreator.java
License:Open Source License
/** * * @param typeToWorkOn/* ww w . j a va 2 s . c o m*/ * @param method * @return * @throws Exception */ public static IMember generateTest(final IType type, final Map<Object, List<FastCodeEntityHolder>> commitMessage, final IMethod... methods) throws Exception { final VersionControlPreferences versionControlPreferences = VersionControlPreferences.getInstance(); if (JunitPreferences.getInstance(type) == null) { throw new Exception( "Please select the correct project in Windows->Preferences->Fast Code->Unit Test and try again."); } final CreateUnitTestData createUnitTestData = getCreateUnitTestData(type, methods); if (createUnitTestData == null) { return null; } final JunitPreferencesAndType junitPreferencesAndType = createUnitTestData.getJunitPreferencesAndType(); // JUnitUtil.findJunitPreferences(type, // createUnitTestData.getJunitTestProfileName()); /* * if (junitPreferencesAndType == null) { throw new * Exception("This class you selected does not match any profile. " + * "Please configure it first by going to Window -> Preference -> Fast Code Pereference." * ); } */ JunitPreferences junitPreferences = junitPreferencesAndType.getJunitPreferences(); IType typeToWorkOn = junitPreferencesAndType.getType(); /* * junitPreferences.setExpTest(createUnitTestData.getUnitTestType() == * UNIT_TEST_TYPE.EXCEPTION_TEST); * junitPreferences.setHandleException(createUnitTestData * .getHandleException()); * junitPreferences.setResultFormatList(Arrays.asList * (createUnitTestData.getUnitTestRsltFormatSelected())); * junitPreferences * .setMethodReturnType(createUnitTestData.getMethodReturnType()); */ junitPreferences.setCreateUnitTestData(createUnitTestData); // String junitTestLocation = // replacePlaceHolder(junitPreferences.getJunitTestLocation(), // "project", type.getJavaProject().getElementName()); // junitTestLocation = "/" + junitTestLocation; final GlobalSettings globalSettings = getInstance(); String junitTestLocation = globalSettings.isUseDefaultForPath() ? globalSettings.getSourcePathTest() : junitPreferences.getJunitTestLocation(); junitTestLocation = getDefaultPathFromProject(typeToWorkOn.getJavaProject(), "test", junitTestLocation); final IPackageFragmentRoot testPackageFragmentRoot = SourceUtil .getPackageRootFromProject(typeToWorkOn.getJavaProject(), junitTestLocation); if (testPackageFragmentRoot == null || !testPackageFragmentRoot.exists()) { throw new Exception("Path does not exist in the project " + junitTestLocation); } // final String junitTestClassName = // junitPreferences.getJunitTestClass(); final String junitBase = junitPreferences.getJunitBaseType(); // final boolean createMethodBody = // junitPreferences.isCreateMethodBody(); // final boolean alwaysCreateTryCatch = // junitPreferences.isAlwaysCreateTryCatch(); // final boolean createInstance = junitPreferences.isCreateInstance(); // final String[] methodAnnotations = // junitPreferences.getMethodAnnotations(); ICompilationUnit unitTestCU = findTestUnit(typeToWorkOn, junitPreferences); // find the interface if unit test is null if (unitTestCU == null && typeToWorkOn.isClass()) { final IType tmpType = findSuperInterfaceType(typeToWorkOn); if (tmpType != null) { final JunitPreferences junitPref = JunitPreferences.getInstance(tmpType); if (junitPref != null) { unitTestCU = findTestUnit(tmpType, junitPref); if (unitTestCU != null) { junitPreferences = junitPref; typeToWorkOn = tmpType; /* * junitPreferences.setExpTest(createUnitTestData. * getUnitTestType() == UNIT_TEST_TYPE.EXCEPTION_TEST); * junitPreferences * .setHandleException(createUnitTestData * .getHandleException()); * junitPreferences.setResultFormatList * (Arrays.asList(createUnitTestData * .getUnitTestRsltFormatSelected())); * junitPreferences.setMethodReturnType * (createUnitTestData.getMethodReturnType()); */ junitPreferences.setCreateUnitTestData(createUnitTestData); } } } } if (!typeToWorkOn.equals(type) && checkForErrors(typeToWorkOn.getCompilationUnit().getResource())) { if (!MessageDialog.openQuestion(new Shell(), "Error", "There seems to be some problems associated with " + typeToWorkOn.getElementName() + ". It is better to fix those problems and try again. Do you want to continue?")) { return null; } } IType junitBaseType = null; final JUNIT_TYPE junitType = junitPreferences.getJunitType(); if (junitType == JUNIT_TYPE.JUNIT_TYPE_3) { junitBaseType = typeToWorkOn.getJavaProject().findType(junitBase); if (junitBaseType == null || !junitBaseType.exists()) { throw new Exception("Unable to find Junit Base Class " + junitBase + " in the current project. " + "Make sure you have configured it properly by going to Windows -> Preference ->Fast Code Preference"); } } final String testPkg = typeToWorkOn.getPackageFragment().getElementName(); IPackageFragment testPackageFragment = testPackageFragmentRoot.getPackageFragment(testPkg); if (testPackageFragment == null || !testPackageFragment.exists()) { testPackageFragment = testPackageFragmentRoot.createPackageFragment(testPkg, false, null); } //final String testFormat = junitPreferences.getTestFormat(); final String instance = createDefaultInstance(typeToWorkOn.getElementName()); final CreateSimilarDescriptor createSimilarDescriptor = makeCreateSimilarDescriptor(junitPreferences, typeToWorkOn); final FastCodeContext fastCodeContext = new FastCodeContext(typeToWorkOn, true, junitPreferences); final boolean testClassExst = unitTestCU != null && unitTestCU.exists(); final CreateSimilarDescriptorClass createSimilarDescriptorClass = createSimilarDescriptor .getCreateSimilarDescriptorClasses()[0]; IFile unitTestFile = null; boolean createFileAlone = false; if (!testClassExst) { final String prjURI = testPackageFragment.getResource().getLocationURI().toString(); final String path = prjURI.substring(prjURI.indexOf(COLON) + 1); final File newFileObj = new File( path + FORWARD_SLASH + createSimilarDescriptor.getToPattern() + DOT + JAVA_EXTENSION); final boolean prjShared = !isEmpty( testPackageFragment.getResource().getProject().getPersistentProperties()); final boolean prjConfigured = !isEmpty( isPrjConfigured(testPackageFragment.getResource().getProject().getName())); if (versionControlPreferences.isEnable() && prjShared && prjConfigured) { final RepositoryService repositoryService = getRepositoryServiceClass(); 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", junitPreferences.getJunitTestClass() + " is already present in repository. Please synchronise and try again."); return null;*/ 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 null; } } } else { createFileAlone = true; } /*final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache.getFilesToCheckIn().add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath()));*/ addOrUpdateFileStatusInCache(newFileObj); createSimilar(fastCodeContext, null, createSimilarDescriptor, new NullProgressMonitor()); unitTestCU = fastCodeContext.getCompilationUnitRegsistry(createSimilarDescriptorClass); if (!createFileAlone) { unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource();//.getLocationURI()); List<FastCodeEntityHolder> chngsForType = commitMessage.get(unitTestFile); if (chngsForType == null) { chngsForType = new ArrayList<FastCodeEntityHolder>(); chngsForType.add(new FastCodeEntityHolder(PLACEHOLDER_CLASS, new FastCodeType(unitTestCU.findPrimaryType()))); } commitMessage.put(unitTestFile, chngsForType); } } else { createFileAlone = true; } if (testClassExst) { if (!unitTestCU.getResource().isSynchronized(0)) { throw new Exception( unitTestCU.getElementName() + " is not Synchronized, please refresh and try again."); } unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource(); //.getLocationURI()); } final Map<String, FastCodeMethod> stubMethods = createUnitTestData.getStubMethodsMap(); // FastCodeMethodRegistry.getRegisteredUnitTestStubMethods(junitType); if (stubMethods != null) { // && !testClassExst) { /* * final FastCodeMethodSelectionDialog methodSelectionDialog = new * FastCodeMethodSelectionDialog(new Shell(), "Select Methods", * "Select One of more Stub Methods from Below", stubMethods, true); * methodSelectionDialog.open(); final Object[] regularMethods = * methodSelectionDialog.getResult(); */ //unitTestFile = (IFile) unitTestCU.findPrimaryType().getResource(); if (!createFileAlone) { final File newFileObj = new File(unitTestFile.getLocationURI().toString()); final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache.getFilesToCheckIn() .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath())); } if (createUnitTestData.getSelectedStubMethodsList() != null) { for (final FastCodeMethod fastCodeMethod : createUnitTestData.getSelectedStubMethodsList() .toArray(new FastCodeMethod[0])) { createStubMethod(unitTestCU.findPrimaryType(), fastCodeMethod); if (!createFileAlone) { List<FastCodeEntityHolder> chngesForType = commitMessage.get(unitTestFile); if (chngesForType == null) { chngesForType = new ArrayList<FastCodeEntityHolder>(); final List<Object> fastCodeMethodList = new ArrayList<Object>(); fastCodeMethodList.add(fastCodeMethod); chngesForType .add(new FastCodeEntityHolder(PLACEHOLDER_STUBMETHODS, fastCodeMethodList)); } else { boolean isNew = true; Object fastCodeMethodList = null; for (final FastCodeEntityHolder fcEntityHolder : chngesForType) { if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_STUBMETHODS)) { fastCodeMethodList = fcEntityHolder.getFastCodeEntity(); isNew = false; break; } } if (isNew) { fastCodeMethodList = new ArrayList<Object>(); ((List<Object>) fastCodeMethodList).add(fastCodeMethod); chngesForType .add(new FastCodeEntityHolder(PLACEHOLDER_STUBMETHODS, fastCodeMethodList)); } else { ((List<Object>) fastCodeMethodList).add(fastCodeMethod); } } commitMessage.put(unitTestFile, chngesForType); } } } } if (junitType == JUNIT_TYPE.JUNIT_TYPE_3 || junitType == JUNIT_TYPE.JUNIT_TYPE_CUSTOM) { if (junitBaseType != null && junitBaseType.exists()) { unitTestCU.createImport(junitBaseType.getFullyQualifiedName(), null, null); } } else if (junitType == JUNIT_TYPE.JUNIT_TYPE_4) { unitTestCU.createImport("org.junit.*", null, null); unitTestCU.createImport("org.junit.Assert.*", null, AccStatic, null); } else if (junitType == JUNIT_TYPE.JUNIT_TYPE_TESTNG) { unitTestCU.createImport("org.testng.annotations.*", null, null); unitTestCU.createImport("org.testng.Assert.*", null, AccStatic, null); } if (unitTestCU == null || !unitTestCU.exists() || createUnitTestData.getClassMethodsSelected() == null || methods.length == 0) { return unitTestCU != null && unitTestCU.exists() ? unitTestCU.findPrimaryType() : null; } unitTestCU.createImport(typeToWorkOn.getFullyQualifiedName(), null, null); final List<IMethod> retMethods = new ArrayList<IMethod>(); final UnitTestMethodBuilder methodBuilder = new UnitTestMethodBuilder(fastCodeContext); boolean becomeWorkingCopy = false; if (!unitTestCU.isWorkingCopy()) { becomeWorkingCopy = true; unitTestCU.becomeWorkingCopy(null); } try { for (final IMethod method : createUnitTestData.getClassMethodsSelected().toArray(new IMethod[0])) { if (EMPTY_STR.equals(createUnitTestData.getTestMethodName())) { createUnitTestData.setTestMethodName(method.getElementName()); } IMethod methodToWorkOn = method; if (!type.equals(typeToWorkOn)) { methodToWorkOn = typeToWorkOn.getMethod(method.getElementName(), method.getParameterTypes()); if (methodToWorkOn == null || !methodToWorkOn.exists()) { MessageDialog.openError(new Shell(), "Error", "Method " + method.getElementName() + " does not exist in " + typeToWorkOn.getElementName()); continue; } } final IMethod[] testMethods = testClassExst ? findTestMethods(typeToWorkOn, methodToWorkOn, junitPreferences) : null; // boolean testMethodExist = false, createAotherTestMethod = // false; // testMethodExist = createAotherTestMethod = false; if (testMethods != null && testMethods.length > 0) { // testMethodExist = createAotherTestMethod = true; /* * final String[] choices = {"Create an additional test", * "Do Nothing", "Jump To The Test"}; * * final String choice = getChoiceFromMultipleValues(new * Shell(), "Junit Test Exists for method " + * methodToWorkOn.getElementName(), "Would You Like To", * choices); final int result = findInStringArray(choice, * choices); */ if (createUnitTestData.getUnitTestChoice().equals(UNIT_TEST_CHOICE.CREATEADDITIONALTEST)) { // break; } else if (createUnitTestData.getUnitTestChoice().equals(UNIT_TEST_CHOICE.JUMPTOTEST)) { if (methods.length == 1) { if (testMethods.length == 1) { return testMethods[0]; } final MethodSelectionDialog methodSelectionDialog = new MethodSelectionDialog( new Shell(), "Select Test Method", "Multiple tests found for the method you selected, " + "please select one from the list below.", testMethods, false); methodSelectionDialog.open(); return methodSelectionDialog.getResult() == null || methodSelectionDialog.getResult().length == 0 ? null : (IMethod) methodSelectionDialog.getFirstResult(); } } /* * switch (result) { case 0: // createAotherTestMethod = * true; break; case 1: continue; case 2: * * } */ // if (createAotherTestMethod) { // final MessageDialogWithToggle dialogForMethodBody = // openYesNoQuestion(new Shell(), // "Create Method Body", "Do you create method body?", // "Remember Decision", false, // Activator.getDefault().getPreferenceStore(), // P_JUNIT_TEST_ASK_FOR_METHOD_BODY); // if (dialogForMethodBody.getReturnCode() != // MESSAGE_DIALOG_RETURN_YES) { // createMethodBody = false; // alwaysCreateTryCatch = false; // } // } } if (junitBaseType != null) { for (final IMethod meth : junitBaseType.getMethods()) { if (isAbstract(meth.getFlags())) { // add methods here. // copyMethods(junitBaseType, // testCU.findPrimaryType(), meth, null, // METHOD_PATTERN_DEFAULT, null, // RETURN_TYPE.RETURN_TYPE_PASS_THRU, null, null, // false, null, false, false, null, null, null); } } } // if (junitPreferences.isCreateInstance()) { // final IField field = // testCU.findPrimaryType().getField(instance); // if (field == null || !field.exists()) { // testCU.findPrimaryType().createField("protected " + // type.getElementName() + SPACE + instance + ";\n", null, // false, null); // } // } // if (!testMethodExist || createAotherTestMethod) { // copyImports(type.getCompilationUnit(), testCU, method); // copyMethods(type, testCU.findPrimaryType(), method, instance, // junitPreferences.getJunitTestMethod(), // createAotherTestMethod ? EXTENSION_OTHER : null, // RETURN_TYPE.RETURN_TYPE_CONSUME, null, null, false, "result", // createMethodBody, alwaysCreateTryCatch, // methodAnnotations, null, null); // } /** * if (method == null) { for (final IMethod meth: * testCU.findPrimaryType().getMethods()) { if * (!meth.isConstructor()) { testMethod = meth; break; } } } * else { String testMethName = * replacePlaceHolder(junitPreferences.getJunitTestMethod(), * "method_name", method.getElementName()); if * (!junitPreferences * .getJunitTestMethod().startsWith("${method_name}")) { * testMethName = * replacePlaceHolder(junitPreferences.getJunitTestMethod(), * "method_name", * createEmbeddedInstance(method.getElementName())); } * * testMethod = testCU.findPrimaryType().getMethod(testMethName * + (createAotherTestMethod ? EXTENSION_OTHER : EMPTY_STR), * null); } */ if (!createFileAlone) { final File newFileObj = new File(unitTestFile.getLocationURI().toString()); final FastCodeCheckinCache checkinCache = FastCodeCheckinCache.getInstance(); checkinCache.getFilesToCheckIn() .add(new FastCodeFileForCheckin(INITIATED, newFileObj.getAbsolutePath())); } final IMethod tstMethod = methodBuilder.buildMethod(methodToWorkOn, unitTestCU.findPrimaryType(), createSimilarDescriptor, createSimilarDescriptorClass); createUnitTestData.setTestMethodName(EMPTY_STR); if (tstMethod != null) { retMethods.add(tstMethod); if (!createFileAlone) { List<FastCodeEntityHolder> chngesForType = commitMessage.get(unitTestFile); if (chngesForType == null) { chngesForType = new ArrayList<FastCodeEntityHolder>(); final List<Object> fastCodeMethodList = new ArrayList<Object>(); fastCodeMethodList.add(new FastCodeMethod(tstMethod)); chngesForType .add(new FastCodeEntityHolder(PLACEHOLDER_TESTMETHODS, fastCodeMethodList)); } else { boolean isNew = true; Object fastCodeMethodList = null; for (final FastCodeEntityHolder fcEntityHolder : chngesForType) { if (fcEntityHolder.getEntityName().equals(PLACEHOLDER_TESTMETHODS)) { fastCodeMethodList = fcEntityHolder.getFastCodeEntity(); isNew = false; break; } } if (isNew) { fastCodeMethodList = new ArrayList<Object>(); ((List<Object>) fastCodeMethodList).add(new FastCodeMethod(tstMethod)); chngesForType .add(new FastCodeEntityHolder(PLACEHOLDER_TESTMETHODS, fastCodeMethodList)); } else { ((List<Object>) fastCodeMethodList).add(new FastCodeMethod(tstMethod)); } } commitMessage.put(unitTestFile, chngesForType); } } } } catch (final Exception ex) { ex.printStackTrace(); throw new Exception(ex.getMessage(), ex); } finally { // if (testClassExst) { if (!unitTestCU.hasResourceChanged()) { unitTestCU.commitWorkingCopy(false, null); } if (becomeWorkingCopy) { unitTestCU.discardWorkingCopy(); } } if (retMethods.isEmpty()) { return unitTestCU.findPrimaryType(); } else if (retMethods.size() == 1) { return retMethods.get(0); } else { final IMember[] selectedMembers = getSelectedMembers(IJavaElement.METHOD, retMethods.toArray(new IMethod[0]), "Unit Test to Jump", false); return selectedMembers == null || selectedMembers.length == 0 ? retMethods.get(0) : (IMethod) selectedMembers[0]; } }