Example usage for org.eclipse.jdt.core ICompilationUnit createImport

List of usage examples for org.eclipse.jdt.core ICompilationUnit createImport

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ICompilationUnit createImport.

Prototype

IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor)
        throws JavaModelException;

Source Link

Document

Creates and returns an non-static import declaration in this compilation unit with the given name.

Usage

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.PostActivityCreationAction.java

License:Open Source License

/**
 * Processes a newly created Activity.// w  w w .  j a  va2s.c o m
 *
 */
@Override
public void processNewType(IType newType) {
    try {
        String methodContent = "    /** Called when the activity is first created. */\n" + "    @Override\n"
                + "    public void onCreate(Bundle savedInstanceState) {\n"
                + "        super.onCreate(savedInstanceState);\n" + "\n"
                + "        // TODO Auto-generated method stub\n" + "    }";
        newType.createMethod(methodContent, null /* sibling*/, false /* force */, new NullProgressMonitor());

        // we need to add the import for Bundle, so we need the compilation unit.
        // Since the type could be enclosed in other types, we loop till we find it.
        ICompilationUnit compilationUnit = null;
        IJavaElement element = newType;
        do {
            IJavaElement parentElement = element.getParent();
            if (parentElement != null) {
                if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    compilationUnit = (ICompilationUnit) parentElement;
                }

                element = parentElement;
            } else {
                break;
            }
        } while (compilationUnit == null);

        if (compilationUnit != null) {
            compilationUnit.createImport(SdkConstants.CLASS_BUNDLE, null /* sibling */,
                    new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
    }
}

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.PostReceiverCreationAction.java

License:Open Source License

/**
 * Processes a newly created Activity./*from   w w  w  . j  a v a2 s  .c  o m*/
 *
 */
@Override
public void processNewType(IType newType) {
    try {
        String methodContent = "    @Override\n"
                + "    public void onReceive(Context context, Intent intent) {\n"
                + "        // TODO Auto-generated method stub\n" + "    }";
        newType.createMethod(methodContent, null /* sibling*/, false /* force */, new NullProgressMonitor());

        // we need to add the import for Bundle, so we need the compilation unit.
        // Since the type could be enclosed in other types, we loop till we find it.
        ICompilationUnit compilationUnit = null;
        IJavaElement element = newType;
        do {
            IJavaElement parentElement = element.getParent();
            if (parentElement != null) {
                if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    compilationUnit = (ICompilationUnit) parentElement;
                }

                element = parentElement;
            } else {
                break;
            }
        } while (compilationUnit == null);

        if (compilationUnit != null) {
            compilationUnit.createImport(SdkConstants.CLASS_CONTEXT, null /* sibling */,
                    new NullProgressMonitor());
            compilationUnit.createImport(SdkConstants.CLASS_INTENT, null /* sibling */,
                    new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
        // looks like the class already existed (this happens when the user check to create
        // inherited abstract methods).
    }
}

From source file:com.android.ide.eclipse.editors.manifest.descriptors.PostActivityCreationAction.java

License:Open Source License

/**
 * Processes a newly created Activity.//from w w w  .  j  a  v a 2 s .  c  o m
 * 
 */
public void processNewType(IType newType) {
    try {
        String methodContent = "    /** Called when the activity is first created. */\n" + "    @Override\n"
                + "    public void onCreate(Bundle savedInstanceState) {\n"
                + "        super.onCreate(savedInstanceState);\n" + "\n"
                + "        // TODO Auto-generated method stub\n" + "    }";
        newType.createMethod(methodContent, null /* sibling*/, false /* force */, new NullProgressMonitor());

        // we need to add the import for Bundle, so we need the compilation unit.
        // Since the type could be enclosed in other types, we loop till we find it.
        ICompilationUnit compilationUnit = null;
        IJavaElement element = newType;
        do {
            IJavaElement parentElement = element.getParent();
            if (parentElement != null) {
                if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    compilationUnit = (ICompilationUnit) parentElement;
                }

                element = parentElement;
            } else {
                break;
            }
        } while (compilationUnit == null);

        if (compilationUnit != null) {
            compilationUnit.createImport(AndroidConstants.CLASS_BUNDLE, null /* sibling */,
                    new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
    }
}

From source file:com.android.ide.eclipse.editors.manifest.descriptors.PostReceiverCreationAction.java

License:Open Source License

/**
 * Processes a newly created Activity./* www  .j  ava 2s. com*/
 * 
 */
public void processNewType(IType newType) {
    try {
        String methodContent = "    @Override\n"
                + "    public void onReceive(Context context, Intent intent) {\n"
                + "        // TODO Auto-generated method stub\n" + "    }";
        newType.createMethod(methodContent, null /* sibling*/, false /* force */, new NullProgressMonitor());

        // we need to add the import for Bundle, so we need the compilation unit.
        // Since the type could be enclosed in other types, we loop till we find it.
        ICompilationUnit compilationUnit = null;
        IJavaElement element = newType;
        do {
            IJavaElement parentElement = element.getParent();
            if (parentElement != null) {
                if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                    compilationUnit = (ICompilationUnit) parentElement;
                }

                element = parentElement;
            } else {
                break;
            }
        } while (compilationUnit == null);

        if (compilationUnit != null) {
            compilationUnit.createImport(AndroidConstants.CLASS_CONTEXT, null /* sibling */,
                    new NullProgressMonitor());
            compilationUnit.createImport(AndroidConstants.CLASS_INTENT, null /* sibling */,
                    new NullProgressMonitor());
        }
    } catch (JavaModelException e) {
        // looks like the class already existed (this happens when the user check to create
        // inherited abstract methods).
    }
}

From source file:com.arcbees.gwtp.plugin.core.presenter.CreatePresenterPage.java

License:Apache License

/**
 * TODO extract this possibly, but I think I'll wait till I get into slots
 * before I do it see what is common.//from   ww w  . ja va 2 s.c om
 */
private void createPresenterGinlink(ICompilationUnit unit, String modulePackageName, String moduleName,
        IProgressMonitor monitor) throws JavaModelException, MalformedTreeException, BadLocationException {
    unit.createImport(modulePackageName + "." + moduleName, null, monitor);
    Document document = new Document(unit.getSource());

    CompilationUnit astRoot = initAstRoot(unit, monitor);

    // creation of ASTRewrite
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());

    // find the configure method
    MethodDeclaration method = findMethod(astRoot, "configure");
    if (method == null) {
        logger.severe("createPresenterGinLink() unit did not have configure implementation.");
        return;
    }

    // presenter configure method install(new Module());
    String installModuleStatement = "install(new " + moduleName + "());";

    Block block = method.getBody();
    ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
    ASTNode placeHolder = rewrite.createStringPlaceholder(installModuleStatement, ASTNode.EMPTY_STATEMENT);
    listRewrite.insertFirst(placeHolder, null);

    // computation of the text edits
    TextEdit edits = rewrite.rewriteAST(document, unit.getJavaProject().getOptions(true));

    // computation of the new source code
    edits.apply(document);
    String newSource = document.get();

    // update of the compilation unit and save it
    IBuffer buffer = unit.getBuffer();
    buffer.setContents(newSource);
    buffer.save(monitor, true);
}

From source file:com.motorola.studio.android.generatecode.JavaCodeModifier.java

License:Apache License

/**
 * Creates the necessary imports listed in {@link JavaCodeModifier#IMPORT_LIST}.
 * @throws JavaModelException Thrown if there were problems during the insertion of imports in the java file.
 *//*from   w ww.j a v a 2s  .  c  o m*/
protected void createImports(IProgressMonitor monitor, ICompilationUnit compilationUnit)
        throws JavaModelException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);
    //need to look at each GUI item and them create 1 method 
    subMonitor.beginTask(CodeUtilsNLS.JavaViewBasedOnLayoutModifier_CreatingImports, IMPORT_LIST.size());
    if (IMPORT_LIST != null) {
        for (String importItem : IMPORT_LIST) {
            compilationUnit.createImport(importItem, null, subMonitor);
        }
    }
    subMonitor.worked(IMPORT_LIST.size());
}

From source file:edu.washington.cs.cupid.scripting.java.JavaProjectManager.java

License:Open Source License

public static IType createSnippetContext(IJavaProject project, String simpleName, TypeToken<?> inputType,
        TypeToken<?> outputType, String content, IProgressMonitor monitor)
        throws CoreException, IOException, ClassNotFoundException {

    monitor.beginTask("Create Snippet Context", 6);
    try {//from w  w  w.  j  a v a 2s. c o m
        IFile file = project.getProject().getFile("src/" + simpleName + ".java");

        ensureClasspath(inputType);

        if (file.exists()) {
            file.setContents(new ByteArrayInputStream(content.getBytes()), IFile.FORCE,
                    new SubProgressMonitor(monitor, 1));
        } else {
            file.create(new ByteArrayInputStream(content.getBytes()), true, new SubProgressMonitor(monitor, 1));
        }

        file.setHidden(true);
        file.getProject().refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1));

        snippetFiles.add(file);
        ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);

        if (!inputType.getRawType().isPrimitive()) {
            unit.createImport(inputType.getRawType().getName(), null, new SubProgressMonitor(monitor, 1));
        }

        if (!outputType.getRawType().isPrimitive()) {
            unit.createImport(outputType.getRawType().getName(), null, new SubProgressMonitor(monitor, 1));
        }

        return unit.getTypes()[0];
    } finally {
        monitor.done();
    }
}

From source file:net.sf.guavaeclipse.creator.AbstractMethodCreator.java

License:Apache License

protected void generateImport(String importStatement) throws JavaModelException {
    String[] importStatements = importStatement.split(",");
    ICompilationUnit compilationUnit = getCompilationUnit();
    if (compilationUnit != null) {
        for (String importDecl : importStatements) {
            compilationUnit.createImport(importDecl, null, new NullProgressMonitor());
        }/*from  www.  j  a v  a 2s.co m*/
    }
}

From source file:org.autorefactor.ui.ApplyFileMergeRefactoringsJob.java

License:Open Source License

/**
 * Executes the refactoring according to the information stored in the attributes/
 * @param monitor ProgressMonitor/*  w w  w.j  a va2 s  . c o m*/
 * @return
 */
protected IStatus run(IProgressMonitor monitor) {
    try {
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        // Performing the merge of the properties files *.* 
        ICompilationUnit mergedPropertiesCompilationUnit = (ICompilationUnit) this.mergedPropertiesJavaElement;
        for (IJavaElement _currentJavaElement : this.javaElementsToMerge) {
            ICompilationUnit currentPropertiesToMergeCompilationUnit = (ICompilationUnit) _currentJavaElement;

            if (currentPropertiesToMergeCompilationUnit.findPrimaryType() != null) {
                for (IField _field : currentPropertiesToMergeCompilationUnit.findPrimaryType().getFields()) {
                    System.out.println("additionalVariablesList.add(_field.getElementName());");
                    additionalVariablesList.add(_field.getElementName());
                    mergedPropertiesCompilationUnit.findPrimaryType().createField(_field.getSource(), null,
                            false, monitor);
                }
                for (IMethod _method : currentPropertiesToMergeCompilationUnit.findPrimaryType().getMethods()) {
                    mergedPropertiesCompilationUnit.findPrimaryType().createMethod(_method.getSource(), null,
                            false, monitor);
                }
                for (IImportDeclaration _import : currentPropertiesToMergeCompilationUnit.getImports()) {
                    if (!mergedPropertiesCompilationUnit.getImport(_import.getElementName()).exists()) {
                        mergedPropertiesCompilationUnit.createImport(_import.getElementName(), null, monitor);
                    }
                }
            }
        }
        targetProject.refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (Exception e) {
        e.printStackTrace();
        return new Status(IStatus.ERROR, AutoRefactorPlugin.PLUGIN_ID, e.getMessage(), e);
    } finally {
        monitor.done();
    }
    return Status.OK_STATUS;
}

From source file:org.autorefactor.ui.ApplyOverloadingRefactoringsJob.java

License:Open Source License

private IStatus run0(IProgressMonitor monitor) throws Exception {

    final int startSize = 2;
    monitor.beginTask("", startSize);
    try {//from   w  ww .  j a  va 2  s . c o m
        if (monitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }

        if (extensionRefactoringUnit != null && baseRefactoringUnit != null) {
            ICompilationUnit extensionCompilationUnit = extensionRefactoringUnit.getCompilationUnit();
            ICompilationUnit baseCompilationUnit = baseRefactoringUnit.getCompilationUnit();
            IType primaryType = extensionCompilationUnit.findPrimaryType();

            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "extension: " + extensionCompilationUnit.getElementName()
            //                     + " base: " + baseCompilationUnit.getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "extension: " + extensionCompilationUnit.getJavaProject().getElementName()
            //                     + " base: " + baseCompilationUnit.getJavaProject().getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0 " + "base SRC: " + baseCompilationUnit.getSource());

            //               for(IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType().getMethods()){
            //                  System.out.println("_baseMethod: " + _method.getElementName());
            //               }

            for (IMethod _overridingMethod : primaryType.getMethods()) {
                //                  System.out.println("_overridingMethod " + _overridingMethod.getElementName());

                IAnnotation overrideAnnotation = null;
                for (IAnnotation _annotation : _overridingMethod.getAnnotations()) {
                    if (_annotation.getElementName().equals("OverrideRequiredAspectMethod"))
                        overrideAnnotation = _annotation;
                }

                if (overrideAnnotation != null) {
                    IMethod realOverridingMethod = null;

                    for (IMethod _overridingMethod2 : primaryType.getMethods()) {
                        if (_overridingMethod2.getElementName()
                                .equals("_privk3_" + _overridingMethod.getElementName()))
                            realOverridingMethod = _overridingMethod2;
                    }

                    IMethod toRemove = null;

                    for (IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                            .getMethods()) {
                        if (_method.getElementName().equals(realOverridingMethod.getElementName())
                        /*&& _method.getNumberOfParameters() == realOverridingMethod.getNumberOfParameters()
                           && areParametersEquivalent(_method.getParameterTypes(), realOverridingMethod.getParameterTypes())*/) {
                            toRemove = _method;
                        }
                    }

                    IMethod oldOriginal = null;

                    for (IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                            .getMethods()) {
                        if (_method.getElementName().endsWith("_original_" + _overridingMethod.getElementName())
                        /*&& _method.getNumberOfParameters() == _overridingMethod.getNumberOfParameters()
                           && areParametersEquivalent(_method.getParameterTypes(), _overridingMethod.getParameterTypes())*/) {
                            oldOriginal = _method;
                        }
                    }

                    if (toRemove != null && oldOriginal == null) {
                        overrideRequiredMethod(baseRefactoringUnit, toRemove, realOverridingMethod, monitor);
                    } else if (toRemove != null && oldOriginal != null) {
                        ArrayList<IMethod> originalMethods = getAllOriginalMethods(baseRefactoringUnit,
                                _overridingMethod.getElementName());
                        overrideRequiredMethodOriginal(baseRefactoringUnit, toRemove, realOverridingMethod,
                                originalMethods.size(), monitor);
                    }
                    targetProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
                }
            }

            // Adding the additional methods included by the extension
            for (IMethod _method : extensionRefactoringUnit.getCompilationUnit().findPrimaryType()
                    .getMethods()) {
                IAnnotation extensionAnnotation = null;
                for (IAnnotation _annotation : _method.getAnnotations()) {
                    if (_annotation.getElementName().equals("AddExtensionMethod"))
                        extensionAnnotation = _annotation;
                }
                if (extensionAnnotation != null || additionalVariablesList.contains(_method.getElementName())) {
                    IMethod baseMethod = getMethod(baseRefactoringUnit, _method);
                    if (baseMethod == null || (baseMethod != null && !baseMethod.exists())) {
                        baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                                .createMethod(_method.getSource(), null, true, monitor);
                        IMethod privk3baseMethod = getPrivateMethod(extensionRefactoringUnit, _method);
                        if (privk3baseMethod != null) {
                            baseRefactoringUnit.getCompilationUnit().findPrimaryType()
                                    .createMethod(privk3baseMethod.getSource(), null, true, monitor);
                        }
                    }
                }
            }

            // Adding the imports needed by the injected code
            for (IImportDeclaration _import : extensionCompilationUnit.getImports()) {
                if (!baseCompilationUnit.getImport(_import.getElementName()).exists()) {
                    baseCompilationUnit.createImport(_import.getElementName(), null, monitor);
                }
            }

            //               System.out.println("ApplyOverloadingRefactoringsJob.run0.after " + "extension: " + extensionCompilationUnit.getElementName()
            //                     + " base: " + baseCompilationUnit.getElementName());
            //               System.out.println("ApplyOverloadingRefactoringsJob.run0.after " + "extension: " + extensionCompilationUnit.getJavaProject().getElementName()
            //                     + " base: " + baseCompilationUnit.getJavaProject().getElementName());

            //               for(IMethod _method : baseRefactoringUnit.getCompilationUnit().findPrimaryType().getMethods()){
            //                  System.out.println("_baseMethod: " + _method.getElementName());
            //               }
        }
    } finally {
        monitor.done();
    }
    return Status.OK_STATUS;
}