Example usage for org.eclipse.jdt.core.dom TypeDeclaration setName

List of usage examples for org.eclipse.jdt.core.dom TypeDeclaration setName

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom TypeDeclaration setName.

Prototype

public void setName(SimpleName typeName) 

Source Link

Document

Sets the name of the type declared in this type declaration to the given name.

Usage

From source file:br.com.objectos.way.core.code.jdt.ASTTest.java

License:Apache License

@SuppressWarnings("unchecked")
public void stackoverflow_answer() {
    AST ast = AST.newAST(AST.JLS8);/*from w ww .  j a  va2 s. c  o m*/
    CompilationUnit cu = ast.newCompilationUnit();

    PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newSimpleName("foo"));
    cu.setPackage(p1);

    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "util", "Set" }));
    cu.imports().add(id);

    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("Foo"));
    TypeParameter tp = ast.newTypeParameter();
    tp.setName(ast.newSimpleName("X"));
    td.typeParameters().add(tp);
    cu.types().add(td);

    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    md.setName(ast.newSimpleName("bar"));

    SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
    var.setType(ast.newSimpleType(ast.newSimpleName("String")));
    var.setName(ast.newSimpleName("a"));
    md.parameters().add(var);
    td.bodyDeclarations().add(md);

    Block block = ast.newBlock();
    md.setBody(block);

    MethodInvocation mi = ast.newMethodInvocation();
    mi.setName(ast.newSimpleName("x"));

    ExpressionStatement e = ast.newExpressionStatement(mi);
    block.statements().add(e);

    System.out.println(cu);
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.forward.ForwardJavaType.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   ww  w  . ja  v  a 2  s  .  co m
protected void setASTFeatureValue(EStructuralFeature feature, CompilationUnit astElement, Object value)
        throws CodeSyncException {
    if (astElement == null)
        throw new IllegalArgumentException("astElement null ");
    AST ast = astElement.getAST();
    TypeDeclaration masterClass = JavaSyncUtils.getMasterClass(astElement);

    switch (feature.getFeatureID()) {
    case UMLPackage.NAMED_ELEMENT__NAME:
        if (value == null)
            throw new IllegalArgumentException("setting name to null value ");

        String oldName = masterClass.getName().toString();
        if (!oldName.equals(value) && !oldName.equals("MISSING")) { // rename case
            try {
                SyncUtils.renameFile(oldName.toString(), (String) value, ".java", parentFolder);
            } catch (CoreException e) {
                throw new RuntimeException("Error during folder refresh: " + parentFolder, e);
            } catch (Exception e) {
                throw new RuntimeException("Error during file rename ", e);
            }
        }
        try {
            masterClass.setName(ast.newSimpleName((String) value));
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;
    case UMLPackage.NAMED_ELEMENT__VISIBILITY:
        JavaSyncUtils.updateVisibilityFromModelToJavaClass(masterClass, (VisibilityKind) value);
        break;
    case UMLPackage.CLASSIFIER__IS_ABSTRACT:
        JavaSyncUtils.updateModifierFromModelToJavaClass(masterClass, (Boolean) value,
                JavaSyncUtils.MODIFIER_ABSTRACT);
        break;
    case UMLPackage.ELEMENT__OWNED_COMMENT:
        List<Comment> listComments = (List<Comment>) value;
        if (listComments.size() > 1)
            throw new IllegalArgumentException("setting more than one documentation ");
        else if (listComments.size() == 1) {
            String documentation = listComments.get(0).getBody();
            Javadoc javadoc = ast.newJavadoc();
            if (documentation != null) {
                javadoc.setProperty("comment", "\r\n" + documentation + "\r\n");
                documentation = documentation.replace("\n", "\n * ");
            }
            TagElement tag = ast.newTagElement();
            TextElement te = ast.newTextElement();
            tag.fragments().add(te);
            te.setText(documentation);
            javadoc.tags().add(tag);
            JavaSyncUtils.getMasterClass(astElement).setJavadoc(javadoc);
        } else if (listComments.isEmpty())
            JavaSyncUtils.getMasterClass(astElement).setJavadoc(null);
        break;
    default:
        throw new IllegalArgumentException("Cannot get value for feature in ForwardJavaType:" + feature);
    }
}

From source file:com.google.devtools.j2cpp.translate.AnonymousClassConverter.java

License:Open Source License

/**
 * Convert the anonymous class into an inner class.  Fields are added for
 * final variables that are referenced, and a constructor is added.
 *
 * Note: endVisit is used for a depth-first traversal, to make it easier
 * to scan their containing nodes for references.
 *//*  ww w  .  j  a  va 2s .com*/
@Override
@SuppressWarnings("unchecked")
public void endVisit(AnonymousClassDeclaration node) {
    ASTNode parent = node.getParent();
    ClassInstanceCreation newInvocation = null;
    EnumConstantDeclaration enumConstant = null;
    List<Expression> parentArguments;
    String newClassName;
    ITypeBinding innerType;
    boolean isStatic = staticParent(node);
    int modifiers = isStatic ? Modifier.STATIC : 0;
    if (parent instanceof ClassInstanceCreation) {
        newInvocation = (ClassInstanceCreation) parent;
        parentArguments = newInvocation.arguments();
        innerType = Types.getTypeBinding(newInvocation);
        newClassName = innerType.getName();
        innerType = RenamedTypeBinding.rename(newClassName, innerType.getDeclaringClass(), innerType,
                modifiers);
    } else if (parent instanceof EnumConstantDeclaration) {
        enumConstant = (EnumConstantDeclaration) parent;
        parentArguments = enumConstant.arguments();
        innerType = Types.getTypeBinding(node);
        newClassName = Types.getTypeBinding(node).getName();
        innerType = RenamedTypeBinding.rename(newClassName, innerType.getDeclaringClass(), innerType,
                modifiers);
    } else {
        throw new AssertionError("unknown anonymous class declaration parent: " + parent.getClass().getName());
    }

    // Create a type declaration for this anonymous class.
    AST ast = node.getAST();
    TypeDeclaration typeDecl = ast.newTypeDeclaration();
    if (isStatic) {
        typeDecl.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
    }
    Types.addBinding(typeDecl, innerType);
    typeDecl.setName(ast.newSimpleName(newClassName));
    Types.addBinding(typeDecl.getName(), innerType);
    typeDecl.setSourceRange(node.getStartPosition(), node.getLength());

    Type superType = Types.makeType(Types.mapType(innerType.getSuperclass()));
    typeDecl.setSuperclassType(superType);
    for (ITypeBinding interfaceType : innerType.getInterfaces()) {
        typeDecl.superInterfaceTypes().add(Types.makeType(Types.mapType(interfaceType)));
    }

    for (Object bodyDecl : node.bodyDeclarations()) {
        BodyDeclaration decl = (BodyDeclaration) bodyDecl;
        typeDecl.bodyDeclarations().add(NodeCopier.copySubtree(ast, decl));
    }
    typeDecl.accept(new InitializationNormalizer());

    // Fix up references to external types, if necessary.
    Set<IVariableBinding> methodVars = getMethodVars(node);
    final List<ReferenceDescription> references = findReferences(node, methodVars);
    final List<Expression> invocationArgs = parentArguments;
    if (!references.isEmpty() || !invocationArgs.isEmpty()) { // is there anything to fix-up?
        List<IVariableBinding> innerVars = getInnerVars(references);
        if (!innerVars.isEmpty() || !invocationArgs.isEmpty()) {
            GeneratedMethodBinding defaultConstructor = addInnerVars(typeDecl, innerVars, references,
                    parentArguments);
            Types.addBinding(parent, defaultConstructor);
            for (IVariableBinding var : innerVars) {
                if (!isConstant(var)) {
                    parentArguments.add(makeFieldRef(var, ast));
                }
            }
            assert defaultConstructor.getParameterTypes().length == parentArguments.size();
            typeDecl.accept(new ASTVisitor() {
                @Override
                public void endVisit(SimpleName node) {
                    IVariableBinding var = Types.getVariableBinding(node);
                    if (var != null) {
                        for (ReferenceDescription ref : references) {
                            if (var.isEqualTo(ref.binding)) {
                                if (ref.innerField != null) {
                                    setProperty(node, makeFieldRef(ref.innerField, node.getAST()));
                                } else {
                                    // In-line constant.
                                    Object o = var.getConstantValue();
                                    assert o != null;
                                    Expression literal = makeLiteral(o, var.getType().getQualifiedName(),
                                            node.getAST());
                                    setProperty(node, literal);
                                }
                                return;
                            }
                        }
                    }
                }
            });
        }
    }

    // If invocation, replace anonymous class invocation with the new constructor.
    if (newInvocation != null) {
        newInvocation.setAnonymousClassDeclaration(null);
        newInvocation.setType(Types.makeType(innerType));
        IMethodBinding oldBinding = Types.getMethodBinding(newInvocation);
        if (oldBinding == null) {
            oldBinding = newInvocation.resolveConstructorBinding();
        }
        if (oldBinding != null) {
            GeneratedMethodBinding invocationBinding = new GeneratedMethodBinding(oldBinding);
            invocationBinding.setDeclaringClass(innerType);
            Types.addBinding(newInvocation, invocationBinding);
        }
    } else {
        enumConstant.setAnonymousClassDeclaration(null);
    }

    // Add type declaration to enclosing type.
    ITypeBinding outerType = innerType.getDeclaringClass();
    if (outerType.isAnonymous()) {
        // Get outerType node.
        ASTNode n = parent.getParent();
        while (!(n instanceof AnonymousClassDeclaration) && !(n instanceof TypeDeclaration)) {
            n = n.getParent();
        }
        if (n instanceof AnonymousClassDeclaration) {
            AnonymousClassDeclaration outerDecl = (AnonymousClassDeclaration) n;
            outerDecl.bodyDeclarations().add(typeDecl);
        }
    } else {
        AbstractTypeDeclaration outerDecl = (AbstractTypeDeclaration) unit.findDeclaringNode(outerType);
        outerDecl.bodyDeclarations().add(typeDecl);
    }
    Symbols.scanAST(typeDecl);
    super.endVisit(node);
}

From source file:com.google.devtools.j2cpp.translate.DeadCodeEliminator.java

License:Open Source License

/**
 * Creates a type declaration for a new class with the specified parent
 * and interfaces types./*from  w w w.j  a  va 2 s .c  o m*/
 */
@SuppressWarnings("unchecked")
private TypeDeclaration createClass(AST ast, ITypeBinding scope, ITypeBinding superClass,
        List<ITypeBinding> interfaces) {
    TypeDeclaration decl = ast.newTypeDeclaration();
    if (superClass != null) {
        decl.setSuperclassType(createType(ast, scope, superClass));
    }
    for (ITypeBinding intrface : interfaces) {
        decl.superInterfaceTypes().add(createType(ast, scope, intrface));
    }
    decl.modifiers().add(ast.newModifier(ModifierKeyword.ABSTRACT_KEYWORD));
    decl.setName(ast.newSimpleName(generateClassName()));
    return decl;
}

From source file:com.google.gdt.eclipse.designer.builders.GwtBuilder.java

License:Open Source License

/**
 * Generates Async type for given <code>RemoteService</code>.
 *///from   w ww .  jav  a  2 s .c om
private void generateAsync(IPackageFragment servicePackage, ICompilationUnit serviceUnit) throws Exception {
    IJavaProject javaProject = serviceUnit.getJavaProject();
    // parse service unit
    CompilationUnit serviceRoot = Utils.parseUnit(serviceUnit);
    // prepare AST and start modifications recording
    AST ast = serviceRoot.getAST();
    serviceRoot.recordModifications();
    // modify imports (-com.google.gwt.*, -*Exception, +AsyncCallback) 
    {
        List<ImportDeclaration> imports = DomGenerics.imports(serviceRoot);
        // remove useless imports
        for (Iterator<ImportDeclaration> I = imports.iterator(); I.hasNext();) {
            ImportDeclaration importDeclaration = I.next();
            String importName = importDeclaration.getName().getFullyQualifiedName();
            if (importName.startsWith("com.google.gwt.user.client.rpc.")
                    || importName.equals("com.google.gwt.core.client.GWT")
                    || importName.endsWith("Exception")) {
                I.remove();
            }
        }
    }
    // add Async to the name
    TypeDeclaration serviceType = (TypeDeclaration) serviceRoot.types().get(0);
    String remoteServiceAsyncName = serviceType.getName().getIdentifier() + "Async";
    serviceType.setName(serviceRoot.getAST().newSimpleName(remoteServiceAsyncName));
    // update interfaces
    updateInterfacesOfAsync(javaProject, serviceRoot, serviceType);
    // change methods, fields and inner classes
    {
        List<BodyDeclaration> bodyDeclarations = DomGenerics.bodyDeclarations(serviceType);
        for (Iterator<BodyDeclaration> I = bodyDeclarations.iterator(); I.hasNext();) {
            BodyDeclaration bodyDeclaration = I.next();
            if (bodyDeclaration instanceof MethodDeclaration) {
                MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
                // make return type void
                Type returnType;
                {
                    returnType = methodDeclaration.getReturnType2();
                    methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
                }
                // process JavaDoc
                {
                    Javadoc javadoc = methodDeclaration.getJavadoc();
                    if (javadoc != null) {
                        List<TagElement> tags = DomGenerics.tags(javadoc);
                        for (Iterator<TagElement> tagIter = tags.iterator(); tagIter.hasNext();) {
                            TagElement tag = tagIter.next();
                            if ("@gwt.typeArgs".equals(tag.getTagName())) {
                                tagIter.remove();
                            } else if ("@return".equals(tag.getTagName())) {
                                if (!tag.fragments().isEmpty()) {
                                    tag.setTagName("@param callback the callback to return");
                                } else {
                                    tagIter.remove();
                                }
                            } else if ("@wbp.gwt.Request".equals(tag.getTagName())) {
                                tagIter.remove();
                                addImport(serviceRoot, "com.google.gwt.http.client.Request");
                                methodDeclaration.setReturnType2(ast.newSimpleType(ast.newName("Request")));
                            }
                        }
                        // remove empty JavaDoc
                        if (tags.isEmpty()) {
                            methodDeclaration.setJavadoc(null);
                        }
                    }
                }
                // add AsyncCallback parameter
                {
                    addImport(serviceRoot, "com.google.gwt.user.client.rpc.AsyncCallback");
                    // prepare "callback" type
                    Type callbackType;
                    {
                        callbackType = ast.newSimpleType(ast.newName("AsyncCallback"));
                        Type objectReturnType = getObjectType(returnType);
                        ParameterizedType parameterizedType = ast.newParameterizedType(callbackType);
                        DomGenerics.typeArguments(parameterizedType).add(objectReturnType);
                        callbackType = parameterizedType;
                    }
                    // prepare "callback" parameter
                    SingleVariableDeclaration asyncCallback = ast.newSingleVariableDeclaration();
                    asyncCallback.setType(callbackType);
                    asyncCallback.setName(ast.newSimpleName("callback"));
                    // add "callback" parameter
                    DomGenerics.parameters(methodDeclaration).add(asyncCallback);
                }
                // remove throws
                methodDeclaration.thrownExceptions().clear();
            } else if (bodyDeclaration instanceof FieldDeclaration
                    || bodyDeclaration instanceof TypeDeclaration) {
                // remove the fields and inner classes
                I.remove();
            }
        }
    }
    // apply modifications to prepare new source code
    String newSource;
    {
        String source = serviceUnit.getBuffer().getContents();
        Document document = new Document(source);
        // prepare text edits
        MultiTextEdit edits = (MultiTextEdit) serviceRoot.rewrite(document, javaProject.getOptions(true));
        removeAnnotations(serviceType, source, edits);
        // prepare new source code
        edits.apply(document);
        newSource = document.get();
    }
    // update compilation unit
    {
        ICompilationUnit unit = servicePackage.createCompilationUnit(remoteServiceAsyncName + ".java",
                newSource, true, null);
        unit.getBuffer().save(null, true);
    }
}

From source file:com.idega.eclipse.ejbwizards.BeanCreator.java

License:Open Source License

protected TypeDeclaration getTypeDeclaration(AST ast, String name, boolean isInterface, String superClass,
        String[] interfaces, Set imports) {
    TypeDeclaration classType = ast.newTypeDeclaration();
    classType.setInterface(isInterface);
    classType.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    classType.setName(ast.newSimpleName(name));
    if (isInterface) {
        classType.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(superClass)));
    } else {// ww  w  . j a  v a2s . c  o  m
        classType.setSuperclassType(ast.newSimpleType(ast.newSimpleName(superClass)));
    }

    if (interfaces != null) {
        for (int i = 0; i < interfaces.length; i++) {
            if (!Signature.getSignatureSimpleName(interfaces[i]).equals(name)) {
                classType.superInterfaceTypes().add(
                        ast.newSimpleType(ast.newSimpleName(Signature.getSignatureSimpleName(interfaces[i]))));
                imports.add(getImportSignature(Signature.toString(interfaces[i])));
            }
        }
    }

    return classType;
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.ExceptionGenerator.java

License:Apache License

/**
 * Generate the Exception Class./*from   w  w  w. j a v  a 2s. co m*/
 * 
 * @param clazz
 *            the UML class
 * @param ast
 *            the JDT Java AST
 * @param cu
 *            the generated Java compilation unit
 * @return TypeDeclaration JDT
 */
@SuppressWarnings("unchecked")
public TypeDeclaration generateClass(Classifier clazz, AST ast, CompilationUnit cu) {
    String className = getClassName(clazz);
    TypeDeclaration td = ast.newTypeDeclaration();
    td.setInterface(false);
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.setName(ast.newSimpleName(className));

    // Add inheritance
    generateClassInheritance(clazz, ast, td);
    // Add template params
    generateClassTemplateParams(clazz, ast, td);

    cu.types().add(td);

    return td;
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.ExceptionGeneratorTest.java

License:Apache License

@Test
public void testGenerateSerialVersionUID() {
    AST ast = AST.newAST(AST.JLS3);/* w ww  .ja  v  a 2s  .c  om*/
    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("Company"));

    exceptionGenerator.generateSerialVersionUID(clazz, ast, td);

    assertEquals("class Company {\n  private static final long serialVersionUID=1L;\n}\n", td.toString());
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.ExceptionGeneratorTest.java

License:Apache License

@Test
public void testGenerateConstructors() {
    AST ast = AST.newAST(AST.JLS3);/*from w  ww . jav  a  2 s.c  o  m*/
    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("CompanyException"));

    when(clazz.getName()).thenReturn("CompanyException");

    exceptionGenerator.generateConstructors(clazz, ast, td);

    assertEquals("class CompanyException {\n  public CompanyException(){\n  }\n"
            + "  public CompanyException(  Throwable cause){\n"
            + "    super(cause);\n  }\n  public CompanyException(  String message){\n"
            + "    super(message);\n  }\n" + "  public CompanyException(  String message,  Throwable cause){\n"
            + "    super(message,cause);\n  }\n" + "}\n", td.toString());
}

From source file:de.crowdcode.kissmda.cartridges.simplejava.ExceptionGeneratorTest.java

License:Apache License

@Test
public void testGenerateConstructorWithParams() {
    AST ast = AST.newAST(AST.JLS3);/*w  w  w. jav a  2 s . c  o m*/
    TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName("CompanyException"));

    when(clazz.getName()).thenReturn("CompanyException");

    exceptionGenerator.generateConstructorWithParams(clazz, ast, td, new String[] { "String", "Throwable" },
            new String[] { "message", "cause" });

    assertEquals(
            "class CompanyException {\n" + "  public CompanyException(  String message,  Throwable cause){\n"
                    + "    super(message,cause);\n  }\n" + "}\n",
            td.toString());
}