List of usage examples for org.eclipse.jdt.core IBuffer getCharacters
public char[] getCharacters();
null
if the buffer has not been initialized. From source file:org.eclipse.jdt.internal.core.CompilationUnit.java
License:Open Source License
/** * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents() *///from w w w. j a v 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 IFile file = (IFile) getResource(); // Get encoding from file String encoding; try { encoding = file.getCharset(); } catch (CoreException ce) { // do not use any encoding encoding = null; } try { return Util.getResourceContentsAsCharArray(file, encoding); } catch (JavaModelException e) { if (JavaModelManager.getJavaModelManager().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.getFullPath().toString())); } return CharOperation.NO_CHAR; } } char[] contents = buffer.getCharacters(); if (contents == null) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814 if (JavaModelManager.getJavaModelManager().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:org.eclipse.jdt.internal.core.CompilationUnit.java
License:Open Source License
/** * @see Openable#openBuffer(IProgressMonitor, Object) *///from ww w .jav a2 s . c om 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 // GROOVY start /* old { mustSetToOriginalContent = !isPrimary() && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen() ; } new */ mustSetToOriginalContent = !isPrimary() && (original = LanguageSupportFactory.newCompilationUnit((PackageFragment) getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen(); // GROOVY end } // 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 { IFile file = (IFile) getResource(); if (file == null || !file.exists()) { // initialize buffer with empty contents buffer.setContents(CharOperation.NO_CHAR); } else { buffer.setContents(Util.getResourceContentsAsCharArray(file)); } } } else { IFile file = (IFile) getResource(); 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:org.eclipse.jem.internal.adapters.jdom.JDOMAdaptor.java
License:Open Source License
/** * Scan for CRs and LFs within a character buffer * Creation date: (8/17/2001 2:14:13 PM) * @return int LineNo at charOffset/*from ww w . j a va2 s. com*/ * @param charOffset int * @param buffer org.eclipse.jdt.core.IBuffer */ private void computeLineOffset(int charOffset, IBuffer buffer) { fResolvedColNo = fResolvedLineNo = INVALID_LINENO; if (buffer == null) return; char[] charBuff = buffer.getCharacters(); if (charBuff == null) return; int LineCount = 0; int ColNo = 0; for (int i = 0; i <= charOffset; i++) { ColNo++; if (charBuff[i] == '\r') { LineCount++; ColNo = 0; if (charBuff[i + 1] == '\n') i++; // skip LineFeed followed a CR } else if (charBuff[i] == '\n') { LineCount++; ColNo = 0; } } fResolvedColNo = ColNo; fResolvedLineNo = LineCount; }
From source file:org.eclipse.reddeer.eclipse.ui.wizards.NewRedDeerTestWizardPageOne.java
License:Open Source License
private void addAnnotation(IType type) throws JavaModelException { ISourceRange range = type.getSourceRange(); IBuffer buf = type.getCompilationUnit().getBuffer(); char[] source = buf.getCharacters(); IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_8); scanner.setSource(source);// w ww.j a va 2s. c o m int offset = range.getOffset(); try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNamepublic) { offset = scanner.getCurrentTokenStartPosition(); break; } token = scanner.getNextToken(); } } catch (InvalidInputException e) { Activator.log(e); } StringBuffer sb = new StringBuffer(); sb.append("@RunWith(RedDeerSuite.class)").append(getPackageFragment().findRecommendedLineSeparator()); buf.replace(offset, 0, sb.toString()); }
From source file:org.eclipse.wb.internal.core.utils.jdt.core.JavadocContentAccess.java
License:Open Source License
/** * @return the {@link Reader} for an {@link IMember}'s Javadoc comment content from the source * attachment./*from w w w . j av a 2 s . co m*/ */ public static Reader getContentReader(IMember member, boolean allowInherited) throws Exception { // check current type { IBuffer buffer = member.isBinary() ? member.getClassFile().getBuffer() : member.getCompilationUnit().getBuffer(); // no source attachment found if (buffer == null) { return null; } // ISourceRange range = member.getSourceRange(); int start = range.getOffset(); int length = range.getLength(); if (length > 0 && buffer.getChar(start) == '/') { // prepare scanner IScanner scanner; { scanner = ToolFactory.createScanner(true, false, false, false); scanner.setSource(buffer.getCharacters()); scanner.resetTo(start, start + length - 1); } // find last JavaDoc comment { int docOffset = -1; int docEnd = -1; { int terminal = scanner.getNextToken(); while (org.eclipse.jdt.internal.corext.dom.TokenScanner.isComment(terminal)) { if (terminal == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) { docOffset = scanner.getCurrentTokenStartPosition(); docEnd = scanner.getCurrentTokenEndPosition() + 1; } terminal = scanner.getNextToken(); } } // if comment found, return it if (docOffset != -1) { return new JavaDocCommentReader(buffer, docOffset, docEnd); } } } } // check inherited if (allowInherited && member.getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) member; IMethod superMethod = CodeUtils.findSuperMethod(method); if (superMethod != null) { return getContentReader(superMethod, allowInherited); } } // not found return null; }
From source file:org.j2eespider.util.AnnotationUtil.java
License:Open Source License
/** * Return an array of annotations found in method *///w w w . ja v a2 s. c om public static String[] getAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations) { String[] annotationsInMethod = new String[annotations.size()]; try { IBuffer buffer = imethod.getOpenable().getBuffer(); ISourceRange sourceRange = imethod.getSourceRange(); ISourceRange nameRange = imethod.getNameRange(); IScanner scanner = null; // delay initialization if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); } else { return annotationsInMethod; } int i = 0; for (ValidatorType annotationType : annotations) { if (findAnnotation(scanner, annotationType.getClassName()) || findAnnotation(scanner, annotationType.getImplementationClass())) { annotationsInMethod[i] = annotationType.getClassName(); i++; } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return annotationsInMethod; }
From source file:org.j2eespider.util.AnnotationUtil.java
License:Open Source License
/** * Replace annotations in method.// www. jav a 2 s . c om */ public static void replaceAnnotationsInMethod(IMethod imethod, List<ValidatorType> annotations, String textNewAnnotations) { try { //monta o scanner do metodo IBuffer methodBuffer = imethod.getOpenable().getBuffer(); ISourceRange sourceRange = imethod.getSourceRange(); ISourceRange javadocRange = null;//imethod.getJavadocRange(); ISourceRange nameRange = imethod.getNameRange(); IScanner scanner = null; // delay initialization if (sourceRange != null && nameRange != null) { if (scanner == null) { scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(methodBuffer.getCharacters()); } scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); } //apaga todas as annotations que esto em annotationsType e adiciona textNewAnnotations StringBuffer sourceMethod = new StringBuffer(); int tok = scanner.getNextToken(); while (tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //loop nas annotations if (tok == ITerminalSymbols.TokenNameAT) { //encontrou o inicio de uma annotation StringBuffer thisAnnotation = new StringBuffer("@"); tok = scanner.getNextToken(); //trabalha todo o contedo da annotation while (tok != ITerminalSymbols.TokenNameAT && tok != ITerminalSymbols.TokenNameprivate && tok != ITerminalSymbols.TokenNameprotected && tok != ITerminalSymbols.TokenNamepublic) { //pega todo o conteudo desta annotation thisAnnotation.append(scanner.getCurrentTokenSource()); //pega o nome dessa annotation tok = scanner.getNextToken(); } //verifica se para apagar essa annotation (s joga no novo sourceMethod se ela no tiver na lista que para apagar) if (!ValidatorUtil.containsValidator(annotations, thisAnnotation.toString())) { sourceMethod.append(thisAnnotation); } } } //grava o resto do metodo int posStartMethod = scanner.getCurrentTokenStartPosition(); int lengthRemoved = posStartMethod - sourceRange.getOffset(); //conta quantos caracteres foram removidos desse metodo (as annotations) String codeRemain = String.valueOf(scanner.getSource()).substring(posStartMethod, posStartMethod + sourceRange.getLength() - lengthRemoved); if (!sourceMethod.toString().equals("") && sourceMethod.toString().lastIndexOf("\n") != sourceMethod.toString().length() - 1) { //se j tem alguma annotation, ve se precisa de quebra de linha sourceMethod.append("\n\t"); } sourceMethod.append(textNewAnnotations); //adiciona as novas annotations antes do resto do mtodo sourceMethod.append(codeRemain); if (javadocRange != null) { //se tiver javadoc, no altera ele... methodBuffer.replace(sourceRange.getOffset() + javadocRange.getLength(), sourceRange.getLength() - javadocRange.getLength(), "\t" + sourceMethod.toString()); //altera o cdigo do mtodo } else { methodBuffer.replace(sourceRange.getOffset(), sourceRange.getLength(), sourceMethod.toString()); //altera o cdigo do mtodo } imethod.getOpenable().save(null, true); } catch (JavaModelException e) { } catch (InvalidInputException e) { } }
From source file:org.jboss.reddeer.eclipse.ui.wizards.NewRedDeerTestWizardPageOne.java
License:Open Source License
private void addAnnotation(IType type) throws JavaModelException { ISourceRange range = type.getSourceRange(); IBuffer buf = type.getCompilationUnit().getBuffer(); char[] source = buf.getCharacters(); IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_5); scanner.setSource(source);//from ww w. jav a 2s.c o m int offset = range.getOffset(); try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNamepublic) { offset = scanner.getCurrentTokenStartPosition(); break; } token = scanner.getNextToken(); } } catch (InvalidInputException e) { Activator.log(e); } StringBuffer sb = new StringBuffer(); sb.append("@RunWith(RedDeerSuite.class)").append(getPackageFragment().findRecommendedLineSeparator()); buf.replace(offset, 0, sb.toString()); }
From source file:org.jboss.tools.arquillian.ui.internal.wizards.NewArquillianJUnitTestCasePageOne.java
License:Open Source License
@Override protected void createTypeMembers(IType type, ImportsManager imports, IProgressMonitor monitor) throws CoreException { if (fMethodStubsButtons.isSelected(IDX_DEPLOYMENT)) { String delimiter = getLineDelimiter(); NewArquillianJUnitTestCaseDeploymentPage deploymentPage = (NewArquillianJUnitTestCaseDeploymentPage) getWizard() .getPage(//w ww . j a v a 2 s .c om NewArquillianJUnitTestCaseDeploymentPage.ORG_JBOSS_TOOLS_ARQUILLIAN_UI_DEPLOYMENT_PAGE); ArquillianUIUtil.createDeploymentMethod(null, type, imports, isAddComments(), delimiter, deploymentPage, null, false); } if (fMethodStubsButtons.isSelected(IDX_SETUP_CLASS)) { createSetUpClass(type, imports); } if (fMethodStubsButtons.isSelected(IDX_TEARDOWN_CLASS)) { createTearDownClass(type, imports); } if (fMethodStubsButtons.isSelected(IDX_SETUP)) { createSetUp(type, imports); } if (fMethodStubsButtons.isSelected(IDX_TEARDOWN)) { createTearDown(type, imports); } createTestMethodStubs(type, imports); imports.addStaticImport("org.junit.Assert", "*", false); //$NON-NLS-1$ //$NON-NLS-2$ imports.addImport(ORG_JUNIT_RUNNER_RUNWITH); imports.addImport("org.jboss.arquillian.junit.Arquillian"); ISourceRange range = type.getSourceRange(); IBuffer buf = type.getCompilationUnit().getBuffer(); char[] source = buf.getCharacters(); IScanner scanner = ToolFactory.createScanner(false, false, false, JavaCore.VERSION_1_5); scanner.setSource(source); int offset = range.getOffset(); try { int token = scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (token == ITerminalSymbols.TokenNamepublic) { offset = scanner.getCurrentTokenStartPosition(); break; } token = scanner.getNextToken(); } } catch (InvalidInputException e) { ArquillianUIActivator.log(e); } StringBuffer sb = new StringBuffer(); sb.append("@RunWith(Arquillian.class)").append(getPackageFragment().findRecommendedLineSeparator()); buf.replace(offset, 0, sb.toString()); }
From source file:org.sf.feeling.decompiler.editor.ClassFileSourceMap.java
License:Open Source License
private static void mapSource(JavaDecompilerBufferManager bufferManager, ClassFile cf, SourceMapper mapper, IBinaryType info, IClassFile bufferOwner, char[] markedSrc) { char[] contents = mapper.findSource(cf.getType(), info); if (Arrays.equals(markedSrc, contents)) return;/*w ww . j a va 2s .c o m*/ contents = markedSrc; if (contents != null) { // create buffer IBuffer buffer = BufferManager.createBuffer(bufferOwner); if (buffer == null) return; JavaDecompilerBufferManager bufManager = bufferManager; bufManager.addBuffer(buffer); // set the buffer source if (buffer.getCharacters() == null) { buffer.setContents(contents); } // listen to buffer changes // buffer.addBufferChangedListener( cf ); // do the source mapping mapper.mapSource(getOuterMostEnclosingType(cf), contents, info); return; } else { // create buffer IBuffer buffer = BufferManager.createNullBuffer(bufferOwner); if (buffer == null) return; JavaDecompilerBufferManager bufManager = bufferManager; bufManager.addBuffer(buffer); // listen to buffer changes // buffer.addBufferChangedListener( cf ); return; } }