/** @see ISourceReference */ public String getSource() throws JavaModelException { IBuffer buffer = getBuffer(); if (buffer == null) { return null; } return buffer.getContents(); }
/** * Determines is the java element contains a type with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * </ol> * * @param element the element to check for the method * @param annotationName the qualified or unqualified name of the annotation to look for * @return true if the type is found in the element, false otherwise */ private boolean hasTypeWithAnnotation(IJavaElement element, String annotationType) { try { IType type = getType(element); if (type == null || !type.exists()) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } ISourceRange sourceRange = type.getSourceRange(); ISourceRange nameRange = type.getNameRange(); if (sourceRange != null && nameRange != null) { IScanner scanner = ToolFactory.createScanner(false, false, true, false); scanner.setSource(buffer.getCharacters()); scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset()); if (findAnnotation(scanner, annotationType)) { return true; } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
/** @see ICodeAssist#codeSelect(int, int, WorkingCopyOwner) */ public IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner owner) throws JavaModelException { IBuffer buffer = getBuffer(); char[] contents; if (buffer != null && (contents = buffer.getCharacters()) != null) { BinaryType type = (BinaryType) getType(); // GROOVY start /*old{ BasicCompilationUnit cu = new BasicCompilationUnit(contents, null, type.sourceFileName((IBinaryType) type.getElementInfo())); }new*/ // handle code select for Groovy files differently IBinaryType typeInfo = (IBinaryType) type.getElementInfo(); if (LanguageSupportFactory.isInterestingBinary(type, typeInfo)) { return LanguageSupportFactory.binaryCodeSelect(this, offset, length, owner); } BasicCompilationUnit cu = new BasicCompilationUnit(contents, null, type.sourceFileName(typeInfo)); // GROOVY end return super.codeSelect(cu, offset, length, owner); } else { // has no associated souce return new IJavaElement[] {}; } }
private int getLineEnd(IBuffer buffer, int offset) { int pos = offset; int length = buffer.getLength(); while (pos < length && !isDelemiter(buffer.getChar(pos))) { pos++; } return pos; }
/** @see ISourceReference */ public ISourceRange getSourceRange() throws JavaModelException { IBuffer buffer = getBuffer(); if (buffer != null) { String contents = buffer.getContents(); if (contents == null) return null; return new SourceRange(0, contents.length()); } else { return null; } }
public char[] getContents() { try { 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; } }
private static int moveBack(int offset, int start, String ignoreCharacters, ICompilationUnit cu) { try { IBuffer buf = cu.getBuffer(); while (offset >= start) { if (ignoreCharacters.indexOf(buf.getChar(offset - 1)) == -1) { return offset; } offset--; } } catch (JavaModelException e) { } return start; }
private int getLineStart(IBuffer buffer, int offset) { int pos = offset; while (pos >= 0 && !isDelemiter(buffer.getChar(pos))) { pos--; } return pos + 1; }
private void setContentsToCU(ICompilationUnit unit, String value) { if (unit == null) { return; } synchronized (unit) { IBuffer buffer; try { buffer = unit.getBuffer(); if (buffer != null) { buffer.setContents(value); } } catch (JavaModelException e) { e.printStackTrace(); } } }
/** @see Openable#openBuffer(IProgressMonitor, Object) */ 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()), ClassFileBytesDisassembler.WORKING_COPY); // $NON-NLS-1$ buffer.setContents(contents); } } // add buffer to buffer cache BufferManager bufManager = getBufferManager(); bufManager.addBuffer(buffer); // listen to buffer changes buffer.addBufferChangedListener(this); return buffer; }
/** @see ISourceReference */ public String getSource() throws JavaModelException { IOpenable openable = this.parent.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 e) { return null; } }
/** 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); // 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; } }
/** * Determines is the java element contains a method with a specific annotation. * * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name, * modifiers * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit * </code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </code>. * </ol> * * @param element the element to check for the method * @param annotationName the qualified or unqualified name of the annotation to look for * @return true if the method is found in the element, false otherwise */ private boolean hasMethodWithAnnotation(IJavaElement element, Object[] args) { try { String annotationType = (String) args[0]; int flags = 0; if (args.length > 1) { String[] modifiers = ((String) args[1]).split(" "); // $NON-NLS-1$ for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } } else { flags = -1; } IType type = getType(element); if (type == null || !type.exists()) { return false; } IMethod[] methods = type.getMethods(); if (methods.length == 0) { return false; } IBuffer buffer = null; IOpenable openable = type.getOpenable(); if (openable instanceof ICompilationUnit) { buffer = ((ICompilationUnit) openable).getBuffer(); } else if (openable instanceof IClassFile) { buffer = ((IClassFile) openable).getBuffer(); } if (buffer == null) { return false; } IScanner scanner = null; // delay initialization for (int i = 0; i < methods.length; i++) { IMethod curr = methods[i]; if (curr.isConstructor() || (flags != -1 && flags != (curr.getFlags() & FLAGS_MASK))) { continue; } ISourceRange sourceRange = curr.getSourceRange(); ISourceRange nameRange = curr.getNameRange(); 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()); if (findAnnotation(scanner, annotationType)) { return true; } } } } catch (JavaModelException e) { } catch (InvalidInputException e) { } return false; }
public void run(IMarker marker) { IFile file = (IFile) javaDeclaration.getResource(); try { ICompilationUnit original = EclipseUtil.getCompilationUnit(file); if (original == null) { return; } ICompilationUnit compilationUnit = original.getWorkingCopy(new NullProgressMonitor()); String lineDelim = JavaPropertyGenerator.getLineDelimiterUsed(compilationUnit); Hashtable<String, String> options = JavaCore.getOptions(); int tabSize = new Integer(options.get("org.eclipse.jdt.core.formatter.tabulation.size")); StringBuffer tabBuf = new StringBuffer(); for (int i = 0; i < tabSize; i++) tabBuf.append(" "); String tab = tabBuf.toString(); IType type = compilationUnit.findPrimaryType(); IField field = type.getField(property.getName()); String propertyType = ""; if (field != null && field.exists()) { propertyType = field.getTypeSignature(); } else { propertyType = "String"; // $NON-NLS-1$ StringBuffer buf = new StringBuffer(); buf.append( tab + "private " + propertyType + " " + property.getName() + ";"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); field = type.createField(buf.toString(), null, false, new NullProgressMonitor()); if (field != null) { IBuffer buffer = compilationUnit.getBuffer(); buffer.replace( field.getSourceRange().getOffset(), field.getSourceRange().getLength(), buf.toString()); synchronized (compilationUnit) { compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null); } } } IMethod oldMethod = GetterSetterUtil.getSetter(field); if (oldMethod == null || !oldMethod.exists()) { String setterName = GetterSetterUtil.getSetterName(field, null); // JavaPropertyGenerator.createSetter(compilationUnit, type, "public", // field.getTypeSignature(), setterName, lineDelim); String stub = GetterSetterUtil.getSetterStub(field, setterName, true, Flags.AccPublic); IMethod newMethod = type.createMethod(stub, null, false, new NullProgressMonitor()); if (newMethod != null) { IBuffer buffer = compilationUnit.getBuffer(); // format StringBuffer buf = new StringBuffer(); buf.append(lineDelim); buf.append( tab + "public void " + setterName + "(" + propertyType + " " + property.getName() + "){"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); buf.append(tab + tab + "this." + property.getName() + " = " + property.getName() + ";"); buf.append(lineDelim); buf.append(tab + "}"); buf.append(lineDelim); buffer.replace( newMethod.getSourceRange().getOffset(), newMethod.getSourceRange().getLength(), buf.toString()); } } compilationUnit.commitWorkingCopy(false, new NullProgressMonitor()); compilationUnit.discardWorkingCopy(); } catch (CoreException ex) { SeamGuiPlugin.getPluginLog().logError(ex); } }
/** @exception JavaModelException if setting the source of the original compilation unit fails */ protected void executeOperation() throws JavaModelException { try { beginTask(Messages.workingCopy_commit, 2); CompilationUnit workingCopy = getCompilationUnit(); if (ExternalJavaProject.EXTERNAL_PROJECT_NAME.equals( workingCopy.getJavaProject().getElementName())) { // case of a working copy without a resource workingCopy.getBuffer().save(this.progressMonitor, this.force); return; } ICompilationUnit primary = workingCopy.getPrimary(); boolean isPrimary = workingCopy.isPrimary(); JavaElementDeltaBuilder deltaBuilder = null; PackageFragmentRoot root = (PackageFragmentRoot) workingCopy.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); boolean isIncluded = !Util.isExcluded(workingCopy); IFile resource = (IFile) workingCopy.getResource(); IJavaProject project = root.getJavaProject(); if (isPrimary || (root.validateOnClasspath().isOK() && isIncluded && resource.isAccessible() && Util.isValidCompilationUnitName( workingCopy.getElementName(), project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true)))) { // force opening so that the delta builder can get the old info if (!isPrimary && !primary.isOpen()) { primary.open(null); } // creates the delta builder (this remembers the content of the cu) if: // - it is not excluded // - and it is not a primary or it is a non-consistent primary if (isIncluded && (!isPrimary || !workingCopy.isConsistent())) { deltaBuilder = new JavaElementDeltaBuilder(primary); } // save the cu IBuffer primaryBuffer = primary.getBuffer(); if (!isPrimary) { if (primaryBuffer == null) return; char[] primaryContents = primaryBuffer.getCharacters(); boolean hasSaved = false; try { IBuffer workingCopyBuffer = workingCopy.getBuffer(); if (workingCopyBuffer == null) return; primaryBuffer.setContents(workingCopyBuffer.getCharacters()); primaryBuffer.save(this.progressMonitor, this.force); primary.makeConsistent(this); hasSaved = true; } finally { if (!hasSaved) { // restore original buffer contents since something went wrong primaryBuffer.setContents(primaryContents); } } } else { // for a primary working copy no need to set the content of the buffer again primaryBuffer.save(this.progressMonitor, this.force); primary.makeConsistent(this); } } else { // working copy on cu outside classpath OR resource doesn't exist yet String encoding = null; try { encoding = resource.getCharset(); } catch (CoreException ce) { // use no encoding } String contents = workingCopy.getSource(); if (contents == null) return; try { byte[] bytes = encoding == null ? contents.getBytes() : contents.getBytes(encoding); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); if (resource.exists()) { resource.setContents( stream, this.force ? IResource.FORCE | IResource.KEEP_HISTORY : IResource.KEEP_HISTORY, null); } else { resource.create(stream, this.force, this.progressMonitor); } } catch (CoreException e) { throw new JavaModelException(e); } catch (UnsupportedEncodingException e) { throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION); } } setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE); // make sure working copy is in sync workingCopy.updateTimeStamp((CompilationUnit) primary); workingCopy.makeConsistent(this); worked(1); // build the deltas if (deltaBuilder != null) { deltaBuilder.buildDeltas(); // add the deltas to the list of deltas created during this operation if (deltaBuilder.delta != null) { addDelta(deltaBuilder.delta); } } worked(1); } finally { done(); } }
private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException { List<Statement> result = new ArrayList<>(1); TryStatement tryStatement = getAST().newTryStatement(); ITypeBinding[] exceptions = fAnalyzer.getExceptions(); ImportRewriteContext context = new ContextSensitiveImportRewriteContext( fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite); if (!fIsMultiCatch) { for (int i = 0; i < exceptions.length; i++) { ITypeBinding exception = exceptions[i]; CatchClause catchClause = getAST().newCatchClause(); tryStatement.catchClauses().add(catchClause); SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration(); String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject()); String name = fScope.createName(varName, false); decl.setName(getAST().newSimpleName(name)); Type type = fImportRewrite.addImport(exception, getAST(), context); decl.setType(type); catchClause.setException(decl); Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter); if (st != null) { catchClause.getBody().statements().add(st); } fLinkedProposalModel .getPositionGroup(GROUP_EXC_TYPE + i, true) .addPosition(fRewriter.track(decl.getType()), i == 0); fLinkedProposalModel .getPositionGroup(GROUP_EXC_NAME + i, true) .addPosition(fRewriter.track(decl.getName()), false); } } else { List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions); CatchClause catchClause = getAST().newCatchClause(); SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration(); String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject()); String name = fScope.createName(varName, false); decl.setName(getAST().newSimpleName(name)); UnionType unionType = getAST().newUnionType(); List<Type> types = unionType.types(); int i = 0; for (ITypeBinding exception : filteredExceptions) { Type type = fImportRewrite.addImport(exception, getAST(), context); types.add(type); fLinkedProposalModel .getPositionGroup(GROUP_EXC_TYPE + i, true) .addPosition(fRewriter.track(type), i == 0); i++; } decl.setType(unionType); catchClause.setException(decl); fLinkedProposalModel .getPositionGroup(GROUP_EXC_NAME + 0, true) .addPosition(fRewriter.track(decl.getName()), false); Statement st = getCatchBody("Exception", name, lineDelimiter); // $NON-NLS-1$ if (st != null) { catchClause.getBody().statements().add(st); } tryStatement.catchClauses().add(catchClause); } List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements(); ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY); boolean selectedNodeRemoved = false; ASTNode expressionStatement = null; for (int i = 0; i < fSelectedNodes.length; i++) { ASTNode node = fSelectedNodes[i]; if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) { AST ast = getAST(); VariableDeclarationStatement statement = (VariableDeclarationStatement) node; // Create a copy and remove the initializer VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement); List<IExtendedModifier> modifiers = copy.modifiers(); for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) { IExtendedModifier modifier = iter.next(); if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) { iter.remove(); } } List<VariableDeclarationFragment> fragments = copy.fragments(); for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); fragment.setInitializer(null); } CompilationUnit root = (CompilationUnit) statement.getRoot(); int extendedStart = root.getExtendedStartPosition(statement); // we have a leading comment and the comment is covered by the selection if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) { String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart); commentToken = Strings.trimTrailingTabsAndSpaces(commentToken); Type type = statement.getType(); String typeName = buffer.getText(type.getStartPosition(), type.getLength()); copy.setType( (Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType())); } result.add(copy); // convert the fragments into expression statements fragments = statement.fragments(); if (!fragments.isEmpty()) { List<ExpressionStatement> newExpressionStatements = new ArrayList<>(); for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) { VariableDeclarationFragment fragment = iter.next(); Expression initializer = fragment.getInitializer(); if (initializer != null) { Assignment assignment = ast.newAssignment(); assignment.setLeftHandSide( (Expression) fRewriter.createCopyTarget(fragment.getName())); assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer)); newExpressionStatements.add(ast.newExpressionStatement(assignment)); } } if (!newExpressionStatements.isEmpty()) { if (fSelectedNodes.length == 1) { expressionStatement = fRewriter.createGroupNode( newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])); } else { fRewriter.replace( statement, fRewriter.createGroupNode( newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null); } } else { fRewriter.remove(statement, null); selectedNodeRemoved = true; } } else { fRewriter.remove(statement, null); selectedNodeRemoved = true; } } } result.add(tryStatement); ASTNode replacementNode; if (result.size() == 1) { replacementNode = result.get(0); } else { replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()])); } if (fSelectedNodes.length == 1) { ASTNode selectedNode = fSelectedNodes[0]; if (selectedNode instanceof MethodReference) { MethodReference methodReference = (MethodReference) selectedNode; IMethodBinding functionalMethod = QuickAssistProcessor.getFunctionalMethodForMethodReference(methodReference); // functionalMethod is non-null and non-generic. See // ExceptionAnalyzer.handleMethodReference(MethodReference node). Assert.isTrue(functionalMethod != null && !functionalMethod.isGenericMethod()); LambdaExpression lambda = QuickAssistProcessor.convertMethodRefernceToLambda( methodReference, functionalMethod, fRootNode, fRewriter, null, true); ASTNode statementInBlock = (ASTNode) ((Block) lambda.getBody()).statements().get(0); fRewriter.replace(statementInBlock, replacementNode, null); statements.insertLast(statementInBlock, null); return; } LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(selectedNode); if (enclosingLambda != null && selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY && enclosingLambda.resolveMethodBinding() != null) { QuickAssistProcessor.changeLambdaBodyToBlock(enclosingLambda, getAST(), fRewriter); Block blockBody = (Block) fRewriter.get(enclosingLambda, LambdaExpression.BODY_PROPERTY); ASTNode statementInBlock = (ASTNode) blockBody.statements().get(0); fRewriter.replace(statementInBlock, replacementNode, null); statements.insertLast(statementInBlock, null); return; } if (expressionStatement != null) { statements.insertLast(expressionStatement, null); } else { if (!selectedNodeRemoved) statements.insertLast(fRewriter.createMoveTarget(selectedNode), null); } fRewriter.replace(selectedNode, replacementNode, null); } else { ListRewrite source = fRewriter.getListRewrite( fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent()); ASTNode toMove = source.createMoveTarget( fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null); statements.insertLast(toMove, null); } }