Example usage for org.eclipse.jdt.core.dom FieldDeclaration setType

List of usage examples for org.eclipse.jdt.core.dom FieldDeclaration setType

Introduction

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

Prototype

public void setType(Type type) 

Source Link

Document

Sets the base type declared in this field declaration to the given type.

Usage

From source file:ac.at.tuwien.dsg.utest.transformation.umlclassdiagram2javadb.id.rules.UMLClassDiagram2JavaDBTransformationRule.java

License:Open Source License

public Object createTarget(ITransformContext context) {

    ClassImpl source = (ClassImpl) context.getSource();

    Document document = new Document("@NodeType \n public class " + source.getName() + "{ \n");

    //below helper classes toi generate our desired .java file
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(document.get().toCharArray());
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.recordModifications();//from   w  w w . ja v a  2 s  .  co m
    AST ast = cu.getAST();

    ASTRewrite rewriter = ASTRewrite.create(ast);

    ListRewrite listRewrite = rewriter.getListRewrite(cu, CompilationUnit.TYPES_PROPERTY);

    //TODO: here we take each property introduced by each Stereotype

    for (Stereotype stereotype : source.getAppliedStereotypes()) {

        //get all properties
        for (Property attribute : stereotype.getAllAttributes()) {

            //todo
        }
    }

    for (Property property : source.getAllAttributes()) {
        System.out.println(property.getName());

        Association assoc = property.getAssociation();

        if (assoc == null) {
            System.out.format("this is simple %s \n", property.getName());

            VariableDeclarationFragment varDecl = ast.newVariableDeclarationFragment();
            varDecl.setName(ast.newSimpleName(property.getName()));

            FieldDeclaration propertyField = ast.newFieldDeclaration(varDecl);
            propertyField.setType(ast.newSimpleType(ast.newName(property.getType().getName())));

            final SingleMemberAnnotation annot = ast.newSingleMemberAnnotation();
            annot.setTypeName(ast.newName("Property"));

            StringLiteral st = ast.newStringLiteral();
            st.setLiteralValue("type=\"variable\"");

            annot.setValue(st);

            listRewrite.insertLast(annot, null);
            listRewrite.insertLast(propertyField, null);

        } else {
            System.out.format("this is complex %s \n", property.getName());
            Type type = assoc.getEndTypes().stream().filter(a -> !a.equals(source)).findFirst().get();
            System.out.format("Association end is   %s \n", type.getName());

            AggregationKind kind = property.getAggregation();
            if (kind.equals(AggregationKind.COMPOSITE)) {
                System.out.format("Composition \n");
            } else if (kind.equals(AggregationKind.SHARED)) {
                System.out.format("Aggregation \n");
            } else if (kind.equals(AggregationKind.NONE)) {
                System.out.format("Association \n");
            }

        }

    }

    TextEdit edits = rewriter.rewriteAST(document, null);
    try {
        UndoEdit undo = edits.apply(document);
    } catch (MalformedTreeException | BadLocationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println(document.get());

    return null;
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

private static void merge(CompilationUnit unit, String pkgName, String typeName, String auth, String dbName,
        List<String> tableCreators) {
    unit.recordModifications();//from w  ww. j  a v a 2  s.com
    AST ast = unit.getAST();
    TypeDeclaration type = (TypeDeclaration) unit.types().get(0);
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName("cn.ieclipse.aorm.Session"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.content.UriMatcher"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.database.sqlite.SQLiteDatabase"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.database.sqlite.SQLiteOpenHelper"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("java.net.Uri"));
    unit.imports().add(id);

    id = ast.newImportDeclaration();
    id.setName(ast.newName("android.content.ContentValue"));
    unit.imports().add(id);

    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("AUTH"));
    StringLiteral sl = ast.newStringLiteral();
    sl.setLiteralValue(auth);
    vdf.setInitializer(sl);

    FieldDeclaration fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
    fd.setType(ast.newSimpleType(ast.newSimpleName("String")));

    int i = 0;
    type.bodyDeclarations().add(i++, fd);

    // URI = Uri.parse("content://" + AUTH);
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("URI"));

    MethodInvocation mi = ast.newMethodInvocation();
    mi.setExpression(ast.newSimpleName("Uri"));
    mi.setName(ast.newSimpleName("parse"));

    InfixExpression fix = ast.newInfixExpression();
    fix.setOperator(InfixExpression.Operator.PLUS);
    sl = ast.newStringLiteral();
    sl.setLiteralValue("content://");
    fix.setLeftOperand(sl);
    fix.setRightOperand(ast.newSimpleName("AUTH"));

    mi.arguments().add(fix);

    vdf.setInitializer(mi);
    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
    fd.setType(ast.newSimpleType(ast.newSimpleName("Uri")));

    type.bodyDeclarations().add(i++, fd);

    // private mOpenHelper;
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("mOpenHelper"));

    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
    fd.setType(ast.newSimpleType(ast.newName("SQLiteOpenHelper")));
    type.bodyDeclarations().add(i++, fd);

    // private static session;
    vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("session"));

    fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers((Modifier.PRIVATE | Modifier.STATIC)));
    fd.setType(ast.newSimpleType(ast.newName("Session")));
    type.bodyDeclarations().add(i++, fd);

    // public static Session getSession(){
    // return session;
    // }

    MethodDeclaration md = ast.newMethodDeclaration();
    md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC)));
    md.setReturnType2(ast.newSimpleType(ast.newName("Session")));
    md.setName(ast.newSimpleName("getSession"));

    Block methodBlock = ast.newBlock();
    ReturnStatement returnStmt = ast.newReturnStatement();
    returnStmt.setExpression(ast.newSimpleName("session"));
    methodBlock.statements().add(returnStmt);
    md.setBody(methodBlock);
    type.bodyDeclarations().add(i, md);

    // modify onCreate
    rewriteOnCreate(unit, dbName, tableCreators);
}

From source file:com.alex.example.fixlicense.actions.SampleAction.java

License:Open Source License

private FieldDeclaration createLiceseInLineField(AST ast) {
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName("COPYRIGHT"));
    StringLiteral sl = ast.newStringLiteral();
    sl.setLiteralValue(license_inline);//from w ww  .  j  a v a 2  s  . c o m
    vdf.setInitializer(sl);
    FieldDeclaration fd = ast.newFieldDeclaration(vdf);
    fd.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL));
    fd.setType(ast.newSimpleType(ast.newSimpleName("String")));

    return fd;
}

From source file:com.crispico.flower.codesync.tests.java.JavaTestsOnSourceCode.java

License:Open Source License

@SuppressWarnings("unchecked")
public void testField_Adders() {
    javaCompilationUnit = JavaSyncUtils.loadJavaFile(folder.getFile("ClassA.java"),
            ASTParser.newParser(AST.JLS3));
    javaCompilationUnit.recordModifications();
    javaClass = JavaSyncUtils.getMasterClass(javaCompilationUnit);

    AST ast = javaClass.getAST();//from   ww w  .  j a v a 2s. com
    VariableDeclarationFragment vdf = null;
    FieldDeclaration field = null;

    // adding field with all 4 kinds of visibilities
    vdf = ast.newVariableDeclarationFragment(); // public a
    field = ast.newFieldDeclaration(vdf);
    ((VariableDeclarationFragment) field.fragments().get(0)).setName(ast.newSimpleName("addedField1"));
    javaClass.bodyDeclarations().add(field);
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(field, VisibilityKind.PUBLIC_LITERAL);

    vdf = ast.newVariableDeclarationFragment(); // protected a:String
    field = ast.newFieldDeclaration(vdf);
    ((VariableDeclarationFragment) field.fragments().get(0)).setName(ast.newSimpleName("addedField2"));
    javaClass.bodyDeclarations().add(field);
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(field, VisibilityKind.PUBLIC_LITERAL);
    field.setType(JavaSyncUtils.getJavaTypeFromString(ast, "String"));

    vdf = ast.newVariableDeclarationFragment(); // private a:ClassB
    field = ast.newFieldDeclaration(vdf);
    ((VariableDeclarationFragment) field.fragments().get(0)).setName(ast.newSimpleName("addedField3"));
    javaClass.bodyDeclarations().add(field);
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(field, VisibilityKind.PUBLIC_LITERAL);
    field.setType(JavaSyncUtils.getJavaTypeFromString(ast, "ClassB"));

    vdf = ast.newVariableDeclarationFragment(); // default a
    field = ast.newFieldDeclaration(vdf);
    ((VariableDeclarationFragment) field.fragments().get(0)).setName(ast.newSimpleName("addedField4"));
    javaClass.bodyDeclarations().add(field);
    JavaSyncUtils.updateVisibilityFromModelToJavaClass(field, VisibilityKind.PUBLIC_LITERAL);
    field.setType(JavaSyncUtils.getJavaTypeFromString(ast, "ClassA"));

    synchronizeAndCompareMasterClass();
}

From source file:com.crispico.flower.mp.codesync.code.java.adapter.JavaAttributeModelAdapter.java

License:Open Source License

@Override
public void setValueFeatureValue(Object element, Object feature, Object value) {
    if (CodeSyncPackage.eINSTANCE.getCodeSyncElement_Name().equals(feature)) {
        FieldDeclaration field = getFieldDeclaration(element);
        String name = (String) value;
        VariableDeclaration var = (VariableDeclaration) field.fragments().get(0);
        var.setName(field.getAST().newSimpleName(name));
    }//from  ww w.  ja va  2  s .  c  om
    if (AstCacheCodePackage.eINSTANCE.getTypedElement_Type().equals(feature)) {
        FieldDeclaration field = getFieldDeclaration(element);
        Type type = getTypeFromString(field.getAST(), (String) value);
        field.setType(type);
    }
    if (AstCacheCodePackage.eINSTANCE.getAttribute_Initializer().equals(feature)) {
        VariableDeclaration var = (VariableDeclaration) getFieldDeclaration(element).fragments().get(0);
        var.setInitializer(getExpressionFromString(var.getAST(), (String) value));
    }
    super.setValueFeatureValue(element, feature, value);
}

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

License:Open Source License

@Override
protected void setASTFeatureValue(EStructuralFeature feature, FieldDeclaration astElement, Object value)
        throws CodeSyncException {
    if (astElement == null)
        throw new IllegalArgumentException("astElement null ");
    AST ast = astElement.getAST();/* w w  w.j  a va  2  s. com*/
    switch (feature.getFeatureID()) {
    case UMLPackage.NAMED_ELEMENT__NAME:
        if (astElement.fragments().size() == 0)
            throw new IllegalArgumentException("bad assumption size always >0");
        if (value == null)
            throw new IllegalArgumentException("setting name to null value ");
        ((VariableDeclarationFragment) astElement.fragments().get(0))
                .setName(ast.newSimpleName((String) value));
        break;
    case UMLPackage.TYPED_ELEMENT__TYPE:
        String newType = value != null ? ((Type) value).getName() : null;
        if (newType == null)
            throw new IllegalArgumentException("Field has type null: " + astElement);
        parentForwardJavaClass_OwnedFields.parentForwardJavaType.parentForwardJavaSrcDir_Files
                .createImportDeclarationIfNeeded((Type) value);
        astElement.setType(JavaSyncUtils.getJavaTypeFromString(ast, newType, true));
        break;
    case UMLPackage.PROPERTY__DEFAULT_VALUE:
        String newDefaultValue = (LiteralString) value == null ? null : ((LiteralString) value).getValue();
        Expression e = null;
        if (newDefaultValue != null && !newDefaultValue.equals("")) {
            ASTParser expressionParser = ASTParser.newParser(AST.JLS3);
            expressionParser.setKind(ASTParser.K_EXPRESSION);
            expressionParser.setSource(newDefaultValue.toCharArray());
            e = (Expression) expressionParser.createAST(null);
            e = (Expression) ASTNode.copySubtree(ast, e);
        }
        ((VariableDeclarationFragment) astElement.fragments().get(0)).setInitializer(e);
        break;
    default:
        super.setASTFeatureValue(feature, astElement, value);
    }
}

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

License:Open Source License

protected FieldDeclaration createField(String name, ITypeBinding varType, ITypeBinding declaringClass,
        AST ast) {//  w  ww  .  j a va2s  .  c  o  m
    VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
    SimpleName fieldName = ast.newSimpleName(name);
    GeneratedVariableBinding fieldBinding = new GeneratedVariableBinding(fieldName.getIdentifier(),
            Modifier.PRIVATE | Modifier.FINAL, varType, true, false, declaringClass, null);
    Types.addBinding(fieldName, fieldBinding);
    fragment.setName(fieldName);
    Types.addBinding(fragment, fieldBinding);

    FieldDeclaration field = ast.newFieldDeclaration(fragment);
    field.setType(Types.makeType(varType));
    @SuppressWarnings("unchecked")
    List<IExtendedModifier> mods = field.modifiers(); // safe by definition
    mods.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
    mods.add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
    return field;
}

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

License:Open Source License

@Override
public boolean visit(FieldDeclaration node) {
    @SuppressWarnings("unchecked")
    List<VariableDeclarationFragment> vars = node.fragments(); // safe by definition
    for (VariableDeclarationFragment var : vars) {
        IVariableBinding binding = Types.getVariableBinding(var);
        Type newType = Types.makeIOSType(binding.getType());
        if (newType != null) {
            ITypeBinding newTypeBinding = Types.getTypeBinding(newType);
            GeneratedVariableBinding varBinding = new GeneratedVariableBinding(NameTable.getName(binding),
                    binding.getModifiers(), newTypeBinding, true, false, binding.getDeclaringClass(),
                    binding.getDeclaringMethod());
            Types.addMappedVariable(var, varBinding);
            node.setType(newType);
        }//from w ww . jav  a 2  s. c  o m
    }
    return super.visit(node);
}

From source file:com.google.devtools.j2objc.translate.ASTFactory.java

License:Apache License

public static FieldDeclaration newFieldDeclaration(AST ast, VariableDeclarationFragment fragment) {
    IVariableBinding varBinding = Types.getVariableBinding(fragment);
    FieldDeclaration decl = ast.newFieldDeclaration(fragment);
    decl.setType(newType(ast, varBinding.getType()));
    ASTUtil.getModifiers(decl).addAll(newModifiers(ast, varBinding.getModifiers()));
    return decl;//from  w  w  w  .j av a  2 s.  c  om
}

From source file:com.motorola.studio.android.generateviewbylayout.codegenerators.ClassAttributesCodeGenerator.java

License:Apache License

/**
 * Add attributes based on the GUI items declared on layout XML
 * <br>//from  ww w. java 2s.c om
 * GENERATED_CODE_FORMAT:
 * <br>
 * private $GUI_TYPE $GUI_ID;
 * @throws JavaModelException
 */
@SuppressWarnings("unchecked")
private void addAttributes(IProgressMonitor monitor) throws JavaModelException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    subMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_AddingAttributes,
            codeGeneratorData.getGuiItems().size());
    /*  
    * AST to be written       
    *   FieldDeclaration:
    * [Javadoc] { ExtendedModifier } Type VariableDeclarationFragment
    *    { , VariableDeclarationFragment } ;
    */
    for (LayoutNode node : codeGeneratorData.getGuiItems()) {
        if ((node.getNodeId() != null) && node.shouldInsertCode()) {
            boolean containFieldDeclared = getCodeGeneratorData().getJavaLayoutData().getVisitor()
                    .checkIfAttributeAlreadyDeclared(node, false);
            if (!containFieldDeclared) {
                //avoid to declare attribute twice
                Modifier privateMod = typeDeclaration.getAST().newModifier(ModifierKeyword.PRIVATE_KEYWORD);
                SimpleName guiName;
                try {
                    guiName = getNodeVariableTypeBasedOnLayoutNode(node);
                } catch (CoreException e) {
                    throw new JavaModelException(e);
                }
                SimpleType guiType = typeDeclaration.getAST().newSimpleType(guiName);
                VariableDeclarationFragment variableFragment = typeDeclaration.getAST()
                        .newVariableDeclarationFragment();
                SimpleName varName = variableFragment.getAST().newSimpleName(node.getNodeId());
                variableFragment.setName(varName);
                FieldDeclaration declaration = typeDeclaration.getAST().newFieldDeclaration(variableFragment);
                declaration.modifiers().add(privateMod);
                declaration.setType(guiType);
                typeDeclaration.bodyDeclarations().add(0, declaration); //add as the first item                
            }
        }
        subMonitor.worked(1);
    }
}