List of usage examples for org.eclipse.jdt.core IBuffer getText
public String getText(int offset, int length) throws IndexOutOfBoundsException;
From source file:org.eclipse.andmore.internal.build.ConvertSwitchQuickFixProcessor.java
License:Open Source License
@Override public IJavaCompletionProposal[] getCorrections(IInvocationContext context, IProblemLocation[] location) throws CoreException { if (location == null || location.length == 0) { return null; }//from w w w .j a v a 2s. c om ASTNode coveringNode = context.getCoveringNode(); if (coveringNode == null) { return null; } // Look up the fully qualified name of the non-constant expression, if any, and // make sure it's R-something. if (coveringNode.getNodeType() == ASTNode.SIMPLE_NAME) { coveringNode = coveringNode.getParent(); if (coveringNode == null) { return null; } } if (coveringNode.getNodeType() != ASTNode.QUALIFIED_NAME) { return null; } QualifiedName name = (QualifiedName) coveringNode; if (!name.getFullyQualifiedName().startsWith("R.")) { //$NON-NLS-1$ return null; } IProblemLocation error = location[0]; int errorStart = error.getOffset(); int errorLength = error.getLength(); int caret = context.getSelectionOffset(); // Even though the hasCorrections() method above will return false for everything // other than non-constant expression errors, it turns out this getCorrections() // method will ALSO be called on lines where there is no such error. In particular, // if you have an invalid cast expression like this: // Button button = findViewById(R.id.textView); // then this method will be called, and the expression will pass all of the above // checks. However, we -don't- want to show a migrate code suggestion in that case! // Therefore, we'll need to check if we're *actually* on a line with the given // problem. // // Unfortunately, we don't get passed the problemId again, and there's no access // to it. So instead we'll need to look up the markers on the line, and see // if we actually have a constant expression warning. This is not pretty!! boolean foundError = false; ICompilationUnit compilationUnit = context.getCompilationUnit(); IResource file = compilationUnit.getResource(); if (file != null) { IDocumentProvider provider = new TextFileDocumentProvider(); try { provider.connect(file); IDocument document = provider.getDocument(file); if (document != null) { List<IMarker> markers = AdtUtils.findMarkersOnLine(IMarker.PROBLEM, file, document, errorStart); for (IMarker marker : markers) { String message = marker.getAttribute(IMarker.MESSAGE, ""); // There are no other attributes in the marker we can use to identify // the exact error, so we'll need to resort to the actual message // text even though that would not work if the messages had been // localized... This can also break if the error messages change. Yuck. if (message.contains("constant expressions")) { //$NON-NLS-1$ foundError = true; } } } } catch (Exception e) { AndmoreAndroidPlugin.log(e, "Can't validate error message in %1$s", file.getName()); } finally { provider.disconnect(file); } } if (!foundError) { // Not a constant-expression warning, so do nothing return null; } IBuffer buffer = compilationUnit.getBuffer(); boolean sameLine = false; // See if the caret is on the same line as the error if (caret <= errorStart) { // Search backwards to beginning of line for (int i = errorStart; i >= 0; i--) { if (i <= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } else { // Search forwards to the end of the line for (int i = errorStart + errorLength, n = buffer.getLength(); i < n; i++) { if (i >= caret) { sameLine = true; break; } char c = buffer.getChar(i); if (c == '\n') { break; } } } if (sameLine) { String expression = buffer.getText(errorStart, errorLength); return new IJavaCompletionProposal[] { new MigrateProposal(expression) }; } return null; }
From source file:org.eclipse.andmore.internal.refactorings.extractstring.ExtractStringProposal.java
License:Open Source License
@Override public String getAdditionalProposalInfo() { try {/* w w w .j av a2 s . co m*/ ASTNode coveringNode = mContext.getCoveringNode(); int start = coveringNode.getStartPosition(); int length = coveringNode.getLength(); IBuffer buffer = mContext.getCompilationUnit().getBuffer(); StringBuilder sb = new StringBuilder(); String string = buffer.getText(start, length); string = ExtractStringRefactoring.unquoteAttrValue(string); String token = ExtractStringInputPage.guessId(string); // Look up the beginning and the end of the line (outside of the extracted string) // such that we can show a preview of the diff, e.g. if you have // foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello); // so we need to extract "foo.setTitle(" and ");". // Look backwards to the beginning of the line (and strip whitespace) int i = start - 1; while (i > 0) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i--; } String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim(); // Look forwards to the end of the line (and strip whitespace) i = start + length; while (i < buffer.getLength()) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i++; } String lineSuffix = buffer.getText(start + length, i - (start + length)); // Should we show the replacement as just R.string.foo or // context.getString(R.string.foo) ? boolean useContext = false; ASTNode parent = coveringNode.getParent(); if (parent != null) { int type = parent.getNodeType(); if (type == ASTNode.ASSIGNMENT || type == ASTNode.VARIABLE_DECLARATION_STATEMENT || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) { useContext = true; } } // Display .java change: sb.append("...<br>"); //$NON-NLS-1$ sb.append(linePrefix); sb.append("<b>"); //$NON-NLS-1$ if (useContext) { sb.append("context.getString("); //$NON-NLS-1$ } sb.append("R.string."); //$NON-NLS-1$ sb.append(token); if (useContext) { sb.append(")"); //$NON-NLS-1$ } sb.append("</b>"); //$NON-NLS-1$ sb.append(lineSuffix); sb.append("<br>...<br>"); //$NON-NLS-1$ // Display strings.xml change: sb.append("<br>"); //$NON-NLS-1$ sb.append("<resources><br>"); //$NON-NLS-1$ sb.append(" <b><string name=\""); //$NON-NLS-1$ sb.append(token); sb.append("\">"); //$NON-NLS-1$ sb.append(string); sb.append("</string></b><br>"); //$NON-NLS-1$ sb.append("</resources>"); //$NON-NLS-1$ return sb.toString(); } catch (JavaModelException e) { AndmoreAndroidPlugin.log(e, null); } return "Initiates the Extract String refactoring operation"; }
From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java
License:Open Source License
/** * @param type//from w w w . j a va 2s . c o m * @param lineDelimiter * @throws JavaModelException */ private static void format(IType type, String lineDelimiter) throws JavaModelException { ISourceRange range = type.getSourceRange(); ICompilationUnit cu = type.getCompilationUnit(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, 0, lineDelimiter, type.getJavaProject()); formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent); buf.replace(range.getOffset(), range.getLength(), formattedContent); cu.commitWorkingCopy(true, null); }
From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java
License:Open Source License
public void generateTypeMembers(IType type, String argumentType, boolean needsSave, Runnable typeRunner) throws Exception { int indent = 0; IProgressMonitor monitor = new NullProgressMonitor(); Set /* String (import names) */ existingImports; String lineDelimiter = StubUtility.getLineDelimiterUsed(type.getJavaProject()); ICompilationUnit cu = type.getCompilationUnit(); // create a working copy with a new owner cu.becomeWorkingCopy(monitor);//from w w w . j a v a 2 s. com CompilationUnit astRoot = createASTForImports(cu); existingImports = getExistingImports(astRoot); ImportsManager imports = new ImportsManager(astRoot); if (argumentType != null) { imports.addImport(argumentType); } typeRunner.run(); // add imports imports.create(false, monitor); removeUnusedImports(cu, existingImports, false); JavaModelUtil.reconcile(cu); ISourceRange range = type.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, lineDelimiter, type.getJavaProject()); formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (needsSave) { cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } }
From source file:org.eclipse.e4.tools.ui.designer.utils.ASTHelper.java
License:Open Source License
public void createNamedFields(IType type, String fieldType, String fieldName, boolean needSave) throws Exception { if (fieldType == null || fieldName == null) { return;/*from w w w . j a va 2 s . com*/ } IProgressMonitor monitor = new NullProgressMonitor(); Set /* String (import names) */ existingImports; String lineDelimiter = StubUtility.getLineDelimiterUsed(type.getJavaProject()); ICompilationUnit cu = type.getCompilationUnit(); // create a working copy with a new owner cu.becomeWorkingCopy(monitor); CompilationUnit astRoot = createASTForImports(cu); existingImports = getExistingImports(astRoot); ImportsManager imports = new ImportsManager(astRoot); imports.addImport(fieldType); createField(type, fieldType, fieldName); // add imports imports.create(false, monitor); removeUnusedImports(cu, existingImports, false); JavaModelUtil.reconcile(cu); ISourceRange range = type.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, 0, lineDelimiter, type.getJavaProject()); formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (needSave) { cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } }
From source file:org.eclipse.jem.internal.adapters.jdom.JavaFieldJDOMAdaptor.java
License:Open Source License
/** * Return a String for the source starting after the field's name to the end of * the source range. This will be the source after the name which could include comments. *//* w w w . j a va 2s.c o m*/ protected String getFieldInitializerSource() { IOpenable openable = getSourceField().getOpenable(); try { ISourceRange nameRange, sourceRange; int start = -1, length = 0; IBuffer buffer = openable.getBuffer(); if (buffer == null) { return ""; //$NON-NLS-1$ } nameRange = getSourceField().getNameRange(); start = nameRange.getOffset() + nameRange.getLength(); if (start != -1) { sourceRange = getSourceField().getSourceRange(); if (sourceRange.getOffset() != -1) length = sourceRange.getOffset() + sourceRange.getLength() - start; return buffer.getText(start, length); } return null; } catch (JavaModelException e) { return ""; //$NON-NLS-1$ } }
From source file:org.eclipse.objectteams.otdt.internal.core.MethodMapping.java
License:Open Source License
/** * @see ISourceReference//from w w w . j a v a 2 s .c om */ public String getSource() throws JavaModelException { IOpenable openable = getOpenableParent(); IBuffer buffer = openable.getBuffer(); if (buffer == null) { return null; } ISourceRange range = getSourceRange(); int offset = range.getOffset(); int length = range.getLength(); if (offset == -1 || length == 0) { return null; } try { return buffer.getText(offset, length); } catch (RuntimeException ex) { return null; } }
From source file:org.eclipse.objectteams.otdt.internal.core.MethodMapping.java
License:Open Source License
public ISourceRange getJavadocRange() throws JavaModelException { ISourceRange range = this.getSourceRange(); if (range == null) return null; IBuffer buf = null; if (this.isBinary()) { buf = this.getClassFile().getBuffer(); } else {/*w ww.j ava 2 s . co m*/ ICompilationUnit compilationUnit = this.getCompilationUnit(); if (!compilationUnit.isConsistent()) { return null; } buf = compilationUnit.getBuffer(); } final int start = range.getOffset(); final int length = range.getLength(); if (length > 0 && buf.getChar(start) == '/') { IScanner scanner = ToolFactory.createScanner(true, false, false, false); scanner.setSource(buf.getText(start, length).toCharArray()); try { int docOffset = -1; int docEnd = -1; int terminal = scanner.getNextToken(); loop: while (true) { switch (terminal) { case ITerminalSymbols.TokenNameCOMMENT_JAVADOC: docOffset = scanner.getCurrentTokenStartPosition(); docEnd = scanner.getCurrentTokenEndPosition() + 1; terminal = scanner.getNextToken(); break; case ITerminalSymbols.TokenNameCOMMENT_LINE: case ITerminalSymbols.TokenNameCOMMENT_BLOCK: terminal = scanner.getNextToken(); continue loop; default: break loop; } } if (docOffset != -1) { return new SourceRange(docOffset + start, docEnd - docOffset + 1); } } catch (InvalidInputException ex) { // try if there is inherited Javadoc } } return null; }
From source file:org.eclipse.objectteams.otdt.internal.ui.wizards.typecreation.TypeCreator.java
License:Open Source License
public IType createType(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); }//w ww . j av a 2 s . c o m monitor.beginTask(NewWizardMessages.NewTypeWizardPage_operationdesc, 10); List<ICompilationUnit> createdWorkingCopies = new ArrayList<ICompilationUnit>(); try { validateTypeCreation(); IPackageFragment pack = getPackageFragment(); monitor.worked(1); IType createdType; ImportsManager imports; int indent = 0; String lineDelimiter = null; boolean needsSave = false; // first try to setup the CU of the enclosing team: IType enclosingType = getEnclosingType(); ICompilationUnit teamCU = null; CompilationUnit teamAST = null; Set<String> existingImports = null; CompilationUnit newAST = null; if (enclosingType != null) { // if we have an enclosing type, we may indeed not to write to it (RoFi may add imports to enclosing team) teamCU = enclosingType.getCompilationUnit(); needsSave = !teamCU.isWorkingCopy(); teamCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now for sure (primary) a working copy createdWorkingCopies.add(teamCU); teamAST = createASTForImports(teamCU); } else { // sanity check (suppose we are creating a top-level team since enclosingType is null) if (_typeInfo.isInlineType()) throw new CoreException(new Status(IStatus.ERROR, OTDTUIPlugin.UIPLUGIN_ID, "missing enclosing type for inline type")); //$NON-NLS-1$ } if (!_typeInfo.isInlineType()) { // Need one more CU: either team or RoFi: lineDelimiter = StubUtility.getLineDelimiterUsed(pack.getJavaProject()); ICompilationUnit newCU = pack.createCompilationUnit(_typeInfo.getTypeName() + ".java", "", false, //$NON-NLS-1$//$NON-NLS-2$ new SubProgressMonitor(monitor, 2)); // create a working copy with a new owner needsSave = true; newCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); // cu is now a (primary) working copy createdWorkingCopies.add(newCU); IBuffer buffer = newCU.getBuffer(); String cuContent = constructCUContent(newCU, constructSimpleTypeStub(), lineDelimiter); buffer.setContents(cuContent); newAST = createASTForImports(newCU); existingImports = getExistingImports(newAST); imports = (teamAST != null) ? new ImportsManager(newAST, teamAST) : new ImportsManager(newAST); // add an import that will be removed again. Having this import solves 14661 imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), _typeInfo.getTypeName())); String typeContent = constructTypeStub(newCU, imports, lineDelimiter); AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) newAST.types().get(0); int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition(); int end = typeNode.getStartPosition() + typeNode.getLength(); buffer.replace(start, end - start, typeContent); createdType = newCU.getType(_typeInfo.getTypeName()); } else { imports = new ImportsManager(teamAST); existingImports = getExistingImports(teamAST); // add imports that will be removed again. Having the imports solves 14661 IType[] topLevelTypes = teamCU.getTypes(); for (int i = 0; i < topLevelTypes.length; i++) { imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); } lineDelimiter = StubUtility.getLineDelimiterUsed(enclosingType); StringBuffer content = new StringBuffer(); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { String comment = getTypeComment(teamCU, lineDelimiter); if (comment != null) { content.append(comment); content.append(lineDelimiter); } } content.append(constructTypeStub(teamCU, imports, lineDelimiter)); IJavaElement[] elems = enclosingType.getChildren(); IJavaElement sibling = elems.length > 0 ? elems[0] : null; // try // { createdType = enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 2)); // } // catch (Exception ex) // { // OTDTUIPlugin.getExceptionHandler().logException(ex); // } indent = StubUtility.getIndentUsed(enclosingType) + 1; } if (monitor.isCanceled()) { throw new InterruptedException(); } // add imports for superclass/interfaces, so types can be resolved correctly ICompilationUnit cu = createdType.getCompilationUnit(); imports.create(false, new SubProgressMonitor(monitor, 1)); JavaModelUtil.reconcile(cu); // save the team of a rofi if needed: if (imports.fHasAddedBaseImportsForRofi) { teamCU.commitWorkingCopy(true, monitor); teamCU.save(monitor, true); } if (monitor.isCanceled()) { throw new InterruptedException(); } // ---- create methods: ----- // set up again CompilationUnit astRoot = createASTForImports(imports.getCompilationUnit()); imports = new ImportsManager(astRoot); createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1)); // add imports imports.create(false, new SubProgressMonitor(monitor, 1)); removeUnusedImports(cu, existingImports, false); JavaModelUtil.reconcile(cu); ISourceRange range = createdType.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, lineDelimiter, pack.getJavaProject()); formattedContent = Strings.trimLeadingTabsAndSpaces(formattedContent); buf.replace(range.getOffset(), range.getLength(), formattedContent); // ----- file comment for role files: ----- if (!_typeInfo.isInlineType()) { String fileComment = getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } } if (needsSave) { cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } setCreatedType(createdType); } finally { for (ICompilationUnit wc : createdWorkingCopies) wc.discardWorkingCopy(); monitor.done(); } return _createdType; }
From source file:org.eclipseguru.gwt.core.internal.codegen.AsyncServiceCodeGenerator.java
License:Open Source License
@Override protected void createTypeMembers(final IType createdType, final ImportsManager imports, final IProgressMonitor monitor) throws CoreException { monitor.beginTask(NLS.bind("Generating methods in ''{0}''...", createdType.getElementName()), 10); try {//from w w w . j ava2 s. c om // add all existing imports writeImports(imports); // add all public methods final IMethod[] methods = getMethods(); for (final IMethod method : methods) { // skip constructors and binary, static, private or protected methods if (method.isConstructor() || method.isBinary() || Flags.isStatic(method.getFlags()) || Flags.isPrivate(method.getFlags()) || Flags.isProtected(method.getFlags())) { continue; } final StringBuffer methodContent = new StringBuffer(); // javadoc final ISourceRange javadocRange = method.getJavadocRange(); if (null != javadocRange) { final IBuffer buffer = method.getOpenable().getBuffer(); if (buffer != null) { methodContent.append(buffer.getText(javadocRange.getOffset(), javadocRange.getLength())); } } // Java 1.5 features final boolean is50OrHigher = JavaModelUtil.is50OrHigher(createdType.getJavaProject()); // disabled because GWT compiler complains about missing type javax.annotation.Generated // // @Generated annotation // if (is50OrHigher) { // methodContent.append('@'); // methodContent.append(imports.addImport(GENERATED)); // methodContent.append('('); // methodContent.append("value={").append('"').append(GENERATOR).append('"').append('}'); // methodContent.append(','); // methodContent.append("date=").append('"').append(DATE_FORMAT_ISO8601.format(new Date())).append('"'); // methodContent.append(','); // methodContent.append("comments=").append('"').append("from ").append(remoteServiceType.getFullyQualifiedName('.')).append('[').append(Signature.toString(method.getSignature(), method.getElementName(), method.getParameterNames(), true, true)).append(']').append('"'); // methodContent.append(')'); // methodContent.append(' '); // } // generics declaration if (is50OrHigher && (method.getTypeParameters().length > 0)) { appendMethodTypeParameters(method, methodContent); methodContent.append(' '); } // methos declaration methodContent.append(Signature.toString(Signature.SIG_VOID)); methodContent.append(' '); methodContent.append(method.getElementName()); // parameters methodContent.append('('); if (method.getParameterTypes().length > 0) { appendMethodParameters(method, methodContent); methodContent.append(", "); } appendAsyncCallbackParameter(method, imports, methodContent, is50OrHigher); methodContent.append(')'); // method is abstract and without exceptions methodContent.append(';'); // create the method createdType.createMethod(methodContent.toString(), null, false, null); } // update Javadoc updateJavadoc(createdType, ProgressUtil.subProgressMonitor(monitor, 1)); } finally { monitor.done(); } }