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

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

Introduction

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

Prototype

public void setName(Name name) 

Source Link

Document

Sets the package name of this package 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  w w  .j a v  a2 s  .  c om*/
    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.ForwardJavaSrcDir_Files.java

License:Open Source License

/**
 * @throws CodeSyncException /*ww  w .j av a 2 s  .  c o  m*/
 * @flowerModelElementId _IEIN9erfEd6QaI9daHlzjA
 */
@SuppressWarnings("unchecked")
@Override
protected ReverseStatus forwardElement(Type modelElement, IContainer parentAstElement,
        CompilationUnit astElement) throws CodeSyncException {
    try {
        astElement.recordModifications();
    } catch (IllegalArgumentException e) {
        //it is ok, we swallow ,recordModification had been called already on creation of compilation unit 
    }
    // TODO :: should update only when something specific happens? moving in another package,renaming the package,moving the package?
    // this updates the package declaration
    AST ast = astElement.getAST();
    PackageDeclaration packageDeclaration = astElement.getPackage();
    if (packageDeclaration == null) {
        String fullyPackageName = SyncUtils.getFullyQualifiedPackageNameFromType(modelElement);
        // a java type in the default package can not have the package declaration
        if (fullyPackageName.length() > 0) {
            packageDeclaration = ast.newPackageDeclaration();
            astElement.setPackage(packageDeclaration);
            packageDeclaration.setName(ast.newName(fullyPackageName));
        }
    }

    // creating the list 
    HashSet<String> fullyQualifiedImports = new HashSet<String>();
    for (ImportDeclaration importDeclaration : (List<ImportDeclaration>) astElement.imports())
        fullyQualifiedImports.add(importDeclaration.getName().getFullyQualifiedName());
    setContextForImportDeclarations(astElement, fullyQualifiedImports, modelElement.getNearestPackage());

    ReverseStatus status = new ReverseStatus();
    if (modelElement instanceof Interface) {
        forwardJavaInterface.setParentPackage(parentAstElement);
        status.applyOr(forwardJavaInterface.forward((Interface) modelElement, astElement));
    } else if (modelElement instanceof Class) {
        forwardJavaClass.setParentPackage(parentAstElement);
        status.applyOr(forwardJavaClass.forward((Class) modelElement, astElement));
    } else
        throw new IllegalArgumentException("could not recognize instance of " + modelElement);

    IFile javaFile = (IFile) parentAstElement.getFile(new Path(modelElement.getName() + ".java"));

    try {
        JavaSyncUtils.writeJavafile(astElement, javaFile);
        codeSyncAlgorithm.addLogEntry(javaFile.getFullPath().toString() + " - file modified");
        ((TimeStampedSyncElement) modelElement).setSyncTimeStamp(Long.toString(javaFile.getLocalTimeStamp()));
    } catch (Exception e) {
        throw new RuntimeException("Error during file save: " + javaFile, e);
    }
    return status;
}

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

License:Open Source License

protected PackageDeclaration getPackageDeclaration(AST ast, String packageName) {
    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    packageDeclaration.setName(ast.newName(packageName));

    return packageDeclaration;
}

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

License:Open Source License

private void createHomeImplementation(IProgressMonitor monitor, ICompilationUnit iUnit, String typePackage,
        String name) throws JavaModelException, MalformedTreeException, BadLocationException {
    iUnit.getBuffer().setContents("");
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);//from  w  w w .j  av  a  2s .  c o m

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    // Package statement
    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    unit.setPackage(packageDeclaration);
    packageDeclaration.setName(ast.newName(typePackage));

    // class declaration
    TypeDeclaration classType = getTypeDeclaration(ast, name + "HomeImpl", false, "IBOHomeImpl", null,
            getHomeImplImports());
    classType.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
    addHomeImplImport("com.idega.business.IBOHomeImpl");
    unit.types().add(classType);

    // create() method
    MethodDeclaration methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    if (this.isJDK1_5) {
        MarkerAnnotation annotation = ast.newMarkerAnnotation();
        annotation.setTypeName(ast.newSimpleName("Override"));
        methodConstructor.modifiers().add(annotation);
    }
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    if (this.isJDK1_5) {
        ParameterizedType returnType = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Class")));
        returnType.typeArguments().add(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setReturnType2(returnType);
    } else {
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName("Class")));
    }
    methodConstructor.setName(ast.newSimpleName("getBeanInterfaceClass"));

    classType.bodyDeclarations().add(methodConstructor);

    Block constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    TypeLiteral typeLiteral = ast.newTypeLiteral();
    typeLiteral.setType(ast.newSimpleType(ast.newSimpleName(name)));

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(typeLiteral);
    constructorBlock.statements().add(returnStatement);

    // create() method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("create"));
    methodConstructor.thrownExceptions().add(ast.newName("CreateException"));
    addHomeImplImport("javax.ejb.CreateException");
    classType.bodyDeclarations().add(methodConstructor);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("createIBO"));

    CastExpression ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    writeImports(ast, unit, getHomeImplImports());
    commitChanges(iUnit, unit, document);
}

From source file:com.motorola.studio.android.model.java.JavaClass.java

License:Apache License

/**
 * Class constructor. Creates the basic elements for the class:
 * package name and class declaration based on a super class.
 * //from   ww w .  j a va  2  s . co  m
 * @param className The simple class name
 * @param packageName The full-qualified class package name
 * @param superClass The full-qualified super class name
 */
@SuppressWarnings("unchecked")
protected JavaClass(String className, String packageName, String superClass) {
    // It is expected that the parameters have been validated
    // by the UI
    Assert.isNotNull(className);
    Assert.isNotNull(packageName);
    Assert.isNotNull(superClass);

    this.className = className;
    this.packageName = getFQNAsArray(packageName);
    this.superClass = getFQNAsArray(superClass);

    // The package name must have two identifiers at least, according to
    // the Android specifications
    Assert.isLegal(packageName.length() > 1);
    // So, the superclass must have at least two identifiers plus the name
    Assert.isLegal(superClass.length() > 2);

    ast = AST.newAST(AST.JLS3);
    compUnit = ast.newCompilationUnit();

    Type superClassType = null;

    // Sets the package name to the class
    PackageDeclaration pd = ast.newPackageDeclaration();
    QualifiedName qPackageName = ast.newQualifiedName(ast.newName(getQualifier(this.packageName)),
            ast.newSimpleName(getName(this.packageName)));
    pd.setName(qPackageName);
    compUnit.setPackage(pd);

    // Imports the super class
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(superClass));
    compUnit.imports().add(id);
    superClassType = ast.newSimpleType(ast.newName(getName(this.superClass)));

    // Creates the class
    classDecl = ast.newTypeDeclaration();
    classDecl.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    if (superClassType != null) {
        classDecl.setSuperclassType(superClassType);
    }

    classDecl.setName(ast.newSimpleName(className));
    compUnit.types().add(classDecl);

    document = new Document(compUnit.toString());
}

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

License:Apache License

/**
 * Generate the Java package from UML package.
 * /*from  w w w . java  2s. c  om*/
 * @param clazz
 *            the UML class
 * @param ast
 *            the JDT Java AST
 * @param cu
 *            the generated Java compilation unit
 */
public void generatePackage(Classifier clazz, AST ast, CompilationUnit cu) {
    PackageDeclaration pd = ast.newPackageDeclaration();
    String fullPackageName = getFullPackageName(clazz);
    pd.setName(ast.newName(fullPackageName));

    Date now = new Date();
    String commentDate = "Generation date: " + now.toString() + ".";

    interfaceGenerator.generatePackageJavadoc(ast, pd, PackageComment.CONTENT_1.getValue(),
            PackageComment.CONTENT_2.getValue(), " ", PackageComment.CONTENT_3.getValue(), " ", commentDate);

    cu.setPackage(pd);
}

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

License:Apache License

/**
 * Generate the Java package from UML package.
 * /*from   w  w w .j a  va 2  s . com*/
 * @param clazz
 *            the UML class
 * @param ast
 *            the JDT Java AST
 * @param cu
 *            the generated Java compilation unit
 */
private void generatePackage(Classifier clazz, AST ast, CompilationUnit cu) {
    PackageDeclaration pd = ast.newPackageDeclaration();
    String fullPackageName = getFullPackageName(clazz);
    pd.setName(ast.newName(fullPackageName));

    Date now = new Date();
    String commentDate = "Generation date: " + now.toString() + ".";

    interfaceGenerator.generatePackageJavadoc(ast, pd, PackageComment.CONTENT_1.getValue(),
            PackageComment.CONTENT_2.getValue(), " ", PackageComment.CONTENT_3.getValue(), " ", commentDate);

    cu.setPackage(pd);
}

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

License:Apache License

/**
 * Generate the Java package from UML package.
 * //from   ww  w. ja  va  2 s .  com
 * @param clazz
 *            the UML class
 * @param ast
 *            the JDT Java AST
 * @param cu
 *            the generated Java compilation unit
 */
public void generatePackage(Classifier clazz, AST ast, CompilationUnit cu) {
    PackageDeclaration pd = ast.newPackageDeclaration();
    String fullPackageName = getFullPackageName(clazz);
    pd.setName(ast.newName(fullPackageName));

    Date now = new Date();
    String commentDate = "Generation date: " + now.toString() + ".";

    generatePackageJavadoc(ast, pd, PackageComment.CONTENT_1.getValue(), PackageComment.CONTENT_2.getValue(),
            " ", PackageComment.CONTENT_3.getValue(), " ", commentDate);

    cu.setPackage(pd);
}

From source file:de.crowdcode.kissmda.extensions.importpacker.ImportPackerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test//from ww w.  j  a  v  a2  s.c o  m
public void test_Existing_Static_Imports2() {
    AST ast = AST.newAST(AST.JLS4);
    CompilationUnit cu = ast.newCompilationUnit();

    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    packageDeclaration.setName(ast.newName("org.kissmda.test.junit"));
    cu.setPackage(packageDeclaration);

    ImportDeclaration importDeclaration = ast.newImportDeclaration();
    importDeclaration.setName(ast.newName("org.junit.Assert.assertNotNull"));
    importDeclaration.setStatic(true);
    cu.imports().add(importDeclaration);

    logger.info(cu.toString());
    new ImportPacker(cu).pack();

    logger.info(cu.toString());

    assertEquals("package org.kissmda.test.junit;\n" //
            + "import static org.junit.Assert.assertNotNull;", cu.toString().trim());
}

From source file:de.dentrassi.varlink.generator.util.JdtHelper.java

License:Open Source License

public static void createCompilationUnit(final Path root, final String packageName, final String name,
        final Charset charset, final BiConsumer<AST, CompilationUnit> consumer) {

    final AST ast = AST.newAST(AST.JLS8);

    final CompilationUnit cu = ast.newCompilationUnit();

    final PackageDeclaration pkg = ast.newPackageDeclaration();
    pkg.setName(ast.newName(packageName));
    cu.setPackage(pkg);/*from ww w.  j  ava  2s . c o m*/

    final Path path = root.resolve(packageName.replace(".", File.separator)).resolve(name + ".java");

    consumer.accept(ast, cu);

    try {
        Files.createDirectories(path.getParent());

        // format code

        final CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
        final String s = cu.toString();
        final TextEdit result = formatter.format(CodeFormatter.K_COMPILATION_UNIT, s, 0, s.length(), 0, null);

        final Document doc = new Document(s);
        result.apply(doc);

        // write out

        try (final Writer writer = Files.newBufferedWriter(path, charset)) {
            writer.append(doc.get());
        }
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

}