/* * (non-Javadoc) * * @see org.eclipse.andmore.android.model.java.JavaClass#addComments() */ @Override protected void addComments() throws AndroidException { ASTNode todoComment; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(document.get().toCharArray()); compUnit = (CompilationUnit) parser.createAST(null); ast = compUnit.getAST(); rewrite = ASTRewrite.create(ast); todoComment = rewrite.createStringPlaceholder( CodeUtilsNLS.MODEL_Common_ToDoPutYourCodeHere, ASTNode.EMPTY_STATEMENT); TypeDeclaration receiverClass = (TypeDeclaration) compUnit.types().get(0); MethodDeclaration method; Block block; // Adds the Override annotation and ToDo comment to all overridden // methods for (int i = 0; i < receiverClass.bodyDeclarations().size(); i++) { method = (MethodDeclaration) receiverClass.bodyDeclarations().get(i); // Adds the Override annotation rewrite .getListRewrite(method, method.getModifiersProperty()) .insertFirst(OVERRIDE_ANNOTATION, null); // Adds the ToDo comment block = method.getBody(); rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertFirst(todoComment, null); } try { // Writes the modifications TextEdit modifications = rewrite.rewriteAST(document, null); modifications.apply(document); } catch (IllegalArgumentException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (MalformedTreeException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } catch (BadLocationException e) { String errMsg = NLS.bind(CodeUtilsNLS.EXC_JavaClass_ErrorApplyingCommentsToCode, className); AndmoreLogger.error(BroadcastReceiverClass.class, errMsg, e); throw new AndroidException(errMsg); } }
/** * Collects the existing tags on the {@link IJavaElement} we have been activated on * * @param element * @param jcontext * @throws JavaModelException * @throws BadLocationException */ private void collectExistingTags( IJavaElement element, JavaContentAssistInvocationContext jcontext) throws JavaModelException { if (element instanceof IMember) { IMember member = (IMember) element; ICompilationUnit cunit = jcontext.getCompilationUnit(); if (cunit != null) { if (cunit.isWorkingCopy()) { cunit.reconcile(ICompilationUnit.NO_AST, false, false, null, null); } fParser.setSource(member.getSource().toCharArray()); fParser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS); Map<String, String> options = element.getJavaProject().getOptions(true); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); fParser.setCompilerOptions(options); fParser.setStatementsRecovery(false); fParser.setResolveBindings(false); fParser.setBindingsRecovery(false); ASTNode ast = fParser.createAST(null); TagCollector collector = new TagCollector(); if (ast.getNodeType() == ASTNode.TYPE_DECLARATION) { TypeDeclaration typeDeclaration = (TypeDeclaration) ast; List<BodyDeclaration> bodyDeclarations = typeDeclaration.bodyDeclarations(); if (bodyDeclarations.size() == 1) { // only one element should be there as we are parsing a // specific member BodyDeclaration bodyDeclaration = bodyDeclarations.iterator().next(); Javadoc javadoc = bodyDeclaration.getJavadoc(); if (javadoc != null) { javadoc.accept(collector); } } } } } }
// test is for fourth calloutMapping in Testdata (Role) public void testValidMappingListSize1() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(7); int actual = calloutDecl.getParameterMappings().size(); int expected = 3; assertEquals("ParameterMappingList has wrong size", expected, actual); }
// test is for first calloutMapping in Testdata (Role) public void testGetParameterMappings_notEmpty() { // get first role CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(4); List mappings = calloutDecl.getParameterMappings(); assertNotNull("ParametermappingList should be not empty", mappings); assertFalse(mappings.isEmpty()); }
// test is for fourth calloutMapping in Testdata (Role) public void testSubTreeMatch() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(7); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(2); boolean actual = testObj.subtreeMatch(new ASTMatcher(), testObj); assertTrue("Both nodes are equal, even the same.", actual); }
// test is for first calloutMapping in Testdata (Role) public void testHasResultFlag_false() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(4); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(0); boolean actual = testObj.hasResultFlag(); assertFalse("Mapping is a not a result mapping", actual); }
// test is for first calloutMapping in Testdata (Role) public void testGetDirection() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(4); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(0); String actual = testObj.getDirection(); String expected = "->"; assertEquals("Wrong direction", expected, actual); }
// test is for fourth calloutMapping in Testdata (Role) public void testHasResultFlag_true2() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(7); List parameterMappings = calloutDecl.getParameterMappings(); // test the third parameterMapping of this CalloutMappingDeclaration ParameterMapping testObj = (ParameterMapping) parameterMappings.get(2); boolean actual = testObj.hasResultFlag(); assertTrue("Mapping is a result mapping, but was not detected", actual); }
// test is for first calloutMapping in Testdata (Role) public void testGetIdentifier() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(4); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(0); String actual = testObj.getIdentifier().getIdentifier(); String expected = "val"; assertEquals("Identifier is wrong", expected, actual); }
public void testCopySubtree() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(7); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(2); ParameterMapping clonedTestObject = (ParameterMapping) ASTNode.copySubtree(AST.newAST(AST.JLS4), testObj); boolean actual = testObj.subtreeMatch(new ASTMatcher(), clonedTestObject); assertTrue("Copy of subtree not correct", actual); }
// test is for fourth calloutMapping in Testdata (Role) public void testGetExpression_InstanceType3() { CalloutMappingDeclaration calloutDecl = (CalloutMappingDeclaration) _role.bodyDeclarations().get(7); List parameterMappings = calloutDecl.getParameterMappings(); ParameterMapping testObj = (ParameterMapping) parameterMappings.get(0); Expression actual = (Expression) testObj.getExpression(); assertTrue( "Wrong Type of given expression, type is " + actual.getClass(), actual instanceof SimpleName); }
/** Verify that an anonymous class is moved to the compilation unit's types list. */ public void testAnonymousClassExtracted() { List<TypeDeclaration> types = translateClassBody( "Object test() { return new java.util.Enumeration<Object>() { " + "public boolean hasMoreElements() { return false; } " + "public Object nextElement() { return null; } }; }"); assertEquals(2, types.size()); TypeDeclaration type = types.get(1); assertEquals("$1", type.getName().getIdentifier()); type = types.get(0); assertEquals("Test", type.getName().getIdentifier()); MethodDeclaration testMethod = (MethodDeclaration) type.bodyDeclarations().get(0); ReturnStatement stmt = (ReturnStatement) testMethod.getBody().statements().get(0); ClassInstanceCreation expr = (ClassInstanceCreation) stmt.getExpression(); assertNull(expr.getAnonymousClassDeclaration()); }
/** * Regression test: verify that a class passed in the constructor of an anonymous class is * converted. */ public void testAnonymousClassWithTypeArgParameter() { List<TypeDeclaration> types = translateClassBody( "public Test(Class c) {} static Test t = " + "new Test(Test.class) { @Override public int hashCode() { return 1; } };"); assertEquals(2, types.size()); TypeDeclaration type = types.get(0); List<BodyDeclaration> members = type.bodyDeclarations(); for (BodyDeclaration member : members) { if (member instanceof MethodDeclaration) { MethodDeclaration m = (MethodDeclaration) member; if (m.getName().getIdentifier().equals("initialize")) { Block b = (Block) m.getBody().statements().get(0); ExpressionStatement expStmt = (ExpressionStatement) b.statements().get(0); Assignment assign = (Assignment) expStmt.getExpression(); ClassInstanceCreation create = (ClassInstanceCreation) assign.getRightHandSide(); assertTrue(create.arguments().get(0) instanceof TypeLiteral); } } } }
/* * @see ASTVisitor#visit(TypeDeclaration) */ public boolean visit(TypeDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } if (node.getAST().apiLevel() >= AST.JLS3) { printModifiers(node.modifiers()); } this.fBuffer.append(node.isInterface() ? "interface " : "class "); // $NON-NLS-2$//$NON-NLS-1$ node.getName().accept(this); if (node.getAST().apiLevel() >= AST.JLS3) { if (!node.typeParameters().isEmpty()) { this.fBuffer.append("<"); // $NON-NLS-1$ for (Iterator it = node.typeParameters().iterator(); it.hasNext(); ) { TypeParameter t = (TypeParameter) it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(","); // $NON-NLS-1$ } } this.fBuffer.append(">"); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ if (node.getAST().apiLevel() >= AST.JLS3) { if (node.getSuperclassType() != null) { this.fBuffer.append("extends "); // $NON-NLS-1$ node.getSuperclassType().accept(this); this.fBuffer.append(" "); // $NON-NLS-1$ } if (!node.superInterfaceTypes().isEmpty()) { this.fBuffer.append( node.isInterface() ? "extends " : "implements "); // $NON-NLS-2$//$NON-NLS-1$ for (Iterator it = node.superInterfaceTypes().iterator(); it.hasNext(); ) { Type t = (Type) it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ } } this.fBuffer.append("{"); // $NON-NLS-1$ BodyDeclaration prev = null; for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) { BodyDeclaration d = (BodyDeclaration) it.next(); if (prev instanceof EnumConstantDeclaration) { // enum constant declarations do not include punctuation if (d instanceof EnumConstantDeclaration) { // enum constant declarations are separated by commas this.fBuffer.append(", "); // $NON-NLS-1$ } else { // semicolon separates last enum constant declaration from // first class body declarations this.fBuffer.append("; "); // $NON-NLS-1$ } } d.accept(this); prev = d; } this.fBuffer.append("}"); // $NON-NLS-1$ return false; }
@Override public boolean visit(TypeDeclaration node) { if (node.isPackageMemberTypeDeclaration() || node.isMemberTypeDeclaration()) { ITypeBinding typeBinding = node.resolveBinding(); if (typeBinding != null) { // Criando classe ApiClass apiClass = new ApiClass(typeBinding.getQualifiedName()); apiClass.setInterface(typeBinding.isInterface()); this.setModifiers(apiClass, node); this.classMap.put(typeBinding, apiClass); if (!this.attachmentMap.containsKey(node.getRoot())) { Attachment attachment = new Attachment( typeBinding.getQualifiedName().concat(".java"), node.getRoot().toString().getBytes()); this.attachmentMap.put(node.getRoot(), attachment); } List<MethodDeclaration> declarations = new LinkedList<MethodDeclaration>(); for (Object o : node.bodyDeclarations()) { if (o instanceof MethodDeclaration) { declarations.add((MethodDeclaration) o); } } for (final MethodDeclaration declaration : declarations) { final List<Expression> invocations = new LinkedList<Expression>(); this.methodDeclarationHandler(declaration, apiClass); InvocationVisitor visitor = new InvocationVisitor(); declaration.accept(visitor); invocations.addAll(visitor.invocations); // Parte de extracao de exemplos, se não houver invocações eu pulo esta parte if (invocations.isEmpty()) { continue; } else { // Faço a extração de exemplos para cada invocação em separado Set<ApiMethod> methodsInvocations = new HashSet<ApiMethod>(); for (Expression mi : invocations) { methodsInvocations.add(this.mapInvocations.get(mi)); Example newExample = makeExample( declaration, Collections.singleton(mi), Collections.singletonList(this.mapInvocations.get(mi))); if (newExample != null) { this.examples.add(newExample); } } // Se houver mais de uma invocacao faço o slicing com sementes multiplas if (invocations.size() > 1) { // Itero sobre os conjuntos das regras Iterator<Set<ApiMethod>> it = this.methodSets.iterator(); while (it.hasNext()) { // Podando conjuntos Set<ApiMethod> s = it.next(); if (s.size() > methodsInvocations.size()) { break; } else { // Se as invocacoes identificadas envolvem metodos desejados eu processo if (methodsInvocations.containsAll(s)) { List<ApiMethod> methods = new ArrayList<ApiMethod>(); Set<Expression> invocationsTemp = new HashSet<Expression>(); for (Expression mi : invocations) { ApiMethod relatedMethod = this.mapInvocations.get(mi); if (s.contains(relatedMethod)) { methods.add(relatedMethod); invocationsTemp.add(mi); } } Example newExample = makeExample(declaration, invocationsTemp, methods); if (newExample != null) { this.examples.add(newExample); } } } } } } } } } return super.visit(node); }
@SuppressWarnings("unchecked") @Before public void setUp() { manager = ModelManager.getInstance(); manager.clearModel(); AST ast2 = AST.newAST(AST.JLS3); CompilationUnit cu2 = ast2.newCompilationUnit(); PackageDeclaration pack2 = ast2.newPackageDeclaration(); pack2.setName(ast2.newName("be.ac.ua.test.otherpack")); cu2.setPackage(pack2); TypeDeclaration type2 = ast2.newTypeDeclaration(); type2.setName(ast2.newSimpleName("Foo")); cu2.types().add(type2); // created mock compilationunit containing package and class PackageRecorder prec2 = new PackageRecorder(pack2); prec2.storeChange(new Add()); // store the package addition ClassRecorder crec2 = new ClassRecorder(type2); declaredclassadd = new Add(); crec2.storeChange(declaredclassadd); AST ast = AST.newAST(AST.JLS3); CompilationUnit cu = ast.newCompilationUnit(); PackageDeclaration pack = ast.newPackageDeclaration(); pack.setName(ast.newName(packname)); cu.setPackage(pack); TypeDeclaration type = ast.newTypeDeclaration(); type.setName(ast.newSimpleName(classname)); cu.types().add(type); PackageRecorder prec = new PackageRecorder(pack); prec.storeChange(new Add()); // store the package addition ClassRecorder crec = new ClassRecorder(type); classadd = new Add(); crec.storeChange(classadd); // Class and package created and changes logged, now create the Field. VariableDeclarationFragment frag1 = ast.newVariableDeclarationFragment(); frag1.setName(ast.newSimpleName(intfieldname)); FieldDeclaration field = ast.newFieldDeclaration(frag1); field.setType(ast.newPrimitiveType(PrimitiveType.INT)); // field has type int type.bodyDeclarations().add(field); VariableDeclarationFragment frag2 = ast.newVariableDeclarationFragment(); frag2.setName(ast.newSimpleName(fieldname)); FieldDeclaration field2 = ast.newFieldDeclaration(frag2); field2.setType(ast.newSimpleType(ast.newName(declaredTypeName))); // field has type Foo type.bodyDeclarations().add(field2); VariableDeclarationFragment frag3 = ast.newVariableDeclarationFragment(); frag3.setName(ast.newSimpleName(field3Name)); FieldDeclaration field3 = ast.newFieldDeclaration(frag3); field3.setType(ast.newSimpleType(ast.newName("Foo"))); // field has type Foo type.bodyDeclarations().add(field3); ImportDeclaration imp = ast.newImportDeclaration(); imp.setName(ast.newName(declaredTypeName)); cu.imports().add(imp); // created mock compilationunit containing package and class recorder1 = new FieldRecorder(field); recorder2 = new FieldRecorder(field2); recorder3 = new FieldRecorder(field3); }