Search in sources :

Example 21 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class SourceProvider method replaceParameterWithExpression.

private void replaceParameterWithExpression(ASTRewrite rewriter, CallContext context, ImportRewrite importRewrite) throws CoreException {
    Expression[] arguments = context.arguments;
    try {
        ITextFileBuffer buffer = RefactoringFileBuffers.acquire(context.compilationUnit);
        for (int i = 0; i < arguments.length; i++) {
            Expression expression = arguments[i];
            String expressionString = null;
            if (expression instanceof SimpleName) {
                expressionString = ((SimpleName) expression).getIdentifier();
            } else {
                try {
                    expressionString = buffer.getDocument().get(expression.getStartPosition(), expression.getLength());
                } catch (BadLocationException exception) {
                    JavaPlugin.log(exception);
                    continue;
                }
            }
            ParameterData parameter = getParameterData(i);
            List<SimpleName> references = parameter.references();
            for (Iterator<SimpleName> iter = references.iterator(); iter.hasNext(); ) {
                ASTNode element = iter.next();
                Expression newExpression = (Expression) rewriter.createStringPlaceholder(expressionString, expression.getNodeType());
                AST ast = rewriter.getAST();
                ITypeBinding explicitCast = ASTNodes.getExplicitCast(expression, (Expression) element);
                if (explicitCast != null) {
                    CastExpression cast = ast.newCastExpression();
                    if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
                        newExpression = createParenthesizedExpression(newExpression, ast);
                    }
                    cast.setExpression(newExpression);
                    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(expression, importRewrite);
                    cast.setType(importRewrite.addImport(explicitCast, ast, importRewriteContext));
                    expression = newExpression = cast;
                }
                if (NecessaryParenthesesChecker.needsParentheses(expression, element.getParent(), element.getLocationInParent())) {
                    newExpression = createParenthesizedExpression(newExpression, ast);
                }
                rewriter.replace(element, newExpression, null);
            }
        }
    } finally {
        RefactoringFileBuffers.release(context.compilationUnit);
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) CastExpression(org.eclipse.jdt.core.dom.CastExpression) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 22 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class DelegateCreator method createEdit.

/**
	 * Performs the actual rewriting and adds an edit to the ASTRewrite set with
	 * {@link #setSourceRewrite(CompilationUnitRewrite)}.
	 *
	 * @throws JavaModelException
	 */
public void createEdit() throws JavaModelException {
    try {
        IDocument document = new Document(fDelegateRewrite.getCu().getBuffer().getContents());
        TextEdit edit = fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
        edit.apply(document, TextEdit.UPDATE_REGIONS);
        String newSource = Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()), fPreferences.tabWidth, fPreferences.indentWidth, false);
        ASTNode placeholder = fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());
        CategorizedTextEditGroup groupDescription = fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
        ListRewrite bodyDeclarationsListRewrite = fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
        if (fCopy)
            if (fInsertBefore)
                bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
            else
                bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
        else
            bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
    } catch (BadLocationException e) {
        JavaPlugin.log(e);
    }
}
Also used : TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) CategorizedTextEditGroup(org.eclipse.ltk.core.refactoring.CategorizedTextEditGroup)

Example 23 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class SourceProvider method getCodeBlocks.

public String[] getCodeBlocks(CallContext context, ImportRewrite importRewrite) throws CoreException {
    final ASTRewrite rewriter = ASTRewrite.create(fDeclaration.getAST());
    replaceParameterWithExpression(rewriter, context, importRewrite);
    updateImplicitReceivers(rewriter, context);
    makeNamesUnique(rewriter, context.scope);
    updateTypeReferences(rewriter, context);
    updateStaticReferences(rewriter, context);
    updateTypeVariables(rewriter, context);
    updateMethodTypeVariable(rewriter, context);
    List<IRegion> ranges = null;
    if (hasReturnValue()) {
        if (context.callMode == ASTNode.RETURN_STATEMENT) {
            ranges = getStatementRanges();
        } else {
            ranges = getExpressionRanges();
        }
    } else {
        ASTNode last = getLastStatement();
        if (last != null && last.getNodeType() == ASTNode.RETURN_STATEMENT) {
            ranges = getReturnStatementRanges();
        } else {
            ranges = getStatementRanges();
        }
    }
    final TextEdit dummy = rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
    int size = ranges.size();
    RangeMarker[] markers = new RangeMarker[size];
    for (int i = 0; i < markers.length; i++) {
        IRegion range = ranges.get(i);
        markers[i] = new RangeMarker(range.getOffset(), range.getLength());
    }
    int split;
    if (size <= 1) {
        split = Integer.MAX_VALUE;
    } else {
        IRegion region = ranges.get(0);
        split = region.getOffset() + region.getLength();
    }
    TextEdit[] edits = dummy.removeChildren();
    for (int i = 0; i < edits.length; i++) {
        TextEdit edit = edits[i];
        int pos = edit.getOffset() >= split ? 1 : 0;
        markers[pos].addChild(edit);
    }
    MultiTextEdit root = new MultiTextEdit(0, fDocument.getLength());
    root.addChildren(markers);
    try {
        TextEditProcessor processor = new TextEditProcessor(fDocument, root, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS);
        UndoEdit undo = processor.performEdits();
        String[] result = getBlocks(markers);
        // It is faster to undo the changes than coping the buffer over and over again.
        processor = new TextEditProcessor(fDocument, undo, TextEdit.UPDATE_REGIONS);
        processor.performEdits();
        return result;
    } catch (MalformedTreeException exception) {
        JavaPlugin.log(exception);
    } catch (BadLocationException exception) {
        JavaPlugin.log(exception);
    }
    return new String[] {};
}
Also used : TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) RangeMarker(org.eclipse.text.edits.RangeMarker) IRegion(org.eclipse.jface.text.IRegion) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) UndoEdit(org.eclipse.text.edits.UndoEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 24 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class CodeAssist method createOrganizeImportOperation.

private OrganizeImportResult createOrganizeImportOperation(ICompilationUnit compilationUnit, List<String> chosen) throws CoreException {
    CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(compilationUnit.getJavaProject());
    OrganizeImportsOperation operation = new OrganizeImportsOperation(compilationUnit, null, settings.importIgnoreLowercase, !compilationUnit.isWorkingCopy(), true, chosen, null);
    NullProgressMonitor monitor = new NullProgressMonitor();
    TextEdit edit = operation.createTextEdit(monitor);
    OrganizeImportResult result = DtoFactory.newDto(OrganizeImportResult.class);
    TypeNameMatch[][] choices = operation.getChoices();
    //or all conflicts were resolved (!chosen.isEmpty())
    if ((chosen != null && !chosen.isEmpty()) || choices == null || choices.length == 0) {
        IBuffer buffer = compilationUnit.getBuffer();
        IDocument document = new Document(buffer.getContents());
        DocumentChangeListener documentChangeListener = new DocumentChangeListener(document);
        try {
            edit.apply(document);
        } catch (BadLocationException e) {
            LOG.debug("Applying Organize import text edits goes wrong:", e);
        }
        result.setChanges(documentChangeListener.getChanges());
        return result;
    }
    result.setConflicts(createListOfDTOMatches(choices));
    return result;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OrganizeImportsOperation(org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) OrganizeImportResult(org.eclipse.che.ide.ext.java.shared.dto.OrganizeImportResult) TextEdit(org.eclipse.text.edits.TextEdit) DocumentChangeListener(org.eclipse.jdt.internal.corext.format.DocumentChangeListener) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IBuffer(org.eclipse.jdt.core.IBuffer) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 25 with BadLocationException

use of org.eclipse.jface.text.BadLocationException in project che by eclipse.

the class MavenServerService method createProblem.

private Problem createProblem(VirtualFileEntry entry, SAXParseException spe) {
    Problem problem = DtoFactory.newDto(Problem.class);
    problem.setError(true);
    problem.setMessage(spe.getMessage());
    if (entry != null) {
        int lineNumber = spe.getLineNumber();
        int columnNumber = spe.getColumnNumber();
        try {
            String content = entry.getVirtualFile().getContentAsString();
            Document document = new Document(content);
            int lineOffset = document.getLineOffset(lineNumber - 1);
            problem.setSourceStart(lineOffset + columnNumber - 1);
            problem.setSourceEnd(lineOffset + columnNumber);
        } catch (ForbiddenException | ServerException | BadLocationException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    return problem;
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ServerException(org.eclipse.che.api.core.ServerException) MavenProjectProblem(org.eclipse.che.maven.data.MavenProjectProblem) Problem(org.eclipse.che.ide.ext.java.shared.dto.Problem) Document(org.eclipse.jface.text.Document) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

BadLocationException (org.eclipse.jface.text.BadLocationException)133 IDocument (org.eclipse.jface.text.IDocument)58 IRegion (org.eclipse.jface.text.IRegion)43 Document (org.eclipse.jface.text.Document)26 Point (org.eclipse.swt.graphics.Point)17 CoreException (org.eclipse.core.runtime.CoreException)16 Position (org.eclipse.jface.text.Position)13 StyledString (org.eclipse.jface.viewers.StyledString)13 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)13 TemplateBuffer (org.eclipse.jface.text.templates.TemplateBuffer)12 TemplateException (org.eclipse.jface.text.templates.TemplateException)12 TextEdit (org.eclipse.text.edits.TextEdit)12 UndoEdit (org.eclipse.text.edits.UndoEdit)10 Region (org.eclipse.jface.text.Region)9 ASTNode (org.eclipse.jdt.core.dom.ASTNode)8 ArrayList (java.util.ArrayList)7 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)7 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)6 BadPositionCategoryException (org.eclipse.jface.text.BadPositionCategoryException)6 DefaultLineTracker (org.eclipse.jface.text.DefaultLineTracker)6