Search in sources :

Example 51 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project evosuite by EvoSuite.

the class TestExtensionJob method run.

@Override
protected IStatus run(IProgressMonitor monitor) {
    IStatus status = super.run(monitor);
    newTests.clear();
    IJavaElement element = JavaCore.create(target);
    if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
        ICompilationUnit compilationUnit = (ICompilationUnit) element;
        CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
        try {
            if (compilationUnit.getTypes().length == 0) {
                System.out.println("The compilation unit is empty :|");
                return status;
            }
            IType classType = compilationUnit.getTypes()[0];
            // new tests
            loadTestSuiteContent(getTestClassName());
            for (ImportDeclaration newImport : newImports) {
                if (!hasImport(compilationUnit, newImport)) {
                    int flag = newImport.isStatic() ? Flags.AccStatic : Flags.AccDefault;
                    String strImport = newImport.getName().toString();
                    // Names of onDemand import declarations do not contain the '*'
                    if (newImport.isOnDemand())
                        strImport += ".*";
                    compilationUnit.createImport(strImport, null, flag, null);
                }
            }
            for (MethodDeclaration newMethod : newMethods) {
                if (hasMethod(classType, newMethod.getName().toString())) {
                    System.out.println("Test suite already contains method called: " + newMethod.getName());
                    int num = 1;
                    newMethod.setName(newMethod.getAST().newSimpleName(newMethod.getName().toString() + "_" + num));
                    while (hasMethod(classType, newMethod.getName().toString())) {
                        num += 1;
                        String name = newMethod.getName().toString();
                        newMethod.setName(newMethod.getAST().newSimpleName(name.substring(0, name.length() - 2) + "_" + num));
                    }
                }
                String testContent = newMethod.toString();
                IMethod methodToAdd = classType.createMethod(testContent, null, false, new NullProgressMonitor());
                ISourceRange range = methodToAdd.getSourceRange();
                TextEdit indent_edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, classType.getCompilationUnit().getSource(), range.getOffset(), range.getLength(), 0, null);
                classType.getCompilationUnit().applyTextEdit(indent_edit, null);
                newTests.add(newMethod.getName().toString());
            }
            classType.getCompilationUnit().commitWorkingCopy(false, null);
            // write markers
            writeMarkersExtendedTestSuite();
        } catch (JavaModelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return status;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) JavaModelException(org.eclipse.jdt.core.JavaModelException) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) IOException(java.io.IOException) IType(org.eclipse.jdt.core.IType) CodeFormatter(org.eclipse.jdt.core.formatter.CodeFormatter) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) IImportDeclaration(org.eclipse.jdt.core.IImportDeclaration) IMethod(org.eclipse.jdt.core.IMethod) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 52 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project bndtools by bndtools.

the class BaselineErrorHandler method findPackageInfoJavaVersionLocation.

ISourceRange findPackageInfoJavaVersionLocation(String packageName, ICompilationUnit compUnit) throws JavaModelException {
    ISourceRange range = null;
    IPackageDeclaration[] pkgDecls = compUnit.getPackageDeclarations();
    if (pkgDecls != null) {
        for (IPackageDeclaration pkgDecl : pkgDecls) {
            if (packageName.equals(pkgDecl.getElementName())) {
                IAnnotation[] annots = pkgDecl.getAnnotations();
                for (IAnnotation annot : annots) {
                    String name = annot.getElementName();
                    if (ANNOTATION_VERSION_NO_PKG.equals(name) || ANNOTATION_VERSION_OSGI.equals(name) || ANNOTATION_VERSION_BND.equals(name)) {
                        ASTParser parser = ASTParser.newParser(AST.JLS8);
                        parser.setKind(ASTParser.K_COMPILATION_UNIT);
                        parser.setSource(compUnit);
                        parser.setResolveBindings(true);
                        CompilationUnit ast = (CompilationUnit) parser.createAST(null);
                        if (ast != null) {
                            MemberValuePairLocationRetriever mvpRetriever = new MemberValuePairLocationRetriever(annot, new Predicate<String>() {

                                @Override
                                public boolean test(String t) {
                                    return ANNOTATION_VERSION_BND.equals(t) || ANNOTATION_VERSION_OSGI.equals(t);
                                }
                            }, "value");
                            ast.accept(mvpRetriever);
                            range = mvpRetriever.getMemberValuePairSourceRange();
                        }
                    }
                }
            }
        }
    }
    return range;
}
Also used : IAnnotation(org.eclipse.jdt.core.IAnnotation) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTParser(org.eclipse.jdt.core.dom.ASTParser) MemberValuePairLocationRetriever(org.bndtools.builder.utils.MemberValuePairLocationRetriever) IPackageDeclaration(org.eclipse.jdt.core.IPackageDeclaration) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 53 with ISourceRange

use of org.eclipse.jdt.core.ISourceRange in project bndtools by bndtools.

the class NewTypeWizardPage method createType.

// ---- creation ----------------
/**
 * Creates the new type using the entered field values.
 *
 * @param monitor a progress monitor to report progress.
 * @throws CoreException Thrown when the creation failed.
 * @throws InterruptedException Thrown when the operation was canceled.
 */
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
    IProgressMonitor monitorInternal = monitor;
    if (monitorInternal == null) {
        monitorInternal = new NullProgressMonitor();
    }
    monitorInternal.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 8);
    IPackageFragmentRoot root = getPackageFragmentRoot();
    IPackageFragment pack = getPackageFragment();
    if (pack == null) {
        // $NON-NLS-1$
        pack = root.getPackageFragment("");
    }
    if (!pack.exists()) {
        String packName = pack.getElementName();
        pack = root.createPackageFragment(packName, true, new SubProgressMonitor(monitorInternal, 1));
    } else {
        monitorInternal.worked(1);
    }
    boolean needsSave;
    ICompilationUnit connectedCU = null;
    try {
        String typeName = getTypeNameWithoutParameters();
        boolean isInnerClass = isEnclosingTypeSelected();
        IType createdType;
        ImportsManager imports;
        int indent = 0;
        Set<String> existingImports;
        String lineDelimiter = null;
        if (!isInnerClass) {
            lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject());
            String cuName = getCompilationUnitName(typeName);
            // $NON-NLS-1$
            ICompilationUnit parentCU = pack.createCompilationUnit(cuName, "", false, new SubProgressMonitor(monitorInternal, 2));
            // create a working copy with a new owner
            needsSave = true;
            // cu is now a (primary) working
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitorInternal, 1));
            // copy
            connectedCU = parentCU;
            IBuffer buffer = parentCU.getBuffer();
            String simpleTypeStub = constructSimpleTypeStub();
            String cuContent = constructCUContent(parentCU, simpleTypeStub, lineDelimiter);
            buffer.setContents(cuContent);
            CompilationUnit astRoot = createASTForImports(parentCU);
            existingImports = getExistingImports(astRoot);
            imports = new ImportsManager(astRoot);
            // add an import that will be removed again. Having this import solves 14661
            imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), typeName));
            String typeContent = constructTypeStub(parentCU, imports, lineDelimiter);
            int index = cuContent.lastIndexOf(simpleTypeStub);
            if (index == -1) {
                AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0);
                int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition();
                int end = typeNode.getStartPosition() + typeNode.getLength();
                buffer.replace(start, end - start, typeContent);
            } else {
                buffer.replace(index, simpleTypeStub.length(), typeContent);
            }
            createdType = parentCU.getType(typeName);
        } else {
            IType enclosingType = getEnclosingType();
            ICompilationUnit parentCU = enclosingType.getCompilationUnit();
            needsSave = !parentCU.isWorkingCopy();
            // cu is now for sure (primary)
            parentCU.becomeWorkingCopy(new SubProgressMonitor(monitorInternal, 1));
            // a working copy
            connectedCU = parentCU;
            CompilationUnit astRoot = createASTForImports(parentCU);
            imports = new ImportsManager(astRoot);
            existingImports = getExistingImports(astRoot);
            // add imports that will be removed again. Having the imports solves 14661
            IType[] topLevelTypes = parentCU.getTypes();
            for (int i = 0; i < topLevelTypes.length; i++) {
                imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
            }
            lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType);
            StringBuffer content = new StringBuffer();
            String comment = getTypeComment(parentCU, lineDelimiter);
            if (comment != null) {
                content.append(comment);
                content.append(lineDelimiter);
            }
            content.append(constructTypeStub(parentCU, imports, lineDelimiter));
            IJavaElement sibling = null;
            if (enclosingType.isEnum()) {
                IField[] fields = enclosingType.getFields();
                if (fields.length > 0) {
                    for (int i = 0, max = fields.length; i < max; i++) {
                        if (!fields[i].isEnumConstant()) {
                            sibling = fields[i];
                            break;
                        }
                    }
                }
            } else {
                IJavaElement[] elems = enclosingType.getChildren();
                sibling = elems.length > 0 ? elems[0] : null;
            }
            createdType = enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitorInternal, 2));
            indent = StubUtility.getIndentUsed(enclosingType) + 1;
        }
        if (monitorInternal.isCanceled()) {
            throw new InterruptedException();
        }
        // add imports for superclass/interfaces, so types can be resolved correctly
        ICompilationUnit cu = createdType.getCompilationUnit();
        imports.create(false, new SubProgressMonitor(monitorInternal, 1));
        JavaModelUtil.reconcile(cu);
        if (monitorInternal.isCanceled()) {
            throw new InterruptedException();
        }
        // set up again
        CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit());
        imports = new ImportsManager(astRoot);
        createTypeMembers(createdType, imports, new SubProgressMonitor(monitorInternal, 1));
        // add imports
        imports.create(false, new SubProgressMonitor(monitorInternal, 1));
        removeUnusedImports(cu, existingImports, false);
        JavaModelUtil.reconcile(cu);
        ISourceRange range = createdType.getSourceRange();
        IBuffer buf = cu.getBuffer();
        String originalContent = buf.getText(range.getOffset(), range.getLength());
        String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, lineDelimiter, pack.getJavaProject());
        formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent);
        buf.replace(range.getOffset(), range.getLength(), formattedContent);
        if (!isInnerClass) {
            String fileComment = getFileComment(cu);
            if (fileComment != null && fileComment.length() > 0) {
                buf.replace(0, 0, fileComment + lineDelimiter);
            }
        }
        fCreatedType = createdType;
        if (needsSave) {
            cu.commitWorkingCopy(true, new SubProgressMonitor(monitorInternal, 1));
        } else {
            monitorInternal.worked(1);
        }
    } finally {
        if (connectedCU != null) {
            connectedCU.discardWorkingCopy();
        }
        monitorInternal.done();
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) IField(org.eclipse.jdt.core.IField) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) IBuffer(org.eclipse.jdt.core.IBuffer) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) IType(org.eclipse.jdt.core.IType) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ASTNode(org.eclipse.jdt.core.dom.ASTNode) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Aggregations

ISourceRange (org.eclipse.jdt.core.ISourceRange)53 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)18 IJavaElement (org.eclipse.jdt.core.IJavaElement)14 JavaModelException (org.eclipse.jdt.core.JavaModelException)13 ASTNode (org.eclipse.jdt.core.dom.ASTNode)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)10 ISourceReference (org.eclipse.jdt.core.ISourceReference)9 IType (org.eclipse.jdt.core.IType)8 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)6 SourceRange (org.eclipse.jdt.core.SourceRange)6 IBuffer (org.eclipse.jdt.core.IBuffer)5 IMethod (org.eclipse.jdt.core.IMethod)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)5 ArrayList (java.util.ArrayList)4 IField (org.eclipse.jdt.core.IField)4 IMember (org.eclipse.jdt.core.IMember)4 CoreException (org.eclipse.core.runtime.CoreException)3 IClassFile (org.eclipse.jdt.core.IClassFile)3