private String getContents(IClassFile cf) { String source = null; if (cf != null) { try { IBuffer buffer = cf.getBuffer(); if (buffer != null) { source = buffer.getContents(); } } catch (JavaModelException e) { logger.log(Level.SEVERE, String.format("Failed to parse the source contents of the class file: %s", e.toString()), e); } if (source == null) { source = ""; } } return source; }
/** * Creates a range for the given offset and length for an {@link IOpenable} * * @param openable * @param offset * @param length * @return * @throws JavaModelException */ public static Range toRange(IOpenable openable, int offset, int length) throws JavaModelException{ Range range = newRange(); if (offset > 0 || length > 0) { int[] loc = null; int[] endLoc = null; IBuffer buffer = openable.getBuffer(); if (buffer != null) { loc = JsonRpcHelpers.toLine(buffer, offset); endLoc = JsonRpcHelpers.toLine(buffer, offset + length); } if (loc == null) { loc = new int[2]; } if (endLoc == null) { endLoc = new int[2]; } setPosition(range.getStart(), loc); setPosition(range.getEnd(), endLoc); } return range; }
/** * Returns the source of the given node from the location where it was parsed. * @param node the node to get the source from * @param extendedRange if set, the extended ranges of the nodes should ne used * @param removeIndent if set, the indentation is removed. * @return return the source for the given node or null if accessing the source failed. */ public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) { ASTNode root= node.getRoot(); if (root instanceof CompilationUnit) { CompilationUnit astRoot= (CompilationUnit) root; ITypeRoot typeRoot= astRoot.getTypeRoot(); try { if (typeRoot != null && typeRoot.getBuffer() != null) { IBuffer buffer= typeRoot.getBuffer(); int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); String str= buffer.getText(offset, length); if (removeIndent) { IJavaProject project= typeRoot.getJavaProject(); int indent= getIndentUsed(buffer, node.getStartPosition(), project); str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator()); } return str; } } catch (JavaModelException e) { // ignore } } return null; }
@Override public String getSource(IClassFile classFile, IProgressMonitor monitor) throws CoreException { String source = null; try { IBuffer buffer = classFile.getBuffer(); if (buffer != null) { if (monitor.isCanceled()) { return null; } source = buffer.getContents(); JavaLanguageServerPlugin.logInfo("ClassFile contents request completed"); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Exception getting java element ", e); } return source; }
/** * Gets a reader for an IMember's Javadoc comment content from the source attachment. * The content does contain only the text from the comment without the Javadoc leading star characters. * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is available. * @param member The member to get the Javadoc of. * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member * does not contain a Javadoc comment or if no source is available * @throws JavaModelException is thrown when the elements javadoc can not be accessed * @since 3.4 */ private static Reader internalGetContentReader(IMember member) throws JavaModelException { IBuffer buf= member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange != null) { JavaDocCommentReader reader= new JavaDocCommentReader(buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1); if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) { reader.reset(); return reader; } } return null; }
@Before public void initProjectManager() throws CoreException { clientRequests.clear(); logListener = new SimpleLogListener(); Platform.addLogListener(logListener); preferences = new Preferences(); if (preferenceManager != null) { when(preferenceManager.getPreferences()).thenReturn(preferences); } projectsManager = new ProjectsManager(preferenceManager); WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { @Override public IBuffer createBuffer(ICompilationUnit workingCopy) { ICompilationUnit original= workingCopy.getPrimary(); IResource resource= original.getResource(); if (resource instanceof IFile) { return new DocumentAdapter(workingCopy, (IFile)resource); } return DocumentAdapter.Null; } }); }
public static Integer getLineNumber(IMember member) throws JavaModelException { ITypeRoot typeRoot = member.getTypeRoot(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { return null; } Document document = new Document(buffer.getContents()); int offset = 0; if (SourceRange.isAvailable(member.getNameRange())) { offset = member.getNameRange().getOffset(); } else if (SourceRange.isAvailable(member.getSourceRange())) { offset = member.getSourceRange().getOffset(); } try { return document.getLineOfOffset(offset); } catch (BadLocationException e) { return null; } }
private static List<ICompletionProposal> computeProposals( ICompilationUnit compilationUnit, int offset) throws JavaModelException { IBuffer buffer = compilationUnit.getBuffer(); IDocument document; if (buffer instanceof org.eclipse.jdt.internal.ui.javaeditor.DocumentAdapter) { document = ((org.eclipse.jdt.internal.ui.javaeditor.DocumentAdapter) buffer).getDocument(); } else { document = new DocumentAdapter(buffer); } TextViewer viewer = new TextViewer(document, new Point(offset, 0)); JavaContentAssistInvocationContext context = new JavaContentAssistInvocationContext(viewer, offset, compilationUnit); List<ICompletionProposal> proposals = new ArrayList<>(); proposals.addAll( new JavaAllCompletionProposalComputer().computeCompletionProposals(context, null)); // proposals.addAll(new // TemplateCompletionProposalComputer().computeCompletionProposals(context, null)); Collections.sort(proposals, new RelevanceSorter()); return proposals; }
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) { if (start == end) return true; Assert.isTrue(start <= end); String trimmedText = buffer.getText(start, end - start).trim(); if (0 == trimmedText.length()) { return true; } else { IScanner scanner = ToolFactory.createScanner(false, false, false, null); scanner.setSource(trimmedText.toCharArray()); try { return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { return false; } } }
/** * Creates a TokenScanner * * @param typeRoot The type root to scan on * @throws CoreException thrown if the buffer cannot be accessed */ public TokenScanner(ITypeRoot typeRoot) throws CoreException { IJavaProject project = typeRoot.getJavaProject(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { throw new CoreException( createError(DOCUMENT_ERROR, "Element has no source", null)); // $NON-NLS-1$ } String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true); fScanner = ToolFactory.createScanner( true, false, true, sourceLevel, complianceLevel); // line info required fScanner.setSource(buffer.getCharacters()); fDocument = null; // use scanner for line information fEndPosition = fScanner.getSource().length - 1; }
private int getNameEnd(IBuffer doc, int pos) { if (pos > 0) { if (Character.isWhitespace(doc.getChar(pos - 1))) { return pos; } } int len = doc.getLength(); while (pos < len) { char ch = doc.getChar(pos); if (!Character.isJavaIdentifierPart(ch)) { return pos; } pos++; } return pos; }
/** * Gets a reader for an IMember's Javadoc comment content from the source attachment. The content * does contain only the text from the comment without the Javadoc leading star characters. * Returns <code>null</code> if the member does not contain a Javadoc comment or if no source is * available. * * @param member The member to get the Javadoc of. * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member * does not contain a Javadoc comment or if no source is available * @throws org.eclipse.jdt.core.JavaModelException is thrown when the elements javadoc can not be * accessed * @since 3.4 */ private static Reader internalGetContentReader(IMember member) throws JavaModelException { IBuffer buf = member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange = member.getJavadocRange(); if (javadocRange != null) { JavaDocCommentReader reader = new JavaDocCommentReader( buf, javadocRange.getOffset(), javadocRange.getOffset() + javadocRange.getLength() - 1); if (!containsOnlyInheritDoc(reader, javadocRange.getLength())) { reader.reset(); return reader; } } return null; }
private static String getHTMLContentFromSource(IMember member, String urlPrefix) throws JavaModelException { IBuffer buf = member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange = member.getJavadocRange(); if (javadocRange == null) { if (canInheritJavadoc(member)) { // Try to use the inheritDoc algorithm. String inheritedJavadoc = javadoc2HTML(member, "/***/", urlPrefix); // $NON-NLS-1$ if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) { return inheritedJavadoc; } } return null; // getJavaFxPropertyDoc(member); } String rawJavadoc = buf.getText(javadocRange.getOffset(), javadocRange.getLength()); return javadoc2HTML(member, rawJavadoc, urlPrefix); }
protected static void cleanupBuffer(IClassFile file) { IBuffer buffer = BufferManager.getDefaultBufferManager().getBuffer(file); if (buffer != null) { try { // Remove the buffer Method method = BufferManager.class.getDeclaredMethod( "removeBuffer", new Class[] {IBuffer.class}); method.setAccessible(true); method.invoke( BufferManager.getDefaultBufferManager(), new Object[] {buffer}); } catch (Exception e) { JavaDecompilerPlugin.getDefault().getLog().log(new Status( Status.ERROR, JavaDecompilerPlugin.PLUGIN_ID, 0, e.getMessage(), e)); } } }
/** * Examines a string and returns the first line delimiter found. */ private static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null && cu.exists()) { IBuffer buf = cu.getBuffer(); int length = buf.getLength(); for (int i = 0; i < length; i++) { char ch = buf.getChar(i); if (ch == SWT.CR) { if (i + 1 < length) { if (buf.getChar(i + 1) == SWT.LF) { return "\r\n"; } } return "\r"; } else if (ch == SWT.LF) { return "\n"; } } } return System.getProperty("line.separator", "\n"); }
/** * Evaluates the indentation used by a Java element. (in tabulators) */ private int getUsedIndentation(IJavaElement elem) throws JavaModelException { if (elem instanceof ISourceReference) { ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { IBuffer buf = cu.getBuffer(); int offset = ((ISourceReference) elem).getSourceRange().getOffset(); int i = offset; // find beginning of line while (i > 0 && !isLineDelimiterChar(buf.getChar(i - 1))) { i--; } return computeIndent(buf.getText(i, offset - i), getTabWidth()); } } return 0; }
private static void setCompilationUnitContents(ICompilationUnit cu, String source) { if (cu == null) { return; } synchronized (cu) { IBuffer buffer; try { buffer = cu.getBuffer(); } catch (JavaModelException e) { buffer = null; } if (buffer != null) { buffer.setContents(source); } } }
private static String getFieldSource(IField field, SourceTuple tuple) throws CoreException { if (Flags.isEnum(field.getFlags())) { String source= field.getSource(); if (source != null) return source; } else { if (tuple.node == null) { ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); parser.setSource(tuple.unit); tuple.node= (CompilationUnit) parser.createAST(null); } FieldDeclaration declaration= ASTNodeSearchUtil.getFieldDeclarationNode(field, tuple.node); if (declaration.fragments().size() == 1) return getSourceOfDeclararationNode(field, tuple.unit); VariableDeclarationFragment declarationFragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(field, tuple.node); IBuffer buffer= tuple.unit.getBuffer(); StringBuffer buff= new StringBuffer(); buff.append(buffer.getText(declaration.getStartPosition(), ((ASTNode) declaration.fragments().get(0)).getStartPosition() - declaration.getStartPosition())); buff.append(buffer.getText(declarationFragment.getStartPosition(), declarationFragment.getLength())); buff.append(";"); //$NON-NLS-1$ return buff.toString(); } return ""; //$NON-NLS-1$ }
private void initCallTextAndLineNumber() { if (fCallText != null) return; IBuffer buffer= getBufferForMember(); if (buffer == null || buffer.getLength() < fEnd) { //binary, without source attachment || buffer contents out of sync (bug 121900) fCallText= ""; //$NON-NLS-1$ fLineNumber= UNKNOWN_LINE_NUMBER; return; } fCallText= buffer.getText(fStart, (fEnd - fStart)); if (fLineNumber == UNKNOWN_LINE_NUMBER) { Document document= new Document(buffer.getContents()); try { fLineNumber= document.getLineOfOffset(fStart) + 1; } catch (BadLocationException e) { JavaPlugin.log(e); } } }
private static boolean isJustWhitespaceOrComment(int start, int end, IBuffer buffer) { if (start == end) return true; Assert.isTrue(start <= end); String trimmedText= buffer.getText(start, end - start).trim(); if (0 == trimmedText.length()) { return true; } else { IScanner scanner= ToolFactory.createScanner(false, false, false, null); scanner.setSource(trimmedText.toCharArray()); try { return scanner.getNextToken() == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { return false; } } }
/** * Returns the source of the given node from the location where it was parsed. * @param node the node to get the source from * @param extendedRange if set, the extended ranges of the nodes should ne used * @param removeIndent if set, the indentation is removed. * @return return the source for the given node or null if accessing the source failed. */ public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) { ASTNode root= node.getRoot(); if (root instanceof CompilationUnit) { CompilationUnit astRoot= (CompilationUnit) root; ITypeRoot typeRoot= astRoot.getTypeRoot(); try { if (typeRoot != null && typeRoot.getBuffer() != null) { IBuffer buffer= typeRoot.getBuffer(); int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); String str= buffer.getText(offset, length); if (removeIndent) { IJavaProject project= typeRoot.getJavaProject(); int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project); str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator()); } return str; } } catch (JavaModelException e) { // ignore } } return null; }
private int getNameEnd(IBuffer doc, int pos) { if (pos > 0) { if (Character.isWhitespace(doc.getChar(pos - 1))) { return pos; } } int len= doc.getLength(); while (pos < len) { char ch= doc.getChar(pos); if (!Character.isJavaIdentifierPart(ch)) { return pos; } pos++; } return pos; }
private static String getHTMLContentFromSource(IMember member) throws JavaModelException { IBuffer buf= member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange == null) { if (canInheritJavadoc(member)) { // Try to use the inheritDoc algorithm. String inheritedJavadoc= javadoc2HTML(member, "/***/"); //$NON-NLS-1$ if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) { return inheritedJavadoc; } } return getJavaFxPropertyDoc(member); } String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength()); return javadoc2HTML(member, rawJavadoc); }
/** * Returns true if the buffer is successfully closed and * removed from the cache, otherwise false. * * <p>NOTE: this triggers an external removal of this buffer * by closing the buffer. */ protected boolean close(LRUCacheEntry entry) { IBuffer buffer= (IBuffer) entry.value; // prevent buffer that have unsaved changes or working copy buffer to be removed // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=39311 if (!((Openable)buffer.getOwner()).canBufferBeRemovedFromCache(buffer)) { return false; } else { ArrayList buffers = (ArrayList) this.buffersToClose.get(); if (buffers == null) { buffers = new ArrayList(); this.buffersToClose.set(buffers); } buffers.add(buffer); return true; } }
/** * @see org.eclipse.jdt.internal.core.JavaModelOperation#executeOperation() */ protected void executeOperation() throws JavaModelException { try { beginTask(Messages.operation_sortelements, getMainAmountOfWork()); CompilationUnit copy = (CompilationUnit) this.elementsToProcess[0]; ICompilationUnit unit = copy.getPrimary(); IBuffer buffer = copy.getBuffer(); if (buffer == null) { return; } char[] bufferContents = buffer.getCharacters(); String result = processElement(unit, bufferContents); if (!CharOperation.equals(result.toCharArray(), bufferContents)) { copy.getBuffer().setContents(result); } worked(1); } finally { done(); } }
private void removeAndInsertNew(IBuffer buffer, int contentOffset, int contentEnd, ArrayList stringsToInsert, MultiTextEdit resEdit) { int pos= contentOffset; for (int i= 0; i < stringsToInsert.size(); i++) { String curr= (String) stringsToInsert.get(i); int idx= findInBuffer(buffer, curr, pos, contentEnd); if (idx != -1) { if (idx != pos) { resEdit.addChild(new DeleteEdit(pos, idx - pos)); } pos= idx + curr.length(); } else { resEdit.addChild(new InsertEdit(pos, curr)); } } if (pos < contentEnd) { resEdit.addChild(new DeleteEdit(pos, contentEnd - pos)); } }
private static String getHTMLContentFromSource(IMember member) throws JavaModelException { IBuffer buf= member.getOpenable().getBuffer(); if (buf == null) { return null; // no source attachment found } ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange == null) { if (canInheritJavadoc(member)) { // Try to use the inheritDoc algorithm. If it finds nothing (in source), return null. String inheritedJavadoc= javadoc2HTML(member, "/***/"); //$NON-NLS-1$ return inheritedJavadoc != null && inheritedJavadoc.length() > 0 ? inheritedJavadoc : null; } else { return null; } } String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength()); return javadoc2HTML(member, rawJavadoc); }
/** * Set contents of the compilation unit to the translated JSP text. * * @param unit the ICompilationUnit on which to set the buffer contents * @param value Java source code */ public static void setContentsToCU(ICompilationUnit unit, String value){ if (unit == null){ return; } synchronized (unit) { IBuffer buffer; try { buffer = unit.getBuffer(); } catch (JavaModelException e) { BytemanEditorPlugin.logException(e); buffer = null; } if (buffer != null){ buffer.setContents(value); } } }
private static String getJavadocFast(IMember member, boolean prettify) throws JavaModelException { IBuffer buffer = member.getOpenable().getBuffer(); if (buffer == null) return getJavadocSlow(member, prettify); ISourceRange javadocRange = member.getJavadocRange(); if (javadocRange == null) return getJavadocSlow(member, prettify); String javadocText = buffer.getText(javadocRange.getOffset(), javadocRange.getLength()); if (prettify) { javadocText = javadocText.replaceAll("^/[*][*][ \t]*\n?", ""); // Filter starting /** javadocText = javadocText.replaceAll("\n?[ \t]*[*]/$", ""); // Filter ending */ javadocText = javadocText.replaceAll("^\\s*[*]", "\n"); // Trim leading whitespace. javadocText = javadocText.replaceAll("\n\\s*[*]", "\n"); // Trim whitespace at beginning of line. javadocText = javadocText.replaceAll("<[^>]*>", ""); // Remove html tags. javadocText = javadocText.replaceAll("[{]@code([^}]*)[}]", "$1"); // Replace {@code foo} blocks with foo. javadocText = javadocText.replaceAll(" ", " ").replaceAll("<", "<").replaceAll(">", ">").replaceAll(""", "\""); // Replace html formatting. } javadocText = Flags.toString(member.getFlags()) + " " + JavaElementLabels.getElementLabel(member, JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.F_PRE_TYPE_SIGNATURE) + "\n" + javadocText; return javadocText; }
public static Range toRange(IOpenable openable, int offset, int length) throws JavaModelException { if (offset > 0 || length > 0) { int[] loc = null; int[] endLoc = null; IBuffer buffer = openable.getBuffer(); // if (buffer != null) { // loc = JsonRpcHelpers.toLine(buffer, offset); // endLoc = JsonRpcHelpers.toLine(buffer, offset + length); // } // if (loc == null) { // loc = new int[2]; // } // if (endLoc == null) { // endLoc = new int[2]; // } // setPosition(range.getStart(), loc); // setPosition(range.getEnd(), endLoc); IDocument document = toDocument(buffer); try { int line = document.getLineOfOffset(offset); int column = offset - document.getLineOffset(line); return new Range(line + 1, column + 1); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // TODO Auto-generated method stub return null; }