List of usage examples for org.eclipse.jdt.core IJavaElement getElementName
String getElementName();
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 av a 2 s . c o m } 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.electrocodeogram.cpc.ui.utils.EclipseUtils.java
License:BSD License
/** * @param resource/*from w ww .j a va2 s .com*/ * @return full package name in default java notation (with dots) */ public static String getJavaPackageName(IJavaElement resource) { String name = resource == null ? null : resource.getElementName(); //$NON-NLS-1$ if (name == null) { return ""; //$NON-NLS-1$ } int type = resource.getElementType(); if (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) { return name; } IJavaElement ancestor = resource.getAncestor(IJavaElement.PACKAGE_FRAGMENT); if (ancestor != null) { return ancestor.getElementName(); } return ""; //$NON-NLS-1$ }
From source file:org.entirej.ide.ui.utils.PackageAssistProvider.java
License:Apache License
public IContentProposal[] getProposals(String currentContent, int position) { final List<TypeProposal> proposals = new ArrayList<TypeProposal>(); if (currentContent.length() > position) { currentContent = currentContent.substring(0, position); }/* w w w .j a v a 2 s.c om*/ IJavaProject javaProject = projectProvider.getJavaProject(); if (javaProject == null) return new IContentProposal[0]; if (javaProject.exists()) { try { IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(); for (int i = 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { IPackageFragmentRoot sourceRoot = roots[i]; if (sourceRoot != null && sourceRoot.exists()) { IJavaElement[] children = sourceRoot.getChildren(); for (IJavaElement element : children) { if (element instanceof IPackageFragment) { if (filterPkg(currentContent, position, element.getElementName())) { IPackageFragment fragment = (IPackageFragment) element; proposals.add(new TypeProposal(new Type(element.getElementName(), fragment.hasChildren() ? PKG_IMG : PKG_IMG_EMPTY), null)); } } } } } } } catch (JavaModelException e) { EJCoreLog.logException(e); } } Collections.sort(proposals, new Comparator<TypeProposal>() { public int compare(TypeProposal o1, TypeProposal o2) { return o1.type.pkg.compareTo(o2.type.pkg); } }); return proposals.toArray(new IContentProposal[0]); }
From source file:org.evolizer.changedistiller.job.ChangeDistiller.java
License:Apache License
private IStatus processElement(IJavaElement element, IProgressMonitor group, int tick) { Job changeDistillerJob = null;/* w w w. j a v a 2s .c o m*/ try { // ICompilationUnit if (element.getElementType() == IJavaElement.COMPILATION_UNIT) { changeDistillerJob = new SourceDistiller("Process class " + element.getElementName()); SourceDistiller job = (SourceDistiller) changeDistillerJob; List<Revision> revisions = ChangeDistillerPlugin.getPersistencyProvider() .query("from Revision as r where r.file.path like '%/" + element.getElementName() + "' and r.number not like '1.%.%'" + " order by r.report.creationTime asc", Revision.class); job.setProject(element.getJavaProject().getProject()); job.setRevisionsToDistill(revisions); // IPackageFragment; but only process source fragments (exclude binary Jars) } else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { IPackageFragment fragment = (IPackageFragment) element; if ((fragment.getKind() == IPackageFragmentRoot.K_SOURCE) && fragment.containsJavaResources()) { changeDistillerJob = new PackageFragmentDistiller( "Process Package " + fragment.getElementName()); ((PackageFragmentDistiller) changeDistillerJob).setPackageFragment(fragment); } // IJavaProject } else if (element.getElementType() == IJavaElement.JAVA_PROJECT) { changeDistillerJob = new ProjectDistiller("Process project " + element.getElementName()); ((ProjectDistiller) changeDistillerJob).setJavaProject((IJavaProject) element); } } catch (JavaModelException e) { e.printStackTrace(); } if (changeDistillerJob != null) { changeDistillerJob.setProgressGroup(group, tick); changeDistillerJob.setPriority(Job.LONG); changeDistillerJob.schedule(); try { // wait until ChangeDistiller finished selected element changeDistillerJob.join(); } catch (InterruptedException e) { e.printStackTrace(); } return changeDistillerJob.getResult(); } return Status.OK_STATUS; }
From source file:org.evolizer.da4java.plugin.selectionhandler.JavaElementSelectionHandler.java
License:Apache License
/** * {@inheritDoc}//from ww w . java 2 s .c o m */ @Override public String getEditorTitle() { String editorTitle = "Graph"; if (getSelection() instanceof ITreeSelection) { ITreeSelection strucSelection = (ITreeSelection) getSelection(); Object elem = strucSelection.getFirstElement(); if (elem instanceof IJavaElement) { IJavaElement javaElem = (IJavaElement) elem; editorTitle = javaElem.getElementName(); } } return editorTitle; }
From source file:org.evolizer.da4java.plugin.selectionhandler.JavaElementSelectionHandler.java
License:Apache License
/** * Get the FAMIX model conform unique names plus the source reference for the given Java elements. * Currently this only applies to {@link IMethod} elements. * //from w ww. ja v a 2s . co m * @param javaElements the java elements * * @return the java element names and source reference * * @throws JavaModelException the java model exception */ private Hashtable<String, Integer> getJavaElementNamesAndSourceReference(List<IJavaElement> javaElements) throws EvolizerRuntimeException { Hashtable<String, Integer> sourceReferences = new Hashtable<String, Integer>(); for (IJavaElement element : javaElements) { if (element instanceof IMethod) { try { sourceReferences.put(JavaElementUtilities.getUniqueNameFromJavaElement(element), ((IMethod) element).getSourceRange().getOffset()); } catch (JavaModelException jme) { throw new EvolizerRuntimeException( "Error determining source range of Java element " + element.getElementName(), jme); } } } return sourceReferences; }
From source file:org.evosuite.eclipse.popup.actions.ExtendSuiteAction.java
License:Open Source License
/** * Add a new test generation job to the job queue * /*w ww . j a v a 2 s . c o m*/ * @param target */ @Override protected void addTestJob(final IResource target) { IJavaElement element = JavaCore.create(target); IJavaElement packageElement = element.getParent(); String packageName = packageElement.getElementName(); final String suiteClass = (!packageName.equals("") ? packageName + "." : "") + target.getName().replace(".java", "").replace(File.separator, "."); System.out.println("Building new job for " + suiteClass); DetermineSUT det = new DetermineSUT(); IJavaProject jProject = JavaCore.create(target.getProject()); try { String classPath = target.getWorkspace().getRoot().findMember(jProject.getOutputLocation()) .getLocation().toOSString(); String SUT = det.getSUTName(suiteClass, classPath); // choose SelectionDialog typeDialog = JavaUI.createTypeDialog(shell, new ProgressMonitorDialog(shell), target.getProject(), IJavaElementSearchConstants.CONSIDER_CLASSES, false); Object[] sutDefault = new Object[1]; sutDefault[0] = SUT; typeDialog.setInitialSelections(sutDefault); typeDialog.setTitle("Please select the class under test"); typeDialog.open(); // Type selected by the user Object[] result = typeDialog.getResult(); if (result.length > 0) { SourceType sourceType = (SourceType) result[0]; SUT = sourceType.getFullyQualifiedName(); } else { return; } Job job = new TestExtensionJob(shell, target, SUT, suiteClass); job.setPriority(Job.SHORT); IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory(); ISchedulingRule rule = ruleFactory.createRule(target.getProject()); //IFolder folder = proj.getFolder(ResourceUtil.EVOSUITE_FILES); job.setRule(rule); job.setUser(true); job.schedule(); // start as soon as possible } catch (JavaModelException e) { e.printStackTrace(); } catch (NoJUnitClassException e) { MessageDialog.openError(shell, "Evosuite", "Cannot find JUnit tests in " + suiteClass); } }
From source file:org.evosuite.eclipse.popup.actions.TestGenerationAction.java
License:Open Source License
/** * Add a new test generation job to the job queue * // ww w. j av a2s .co m * @param target */ protected void addTestJob(final IResource target) { IJavaElement element = JavaCore.create(target); if (element == null) { return; } IJavaElement packageElement = element.getParent(); String packageName = packageElement.getElementName(); final String targetClass = (!packageName.isEmpty() ? packageName + "." : "") + target.getName().replace(".java", "").replace(File.separator, "."); System.out.println("* Scheduling new automated job for " + targetClass); final String targetClassWithoutPackage = target.getName().replace(".java", ""); final String suiteClassName = targetClass + Properties.JUNIT_SUFFIX; final String suiteFileName = target.getProject().getLocation() + "/evosuite-tests/" + suiteClassName.replace('.', File.separatorChar) + ".java"; System.out.println("Checking for " + suiteFileName); File suiteFile = new File(suiteFileName); Job job = null; if (suiteFile.exists()) { MessageDialog dialog = new MessageDialog(shell, "Existing test suite found", null, // image "A test suite for class \"" + targetClass + "\" already exists. EvoSuite will overwrite this test suite. Do you really want to proceed?", MessageDialog.QUESTION_WITH_CANCEL, new String[] { "Overwrite", "Extend", "Rename Original", "Cancel" }, 0); int returnCode = dialog.open(); // 0 == overwrite // 1 == extend if (returnCode == 1) { IWorkspaceRoot wroot = target.getWorkspace().getRoot(); IResource suiteResource = wroot.getFileForLocation(new Path(suiteFileName)); job = new TestExtensionJob(shell, suiteResource, targetClass, suiteClassName); } else if (returnCode == 2) { // 2 == Rename renameSuite(target, packageName, targetClassWithoutPackage + Properties.JUNIT_SUFFIX + ".java"); } else if (returnCode > 2) { // Cancel return; } } if (job == null) job = new TestGenerationJob(shell, target, targetClass, suiteClassName); job.setPriority(Job.SHORT); IResourceRuleFactory ruleFactory = ResourcesPlugin.getWorkspace().getRuleFactory(); ISchedulingRule rule = ruleFactory.createRule(target.getProject()); //IFolder folder = proj.getFolder(ResourceUtil.EVOSUITE_FILES); job.setRule(rule); job.setUser(true); job.schedule(); // start as soon as possible }
From source file:org.evosuite.eclipse.quickfixes.MarkerWriter.java
License:Open Source License
public void writeMarkers() { System.out.println(tgr);/*from w w w . j a v a2 s .c o m*/ // ServerStatistics.getInstance().getX(); (getCoverage();) ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setResolveBindings(true); parser.setSource(tgr.getTestSuiteCode().toCharArray()); CompilationUnit compTest = (CompilationUnit) parser.createAST(null); IJavaElement jEle = JavaCore.create(res); if (jEle instanceof ICompilationUnit) { final ICompilationUnit icomp = (ICompilationUnit) jEle; // System.out.println(icomp); BufferedReader br; char[] varcontent = null; try { br = new BufferedReader(new FileReader(res.getLocation().toFile())); int size = 0; while (br.read() != -1) { size++; } // String content = ""; // String line = br.readLine(); // content += line; // while ((line = br.readLine()) != null){ // content += line; // } // parser.setSource(content.toCharArray()); br = new BufferedReader(new FileReader(res.getLocation().toFile())); varcontent = new char[size]; br.read(varcontent, 0, size); parser.setSource(varcontent); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } final char[] content = varcontent; final CompilationUnit compClass = (CompilationUnit) parser.createAST(null); compTest.accept(testM); compClass.accept(raw); IJavaElement element = JavaCore.create(res); IJavaElement packageElement = element.getParent(); String packageName = packageElement.getElementName(); final String className = (!packageName.isEmpty() ? packageName + "." : "") + res.getName().replace(".java", "").replace(File.separator, "."); final char[] classContent = varcontent; if (tgr != null) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ArrayList<Integer> lines = new ArrayList<Integer>(); Set<Integer> actualLines = new HashSet<Integer>(); actualLines.addAll(tgr.getUncoveredLines()); actualLines.addAll(tgr.getCoveredLines()); int contentPosition = 0; int line = 1; while (contentPosition != -2 && contentPosition != -1) { if (!actualLines.contains(line)) { lines.add(line); } contentPosition = compClass.getPosition(line, 0); line++; } IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (store.getBoolean("removed")) { for (Integer i : lines) { // this line couldn't be reached in the test! IJavaElement currentElement = null; int position = compClass.getPosition(i, 0); int maxPosition = compClass.getPosition(i + 1, 0); if (position == -1 || position == -2) { continue; } while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } if (position > maxPosition) { continue; } while (maxPosition < classContent.length && Character.isWhitespace(classContent[maxPosition])) { // System.out.println(classContent); maxPosition++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } if (isMethodDeclaration(i, currentElement, content, compClass, icomp)) { continue; } IJavaElement nextElement = null; int nextPosition = compClass.getPosition(i + 1, 0); if (nextPosition != -1 || nextPosition != -2) { try { nextElement = icomp.getElementAt(nextPosition); if (nextElement != currentElement) { continue; } } catch (JavaModelException e) { e.printStackTrace(); } } if (position > maxPosition) { continue; } while (maxPosition < classContent.length && Character.isWhitespace(classContent[maxPosition])) { // System.out.println(classContent); maxPosition++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } if (content[position] == '/' && content[position + 1] == '/') { continue; } if (content[position] == '}') { continue; } if (getMethod(currentElement) == null) { continue; } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.lineremovedmarker"); m.setAttribute(IMarker.MESSAGE, "This line appears to be removed by the Java Compiler."); m.setAttribute(IMarker.LINE_NUMBER, i); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0)); } catch (CoreException e) { e.printStackTrace(); } } } } if (store.getBoolean("uncovered")) { for (Integer i : tgr.getUncoveredLines()) { // this line couldn't be reached in the test! IJavaElement currentElement = null; int position = compClass.getPosition(i, 0); if (position == -1) { continue; } while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker"); m.setAttribute(IMarker.LINE_NUMBER, i); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0)); } catch (CoreException e) { e.printStackTrace(); } } } } for (BranchInfo bi : tgr.getUncoveredBranches()) { int j = bi.getLineNo(); IJavaElement currentElement = null; int position = compClass.getPosition(j, 0); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.notcoveredmarker"); m.setAttribute(IMarker.MESSAGE, "This branch (starting line " + j + ") could not be covered by EvoSuite."); m.setAttribute(IMarker.LINE_NUMBER, j); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker"); // m.setAttribute(IMarker.LINE_NUMBER, j); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1); } catch (CoreException e) { e.printStackTrace(); } } } for (MethodDeclaration method : testM.getMethods()) { String test = method.getName().getFullyQualifiedName(); Set<Failure> failures = tgr.getContractViolations(test); if (failures != null && failures.size() != 0) { // uncaught Exception! try { for (Failure f : failures) { if (f != null) { int lineNumber = 1; String message = ""; for (int i = 0; i < f.getStackTrace().length; i++) { if (f.getStackTrace()[i].getClassName().equals(className)) { boolean found = false; for (MethodDeclaration method2 : raw.getMethods()) { String s = method2.getName().getFullyQualifiedName(); if (s.equals(f.getStackTrace()[i].getMethodName())) { found = true; break; } } if (found) { message = f.getStackTrace()[i].toString(); lineNumber = f.getStackTrace()[i].getLineNumber(); break; } } } IJavaElement currentElement = null; int position = compClass.getPosition(lineNumber, 0); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { IMarker m = res.createMarker("EvoSuiteQuickFixes.exceptionmarker"); m.setAttribute(IMarker.MESSAGE, f.getExceptionName() + " detected " + message); m.setAttribute(IMarker.LINE_NUMBER, lineNumber); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(lineNumber + 1, 0) - 1); } } } } catch (CoreException e) { e.printStackTrace(); } } } } }); } } }
From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForMethod.java
License:Open Source License
@Override public void run(IMarker marker) { // TODO Auto-generated method stub IResource res = marker.getResource(); try {/*from w w w .ja v a2s.com*/ ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res); CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res); int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1; if (position == 1) { int line = marker.getAttribute(IMarker.LINE_NUMBER, 0); position = compunit.getPosition(line, 0); } AST ast = compunit.getAST(); ASTRewrite rewriter = ASTRewrite.create(ast); IJavaElement element = icomp.getElementAt(position); IJavaElement method = getMethod(element); // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); TypeDeclaration td = (TypeDeclaration) compunit.types().get(0); MethodDeclaration md = td.getMethods()[0]; int counter = 1; while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) { md = td.getMethods()[counter]; System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName()); counter++; } Annotation annotation = ast.newNormalAnnotation(); annotation.setTypeName(ast.newName("EvoIgnore")); ImportDeclaration id = ast.newImportDeclaration(); id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore")); ListRewrite lr = rewriter.getListRewrite(md.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY); ListRewrite lr2 = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY); //lr.insertFirst(annotation, null); lr.insertBefore(annotation, md, null); lr2.insertAt(id, 0, null); ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager(); IPath path = compunit.getJavaElement().getPath(); try { bm.connect(path, null, null); ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null); IDocument document = textFileBuffer.getDocument(); TextEdit edits = rewriter.rewriteAST(document, null); edits.apply(document); textFileBuffer.commit(null, false); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedTreeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { bm.disconnect(path, null, null); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } // (4) } System.out .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString()); } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { marker.delete(); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }