private void fix(IMarker marker, IProgressMonitor monitor) { MarkerResolutionGenerator.printAttributes (marker); try { String filepath = (String) marker.getAttribute(BuildPolicyConfigurationException.JAVAFILENAME); int start = (int) marker.getAttribute(IMarker.CHAR_START); int end = (int) marker.getAttribute(IMarker.CHAR_END); IFile ifile = (IFile) ResourceManager.toResource(new Path(filepath)); ICompilationUnit cu = JavaCore.createCompilationUnitFrom(ifile); String source = cu.getBuffer().getContents(); String part1 = source.substring(0,start); String part2 = source.substring(end); source = part1 + "value=\"" + resolutionMarkerDescription.getGenerator() + "\"" + part2; final Document document = new Document(source); cu.getBuffer().setContents(document.get()); cu.save(monitor, false); } catch (Exception e) { ResourceManager.logException(e); } }
/** * Collects all compilation units within the project. * @return the collection of the compilation units */ public static List<ICompilationUnit> collectAllCompilationUnits() { List<ICompilationUnit> units = new ArrayList<ICompilationUnit>(); try { IProject[] projects = getWorkspace().getRoot().getProjects(); for (int i = 0; i < projects.length; i++) { IJavaProject project = (IJavaProject)JavaCore.create((IProject)projects[i]); IPackageFragment[] packages = project.getPackageFragments(); for (int j = 0; j < packages.length; j++) { ICompilationUnit[] cus = packages[j].getCompilationUnits(); for (int k = 0; k < cus.length; k++) { IResource res = cus[k].getResource(); if (res.getType() == IResource.FILE) { String name = cus[k].getPath().toString(); if (name.endsWith(".java")) { units.add(cus[k]); } } } } } } catch (JavaModelException e) { e.printStackTrace(); } return units; }
/** * @param project * @param itype * @return * @throws JavaModelException */ private static IPath findPathInGeneratedAnnotation(IProject project, IType itype) throws JavaModelException { ICompilationUnit cu = itype.getCompilationUnit(); List<IAnnotationBinding> annotations = resolveAnnotation(cu, Generated.class).getAnnotations(); if ((annotations != null) && (annotations.size() > 0)) { IAnnotationBinding ab = annotations.get(0); IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs(); for (int i = 0; i < attributes.length; i++) { IMemberValuePairBinding attribut = attributes[i]; if (attribut.getName().equalsIgnoreCase("value")) { Object[] o = (Object[]) attribut.getValue(); if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) { try { IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim()); return p; } catch (Exception e) { ResourceManager.logException(e); return null; } } } } } return null; }
public static ICompilationUnit[] getOrCreateGeneratedTestInterfaces(IProject project) throws CoreException, FileNotFoundException { project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); IPath folderForMain = project.getFullPath() .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), true)); IPath folderForTest = project.getFullPath() .append(GraphWalkerContextManager.getTargetFolderForTestInterface(project.getName(), false)); if (ResourceManager.getResource(folderForMain.toString()) == null && ResourceManager.getResource(folderForTest.toString()) == null) { throw new IllegalStateException( "No target/generated-sources or target/generated-test-sources folders found"); } // In main resource folder ICompilationUnit[] inMain = getExistingGeneratedTestInterfaces(project, true); // In test resource folder ICompilationUnit[] inTest = getExistingGeneratedTestInterfaces(project, false); ICompilationUnit[] ret = new ICompilationUnit[inMain.length+inTest.length]; System.arraycopy(inMain, 0, ret, 0, inMain.length); System.arraycopy(inTest, 0, ret, inMain.length, inTest.length); return ret; }
/** * @param project * @param itype * @return * @throws JavaModelException */ public static IPath findPathInModelAnnotation(IProject project, IType itype) throws JavaModelException { ICompilationUnit cu = itype.getCompilationUnit(); List<IAnnotationBinding> annotations = resolveAnnotation(cu, Model.class).getAnnotations(); if ((annotations != null) && (annotations.size() > 0)) { IAnnotationBinding ab = annotations.get(0); IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs(); for (int i = 0; i < attributes.length; i++) { IMemberValuePairBinding attribut = attributes[i]; if (attribut.getName().equalsIgnoreCase("value")) { Object[] o = (Object[]) attribut.getValue(); if (o != null && o.length > 0 && String.valueOf(o[0]).trim().length() > 0) { try { IPath p = ResourceManager.find(project, String.valueOf(o[0]).trim()); return p; } catch (Exception e) { ResourceManager.logException(e); return null; } } } } } return null; }
/** * @param cu * @return */ public static String findPathGeneratorInGraphWalkerAnnotation(ICompilationUnit cu) { CompilationUnit ast = parse(cu); Map<String, String> ret = new HashMap<String, String>(); ast.accept(new ASTVisitor() { public boolean visit(MemberValuePair node) { String name = node.getName().getFullyQualifiedName(); if ("value".equals(name) && node.getParent() != null && node.getParent() instanceof NormalAnnotation) { IAnnotationBinding annoBinding = ((NormalAnnotation) node.getParent()).resolveAnnotationBinding(); String qname = annoBinding.getAnnotationType().getQualifiedName(); if (GraphWalker.class.getName().equals(qname)) { StringLiteral sl = (StringLiteral) node.getValue(); ret.put("ret", sl.getLiteralValue()); } } return true; } }); return ret.get("ret"); }
private static IType getClassesWithAnnotation(ICompilationUnit compilationUnit, Class annotationClass, String attributName, boolean valued) throws JavaModelException { List<IAnnotationBinding> annotations = resolveAnnotation(compilationUnit, annotationClass).getAnnotations(); if ((annotations != null) && (annotations.size() > 0)) { IAnnotationBinding ab = annotations.get(0); IMemberValuePairBinding[] attributes = ab.getAllMemberValuePairs(); for (int i = 0; i < attributes.length; i++) { IMemberValuePairBinding attribut = attributes[i]; if (attribut.getName().equalsIgnoreCase(attributName)) { if (valued) { if (String.valueOf(attribut.getValue()).trim().length() > 0) { return compilationUnit.findPrimaryType(); } } else { if (String.valueOf(attribut.getValue()).trim().length() == 0) { return compilationUnit.findPrimaryType(); } } } } } return null; }
/** * @param projectName * @return * @throws JavaModelException */ private static List<IType> findClassesWithAnnotation(String projectName, Class annotationClass, String attributName, boolean valued) throws JavaModelException { List<IType> classList = new ArrayList<IType>(); IProject project = ResourceManager.getProject(projectName); IJavaProject javaProject = JavaCore.create(project); IPackageFragment[] packages = javaProject.getPackageFragments(); for (IPackageFragment packageFragment : packages) { for (final ICompilationUnit compilationUnit : packageFragment.getCompilationUnits()) { if (compilationUnit.exists()) { IType type = getClassesWithAnnotation(compilationUnit, annotationClass, attributName, valued); if (type != null) classList.add(type); } } } return classList; }
/** * @param testInterface * @return * @throws JavaModelException */ public static boolean isGraphWalkerExecutionContextClass(ICompilationUnit unit) throws JavaModelException { IType[] types = unit.getAllTypes(); if (types == null || types.length == 0) { ResourceManager.logInfo(unit.getJavaProject().getProject().getName(), "getAllTypes return null" + unit.getPath()); return false; } IType execContextType = unit.getJavaProject().findType(ExecutionContext.class.getName()); for (int i = 0; i < types.length; i++) { IType type = types[i]; String typeNname = type.getFullyQualifiedName(); String compilationUnitName = JDTManager.getJavaFullyQualifiedName(unit); if (typeNname.equals(compilationUnitName)) { try { ITypeHierarchy th = types[0].newTypeHierarchy(new NullProgressMonitor()); return th.contains(execContextType); } catch (Exception e) { ResourceManager.logException(e); } } } return false; }
/** * @param project */ public static void reorganizeImport(final ICompilationUnit cu) { Display.getDefault().syncExec(() -> { try { IWorkbenchWindow iww = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (iww == null) return; IPartService partService = iww.getPartService(); if (partService == null) return; IWorkbenchPart wp = partService.getActivePart(); if (wp == null) return; IWorkbenchPartSite targetSite = wp.getSite(); if (targetSite == null) return; organizeImports(cu, targetSite); } catch (Exception e) { ResourceManager.logException(e); } }); }
/** * @param file */ public static void updateBuildPolicyFileFor(IFile file) { Job job = new WorkspaceJob("Updating Build Policies from " + file.getName()) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(file); if (compilationUnit != null) { if (JDTManager.isGraphWalkerExecutionContextClass(compilationUnit)) { updateBuildPolicyFileForCompilatioUnit(compilationUnit); } } return Status.OK_STATUS; } }; job.setUser(true); job.setRule(file.getProject()); job.schedule(); }
@Test public void testUpdatePathGeneratorInSourceFile () throws CoreException, FileNotFoundException { System.out.println("XXXXXXXXXXXXXXXXXXXX testUpdatePathGeneratorInSourceFile"); String expectedNewGenerator = "random(vertex_coverage(50))"; PetClinicProject.create (bot,gwproject); // At this step the generator is "random(edge_coverage(100))" IFile veterinarien = PetClinicProject.getVeterinariensSharedStateImplFile(gwproject); ICompilationUnit cu = JavaCore.createCompilationUnitFrom(veterinarien); String oldGenerator = JDTManager.findPathGeneratorInGraphWalkerAnnotation(cu); SourceHelper.updatePathGenerator(veterinarien, oldGenerator, expectedNewGenerator); cu = JavaCore.createCompilationUnitFrom(veterinarien); String newGenerator = JDTManager.findPathGeneratorInGraphWalkerAnnotation(cu); assertEquals(newGenerator,expectedNewGenerator); String location = JDTManager.getGW4EGeneratedAnnotationValue(cu,"value"); IPath path = new Path (gwproject).append(location); IFile graphModel = (IFile)ResourceManager.getResource(path.toString()); IPath buildPolicyPath = ResourceManager.getBuildPoliciesPathForGraphModel(graphModel); IFile buildPolicyFile = (IFile)ResourceManager.getResource(buildPolicyPath.toString()); PropertyValueCondition condition = new PropertyValueCondition(buildPolicyFile,graphModel.getName(),"random(edge_coverage(100));I;random(vertex_coverage(50));I;"); bot.waitUntil(condition); }
public static boolean containsMethod (String path, String[] requiredMethods) throws JavaModelException { IResource resource = ResourceManager.getResource(path); IFile file = (IFile) resource; ICompilationUnit cu = JavaCore.createCompilationUnitFrom(file); IType[] types = cu.getAllTypes(); List<String> list = new ArrayList<String>(); for (int i = 0; i < types.length; i++) { IMethod[] methods = types[i].getMethods(); for (int j = 0; j < methods.length; j++) { list.add(methods[j].getElementName()); } } for (int i = 0; i < requiredMethods.length; i++) { String method = requiredMethods[i]; if (!list.contains(method)) return false; } return true; }
@Test public void testFindAnnotationParsingInGeneratedAnnotation() throws Exception { IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true); IFile impl = (IFile) ResourceManager .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString()); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); AnnotationParsing annoParsing = JDTManager.findAnnotationParsingInGeneratedAnnotation(compilationUnit, "value"); Location location = annoParsing.getLocation(); assertNotNull(location); int line = IOHelper.findLocationLineInFile(impl, "@Generated"); assertEquals(line,location.getLineNumber()); Location loc = IOHelper.findLocationInFile(impl, line, "value = \"src/test/resources/Simple.json\""); assertEquals(location,loc); String value = annoParsing.getValue ( ); assertEquals("src/test/resources/Simple.json", value); }
@Test public void testFindAnnotationParsingInGraphWalkerAnnotation() throws Exception { IJavaProject project = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME, true,true); IFile impl = (IFile) ResourceManager .getResource(project.getProject().getFullPath().append("src/test/java/SimpleImpl.java").toString()); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); AnnotationParsing annoParsing = JDTManager.findAnnotationParsingInGraphWalkerAnnotation(compilationUnit, "value"); Location location = annoParsing.getLocation(); assertNotNull(location); int line = IOHelper.findLocationLineInFile(impl, "@GraphWalker"); assertEquals(line,location.getLineNumber()); Location loc = IOHelper.findLocationInFile(impl, line, "value = \"random(edge_coverage(100))\""); assertEquals(location,loc); String value = annoParsing.getValue ( ); assertEquals("random(edge_coverage(100))", value); }
@Test public void testEnrichClass() throws Exception { IJavaProject pj = ProjectHelper.getOrCreateSimpleGW4EProject(PROJECT_NAME,true,false); IFile impl = ProjectHelper.createDummyClass (pj); ICompilationUnit compilationUnit = JavaCore.createCompilationUnitFrom(impl); IMethod m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]); assertFalse (m.exists()); IFile file = (IFile) ResourceManager.getResource(pj.getProject().getFullPath().append("src/test/resources/Simple.json").toString()); ResourceContext context = GenerationFactory.getResourceContext(file); ClassExtension ce = context.getClassExtension(); ce.setGenerateRunFunctionalTest(true); ce.setStartElementForJunitTest("start_app"); TestResourceGeneration trg = new TestResourceGeneration(context); JDTManager.enrichClass(impl, trg, new NullProgressMonitor()); m = compilationUnit.getTypes() [0].getMethod("runFunctionalTest",new String[0]); assertTrue (m.exists()); }
@Override protected ContentAssistInvocationContext createContext(ITextViewer viewer, int offset) { ICompilationUnit compilationUnit = ((SourceViewer) viewer).getCompilatioUnit(); if (compilationUnit != null) { CompletionProposalCollector completionProposalCollector = new CompletionProposalCollector(compilationUnit); JavaContentAssistInvocationContext invocContext = new JavaContentAssistInvocationContext(viewer, offset, new NullEditorPart()); completionProposalCollector.setInvocationContext(invocContext); return invocContext; } else { return null; } }
/** * Parse un fichier candidat de service métier. * * @param document Document du service métier. * @param javaProject Projet Java du service. * @return Le service, <code>null</code> sinon. */ private ServiceFile createServiceFile(IFile file, IJavaProject javaProject) { /* Charge l'AST du fichier Java. */ ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject); if (compilationUnit == null) { return null; } List<ServiceImplementation> serviceImplementations = new ArrayList<>(); try { /* Parcourt les types du fichier Java. */ for (IType type : compilationUnit.getAllTypes()) { handleType(type, file, serviceImplementations); } } catch (JavaModelException e) { ErrorUtils.handle(e); } /* Créé le fichier de service. */ return new ServiceFile(serviceImplementations); }
/** * Parse un fichier candidat de webservice. * * @param file Fichier du webservice. * @param javaProject Projet Java du fichier. * @return Le webservice, <code>null</code> sinon. */ private WsFile createWsFile(IFile file, IJavaProject javaProject) { /* Charge l'AST du fichier Java. */ ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject); if (compilationUnit == null) { return null; } List<WsRoute> wsRoutes = new ArrayList<>(); try { /* Parcourt les types du fichier Java. */ for (IType type : compilationUnit.getAllTypes()) { handleType(type, file, wsRoutes); } } catch (JavaModelException e) { ErrorUtils.handle(e); } /* Créé le fichier de webservice. */ return new WsFile(file, wsRoutes); }
/** * Parse un fichier candidat de DAO/PAO. * * @param file Fichier. * @param javaProject Projet Java du fichier. * @return Le DAO, <code>null</code> sinon. */ private DaoFile createDaoFile(IFile file, IJavaProject javaProject) { /* Charge l'AST du fichier Java. */ ICompilationUnit compilationUnit = JdtUtils.getCompilationUnit(file, javaProject); if (compilationUnit == null) { return null; } List<DaoImplementation> daoImplementations = new ArrayList<>(); try { /* Parcourt les types du fichier Java. */ for (IType type : compilationUnit.getAllTypes()) { handleType(type, file, daoImplementations); } } catch (JavaModelException e) { ErrorUtils.handle(e); } /* Créé le fichier de DAO/PAO. */ String daoName = StringUtils.removeExtension(compilationUnit.getElementName()); return new DaoFile(daoName, file, daoImplementations); }
private void complete(String projectName, String packageName, String unitName, String completeAt, String completeBehind, int[] ignoredKinds, int warmupCount, int iterationCount) throws CoreException { AbstractJavaModelTests.waitUntilIndexesReady(); TestCompletionRequestor requestor = new TestCompletionRequestor(); if (ignoredKinds != null) { for (int i = 0; i < ignoredKinds.length; i++) { requestor.setIgnored(ignoredKinds[i], true); } } ICompilationUnit unit = getCompilationUnit(projectName, packageName, unitName); String str = unit.getSource(); int completionIndex = str.indexOf(completeAt) + completeBehind.length(); if (DEBUG) System.out.print("Perform code assist inside " + unitName + "..."); for (int j = 0; j < iterationCount; j++) { unit.codeComplete(completionIndex, requestor); } if (DEBUG) System.out.println("done!"); }
@Override public Object execute(final ExecutionEvent event) throws ExecutionException { final IEditorPart editorPart = HandlerUtil.getActiveEditor(event); final ICompilationUnit icu = JavaUI.getWorkingCopyManager().getWorkingCopy(editorPart.getEditorInput()); try { final IType type = icu.getTypes()[0]; final List<Field> fields = new ArrayList<>(); for (final IField field : type.getFields()) { final String fieldName = field.getElementName(); final String fieldType = Signature.getSignatureSimpleName(field.getTypeSignature()); fields.add(new Field(fieldName, fieldType)); } new WizardDialog(HandlerUtil.getActiveShell(event), new BuilderGeneratorWizard(icu, fields)).open(); } catch (final JavaModelException e) { e.printStackTrace(); } return null; }
/** * Returns the source file associated with the given type, or <code>null</code> * if no source file could be found. * * @param project * the java project containing the classfile * @param qualifiedName * fully qualified name of the type, slash delimited * @param sourceAttribute * debug source attribute, or <code>null</code> if none */ private IResource getSourceFile(IJavaProject project, String qualifiedName, String sourceAttribute) { String name = null; IJavaElement element = null; try { if (sourceAttribute == null) { element = findElement(qualifiedName, project); } else { int i = qualifiedName.lastIndexOf('/'); if (i > 0) { name = qualifiedName.substring(0, i + 1); name = name + sourceAttribute; } else { name = sourceAttribute; } element = project.findElement(new Path(name)); } if (element instanceof ICompilationUnit) { ICompilationUnit cu = (ICompilationUnit) element; return cu.getCorrespondingResource(); } } catch (CoreException e) { logger.log(Level.INFO, "Failed to get source file with exception" + e.getMessage(), e); } return null; }
public List<IFile> toFiles(IStructuredSelection selection) { List<IFile> result = new ArrayList<>(); for (Iterator<?> iterator = selection.iterator(); iterator.hasNext();) { Object next = iterator.next(); if (next instanceof ICompilationUnit) { addFileToList((ICompilationUnit) next, result); } else if (next instanceof IPackageFragment) { for (ICompilationUnit unit : getCompilationUnits(next)) { addFileToList(unit, result); } } } return result; }
@Test public void testTypeMismatchInVarDecl3() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" Thread th= foo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public Thread foo() {\n"); buf.append(" Thread th= foo();\n"); buf.append(" }\n"); buf.append("}\n"); Expected e1 = new Expected("Change return type of 'foo(..)' to 'Thread'", buf.toString()); assertCodeActions(cu, e1); }
@Test public void testSignatureHelp_multipeMethod() throws JavaModelException { IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo(String s) { }\n"); buf.append(" public int foo(int s) { }\n"); buf.append(" public int foo(int s, String s) { }\n"); buf.append(" public int bar(String s) { this.foo(2, ) }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); SignatureHelp help = getSignatureHelp(cu, 5, 42); assertNotNull(help); assertEquals(help.getSignatures().size(), 3); assertEquals(help.getActiveParameter(), (Integer) 1); assertEquals(help.getSignatures().get(help.getActiveSignature()).getLabel(), "foo(int s, String s) : int"); }
private void changeDocument(ICompilationUnit cu, String content, int version, Range range, int length) throws JavaModelException { DidChangeTextDocumentParams changeParms = new DidChangeTextDocumentParams(); VersionedTextDocumentIdentifier textDocument = new VersionedTextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); textDocument.setVersion(version); changeParms.setTextDocument(textDocument); TextDocumentContentChangeEvent event = new TextDocumentContentChangeEvent(); if (range != null) { event.setRange(range); event.setRangeLength(length); } event.setText(content); List<TextDocumentContentChangeEvent> contentChanges = new ArrayList<>(); contentChanges.add(event); changeParms.setContentChanges(contentChanges); lifeCycleHandler.didChange(changeParms); }
private IJavaCompletionProposal[] getAddAPGASToBuildPathProposals( IInvocationContext context) { final ICompilationUnit unit = context.getCompilationUnit(); final IJavaProject project = unit.getJavaProject(); final String name = "static apgas.Constructs.*"; final ClasspathFixProposal[] fixProposals = ClasspathFixProcessor .getContributedFixImportProposals(project, name, null); final List<ImportRewrite> importRewrites = new ArrayList<ImportRewrite>(); importRewrites.add(getImportRewrite(context.getASTRoot(), name)); importRewrites.add(getImportRewrite(context.getASTRoot(), "apgas.*")); final ArrayList<IJavaCompletionProposal> proposals = new ArrayList<IJavaCompletionProposal>(); for (final ClasspathFixProposal fixProposal : fixProposals) { proposals.add(new APGASClasspathFixCorrelationProposal(project, fixProposal, importRewrites)); } final IJavaCompletionProposal[] propArr = new IJavaCompletionProposal[proposals .size()]; for (int i = 0; i < proposals.size(); i++) { propArr[i] = proposals.get(i); } return propArr; }
@Test public void testStaticMethodInInterface4() throws Exception { StringBuilder buf = new StringBuilder(); IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("interface I {\n"); buf.append(" int i= n();\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("I.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("interface I {\n"); buf.append(" int i= n();\n"); buf.append("\n"); buf.append(" static int n() {\n"); buf.append(" return 0;\n"); buf.append(" }\n"); buf.append("}\n"); Expected e1 = new Expected("Create method 'n()'", buf.toString()); assertCodeActions(cu, e1); }
private LaunchableResource toLaunchableResource(IResource resource) { if (resource == null) { return null; } IJavaElement javaElement = resource.getAdapter(IJavaElement.class); if (javaElement != null && javaElement.exists() && javaElement instanceof ICompilationUnit) { ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; IType javaType = compilationUnit.findPrimaryType(); if (javaType == null) { return null; } IMethod mainMethod = javaType.getMethod( "main", new String[] {Signature.createTypeSignature("String[]", false)}); return new LaunchableResource(resource, mainMethod, javaType); } return new LaunchableResource(resource); }
@Test public void testWrongTypeNameInAnnot() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public @interface X {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf.append("package test1;\n"); buf.append("\n"); buf.append("public @interface X {\n"); buf.append("}\n"); pack1.createCompilationUnit("X.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public @interface E {\n"); buf.append("}\n"); Expected e1 = new Expected("Rename type to 'E'", buf.toString()); assertCodeActions(cu, e1); }
/** * @see Measure#measure */ @Override public <T> void measure(T unit) { IType[] iTypes = null; try { iTypes = ((ICompilationUnit)unit).getTypes(); } catch (JavaModelException exception) { logger.error(exception); } CompilationUnit parse = parse(unit); CouplingBetweenObjectsVisitor visitor = CouplingBetweenObjectsVisitor.getInstance(); visitor.cleanArrayAndVariable(); visitor.addListOfTypes(iTypes); parse.accept(visitor); setCalculatedValue(getCouplingBetweenObjectsValue(visitor)); setMeanValue(getCalculatedValue()); setMaxValue(getCalculatedValue(), parse.getJavaElement().getElementName()); }
protected List<Command> evaluateCodeActions(ICompilationUnit cu) throws JavaModelException { CompilationUnit astRoot = SharedASTProvider.getInstance().getAST(cu, null); IProblem[] problems = astRoot.getProblems(); Range range = getRange(cu, problems); CodeActionParams parms = new CodeActionParams(); TextDocumentIdentifier textDocument = new TextDocumentIdentifier(); textDocument.setUri(JDTUtils.toURI(cu)); parms.setTextDocument(textDocument); parms.setRange(range); CodeActionContext context = new CodeActionContext(); context.setDiagnostics(DiagnosticsHandler.toDiagnosticsArray(Arrays.asList(problems))); parms.setContext(context); return new CodeActionHandler().getCodeActionCommands(parms, new NullProgressMonitor()); }
/** * @see IJavaModel#calculateValue */ @Override public void calculateValue(ICompilationUnit unit) { int length = 0; try { IType[] types = unit.getAllTypes(); for (IType type : types) { IJavaProject ancestor = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT); ITypeHierarchy th= type.newTypeHierarchy(ancestor, null); if (th != null) superclassesList = th.getAllSuperclasses(type); if (superclassesList != null) length = superclassesList.length; Double value = new BigDecimal(length, new MathContext(2, RoundingMode.UP)).doubleValue(); setDitValue(value); } }catch (JavaModelException javaException) { logger.error(javaException); }catch (NullPointerException nullPointerException){ logger.error(nullPointerException); } }
@Test public void testVarInArray() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" void foo(Object[] arr) {\n"); buf.append(" for (int i = 0; i > arr.lenght; i++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" void foo(Object[] arr) {\n"); buf.append(" for (int i = 0; i > arr.length; i++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); Expected e1 = new Expected("Change to 'length'", buf.toString()); assertCodeActionExists(cu, e1); }
@Test public void testUnusedMethod() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private void foo() {}\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("}\n"); Expected e1 = new Expected("Remove method 'foo'", buf.toString()); assertCodeActions(cu, e1); }
@Test public void testWrongPackageStatementInEnum() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test2;\n"); buf.append("\n"); buf.append("public enum E {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public enum E {\n"); buf.append("}\n"); Expected e1 = new Expected("Change package declaration to 'test1'", buf.toString()); assertCodeActions(cu, e1); }
@Test public void testWrongTypeNameButColliding() throws Exception { IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null); StringBuilder buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class X {\n"); buf.append("}\n"); pack1.createCompilationUnit("X.java", buf.toString(), false, null); buf = new StringBuilder(); buf.append("package test1;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append("}\n"); Expected e1 = new Expected("Rename type to 'E'", buf.toString()); assertCodeActions(cu, e1); }
/** * Obtains source code after this resource change. * @param elem the changed resource * @return the contents of the source code, or an empty string if the changed resource is not a file */ private String getCode(IJavaElement elem) { if (elem instanceof ICompilationUnit) { ICompilationUnit cu = (ICompilationUnit)elem; try { return cu.getSource(); } catch (JavaModelException e) { } } return ""; }
/** * Returns the encoding of the changed source code. * @param elem the changed resource * @return the encoding of the source code, or <code>null</code> */ private String getEncoding(IJavaElement elem) { if (elem instanceof ICompilationUnit) { ICompilationUnit cu = (ICompilationUnit)elem; try { IFile file = (IFile)cu.getCorrespondingResource(); return file.getCharset(); } catch (CoreException e) { } } return null; }