Example usage for org.eclipse.jdt.core IBuffer getCharacters

List of usage examples for org.eclipse.jdt.core IBuffer getCharacters

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IBuffer getCharacters.

Prototype

public char[] getCharacters();

Source Link

Document

Returns the contents of this buffer as a character array, or null if the buffer has not been initialized.

Usage

From source file:com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Try to find the selected Java element in the compilation unit.
 *
 * If selection matches a string literal, capture it, otherwise add a fatal error
 * to the status.//w w w  .  j  a  v  a 2 s .co m
 *
 * On success, advance the monitor by 3.
 * Returns status.isOK().
 */
private boolean findSelectionInJavaUnit(ICompilationUnit unit, RefactoringStatus status,
        IProgressMonitor monitor) {
    try {
        IBuffer buffer = unit.getBuffer();

        IScanner scanner = ToolFactory.createScanner(false, //tokenizeComments
                false, //tokenizeWhiteSpace
                false, //assertMode
                false //recordLineSeparator
        );
        scanner.setSource(buffer.getCharacters());
        monitor.worked(1);

        for (int token = scanner.getNextToken(); token != ITerminalSymbols.TokenNameEOF; token = scanner
                .getNextToken()) {
            if (scanner.getCurrentTokenStartPosition() <= mSelectionStart
                    && scanner.getCurrentTokenEndPosition() >= mSelectionEnd) {
                // found the token, but only keep if the right type
                if (token == ITerminalSymbols.TokenNameStringLiteral) {
                    mTokenString = new String(scanner.getCurrentTokenSource());
                }
                break;
            } else if (scanner.getCurrentTokenStartPosition() > mSelectionEnd) {
                // scanner is past the selection, abort.
                break;
            }
        }
    } catch (JavaModelException e1) {
        // Error in unit.getBuffer. Ignore.
    } catch (InvalidInputException e2) {
        // Error in scanner.getNextToken. Ignore.
    } finally {
        monitor.worked(1);
    }

    if (mTokenString != null) {
        // As a literal string, the token should have surrounding quotes. Remove them.
        // Note: unquoteAttrValue technically removes either " or ' paired quotes, whereas
        // the Java token should only have " quotes. Since we know the type to be a string
        // literal, there should be no confusion here.
        mTokenString = unquoteAttrValue(mTokenString);

        // We need a non-empty string literal
        if (mTokenString.length() == 0) {
            mTokenString = null;
        }
    }

    if (mTokenString == null) {
        status.addFatalError("Please select a Java string literal.");
    }

    monitor.worked(1);
    return status.isOK();
}

From source file:com.android.ide.eclipse.adt.refactorings.extractstring.ExtractStringRefactoring.java

License:Open Source License

/**
 * Try to find the selected Java element in the compilation unit.
 * /*from   w  w  w.j  a  v a 2s.  c  om*/
 * If selection matches a string literal, capture it, otherwise add a fatal error
 * to the status.
 * 
 * On success, advance the monitor by 3.
 */
private boolean findSelectionInJavaUnit(ICompilationUnit unit, RefactoringStatus status,
        IProgressMonitor monitor) {
    try {
        IBuffer buffer = unit.getBuffer();

        IScanner scanner = ToolFactory.createScanner(false, //tokenizeComments
                false, //tokenizeWhiteSpace
                false, //assertMode
                false //recordLineSeparator
        );
        scanner.setSource(buffer.getCharacters());
        monitor.worked(1);

        for (int token = scanner.getNextToken(); token != ITerminalSymbols.TokenNameEOF; token = scanner
                .getNextToken()) {
            if (scanner.getCurrentTokenStartPosition() <= mSelectionStart
                    && scanner.getCurrentTokenEndPosition() >= mSelectionEnd) {
                // found the token, but only keep of the right type
                if (token == ITerminalSymbols.TokenNameStringLiteral) {
                    mTokenString = new String(scanner.getCurrentTokenSource());
                }
                break;
            } else if (scanner.getCurrentTokenStartPosition() > mSelectionEnd) {
                // scanner is past the selection, abort.
                break;
            }
        }
    } catch (JavaModelException e1) {
        // Error in unit.getBuffer. Ignore.
    } catch (InvalidInputException e2) {
        // Error in scanner.getNextToken. Ignore.
    } finally {
        monitor.worked(1);
    }

    if (mTokenString != null) {
        // As a literal string, the token should have surrounding quotes. Remove them.
        int len = mTokenString.length();
        if (len > 0 && mTokenString.charAt(0) == '"' && mTokenString.charAt(len - 1) == '"') {
            mTokenString = mTokenString.substring(1, len - 1);
        }
        // We need a non-empty string literal
        if (mTokenString.length() == 0) {
            mTokenString = null;
        }
    }

    if (mTokenString == null) {
        status.addFatalError("Please select a Java string literal.");
    }

    monitor.worked(1);
    return status.isOK();
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClassFile.java

License:Open Source License

/** Loads the buffer via SourceMapper, and maps it in SourceMapper */
private IBuffer mapSource(SourceMapper mapper, IBinaryType info, IClassFile bufferOwner) {
    char[] contents = mapper.findSource(getType(), info);
    if (contents != null) {
        // create buffer
        IBuffer buffer = BufferManager.createBuffer(bufferOwner);
        if (buffer == null)
            return null;
        BufferManager bufManager = getBufferManager();
        bufManager.addBuffer(buffer);/*from  w  w  w.j ava 2s  .com*/

        // set the buffer source
        if (buffer.getCharacters() == null) {
            buffer.setContents(contents);
        }

        // listen to buffer changes
        buffer.addBufferChangedListener(this);

        // do the source mapping
        mapper.mapSource(getOuterMostEnclosingType(), contents, info);

        return buffer;
    } else {
        // create buffer
        IBuffer buffer = BufferManager.createNullBuffer(bufferOwner);
        if (buffer == null)
            return null;
        BufferManager bufManager = getBufferManager();
        bufManager.addBuffer(buffer);

        // listen to buffer changes
        buffer.addBufferChangedListener(this);
        return buffer;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnit.java

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
 *///  w w  w  .jav  a2s .  c o m
public char[] getContents() {
    IBuffer buffer = getBufferManager().getBuffer(this);
    if (buffer == null) {
        // no need to force opening of CU to get the content
        // also this cannot be a working copy, as its buffer is never closed while the working copy is alive
        File file = resource();
        // Get encoding from file
        String encoding;
        encoding = "UTF-8"; //file.getCharset();
        try {
            return Util.getResourceContentsAsCharArray(file, encoding);
        } catch (JavaModelException e) {
            if (manager.abortOnMissingSource.get() == Boolean.TRUE) {
                IOException ioException = e.getJavaModelStatus()
                        .getCode() == IJavaModelStatusConstants.IO_EXCEPTION ? (IOException) e.getException()
                                : new IOException(e.getMessage());
                throw new AbortCompilationUnit(null, ioException, encoding);
            } else {
                Util.log(e, Messages.bind(Messages.file_notFound, file.getAbsolutePath()));
            }
            return CharOperation.NO_CHAR;
        }
    }
    char[] contents = buffer.getCharacters();
    if (contents == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814
        if (manager.abortOnMissingSource.get() == Boolean.TRUE) {
            IOException ioException = new IOException(Messages.buffer_closed);
            IFile file = (IFile) getResource();
            // Get encoding from file
            String encoding;
            try {
                encoding = file.getCharset();
            } catch (CoreException ce) {
                // do not use any encoding
                encoding = null;
            }
            throw new AbortCompilationUnit(null, ioException, encoding);
        }
        return CharOperation.NO_CHAR;
    }
    return contents;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.CompilationUnit.java

License:Open Source License

/**
 * @see Openable#openBuffer(org.eclipse.core.runtime.IProgressMonitor, Object)
 *//*from  ww  w.  j  av a2 s . c o m*/
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    BufferManager bufManager = getBufferManager();
    boolean isWorkingCopy = isWorkingCopy();
    IBuffer buffer = isWorkingCopy ? this.owner.createBuffer(this) : BufferManager.createBuffer(this);
    if (buffer == null)
        return null;

    ICompilationUnit original = null;
    boolean mustSetToOriginalContent = false;
    if (isWorkingCopy) {
        // ensure that isOpen() is called outside the bufManager synchronized block
        // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=237772
        mustSetToOriginalContent = !isPrimary()
                && (original = new CompilationUnit((PackageFragment) getParent(), manager, getElementName(),
                        DefaultWorkingCopyOwner.PRIMARY)).isOpen();
    }

    // synchronize to ensure that 2 threads are not putting 2 different buffers at the same time
    // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331
    synchronized (bufManager) {
        IBuffer existingBuffer = bufManager.getBuffer(this);
        if (existingBuffer != null)
            return existingBuffer;

        // set the buffer source
        if (buffer.getCharacters() == null) {
            if (isWorkingCopy) {
                if (mustSetToOriginalContent) {
                    buffer.setContents(original.getSource());
                } else {
                    File file = resource();
                    if (file == null || !file.exists()) {
                        // initialize buffer with empty contents
                        buffer.setContents(CharOperation.NO_CHAR);
                    } else {
                        buffer.setContents(Util.getResourceContentsAsCharArray(file));
                    }
                }
            } else {
                File file = resource();
                if (file == null || !file.exists())
                    throw newNotPresentException();
                buffer.setContents(Util.getResourceContentsAsCharArray(file));
            }
        }

        // add buffer to buffer cache
        // note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer
        // can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block.
        bufManager.addBuffer(buffer);

        // listen to buffer changes
        buffer.addBufferChangedListener(this);
    }
    return buffer;
}

From source file:com.github.parzonka.ccms.engine.SortElementsOperation.java

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.core.JavaModelOperation#executeOperation()
 *//*  w w  w. ja v a  2  s  .  co m*/
@Override
protected void executeOperation() throws JavaModelException {
    try {
        beginTask(Messages.operation_sortelements, getMainAmountOfWork());
        final CompilationUnit copy = (CompilationUnit) this.elementsToProcess[0];
        final ICompilationUnit unit = copy.getPrimary();
        final IBuffer buffer = copy.getBuffer();
        if (buffer == null) {
            return;
        }
        final char[] bufferContents = buffer.getCharacters();
        final String result = processElement(unit, bufferContents);
        if (!CharOperation.equals(result.toCharArray(), bufferContents)) {
            copy.getBuffer().setContents(result);
        }
        worked(1);
    } finally {
        done();
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java

License:Open Source License

public char[] getContents() {
    try {//  ww w  .  j  a va2s  .  c o m
        IBuffer buffer = getBuffer();
        if (buffer == null)
            return CharOperation.NO_CHAR;
        char[] characters = buffer.getCharacters();
        if (characters == null)
            return CharOperation.NO_CHAR;
        return characters;
    } catch (JavaModelException e) {
        return CharOperation.NO_CHAR;
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java

License:Open Source License

/**
 * @see Openable#openBuffer(IProgressMonitor, Object)
 *///from  w w  w. java2s. co  m
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    IBuffer buffer = this.owner.createBuffer(this);
    if (buffer == null)
        return null;

    // set the buffer source
    if (buffer.getCharacters() == null) {
        IBuffer classFileBuffer = this.classFile.getBuffer();
        if (classFileBuffer != null) {
            buffer.setContents(classFileBuffer.getCharacters());
        } else {
            // Disassemble
            IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile,
                    IClassFileReader.ALL);
            Disassembler disassembler = new Disassembler();
            String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), //$NON-NLS-1$
                    ClassFileBytesDisassembler.WORKING_COPY);
            buffer.setContents(contents);
        }
    }

    // add buffer to buffer cache
    BufferManager bufManager = getBufferManager();

    // GROOVY Change access to private member
    // old
    // bufManager.addBuffer(buffer);
    // new
    if (buffer.getContents() != null) {
        ReflectionUtils.executePrivateMethod(BufferManager.class, "addBuffer", new Class<?>[] { IBuffer.class }, //$NON-NLS-1$
                bufManager, new Object[] { buffer });
    }
    // GROOVY End

    // listen to buffer changes
    buffer.addBufferChangedListener(this);

    return buffer;
}

From source file:org.eclipse.ajdt.core.javaelements.AJCompilationUnit.java

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
 *///w  w  w  .ja  va  2  s .c om
public char[] getContents() {
    try {
        IBuffer buffer = this.getBuffer();
        return buffer == null ? CharOperation.NO_CHAR : buffer.getCharacters();
    } catch (JavaModelException e) {
        AspectJPlugin.getDefault().getLog().log(e.getStatus());
        return CharOperation.NO_CHAR;
    }
}

From source file:org.eclipse.ajdt.internal.ui.editor.CompilationUnitAnnotationModelWrapper.java

License:Open Source License

public void beginReporting() {
    if (delegate != null) {
        ((IProblemRequestor) delegate).beginReporting();

        IJavaProject project = unit.getJavaProject();

        AJCompilationUnitStructureRequestor requestor = new AJCompilationUnitStructureRequestor(unit,
                new AJCompilationUnitInfo(), new HashMap());
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = ((CompilationUnit) unit)
                .getPerWorkingCopyInfo();
        boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null
                && perWorkingCopyInfo.isActive();
        IProblemFactory problemFactory = new DefaultProblemFactory();
        Map options = project.getOptions(true);
        IBuffer buffer;
        try {/* www .ja v a  2s  .c  om*/
            buffer = unit.getBuffer();

            final char[] contents = buffer == null ? null : buffer.getCharacters();

            AJSourceElementParser parser = new AJSourceElementParser(requestor, problemFactory,
                    new CompilerOptions(options), true/*report local declarations*/, false);
            parser.reportOnlyOneSyntaxError = !computeProblems;

            parser.scanner.source = contents;
            requestor.setParser(parser);

            CompilationUnitDeclaration unitDec = parser.parseCompilationUnit(
                    new org.aspectj.org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
                        public char[] getContents() {
                            return contents;
                        }

                        public char[] getMainTypeName() {
                            return ((CompilationUnit) unit).getMainTypeName();
                        }

                        public char[][] getPackageName() {
                            return ((CompilationUnit) unit).getPackageName();
                        }

                        public char[] getFileName() {
                            return ((CompilationUnit) unit).getFileName();
                        }

                        public boolean ignoreOptionalProblems() {
                            return false;
                        }
                    }, true /*full parse to find local elements*/);
            org.aspectj.org.eclipse.jdt.core.compiler.IProblem[] problems = unitDec.compilationResult.problems;
            if (problems != null) {
                for (int i = 0; i < problems.length; i++) {
                    org.aspectj.org.eclipse.jdt.core.compiler.IProblem problem = problems[i];
                    if (problem == null)
                        continue;
                    ((IProblemRequestor) delegate)
                            .acceptProblem(
                                    new DefaultProblem(problem.getOriginatingFileName(), problem.getMessage(),
                                            problem.getID(), problem.getArguments(),
                                            problem.isError() ? ProblemSeverities.Error
                                                    : ProblemSeverities.Warning,
                                            problem.getSourceStart(), problem.getSourceEnd(),
                                            problem.getSourceLineNumber(), 0)); // unknown column
                }
            }
        } catch (JavaModelException e) {
        }
    }
}