Example usage for org.eclipse.jdt.core.dom CompilationUnit getPosition

List of usage examples for org.eclipse.jdt.core.dom CompilationUnit getPosition

Introduction

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

Prototype

public int getPosition(int line, int column) 

Source Link

Document

Given a line number and column number, returns the corresponding position in the original source string.

Usage

From source file:de.bodden.tamiflex.resolution.MethodResolver.java

License:Open Source License

private static void disambiguateMethodByLineNumber(String containerClassName, String methodName,
        IProject containerProject, int lineNumber) {
    IJavaProject javaProject = JavaCore.create(containerProject);
    try {//  w  ww . java2  s.  c  o m
        IType type = javaProject.findType(containerClassName, (IProgressMonitor) null);
        ICompilationUnit compilationUnit = type.getCompilationUnit();

        if (compilationUnit != null) {
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setSource(compilationUnit);
            parser.setResolveBindings(true);

            CompilationUnit cu = (CompilationUnit) parser.createAST(null);
            final int linePosition = cu.getPosition(lineNumber, 0);

            cu.accept(new ASTVisitor() {

                public boolean visit(MethodDeclaration method) {
                    if (method.getStartPosition() <= linePosition
                            && method.getStartPosition() + method.getLength() >= linePosition) {
                        //method is resolved
                        resolvedMethods.clear();
                        resolvedMethods.add((IMethod) method.resolveBinding().getJavaElement());
                    }
                    return false;
                }

            });
        } else {
            IClassFile classFile = type.getClassFile();
            if (classFile != null) {
                IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile,
                        IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
                for (IMethodInfo method : reader.getMethodInfos()) {
                    String currMethodName = new String(method.getName());
                    if (!currMethodName.equals(methodName))
                        continue;

                    ICodeAttribute codeAttribute = method.getCodeAttribute();
                    ILineNumberAttribute lineNumberAttribute = codeAttribute.getLineNumberAttribute();
                    if (lineNumberAttribute != null) {
                        int[][] lineNumberTable = lineNumberAttribute.getLineNumberTable();
                        if (lineNumberTable != null && lineNumberTable.length > 0) {
                            int startLine = Integer.MAX_VALUE;
                            int endLine = 0;
                            for (int[] entry : lineNumberTable) {
                                int line = entry[1];
                                startLine = Math.min(startLine, line);
                                endLine = Math.max(endLine, line);
                            }
                            if (startLine >= lineNumber && endLine <= lineNumber) {
                                char[][] parameterTypes = Signature.getParameterTypes(method.getDescriptor());
                                String[] parameterTypeNames = new String[parameterTypes.length];
                                int i = 0;
                                for (char[] cs : parameterTypes) {
                                    parameterTypeNames[i] = new String(cs);
                                    i++;
                                }
                                IMethod iMethod = type.getMethod(currMethodName, parameterTypeNames);

                                //method resolved
                                resolvedMethods.clear();
                                resolvedMethods.add(iMethod);
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:org.evosuite.eclipse.quickfixes.MarkerWriter.java

License:Open Source License

public void writeMarkers() {
    System.out.println(tgr);/*from w  ww .j  a v a  2  s . co  m*/
    // ServerStatistics.getInstance().getX(); (getCoverage();)
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);
    parser.setSource(tgr.getTestSuiteCode().toCharArray());

    CompilationUnit compTest = (CompilationUnit) parser.createAST(null);
    IJavaElement jEle = JavaCore.create(res);

    if (jEle instanceof ICompilationUnit) {

        final ICompilationUnit icomp = (ICompilationUnit) jEle;
        // System.out.println(icomp);
        BufferedReader br;
        char[] varcontent = null;
        try {
            br = new BufferedReader(new FileReader(res.getLocation().toFile()));
            int size = 0;
            while (br.read() != -1) {
                size++;
            }
            // String content = "";
            // String line = br.readLine();
            // content += line;
            // while ((line = br.readLine()) != null){
            // content += line;
            // }
            // parser.setSource(content.toCharArray());
            br = new BufferedReader(new FileReader(res.getLocation().toFile()));
            varcontent = new char[size];
            br.read(varcontent, 0, size);
            parser.setSource(varcontent);
        } catch (FileNotFoundException e2) {
            e2.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final char[] content = varcontent;
        final CompilationUnit compClass = (CompilationUnit) parser.createAST(null);
        compTest.accept(testM);
        compClass.accept(raw);
        IJavaElement element = JavaCore.create(res);
        IJavaElement packageElement = element.getParent();

        String packageName = packageElement.getElementName();

        final String className = (!packageName.isEmpty() ? packageName + "." : "")
                + res.getName().replace(".java", "").replace(File.separator, ".");

        final char[] classContent = varcontent;
        if (tgr != null) {
            Display.getDefault().asyncExec(new Runnable() {

                @Override
                public void run() {
                    ArrayList<Integer> lines = new ArrayList<Integer>();
                    Set<Integer> actualLines = new HashSet<Integer>();
                    actualLines.addAll(tgr.getUncoveredLines());
                    actualLines.addAll(tgr.getCoveredLines());
                    int contentPosition = 0;
                    int line = 1;
                    while (contentPosition != -2 && contentPosition != -1) {
                        if (!actualLines.contains(line)) {
                            lines.add(line);
                        }
                        contentPosition = compClass.getPosition(line, 0);
                        line++;
                    }

                    IPreferenceStore store = Activator.getDefault().getPreferenceStore();
                    if (store.getBoolean("removed")) {
                        for (Integer i : lines) {
                            // this line couldn't be reached in the test!
                            IJavaElement currentElement = null;
                            int position = compClass.getPosition(i, 0);
                            int maxPosition = compClass.getPosition(i + 1, 0);
                            if (position == -1 || position == -2) {
                                continue;
                            }
                            while (position < classContent.length
                                    && Character.isWhitespace(classContent[position])) {
                                // System.out.println(classContent);
                                position++;
                            }
                            if (position > maxPosition) {
                                continue;
                            }
                            while (maxPosition < classContent.length
                                    && Character.isWhitespace(classContent[maxPosition])) {
                                // System.out.println(classContent);
                                maxPosition++;
                            }
                            try {
                                currentElement = icomp.getElementAt(position + 1);
                            } catch (JavaModelException e1) {
                                e1.printStackTrace();
                            }
                            if (isMethodDeclaration(i, currentElement, content, compClass, icomp)) {
                                continue;
                            }
                            IJavaElement nextElement = null;
                            int nextPosition = compClass.getPosition(i + 1, 0);
                            if (nextPosition != -1 || nextPosition != -2) {
                                try {
                                    nextElement = icomp.getElementAt(nextPosition);
                                    if (nextElement != currentElement) {
                                        continue;
                                    }
                                } catch (JavaModelException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (position > maxPosition) {
                                continue;
                            }
                            while (maxPosition < classContent.length
                                    && Character.isWhitespace(classContent[maxPosition])) {
                                // System.out.println(classContent);
                                maxPosition++;
                            }
                            try {
                                currentElement = icomp.getElementAt(position + 1);
                            } catch (JavaModelException e1) {
                                e1.printStackTrace();
                            }
                            if (content[position] == '/' && content[position + 1] == '/') {
                                continue;
                            }
                            if (content[position] == '}') {
                                continue;
                            }

                            if (getMethod(currentElement) == null) {
                                continue;
                            }
                            boolean marker = shouldWriteMarkers(currentElement);
                            if (marker) {
                                try {
                                    IMarker m = res.createMarker("EvoSuiteQuickFixes.lineremovedmarker");
                                    m.setAttribute(IMarker.MESSAGE,
                                            "This line appears to be removed by the Java Compiler.");
                                    m.setAttribute(IMarker.LINE_NUMBER, i);
                                    m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                                    m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
                                    m.setAttribute(IMarker.LOCATION, res.getName());
                                    m.setAttribute(IMarker.CHAR_START, position);
                                    m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0));

                                } catch (CoreException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    if (store.getBoolean("uncovered")) {
                        for (Integer i : tgr.getUncoveredLines()) {
                            // this line couldn't be reached in the test!

                            IJavaElement currentElement = null;
                            int position = compClass.getPosition(i, 0);
                            if (position == -1) {
                                continue;
                            }
                            while (position < classContent.length
                                    && Character.isWhitespace(classContent[position])) {
                                // System.out.println(classContent);
                                position++;
                            }
                            try {
                                currentElement = icomp.getElementAt(position + 1);
                            } catch (JavaModelException e1) {
                                e1.printStackTrace();
                            }
                            boolean marker = shouldWriteMarkers(currentElement);
                            if (marker) {
                                try {
                                    IMarker m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker");
                                    m.setAttribute(IMarker.LINE_NUMBER, i);
                                    m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                                    m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
                                    m.setAttribute(IMarker.LOCATION, res.getName());
                                    m.setAttribute(IMarker.CHAR_START, position);
                                    m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0));

                                } catch (CoreException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    for (BranchInfo bi : tgr.getUncoveredBranches()) {
                        int j = bi.getLineNo();
                        IJavaElement currentElement = null;
                        int position = compClass.getPosition(j, 0);
                        while (position < classContent.length
                                && Character.isWhitespace(classContent[position])) {
                            // System.out.println(classContent);
                            position++;
                        }
                        try {
                            currentElement = icomp.getElementAt(position + 1);
                        } catch (JavaModelException e1) {
                            e1.printStackTrace();
                        }
                        boolean marker = shouldWriteMarkers(currentElement);
                        if (marker) {
                            try {
                                IMarker m = res.createMarker("EvoSuiteQuickFixes.notcoveredmarker");
                                m.setAttribute(IMarker.MESSAGE, "This branch (starting line " + j
                                        + ") could not be covered by EvoSuite.");
                                m.setAttribute(IMarker.LINE_NUMBER, j);
                                m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                                m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
                                m.setAttribute(IMarker.LOCATION, res.getName());
                                m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker");
                                // m.setAttribute(IMarker.LINE_NUMBER, j);
                                m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                                m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
                                m.setAttribute(IMarker.LOCATION, res.getName());
                                m.setAttribute(IMarker.CHAR_START, position);
                                m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1);

                                m.setAttribute(IMarker.CHAR_START, position);
                                m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1);

                            } catch (CoreException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    for (MethodDeclaration method : testM.getMethods()) {
                        String test = method.getName().getFullyQualifiedName();
                        Set<Failure> failures = tgr.getContractViolations(test);
                        if (failures != null && failures.size() != 0) {
                            // uncaught Exception!
                            try {
                                for (Failure f : failures) {
                                    if (f != null) {
                                        int lineNumber = 1;
                                        String message = "";
                                        for (int i = 0; i < f.getStackTrace().length; i++) {
                                            if (f.getStackTrace()[i].getClassName().equals(className)) {
                                                boolean found = false;

                                                for (MethodDeclaration method2 : raw.getMethods()) {
                                                    String s = method2.getName().getFullyQualifiedName();
                                                    if (s.equals(f.getStackTrace()[i].getMethodName())) {
                                                        found = true;
                                                        break;
                                                    }
                                                }
                                                if (found) {
                                                    message = f.getStackTrace()[i].toString();
                                                    lineNumber = f.getStackTrace()[i].getLineNumber();
                                                    break;
                                                }
                                            }
                                        }
                                        IJavaElement currentElement = null;
                                        int position = compClass.getPosition(lineNumber, 0);
                                        while (position < classContent.length
                                                && Character.isWhitespace(classContent[position])) {
                                            // System.out.println(classContent);
                                            position++;
                                        }
                                        try {
                                            currentElement = icomp.getElementAt(position + 1);
                                        } catch (JavaModelException e1) {
                                            e1.printStackTrace();
                                        }
                                        boolean marker = shouldWriteMarkers(currentElement);
                                        if (marker) {
                                            IMarker m = res.createMarker("EvoSuiteQuickFixes.exceptionmarker");
                                            m.setAttribute(IMarker.MESSAGE,
                                                    f.getExceptionName() + " detected " + message);
                                            m.setAttribute(IMarker.LINE_NUMBER, lineNumber);
                                            m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
                                            m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
                                            m.setAttribute(IMarker.LOCATION, res.getName());
                                            while (position < classContent.length
                                                    && Character.isWhitespace(classContent[position])) {
                                                // System.out.println(classContent);
                                                position++;
                                            }
                                            m.setAttribute(IMarker.CHAR_START, position);
                                            m.setAttribute(IMarker.CHAR_END,
                                                    compClass.getPosition(lineNumber + 1, 0) - 1);
                                        }
                                    }
                                }
                            } catch (CoreException e) {
                                e.printStackTrace();
                            }
                        }

                    }

                }

            });
        }
    }
}

From source file:org.evosuite.eclipse.quickfixes.MarkerWriter.java

License:Open Source License

private boolean isMethodDeclaration(int lineNumber, IJavaElement currentElement, char[] content,
        CompilationUnit cu, ICompilationUnit icu) {
    IJavaElement previousElement = null;
    int prevPosition = cu.getPosition(lineNumber - 1, 0);
    int limit = cu.getPosition(lineNumber, 0);
    while (Character.isWhitespace(content[limit])) {
        // System.out.println(classContent);
        limit++;//from w  w  w .ja v  a  2 s  .c om
    }
    limit++;
    if (prevPosition != -1 && prevPosition != -2) {
        try {
            previousElement = icu.getElementAt(prevPosition + 1);
            if (previousElement != currentElement) {
                return true;
            } else {
                for (int i = prevPosition; i < limit; i++) {
                    if (content[i] == '{') {
                        return false;
                    }
                }
                return isMethodDeclaration(lineNumber - 1, currentElement, content, cu, icu);
            }
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForClass.java

License:Open Source License

@Override
public void run(IMarker marker) {
    IResource res = marker.getResource();

    try {//from   w w w . j  av a 2 s.  c  om

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 0) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();

        ASTRewrite rewriter = ASTRewrite.create(ast);

        Annotation annotation = ast.newNormalAnnotation();
        annotation.setTypeName(ast.newName("EvoIgnore"));
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
        ListRewrite lr = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);

        //lr.insertFirst(annotation, null);
        lr.insertAt(annotation, 0, null);
        lr.insertAt(id, 0, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        System.out
                .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        marker.delete();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerEvoIgnoreForMethod.java

License:Open Source License

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();

    try {//from   www . jav  a2s. c  om

        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 1) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);

        //         TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);

        MethodDeclaration md = td.getMethods()[0];

        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName())
                && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }

        Annotation annotation = ast.newNormalAnnotation();
        annotation.setTypeName(ast.newName("EvoIgnore"));
        ImportDeclaration id = ast.newImportDeclaration();

        id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
        ListRewrite lr = rewriter.getListRewrite(md.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        ListRewrite lr2 = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);

        //lr.insertFirst(annotation, null);
        lr.insertBefore(annotation, md, null);
        lr2.insertAt(id, 0, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        System.out
                .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        marker.delete();
    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerThrowsException.java

License:Open Source License

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();

    try {//  ww w  .  j  a v  a  2  s.  c o m
        String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE);
        String exception = markerMessage.split(" ")[0];
        String[] exceptionPackageArray = exception.split("\\.");
        String exceptionPackage = "";
        for (int i = 0; i < exceptionPackageArray.length - 1; i++) {
            exceptionPackage += exceptionPackageArray[i] + ".";
        }
        exception = exception.substring(exceptionPackage.length());

        System.out.println("Package: " + exceptionPackage + ", Exception: " + exception);

        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 1) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);

        //         TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);

        MethodDeclaration md = td.getMethods()[0];

        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName())
                && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }

        ListRewrite lr = rewriter.getListRewrite(md, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY);
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(exceptionPackage + exception));
        ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        lrClass.insertAt(id, 0, null);

        Statement s = (Statement) rewriter.createStringPlaceholder(exception, ASTNode.EMPTY_STATEMENT);

        lr.insertAt(s, 0, null);
        System.out.println("MD: " + md.getName() + "\nList: " + lr.getOriginalList());

        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        System.out
                .println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerTryBlock.java

License:Open Source License

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();

    try {/* w  w  w  .  ja v  a2s.c  om*/
        String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE);
        String exception = markerMessage.split(" ")[0];
        String[] exceptionPackageArray = exception.split("\\.");
        String exceptionPackage = "";
        for (int i = 0; i < exceptionPackageArray.length - 1; i++) {
            exceptionPackage += exceptionPackageArray[i] + ".";
        }
        exception = exception.substring(exceptionPackage.length());

        System.out.println("Package: " + exceptionPackage + ", Exception: " + exception);

        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);

        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);

        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
        if (position == 1) {
            position = compunit.getPosition(line, 0);
        }

        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);

        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);

        // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);

        MethodDeclaration md = td.getMethods()[0];

        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName())
                && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }

        Block block = md.getBody();

        ListRewrite lr = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(exceptionPackage + exception));
        ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        lrClass.insertAt(id, 0, null);
        ASTNode currentNode = null;
        List<ASTNode> list = new ArrayList<ASTNode>();
        for (Object o : lr.getOriginalList()) {
            if (o instanceof ASTNode) {
                list.add((ASTNode) o);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            ASTNode node = list.get(i);
            int nodeLine = compunit.getLineNumber(node.getStartPosition());
            System.out.println(line + " " + nodeLine);
            if (line == nodeLine) {
                currentNode = node;
                break;
            }
            List childrenList = node.structuralPropertiesForType();
            for (int j = 0; j < childrenList.size(); j++) {
                StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) childrenList.get(j);
                Object child = node.getStructuralProperty(curr);
                if (child instanceof List) {
                    for (Object ob : (List) child) {
                        if (ob instanceof ASTNode) {
                            list.add((ASTNode) ob);
                        }
                    }
                } else if (child instanceof ASTNode) {
                    list.add((ASTNode) child);
                }
            }
        }

        TryStatement ts = ast.newTryStatement();
        Statement emptyStatement = (Statement) rewriter.createStringPlaceholder("\n", ASTNode.EMPTY_STATEMENT);
        Statement emptyStatement2 = (Statement) rewriter.createStringPlaceholder("\n\t",
                ASTNode.EMPTY_STATEMENT);
        Block b2 = ast.newBlock();
        b2.statements().add(0, ASTNode.copySubtree(b2.getAST(), currentNode));
        b2.statements().add(1, emptyStatement);
        b2.statements().add(0, emptyStatement2);
        ts.setBody(b2);
        CatchClause cc = ast.newCatchClause();
        SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
        svd.setName(ast.newSimpleName("e"));
        Type type = ast.newSimpleType(ast.newName(exception));
        svd.setType(type);
        cc.setException(svd);
        Block b3 = ast.newBlock();
        Statement printStatement = (Statement) rewriter.createStringPlaceholder("e.printStackTrace();",
                ASTNode.EMPTY_STATEMENT);
        b3.statements().add(0, printStatement);
        cc.setBody(b3);
        ListRewrite parentList = rewriter.getListRewrite(currentNode.getParent(), Block.STATEMENTS_PROPERTY);
        parentList.replace(currentNode, ts, null);
        parentList.insertAfter(cc, ts, null);

        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);

        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } // (4)
        }
        marker.delete();
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

From source file:org.juniversal.translator.core.SourceCopier.java

License:Open Source License

/**
 * Skips all whitespace, newlines, and comments from the source starting at startPosition and continuing backwards
 * until the beginning of the whitespace/newlines/comments. The returned position points to the beginning of the
 * whitespace/newlines/comments or the original position if there wasn't any whitespace/newlines/comments.
 *
 * @param startPosition starting position in source
 * @return position of first character in sequence of space and comments
 *//* w w  w.  j a v a  2s. c  o  m*/
public int skipSpaceAndCommentsBackward(int startPosition) {
    int position = startPosition - 1;

    while (true) {
        int currChar = getSourceCharAtForBackward(position);

        if (currChar == -1)
            return position + 1;
        else if (currChar == ' ' || currChar == '\t' || currChar == '\r')
            --position;
        else if (currChar == '\n') {
            CompilationUnit compilationUnit = sourceFile.getCompilationUnit();
            int lineStartPosition = compilationUnit.getPosition(compilationUnit.getLineNumber(position), 0);
            int lineCommentStartPosition = getLineCommentStartPosition(lineStartPosition);

            if (lineCommentStartPosition != -1)
                position = lineCommentStartPosition - 1;
            else
                --position;
        } else if (currChar == '/' && getSourceCharAtForBackward(position - 1) == '*') {
            position -= 2;

            while (true) {
                currChar = getSourceCharAtForBackward(position);

                if (currChar == -1)
                    break;
                else if (currChar == '*' && getSourceCharAtForBackward(position - 1) == '/') {
                    position -= 2;
                    break;
                } else
                    --position;
            }
        } else
            return position + 1;
    }
}

From source file:org.juniversal.translator.core.SourceFile.java

License:Open Source License

/**
 * Returns a description of the specified position, including line number, column number, and the contents of the
 * entire line with the position marked. Normally this description is put in error messages. The description should
 * normally be output starting on a new line; the description doesn't include a line break at the beginning though
 * it does include a line break in the middle. If more text will be output following the description, the caller
 * should normally add a line break before appending additional text.
 *
 * @param position position in source file
 * @return description string for position, with one line break in the middle
 */// ww  w .j  a  va2  s. c  om
public String getPositionDescription(int position) {
    String prefix = isDiskFile() ? "    File " + sourceFile + "\n" : "";

    CompilationUnit compilationUnit = getCompilationUnit();

    int lineNumber = compilationUnit.getLineNumber(position);
    if (lineNumber < 0) {
        if (position == source.length())
            return prefix + "End of file";
        else
            return prefix + "Position " + position + " isn't valid";
    }

    int columnNumber = getSourceLogicalColumn(position);

    int startPosition = compilationUnit.getPosition(lineNumber, 0);
    int startOfNextLine = compilationUnit.getPosition(lineNumber + 1, 0);
    // If on last line, set endPosition to end of source else set it to end of line
    int endPosition = (startOfNextLine == -1) ? source.length() - 1 : startOfNextLine - 1;

    // Chop off newlines / carriage returns on the end of the line
    while (endPosition >= 0 && (source.charAt(endPosition) == '\n' || source.charAt(endPosition) == '\r'))
        --endPosition;
    if (endPosition < position)
        endPosition = position;

    String linePrefix = "    " + lineNumber + ":" + columnNumber + ":  ";

    String line = source.substring(startPosition, endPosition + 1);

    StringBuilder description = new StringBuilder(prefix);
    description.append(linePrefix).append(line).append("\n");

    // Append spaces or tabs to position the caret at the right spot on the line
    String textBeforePositionMarker = linePrefix + source.substring(startPosition, position);
    int length = textBeforePositionMarker.length();
    for (int i = 0; i < length; ++i)
        if (textBeforePositionMarker.charAt(i) == '\t')
            description.append('\t');
        else
            description.append(' ');
    description.append("^");

    return description.toString();
}

From source file:org.juniversal.translator.cplusplus.SourceTypeDeclarationWriter.java

License:Open Source License

private void writeMethod(MethodDeclaration methodDeclaration) {
    // We assume that the first non-whitespace text on the first line of the method
    // isn't indented at all--there's nothing in the method left of it. Unindent the
    // whole method by that amount, since methods aren't indented in the C++ source.
    CompilationUnit compilationUnit = getSourceFileWriter().getCompilationUnit();
    int methodLine = compilationUnit.getLineNumber(methodDeclaration.getStartPosition());
    int methodLineStartPosition = compilationUnit.getPosition(methodLine, 0);
    setPosition(methodLineStartPosition);
    skipSpacesAndTabs();/*w  w  w  .  ja v  a  2 s .  co  m*/
    int additionalIndent = getSourceLogicalColumn();

    int previousIndent = getTargetWriter().setAdditionalIndentation(-1 * additionalIndent);

    getContext().setWritingMethodImplementation(true);

    // Skip back to the beginning of the comments, ignoring any comments associated with
    // the previous node
    setPositionToStartOfNodeSpaceAndComments(methodDeclaration);

    // If we haven't output anything yet, don't include the separator blank lines
    if (!outputSomething)
        skipBlankLines();

    copySpaceAndComments();
    writeNode(methodDeclaration);

    getContext().setWritingMethodImplementation(false);
    getTargetWriter().setAdditionalIndentation(previousIndent);

    copySpaceAndCommentsUntilEOL();
    writeln();

    outputSomething = true;
}