Search in sources :

Example 16 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project jbosstools-hibernate by jbosstools.

the class NewHibernateMappingPreviewPage method performCommit.

protected void performCommit() {
    final CompositeChange cc = (CompositeChange) getChange();
    if (cc == null) {
        return;
    }
    final ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    Change[] changes = cc.getChildren();
    for (int i = 0; i < changes.length; i++) {
        Change change = changes[i];
        if (!(change instanceof TextFileChange)) {
            continue;
        }
        TextFileChange tfc = (TextFileChange) change;
        if (tfc.isEnabled() && tfc.getEdit() != null) {
            IPath path = new Path(tfc.getName());
            ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
            IDocument document = textFileBuffer.getDocument();
            try {
                tfc.getEdit().apply(document);
            } catch (MalformedTreeException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("MalformedTreeException: ", e);
            } catch (BadLocationException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("BadLocationException: ", e);
            }
            try {
                // commit changes to underlying file
                textFileBuffer.commit(null, true);
            } catch (CoreException e) {
                // $NON-NLS-1$
                HibernateConsolePlugin.getDefault().logErrorMessage("CoreException: ", e);
            }
        }
    }
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CompositeChange(org.eclipse.ltk.core.refactoring.CompositeChange) Change(org.eclipse.ltk.core.refactoring.Change) CreateTextFileChange(org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateTextFileChange) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) CreateTextFileChange(org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateTextFileChange) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) CoreException(org.eclipse.core.runtime.CoreException) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) CompositeChange(org.eclipse.ltk.core.refactoring.CompositeChange) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 17 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project eclipse-cs by checkstyle.

the class AbstractASTResolution method run.

/**
 * {@inheritDoc}
 */
@Override
public void run(IMarker marker) {
    IResource resource = marker.getResource();
    if (!(resource instanceof IFile)) {
        return;
    }
    ICompilationUnit compilationUnit = getCompilationUnit(marker);
    if (compilationUnit == null) {
        return;
    }
    ITextFileBufferManager bufferManager = null;
    IPath path = compilationUnit.getPath();
    try {
        final IProgressMonitor monitor = new NullProgressMonitor();
        // open the file the editor
        JavaUI.openInEditor(compilationUnit);
        // reimplemented according to this article
        // http://www.eclipse.org/articles/Article-JavaCodeManipulation_AST/index.html
        bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, null);
        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
        IDocument document = textFileBuffer.getDocument();
        IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();
        MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
        // by a previous quickfix
        if (annotation == null) {
            return;
        }
        Position pos = annotationModel.getPosition(annotation);
        final IRegion lineInfo = document.getLineInformationOfOffset(pos.getOffset());
        final int markerStart = pos.getOffset();
        ASTParser astParser = ASTParser.newParser(AST.JLS3);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setSource(compilationUnit);
        CompilationUnit ast = (CompilationUnit) astParser.createAST(monitor);
        ast.recordModifications();
        ast.accept(handleGetCorrectingASTVisitor(lineInfo, markerStart));
        // rewrite all recorded changes to the document
        TextEdit edit = ast.rewrite(document, compilationUnit.getJavaProject().getOptions(true));
        edit.apply(document);
        // commit changes to underlying file
        if (mAutoCommit) {
            textFileBuffer.commit(monitor, false);
        }
    } catch (CoreException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } catch (MalformedTreeException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } catch (BadLocationException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } finally {
        if (bufferManager != null) {
            try {
                bufferManager.disconnect(path, null);
            } catch (CoreException e) {
                // $NON-NLS-1$
                CheckstyleLog.log(e, "Error processing quickfix");
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Position(org.eclipse.jface.text.Position) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IAnnotationModel(org.eclipse.jface.text.source.IAnnotationModel) IRegion(org.eclipse.jface.text.IRegion) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) MarkerAnnotation(org.eclipse.ui.texteditor.MarkerAnnotation) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 18 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project evosuite by EvoSuite.

the class ResolutionMarkerThrowsException method run.

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();
    try {
        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();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) AST(org.eclipse.jdt.core.dom.AST) JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 19 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project ch.hsr.ifs.cdttesting by IFS-HSR.

the class TestProjectHolder method formatFileAsync.

@Override
public ProjectHolderJob formatFileAsync(IPath path) {
    return ProjectHolderJob.create("Formatting project " + projectName, ITestProjectHolder.FORMATT_FILE_JOB_FAMILY, mon -> {
        if (!formattedDocuments.contains(path)) {
            final IDocument doc = getDocument(getFile(path));
            final Map<String, Object> options = new HashMap<>(cProject.getOptions(true));
            try {
                final ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(path, cProject);
                options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu);
                final CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
                final TextEdit te = formatter.format(CodeFormatter.K_TRANSLATION_UNIT, path.toOSString(), 0, doc.getLength(), 0, NL);
                te.apply(doc);
                formattedDocuments.add(path);
            } catch (CModelException | MalformedTreeException | BadLocationException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : CodeFormatter(org.eclipse.cdt.core.formatter.CodeFormatter) HashMap(java.util.HashMap) TextEdit(org.eclipse.text.edits.TextEdit) CModelException(org.eclipse.cdt.core.model.CModelException) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) ITranslationUnit(org.eclipse.cdt.core.model.ITranslationUnit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 20 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project webtools.sourceediting by eclipse.

the class AutoImportProposal method addImportDeclaration.

/**
 * adds the import declaration to the document in the viewer in the appropriate position
 * @param viewer
 */
private void addImportDeclaration(ITextViewer viewer) {
    IDocument doc = viewer.getDocument();
    // calculate once and pass along
    boolean isXml = isXmlFormat(doc);
    int insertPosition = getInsertPosition(doc, isXml);
    String insertText = createImportDeclaration(doc, isXml);
    InsertEdit insert = new InsertEdit(insertPosition, insertText);
    try {
        insert.apply(doc);
    } catch (MalformedTreeException e) {
        Logger.logException(e);
    } catch (BadLocationException e) {
        Logger.logException(e);
    }
    // make sure the cursor position after is correct
    setCursorPosition(getCursorPosition() + insertText.length());
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)52 BadLocationException (org.eclipse.jface.text.BadLocationException)38 IDocument (org.eclipse.jface.text.IDocument)25 TextEdit (org.eclipse.text.edits.TextEdit)19 CoreException (org.eclipse.core.runtime.CoreException)12 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)11 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)11 Document (org.eclipse.jface.text.Document)11 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)11 Test (org.junit.Test)11 ITextFileBufferManager (org.eclipse.core.filebuffers.ITextFileBufferManager)10 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)10 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)9 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)9 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)8 InsertEdit (org.eclipse.text.edits.InsertEdit)8 IPath (org.eclipse.core.runtime.IPath)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)7 ArrayList (java.util.ArrayList)6