Java Examples for org.eclipse.jdt.core.dom.MethodDeclaration
The following java examples will help you to understand the usage of org.eclipse.jdt.core.dom.MethodDeclaration. These source code samples are taken from different open source projects.
Example 1
Project: bndtools-master File: AbstractBuildErrorDetailsHandler.java View source code |
@Override
public boolean visit(MethodDeclaration methodDecl) {
if (matches(ast, methodDecl, methodName, methodSignature)) {
// Create the marker attribs here
markerAttributes.put(IMarker.CHAR_START, methodDecl.getStartPosition());
markerAttributes.put(IMarker.CHAR_END, methodDecl.getStartPosition() + methodDecl.getLength());
}
return false;
}
Example 2
Project: ChangeScribe-master File: StereotypeIdentifier.java View source code |
public void identifyStereotypes() { if (this.parser == null) { return; } this.parser.parse(); for (final ASTNode element : this.parser.getElements()) { try { StereotypedElement stereoElement; if (element instanceof TypeDeclaration) { stereoElement = new StereotypedType((TypeDeclaration) element, this.methodsMean, this.methodsStdDev); } else { if (!(element instanceof MethodDeclaration)) { continue; } stereoElement = new StereotypedMethod((MethodDeclaration) element); } stereoElement.findStereotypes(); this.stereotypedElements.add(stereoElement); } catch (NullPointerException ex) { ex.printStackTrace(); } } }
Example 3
Project: eclipse.jdt.core-master File: DefaultJavaElementComparator.java View source code |
/** * This method is used to retrieve the category for a body declaration node according to the * preferences passed at the creation of the comparator. * * @param node the given node * @return the category corresponding to the given node * * @since 2.1 */ private int getCategory(BodyDeclaration node) { switch(node.getNodeType()) { case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration = (MethodDeclaration) node; if (methodDeclaration.isConstructor()) { return this.categories[CONSTRUCTOR_CATEGORY]; } if (Flags.isStatic(methodDeclaration.getModifiers())) { return this.categories[STATIC_METHOD_CATEGORY]; } return this.categories[METHOD_CATEGORY]; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: if (Flags.isStatic(node.getModifiers())) { return this.categories[STATIC_METHOD_CATEGORY]; } return this.categories[METHOD_CATEGORY]; case ASTNode.FIELD_DECLARATION: FieldDeclaration fieldDeclaration = (FieldDeclaration) node; if (Flags.isStatic(fieldDeclaration.getModifiers())) { return this.categories[STATIC_FIELD_CATEGORY]; } return this.categories[FIELD_CATEGORY]; case ASTNode.ENUM_CONSTANT_DECLARATION: return this.categories[STATIC_FIELD_CATEGORY]; case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: case ASTNode.ANNOTATION_TYPE_DECLARATION: AbstractTypeDeclaration abstractTypeDeclaration = (AbstractTypeDeclaration) node; if (Flags.isStatic(abstractTypeDeclaration.getModifiers())) { return this.categories[STATIC_TYPE_CATEGORY]; } return this.categories[TYPE_CATEGORY]; case ASTNode.INITIALIZER: Initializer initializer = (Initializer) node; if (Flags.isStatic(initializer.getModifiers())) { return this.categories[STATIC_INITIALIZER_CATEGORY]; } return this.categories[INITIALIZER_CATEGORY]; } return 0; }
Example 4
Project: evosuite-master File: MarkerWriter.java View source code |
@Override public void run() { ArrayList<Integer> lines = new ArrayList<Integer>(); Set<Integer> actualLines = new HashSet<Integer>(); actualLines.addAll(tgr.getUncoveredLines()); actualLines.addAll(tgr.getCoveredLines()); int contentPosition = 0; int line = 1; while (contentPosition != -2 && contentPosition != -1) { if (!actualLines.contains(line)) { lines.add(line); } contentPosition = compClass.getPosition(line, 0); line++; } IPreferenceStore store = Activator.getDefault().getPreferenceStore(); if (store.getBoolean("removed")) { for (Integer i : lines) { // this line couldn't be reached in the test! IJavaElement currentElement = null; int position = compClass.getPosition(i, 0); int maxPosition = compClass.getPosition(i + 1, 0); if (position == -1 || position == -2) { continue; } while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } if (position > maxPosition) { continue; } while (maxPosition < classContent.length && Character.isWhitespace(classContent[maxPosition])) { // System.out.println(classContent); maxPosition++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } if (isMethodDeclaration(i, currentElement, content, compClass, icomp)) { continue; } IJavaElement nextElement = null; int nextPosition = compClass.getPosition(i + 1, 0); if (nextPosition != -1 || nextPosition != -2) { try { nextElement = icomp.getElementAt(nextPosition); if (nextElement != currentElement) { continue; } } catch (JavaModelException e) { e.printStackTrace(); } } if (position > maxPosition) { continue; } while (maxPosition < classContent.length && Character.isWhitespace(classContent[maxPosition])) { // System.out.println(classContent); maxPosition++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } if (content[position] == '/' && content[position + 1] == '/') { continue; } if (content[position] == '}') { continue; } if (getMethod(currentElement) == null) { continue; } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.lineremovedmarker"); m.setAttribute(IMarker.MESSAGE, "This line appears to be removed by the Java Compiler."); m.setAttribute(IMarker.LINE_NUMBER, i); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0)); } catch (CoreException e) { e.printStackTrace(); } } } } if (store.getBoolean("uncovered")) { for (Integer i : tgr.getUncoveredLines()) { // this line couldn't be reached in the test! IJavaElement currentElement = null; int position = compClass.getPosition(i, 0); if (position == -1) { continue; } while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker"); m.setAttribute(IMarker.LINE_NUMBER, i); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(i + 1, 0)); } catch (CoreException e) { e.printStackTrace(); } } } } for (BranchInfo bi : tgr.getUncoveredBranches()) { int j = bi.getLineNo(); IJavaElement currentElement = null; int position = compClass.getPosition(j, 0); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { try { IMarker m = res.createMarker("EvoSuiteQuickFixes.notcoveredmarker"); m.setAttribute(IMarker.MESSAGE, "This branch (starting line " + j + ") could not be covered by EvoSuite."); m.setAttribute(IMarker.LINE_NUMBER, j); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m = res.createMarker("EvoSuiteQuickFixes.uncoveredlinemarker"); // m.setAttribute(IMarker.LINE_NUMBER, j); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1); m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(j + 1, 0) - 1); } catch (CoreException e) { e.printStackTrace(); } } } for (MethodDeclaration method : testM.getMethods()) { String test = method.getName().getFullyQualifiedName(); Set<Failure> failures = tgr.getContractViolations(test); if (failures != null && failures.size() != 0) { // uncaught Exception! try { for (Failure f : failures) { if (f != null) { int lineNumber = 1; String message = ""; for (int i = 0; i < f.getStackTrace().length; i++) { if (f.getStackTrace()[i].getClassName().equals(className)) { boolean found = false; for (MethodDeclaration method2 : raw.getMethods()) { String s = method2.getName().getFullyQualifiedName(); if (s.equals(f.getStackTrace()[i].getMethodName())) { found = true; break; } } if (found) { message = f.getStackTrace()[i].toString(); lineNumber = f.getStackTrace()[i].getLineNumber(); break; } } } IJavaElement currentElement = null; int position = compClass.getPosition(lineNumber, 0); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } try { currentElement = icomp.getElementAt(position + 1); } catch (JavaModelException e1) { e1.printStackTrace(); } boolean marker = shouldWriteMarkers(currentElement); if (marker) { IMarker m = res.createMarker("EvoSuiteQuickFixes.exceptionmarker"); m.setAttribute(IMarker.MESSAGE, f.getExceptionName() + " detected " + message); m.setAttribute(IMarker.LINE_NUMBER, lineNumber); m.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH); m.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING); m.setAttribute(IMarker.LOCATION, res.getName()); while (position < classContent.length && Character.isWhitespace(classContent[position])) { // System.out.println(classContent); position++; } m.setAttribute(IMarker.CHAR_START, position); m.setAttribute(IMarker.CHAR_END, compClass.getPosition(lineNumber + 1, 0) - 1); } } } } catch (CoreException e) { e.printStackTrace(); } } } }
Example 5
Project: jbosstools-webservices-master File: ImplementationClassCreationCommand.java View source code |
@SuppressWarnings("unchecked") protected void generateImplClass(ICompilationUnit portType, IPackageFragment pack, String ptCls, String clsName) throws CoreException, BadLocationException { ASTParser astp = ASTParser.newParser(AST.JLS3); astp.setKind(ASTParser.K_COMPILATION_UNIT); astp.setSource(portType); CompilationUnit cu = (CompilationUnit) astp.createAST(null); String implFileName = getJavaFileName(clsName); //$NON-NLS-1$ ICompilationUnit icu = pack.createCompilationUnit(implFileName, "", true, null); // create a working copy with a new owner icu.becomeWorkingCopy(null); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(icu); parser.setResolveBindings(false); parser.setFocalPosition(0); CompilationUnit implCu = (CompilationUnit) parser.createAST(null); AST ast = implCu.getAST(); // creation of a Document and ASTRewrite String source = icu.getBuffer().getContents(); Document document = new Document(source); implCu.recordModifications(); // start to add content into implementation class // add package declaration for impl class: PackageDeclaration implPackage = ast.newPackageDeclaration(); implPackage.setName(ast.newName(pack.getElementName())); implCu.setPackage(implPackage); // add imports for implementation class addImportsToImplementationClass(implCu, cu, ptCls); // add class declaration TypeDeclaration type = ast.newTypeDeclaration(); type.setInterface(false); // add WebService annotation String endpoint = getPortTypeFullName(portType.getParent().getElementName(), ptCls); NormalAnnotation ann = null; if (serviceName != null) { ann = createAnnotation(ast, serviceName, endpoint, targetNamespace); } else { ann = createAnnotation(ast, clsName, endpoint, targetNamespace); } type.modifiers().add(ann); type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); type.setName(ast.newSimpleName(clsName)); type.superInterfaceTypes().add(ast.newSimpleType(ast.newName(ptCls))); // add Logger variable declaration // createLoggerField(ast, type, portTypeName); // add method implementation TypeDeclaration inTD = (TypeDeclaration) cu.types().get(0); // firstly, get all methods that declared in Interface class and then // add corresponding methods to // the impl class MethodDeclaration[] methods = inTD.getMethods(); for (int i = 0; i < methods.length; i++) { MethodDeclaration newMethod = createMethodForImplClass(ast, methods[i]); type.bodyDeclarations().add(newMethod); } implCu.types().add(type); // try to save the Java file TextEdit edits = implCu.rewrite(document, icu.getJavaProject().getOptions(true)); edits.apply(document); String newSource = document.get(); icu.getBuffer().setContents(newSource); icu.reconcile(ICompilationUnit.NO_AST, false, null, null); icu.commitWorkingCopy(true, null); icu.discardWorkingCopy(); }
Example 6
Project: fb-contrib-eclipse-quick-fixes-master File: UseEnumCollectionsResolution.java View source code |
private ClassInstanceCreation findInitializerOfCollection(SimpleName collectionName, MethodInvocation startOfSearch) throws EnumParsingException {
IBinding collectionBinding = collectionName.resolveBinding();
// where it is being initialized
if (collectionBinding instanceof IVariableBinding) {
if (((IVariableBinding) collectionBinding).isField()) {
return findFieldInitialization(collectionName, TraversalUtil.findClosestAncestor(startOfSearch, TypeDeclaration.class));
}
return findMethodInitialization(collectionName, TraversalUtil.findClosestAncestor(startOfSearch, MethodDeclaration.class), false);
}
throw new EnumParsingException();
}
Example 7
Project: ClearJS-master File: WrongReturnTypeSubProcessor.java View source code |
public static void addTypeMismatchProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, String simpleType) throws CoreException { String args[] = problem.getProblemArguments(); if (args.length != 2) return; org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit(); CompilationUnit astRoot = context.getASTRoot(); AST ast = astRoot.getAST(); ASTNode selectedNode = problem.getCoveredNode(astRoot); BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) decl; ASTRewrite rewrite = ASTRewrite.create(ast); String label = Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturntype_description, BasicElementLabels.getJavaElementName("java.util." + simpleType)); org.eclipse.swt.graphics.Image image = JavaPluginImages.get("org.eclipse.jdt.ui.correction_change.gif"); LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, 6, image); ImportRewrite imports = proposal.createImportRewrite(astRoot); String newReturnType = imports.addImport("java.util." + simpleType); rewrite.replace(methodDeclaration.getReturnType2(), rewrite.createStringPlaceholder(simpleType + "<?>", 43), null); proposals.add(proposal); } }
Example 8
Project: composite-refactorings-master File: NewClassCreator.java View source code |
public TypeDeclaration createClassDeclaration(String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
AST ast = cuRewrite.getAST();
TypeDeclaration typeDeclaration = ast.newTypeDeclaration();
typeDeclaration.setName(ast.newSimpleName(fClassName));
if (fSuperclassType != null) {
Type superclassASTNode = (Type) Type.copySubtree(typeDeclaration.getAST(), fSuperclassType);
typeDeclaration.setSuperclassType(superclassASTNode);
}
List<BodyDeclaration> body = typeDeclaration.bodyDeclarations();
MethodDeclaration constructor = createConstructor(declaringType, cuRewrite);
body.add(constructor);
return typeDeclaration;
}
Example 9
Project: gwt-eclipse-plugin-master File: JsniParser.java View source code |
public static JavaValidationResult parse(MethodDeclaration method) {
final JavaValidationResult result = new JavaValidationResult();
try {
try {
// Find all Java references
result.addAllJavaRefs(findJavaRefs(method));
// Validate the Java references
for (JsniJavaRef ref : result.getJavaRefs()) {
GWTJavaProblem problem = validateJavaRef(method, ref);
if (problem != null) {
result.addProblem(problem);
}
}
} catch (JavaScriptParseException e) {
int offset = e.getOffset() + method.getStartPosition();
result.addProblem(GWTJavaProblem.create(method, offset, 1, GWTProblemType.JSNI_PARSE_ERROR, e.getMessage()));
} catch (IOException e) {
GWTPluginLog.logError(e, "IO error while parsing JSNI method " + method.getName());
} catch (InternalCompilerException e) {
String errorMsg = "Unexpected error parsing JSNI method " + method.getName() + ": " + e.getMessage();
Throwable cause = (e.getCause() != null ? e.getCause() : e);
GWTPluginLog.logError(cause, errorMsg);
}
} catch (BadLocationException e) {
GWTPluginLog.logError(e, "Error translating JS parse error location in " + method.getName());
}
return result;
}
Example 10
Project: roaster-master File: PropertyImpl.java View source code |
@Override public PropertySource<O> setName(final String name) { Assert.isFalse(Strings.isBlank(name), "Property name cannot be null/empty/blank"); if (hasField()) { getField().setName(name); } final String oldName = this.name; final boolean visitDocTags = true; final ASTVisitor renameVisitor = new ASTVisitor(visitDocTags) { @Override public boolean visit(SimpleName node) { if (Strings.areEqual(oldName, node.getIdentifier())) { node.setIdentifier(name); } return super.visit(node); } @Override public boolean visit(TextElement node) { final String text = node.getText(); if (!text.contains(oldName)) { return super.visit(node); } final int matchLength = oldName.length(); final int textLength = text.length(); final StringBuilder buf = new StringBuilder(text.length()); final ParsePosition pos = new ParsePosition(0); while (pos.getIndex() < textLength) { final int index = pos.getIndex(); final char c = text.charAt(index); if (Character.isJavaIdentifierStart(c)) { final int next = index + matchLength; if (next <= textLength && Strings.areEqual(oldName, text.substring(index, next))) { buf.append(name); pos.setIndex(next); continue; } } buf.append(c); pos.setIndex(index + 1); } node.setText(buf.toString()); return super.visit(node); } }; if (isAccessible()) { final MethodSource<O> accessor = getAccessor(); final String prefix = accessor.getReturnType().isType(boolean.class) ? "is" : "get"; accessor.setName(methodName(prefix, name)); ((MethodDeclaration) accessor.getInternal()).accept(renameVisitor); } if (isMutable()) { final MethodSource<O> mutator = getMutator(); mutator.setName(methodName("set", name)); ((MethodDeclaration) mutator.getInternal()).accept(renameVisitor); } this.name = name; return this; }
Example 11
Project: Slithice-master File: JavaASTUtils.java View source code |
public static TypeDeclaration getOutMostClass(MethodDeclaration method) {
ASTNode node = method;
TypeDeclaration lastTypeDecl = null;
while (node != null) {
if (node instanceof TypeDeclaration) {
TypeDeclaration type = (TypeDeclaration) node;
lastTypeDecl = type;
}
node = node.getParent();
}
return lastTypeDecl;
}
Example 12
Project: spring-ide-master File: QuickfixUtils.java View source code |
@Override
public boolean visit(MethodDeclaration node) {
if (methodToMatch != null) {
if (node.getName().getFullyQualifiedName().equals(methodToMatch.getElementName()) && node.parameters().size() == methodToMatch.getNumberOfParameters()) {
this.methodDecl = node;
return false;
}
}
return super.visit(node);
}
Example 13
Project: testng-eclipse-master File: TestNGMethodParameterVisitor.java View source code |
@Override public boolean visit(NormalAnnotation annotation) { if (!isKnownAnnotation(annotation.getTypeName().getFullyQualifiedName())) { return false; } List<?> values = annotation.values(); if (null != values && !values.isEmpty()) { for (int i = 0; i < values.size(); i++) { MemberValuePair pair = (MemberValuePair) values.get(i); if ("parameters".equals(pair.getName().toString())) { Expression paramAttr = pair.getValue(); if (paramAttr instanceof ArrayInitializer) { record((MethodDeclaration) annotation.getParent(), (ArrayInitializer) paramAttr); } else if (paramAttr instanceof StringLiteral) { record((MethodDeclaration) annotation.getParent(), (StringLiteral) paramAttr); } } } } return false; }
Example 14
Project: usus-plugins-master File: CCCollectorTest.java View source code |
@Test public void methodInsideMethodYieldsCC2() { MethodDeclaration innerMethod = setupMethodDeclMock(INNER_METHOD); collector.init(innerMethod); collector.commit(innerMethod); // now we need to make sure that the outer method has a different enclosing class and start position in the file: TypeDeclaration parent = setupMockFor(TypeDeclaration.class, OUTER_CLASS_NAME); when(nodeHelper.findEnclosingClassOf(org.mockito.Matchers.any(MethodDeclaration.class))).thenReturn(parent); when(Integer.valueOf(nodeHelper.getStartPositionFor(org.mockito.Matchers.any(ASTNode.class)))).thenReturn(Integer.valueOf(100)); collector.commit(method); methodVisitor.visit(); assertEquals(1, methodVisitor.getValueMap().get(OUTER_CLASS_NAME + "." + METHOD + "()").intValue()); assertEquals(1, methodVisitor.getValueMap().get(CLASS_NAME + "." + INNER_METHOD + "()").intValue()); }
Example 15
Project: whole-master File: AbstractVisitorCompilationUnitBuilder.java View source code |
public void addConstructorWithSuper(String[][] params) {
MethodDeclaration constructor = addConstructorDeclaration();
SuperConstructorInvocation superCall = newSuperConstructorInvocation();
for (int i = 0; i < params.length; i++) {
String pName = params[i][1];
constructor.parameters().add(newSingleVariableDeclaration(generator.visitorInterfaceName(), pName));
superCall.arguments().add(ast.newSimpleName(pName));
}
constructor.getBody().statements().add(superCall);
}
Example 16
Project: eclipse-optimus-master File: GeneratedAnnotationHelper.java View source code |
/** * Updates the source passed as parameter, by populating the hashCode * values. * * @param source * : Source * @return updated Source */ public static String updateHashcodeInSource(String source) { ASTParser parser = ASTParserFactory.INSTANCE.newParser(); parser.setSource(source.toCharArray()); parser.setCompilerOptions(GeneratedAnnotationHelper.compilerOptions); CompilationUnit cu = (CompilationUnit) parser.createAST(null); // Create and call the new Visitor, which role will be to // gather the methods on which the Generated annotation is yet not // defined. GeneratedAnnotationVisitor ev = new GeneratedAnnotationVisitor(); ev.process(cu); // Get the annotations to modify, fetched by the Visitor List<NormalAnnotation> annotationsToEnrich = ev.getAnnotationsToEnrich(); if (annotationsToEnrich.size() > 0) { cu.recordModifications(); boolean modified = false; for (NormalAnnotation annotationToEnrich : annotationsToEnrich) { // For each annotation to modify, replace the null value of // the comments field by the method's hashcode ASTNode parent = annotationToEnrich.getParent(); if (parent instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) parent; if (methodDeclaration.getBody() != null) { int hashCode = ASTHelper.methodBodyHashCode(methodDeclaration.getBody().toString()); modified = setGeneratedAnnotationHashcode(cu, annotationToEnrich, String.valueOf(hashCode)); } else { modified = setGeneratedAnnotationHashcode(cu, annotationToEnrich, "0"); } } else if (parent instanceof EnumConstantDeclaration) { EnumConstantDeclaration enumConstantDeclaration = (EnumConstantDeclaration) parent; int hashCode = ASTHelper.enumConstantHashCode(enumConstantDeclaration); modified = setGeneratedAnnotationHashcode(cu, annotationToEnrich, String.valueOf(hashCode)); } else if (parent instanceof FieldDeclaration) { modified = setGeneratedAnnotationHashcode(cu, annotationToEnrich, "0"); } } if (modified) { // Writes file on disk IDocument document = new Document(source); try { cu.rewrite(document, null).apply(document); return document.get(); } catch (MalformedTreeException e) { Activator.getDefault().logError("The compilation unit could not be" + " written on FileSystem because of thrown Exception.", e); } catch (BadLocationException e) { Activator.getDefault().logError("The compilation unit could not be" + " written on FileSystem because of thrown Exception", e); } } } return source; }
Example 17
Project: CodingSpectator-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 18
Project: Eclipse-Postfix-Code-Completion-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 19
Project: eclipse.jdt.ui-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 20
Project: AP-Refactoring-master File: HideMethodSolver.java View source code |
//TODO clean @Override protected Solution internalSolve(Issue issue, Map<String, Parameter> parameters) { ASTNode node = issue.getNodes().get(0); Solution solution = new Solution(issue, this, parameters); SourceFile sourceFile = (SourceFile) node.getRoot().getProperty(SourceFile.SOURCE_FILE_PROPERTY); IDocument document = null; try { document = sourceFile.toDocument(); } catch (IOException e) { } Delta delta = solution.createDelta(sourceFile); delta.setBefore(document.get()); ASTRewrite rewrite = ASTRewrite.create(node.getAST()); MethodDeclaration newMethodDeclaration = (MethodDeclaration) ASTNode.copySubtree(node.getAST(), node); if (node instanceof MethodDeclaration) { int modifiers = newMethodDeclaration.getModifiers(); int modifierLocation = getAnnotationsSize((MethodDeclaration) node); if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) { newMethodDeclaration.modifiers().remove(modifierLocation); } newMethodDeclaration.modifiers().addAll(modifierLocation, newMethodDeclaration.getAST().newModifiers(Modifier.PRIVATE)); } rewrite.replace(node, newMethodDeclaration, null); TextEdit textEdit = rewrite.rewriteAST(document, JavaCore.getOptions()); try { textEdit.apply(document); } catch (MalformedTreeExceptionBadLocationException | e) { } delta.setAfter(document.get()); return solution; }
Example 21
Project: che-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 22
Project: che-plugins-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 23
Project: DevTools-master File: SuppressWarningsSubProcessor.java View source code |
/** * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance). * * @param cu the compilation unit * @param node the node on which to add a SuppressWarning token * @param warningToken the warning token to add * @param relevance the proposal's relevance * @param proposals collector to which the proposal should be added * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal * * @since 3.6 */ private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) { ChildListPropertyDescriptor property; String name; boolean isLocalVariable = false; switch(node.getNodeType()) { case ASTNode.SINGLE_VARIABLE_DECLARATION: property = SingleVariableDeclaration.MODIFIERS2_PROPERTY; name = ((SingleVariableDeclaration) node).getName().getIdentifier(); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_STATEMENT: property = VariableDeclarationStatement.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments()); isLocalVariable = true; break; case ASTNode.VARIABLE_DECLARATION_EXPRESSION: property = VariableDeclarationExpression.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments()); isLocalVariable = true; break; case ASTNode.TYPE_DECLARATION: property = TypeDeclaration.MODIFIERS2_PROPERTY; name = ((TypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ANNOTATION_TYPE_DECLARATION: property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY; name = ((AnnotationTypeDeclaration) node).getName().getIdentifier(); break; case ASTNode.ENUM_DECLARATION: property = EnumDeclaration.MODIFIERS2_PROPERTY; name = ((EnumDeclaration) node).getName().getIdentifier(); break; case ASTNode.FIELD_DECLARATION: property = FieldDeclaration.MODIFIERS2_PROPERTY; name = getFirstFragmentName(((FieldDeclaration) node).fragments()); break; // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations case ASTNode.METHOD_DECLARATION: property = MethodDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((MethodDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY; name = //$NON-NLS-1$ ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + //$NON-NLS-1$ "()"; break; case ASTNode.ENUM_CONSTANT_DECLARATION: property = EnumConstantDeclaration.MODIFIERS2_PROPERTY; name = ((EnumConstantDeclaration) node).getName().getIdentifier(); break; default: return relevance; } String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) }); ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance); proposals.add(proposal); return isLocalVariable ? relevance - 1 : 0; }
Example 24
Project: fest-eclipse-plugin-master File: GetterCollector.java View source code |
@Override
public void endVisit(MethodDeclaration method) {
if (!isGetter(method)) {
return;
}
ITypeBinding returnTypeBinding = method.getReturnType2().resolveBinding();
String getterName = method.getName().toString();
Type getterReturnType = new Type(returnTypeBinding, projectBindings);
collectedGetters.add(new Getter(getterName, getterReturnType));
}
Example 25
Project: fsmls-master File: FSMLCodeGenDragSourceListener.java View source code |
@Override public void dragSetData(DragSourceEvent event) { // TODO Auto-generated method stub // super.dragFinished(event); // PackageExplorerPart view = (PackageExplorerPart)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("org.eclipse.jdt.ui.PackageExplorer"); // TreeViewer treeViewer = view.getTreeViewer(); // treeViewer.collapseAll(); // treeViewer.addFilter(new ViewerFilter() { // // @Override // public boolean select(Viewer viewer, Object parentElement, Object element) { // // TODO Auto-generated method stub // return true; // } // // }); ArrayList<IMarker> markers = new ArrayList<IMarker>(); List<String> methodLocationNamesForMarkers = new ArrayList<String>(); EObject selectedEObject = (EObject) ((IStructuredSelection) viewer.getSelection()).toArray()[0]; Model assertedModel = ((ModelContainer) selectedEObject.eResource().getContents().get(0)).getAssertedModel(); TreeIterator<EObject> allContents = assertedModel.eAllContents(); HashMap<String, CompilationUnit> cuCache = new HashMap<String, CompilationUnit>(); HashMap<String, Integer> methodLocations = new HashMap<String, Integer>(); while (allContents.hasNext()) { EObject currentObject = allContents.next(); if (currentObject.eClass().equals(selectedEObject.eClass())) { List<IMarker> markersForCurrentObject = Markers.INSTANCE.getMarkers(FSMLEcoreUtil.getFSMLId(currentObject, null)); if (!markersForCurrentObject.isEmpty()) { markers.addAll(markersForCurrentObject); IResource resource = null; ICompilationUnit cu = null; int markerStartPos; int markerEndPos; for (int i = 0; i < markersForCurrentObject.size(); i++) { resource = markersForCurrentObject.get(i).getResource(); cu = JavaCore.createCompilationUnitFrom(FileBuffers.getWorkspaceFileAtLocation(resource.getFullPath())); ; try { markerStartPos = ((Integer) markersForCurrentObject.get(i).getAttribute(MarkerDescriptor.ATTRIBUTE_CHAR_START)).intValue(); markerEndPos = ((Integer) markersForCurrentObject.get(i).getAttribute(MarkerDescriptor.ATTRIBUTE_CHAR_END)).intValue(); CompilationUnit astRoot = null; CompilationUnit cuInCache = cuCache.get(resource.getFullPath().toString()); if (cuInCache == null) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(cu); parser.setResolveBindings(true); parser.setBindingsRecovery(true); astRoot = (CompilationUnit) parser.createAST(null); cuCache.put(resource.getFullPath().toString(), astRoot); } else { astRoot = cuInCache; } ASTNode astNode = ASTNodeSearchUtil.getAstNode(astRoot, markerStartPos, markerEndPos - markerStartPos); while (astNode != null && !(astNode instanceof MethodDeclaration)) { astNode = astNode.getParent(); } if (astNode != null) { String methodKey = ((ResolvedSourceMethod) ((MethodDeclaration) astNode).resolveBinding().getJavaElement()).getKey(); methodKey = methodKey.substring(methodKey.indexOf(";.") + 2); if (methodLocations.get(methodKey) == null) { methodLocations.put(methodKey, 1); } else { methodLocations.put(methodKey, methodLocations.get(methodKey) + 1); } methodLocationNamesForMarkers.add(methodKey); } else { methodLocationNamesForMarkers.add("N/A"); } } catch (JavaModelException e) { e.printStackTrace(); } catch (CoreException e) { e.printStackTrace(); } } } } } Set<Entry<String, Integer>> entrySet = methodLocations.entrySet(); ArrayList<Entry<String, Integer>> sortedMethodLocations = new ArrayList<Entry<String, Integer>>(); sortedMethodLocations.addAll(entrySet); Collections.sort(sortedMethodLocations, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { if (o1.getValue() > o2.getValue()) { return -1; } else if (o1.getValue() == o2.getValue()) { return 0; } else { return 1; } } }); //find the context class EObject classEObject = selectedEObject; while (classEObject != null && classEObject.eClass().getEAnnotation(JavaMappingInterpreter.CONTEXT_CLASS) == null) { classEObject = classEObject.eContainer(); } if (classEObject != null) { List<IMarker> classEObjectMarker = Markers.INSTANCE.getMarkers(FSMLEcoreUtil.getFSMLId(classEObject, null)); if (classEObjectMarker.size() > 0) { IResource resource = classEObjectMarker.get(0).getResource(); ICompilationUnit cu = JavaCore.createCompilationUnitFrom(FileBuffers.getWorkspaceFileAtLocation(resource.getFullPath())); ; ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(cu); parser.setResolveBindings(true); parser.setBindingsRecovery(true); CompilationUnit astRoot = (CompilationUnit) parser.createAST(null); for (Entry<String, Integer> entry : sortedMethodLocations) { System.out.println(entry.getKey() + "\t(" + entry.getValue() + ")"); } for (Entry<String, Integer> entry : sortedMethodLocations) { String targetMethodKey = "L" + astRoot.getPackage().getName().toString().replaceAll("\\.", "\\/") + "/" + resource.getName().replaceAll(resource.getFileExtension(), "").replaceAll("\\.", "") + ";." + entry.getKey(); ASTNode targetMethod = astRoot.findDeclaringNode(targetMethodKey); if (targetMethod != null) { try { ResolvedSourceMethod resolvedSourceMethod = ((ResolvedSourceMethod) ((MethodDeclaration) targetMethod).resolveBinding().getJavaElement()); ISourceRange sourceRange = resolvedSourceMethod.getSourceRange(); int sourceStart = resolvedSourceMethod.getSource().indexOf("{") + 2; IMarker codeLocationAssistMarker = resource.createMarker("fsml code location assist"); codeLocationAssistMarker.setAttribute(MarkerDescriptor.ATTRIBUTE_ID, targetMethodKey); codeLocationAssistMarker.setAttribute(MarkerDescriptor.ATTRIBUTE_CHAR_START, sourceRange.getOffset() + sourceStart); codeLocationAssistMarker.setAttribute(MarkerDescriptor.ATTRIBUTE_CHAR_END, sourceRange.getOffset() + sourceStart); event.data = new Marker[] { (Marker) codeLocationAssistMarker }; } catch (CoreException e) { e.printStackTrace(); } break; } } } } if (event.data == null) { event.data = new Marker[] {}; } try { IViewPart showView = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("ca.uwaterloo.gsd.fsml.codeLocationAssist.featureInstancesCodeLocatorView"); if (showView != null && showView instanceof FeatureInstancesCodeLocatorView) { ((FeatureInstancesCodeLocatorView) showView).showMarker(markers, methodLocationNamesForMarkers); } } catch (PartInitException e) { e.printStackTrace(); } }
Example 26
Project: generator-master File: JavaFileMerger.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" }) public String getMergedSource() throws ShellException, InvalidExistingFileException { NewJavaFileVisitor newJavaFileVisitor = visitNewJavaFile(); IDocument document = new Document(existingJavaSource); // delete generated stuff, and collect imports ExistingJavaFileVisitor visitor = new ExistingJavaFileVisitor(javaDocTags); CompilationUnit cu = getCompilationUnitFromSource(existingJavaSource); AST ast = cu.getAST(); cu.recordModifications(); cu.accept(visitor); TypeDeclaration typeDeclaration = visitor.getTypeDeclaration(); if (typeDeclaration == null) { throw new InvalidExistingFileException(ErrorCode.NO_TYPES_DEFINED_IN_FILE); } // reconcile the superinterfaces List<Type> newSuperInterfaces = getNewSuperInterfaces(typeDeclaration.superInterfaceTypes(), newJavaFileVisitor); for (Type newSuperInterface : newSuperInterfaces) { typeDeclaration.superInterfaceTypes().add(ASTNode.copySubtree(ast, newSuperInterface)); } // set the superclass if (newJavaFileVisitor.getSuperclass() != null) { typeDeclaration.setSuperclassType((Type) ASTNode.copySubtree(ast, newJavaFileVisitor.getSuperclass())); } else { typeDeclaration.setSuperclassType(null); } // interface or class? if (newJavaFileVisitor.isInterface()) { typeDeclaration.setInterface(true); } else { typeDeclaration.setInterface(false); } // reconcile the imports List<ImportDeclaration> newImports = getNewImports(cu.imports(), newJavaFileVisitor); for (ImportDeclaration newImport : newImports) { Name name = ast.newName(newImport.getName().getFullyQualifiedName()); ImportDeclaration newId = ast.newImportDeclaration(); newId.setName(name); cu.imports().add(newId); } TextEdit textEdit = cu.rewrite(document, null); try { textEdit.apply(document); } catch (BadLocationException e) { throw new ShellException("BadLocationException removing prior fields and methods"); } // regenerate the CompilationUnit to reflect all the deletes and changes CompilationUnit strippedCu = getCompilationUnitFromSource(document.get()); // find the top level public type declaration TypeDeclaration topLevelType = null; Iterator iter = strippedCu.types().iterator(); while (iter.hasNext()) { TypeDeclaration td = (TypeDeclaration) iter.next(); if (td.getParent().equals(strippedCu) && (td.getModifiers() & Modifier.PUBLIC) > 0) { topLevelType = td; break; } } // now add all the new methods and fields to the existing // CompilationUnit with a ListRewrite ASTRewrite rewrite = ASTRewrite.create(topLevelType.getRoot().getAST()); ListRewrite listRewrite = rewrite.getListRewrite(topLevelType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); Iterator<ASTNode> astIter = newJavaFileVisitor.getNewNodes().iterator(); int i = 0; while (astIter.hasNext()) { ASTNode node = astIter.next(); if (node.getNodeType() == ASTNode.TYPE_DECLARATION) { String name = ((TypeDeclaration) node).getName().getFullyQualifiedName(); if (visitor.containsInnerClass(name)) { continue; } } else if (node instanceof FieldDeclaration) { addExistsAnnotations((BodyDeclaration) node, visitor.getFieldAnnotations((FieldDeclaration) node)); } else if (node instanceof MethodDeclaration) { addExistsAnnotations((BodyDeclaration) node, visitor.getMethodAnnotations((MethodDeclaration) node)); } listRewrite.insertAt(node, i++, null); } textEdit = rewrite.rewriteAST(document, JavaCore.getOptions()); try { textEdit.apply(document); } catch (BadLocationException e) { throw new ShellException("BadLocationException adding new fields and methods"); } String newSource = document.get(); return newSource; }
Example 27
Project: GinTonic-master File: Refactorator.java View source code |
public TrackedStatement addAsLastStatementInMethod(MethodDeclaration method, String statement) {
Statement bindingStatement = ASTParserUtils.parseStatementAst3(statement);
Block methodBody = method.getBody();
ASTRewrite astRewrite = getAstRewrite();
ITrackedNodePosition track = astRewrite.track(bindingStatement);
ListRewrite statementsListRewrite = astRewrite.getListRewrite(methodBody, Block.STATEMENTS_PROPERTY);
statementsListRewrite.insertLast(bindingStatement, null);
int startPosition = track.getStartPosition();
int length = track.getLength();
bindingStatement.setSourceRange(startPosition, length);
return new TrackedStatement(bindingStatement, track);
}
Example 28
Project: mybatis-generator-master File: JavaFileMerger.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" }) public String getMergedSource() throws ShellException, InvalidExistingFileException { NewJavaFileVisitor newJavaFileVisitor = visitNewJavaFile(); IDocument document = new Document(existingJavaSource); // delete generated stuff, and collect imports ExistingJavaFileVisitor visitor = new ExistingJavaFileVisitor(javaDocTags); CompilationUnit cu = getCompilationUnitFromSource(existingJavaSource); AST ast = cu.getAST(); cu.recordModifications(); cu.accept(visitor); TypeDeclaration typeDeclaration = visitor.getTypeDeclaration(); if (typeDeclaration == null) { throw new InvalidExistingFileException(ErrorCode.NO_TYPES_DEFINED_IN_FILE); } // reconcile the superinterfaces List<Type> newSuperInterfaces = getNewSuperInterfaces(typeDeclaration.superInterfaceTypes(), newJavaFileVisitor); for (Type newSuperInterface : newSuperInterfaces) { typeDeclaration.superInterfaceTypes().add(ASTNode.copySubtree(ast, newSuperInterface)); } // set the superclass if (newJavaFileVisitor.getSuperclass() != null) { typeDeclaration.setSuperclassType((Type) ASTNode.copySubtree(ast, newJavaFileVisitor.getSuperclass())); } else { typeDeclaration.setSuperclassType(null); } // interface or class? if (newJavaFileVisitor.isInterface()) { typeDeclaration.setInterface(true); } else { typeDeclaration.setInterface(false); } // reconcile the imports List<ImportDeclaration> newImports = getNewImports(cu.imports(), newJavaFileVisitor); for (ImportDeclaration newImport : newImports) { Name name = ast.newName(newImport.getName().getFullyQualifiedName()); ImportDeclaration newId = ast.newImportDeclaration(); newId.setName(name); cu.imports().add(newId); } TextEdit textEdit = cu.rewrite(document, null); try { textEdit.apply(document); } catch (BadLocationException e) { throw new ShellException("BadLocationException removing prior fields and methods"); } // regenerate the CompilationUnit to reflect all the deletes and changes CompilationUnit strippedCu = getCompilationUnitFromSource(document.get()); // find the top level public type declaration TypeDeclaration topLevelType = null; Iterator iter = strippedCu.types().iterator(); while (iter.hasNext()) { TypeDeclaration td = (TypeDeclaration) iter.next(); if (td.getParent().equals(strippedCu) && (td.getModifiers() & Modifier.PUBLIC) > 0) { topLevelType = td; break; } } // now add all the new methods and fields to the existing // CompilationUnit with a ListRewrite ASTRewrite rewrite = ASTRewrite.create(topLevelType.getRoot().getAST()); ListRewrite listRewrite = rewrite.getListRewrite(topLevelType, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); Iterator<ASTNode> astIter = newJavaFileVisitor.getNewNodes().iterator(); int i = 0; while (astIter.hasNext()) { ASTNode node = astIter.next(); if (node.getNodeType() == ASTNode.TYPE_DECLARATION) { String name = ((TypeDeclaration) node).getName().getFullyQualifiedName(); if (visitor.containsInnerClass(name)) { continue; } } else if (node instanceof FieldDeclaration) { addExistsAnnotations((BodyDeclaration) node, visitor.getFieldAnnotations((FieldDeclaration) node)); } else if (node instanceof MethodDeclaration) { addExistsAnnotations((BodyDeclaration) node, visitor.getMethodAnnotations((MethodDeclaration) node)); } listRewrite.insertAt(node, i++, null); } textEdit = rewrite.rewriteAST(document, JavaCore.getOptions()); try { textEdit.apply(document); } catch (BadLocationException e) { throw new ShellException("BadLocationException adding new fields and methods"); } String newSource = document.get(); return newSource; }
Example 29
Project: Clean-Code-Method-Sorter-master File: BodyDeclarationComparator.java View source code |
/** * This comparator follows the contract defined in * CompilationUnitSorter.sort. * * @see Comparator#compare(java.lang.Object, java.lang.Object) * @see CompilationUnitSorter#sort(int, * org.eclipse.jdt.core.ICompilationUnit, int[], java.util.Comparator, * int, org.eclipse.core.runtime.IProgressMonitor) */ @Override public int compare(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) { if (isSortPreserved(bodyDeclaration1) && isSortPreserved(bodyDeclaration2)) { final int preservedOrder = preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); logger.trace("Keeping preserved order: [{}] : [{}] = " + preservedOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return preservedOrder; } final int cat1 = category(bodyDeclaration1); final int cat2 = category(bodyDeclaration2); if (cat1 != cat2) { final int categoryOrder = cat1 - cat2; logger.trace("Keeping category order: [{}] : [{}] = " + categoryOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return categoryOrder; } if (bodyDeclaration1.getNodeType() == ASTNode.METHOD_DECLARATION) { final MethodDeclaration method1 = (MethodDeclaration) bodyDeclaration1; final MethodDeclaration method2 = (MethodDeclaration) bodyDeclaration2; final Signature signature1 = new Signature(method1); final Signature signature2 = new Signature(method2); if (this.knownMethodSignatures.contains(signature1) && this.knownMethodSignatures.contains(signature2)) { final int compare = this.methodDeclarationComparator.compare(signature1, signature2); logger.trace("Comparing methods [{}] : [{}] = " + compare, signature1, signature2); if (compare == 0) logger.warn("No absolute compare value between [{}] and [{}]", signature1, signature2); return compare; } logger.warn("A method signature was not known!"); logger.warn("{} known={}", signature1, this.knownMethodSignatures.contains(signature1)); logger.warn("{} known={}", signature2, this.knownMethodSignatures.contains(signature2)); } final int relativeOrder = preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); logger.trace("Keeping relative order: [{}] : [{}]= " + relativeOrder, bodyDeclaration1.toString(), bodyDeclaration2.toString()); return relativeOrder; }
Example 30
Project: Diver-master File: JavaMessageGrouper.java View source code |
public IMessageGrouping[] calculateGroups2(UMLSequenceViewer viewer, Object activationElement, Object[] children) {
HashMap<ASTNode, MappedMessageGrouping> groups = new HashMap<ASTNode, MappedMessageGrouping>();
if (!(activationElement instanceof IAdaptable)) {
return new IMessageGrouping[0];
}
ASTNode activationNode = (ASTNode) ((IAdaptable) activationElement).getAdapter(ASTNode.class);
if (!(activationNode instanceof MethodDeclaration)) {
return new IMessageGrouping[0];
}
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof IAdaptable) {
ASTNode messageNode = (ASTNode) ((IAdaptable) children[i]).getAdapter(ASTNode.class);
if (messageNode != null) {
ASTNode currentParent = messageNode.getParent();
while (currentParent != null && currentParent != activationNode) {
ASTNode block = null;
String text = null;
Color c = null;
Color bc = null;
String expressionString = "";
switch(currentParent.getNodeType()) {
case ASTNode.IF_STATEMENT:
block = checkIfSide((IfStatement) currentParent, messageNode);
if (block != null && block == ((IfStatement) currentParent).getElseStatement()) {
text = "else";
} else if (block == ((IfStatement) currentParent).getThenStatement()) {
text = "if (" + ((IfStatement) currentParent).getExpression().toString() + ")";
}
c = ISketchColorConstants.CONDITION_FG;
bc = ISketchColorConstants.CONDITION_FG;
break;
case ASTNode.WHILE_STATEMENT:
if (((WhileStatement) currentParent).getExpression() != null) {
expressionString = ((WhileStatement) currentParent).getExpression().toString();
}
text = "while (" + expressionString + ")";
block = currentParent;
c = ISketchColorConstants.LOOP_FG;
bc = ISketchColorConstants.LOOP_BG;
break;
case ASTNode.FOR_STATEMENT:
if (((ForStatement) currentParent).getExpression() != null) {
expressionString = ((ForStatement) currentParent).getExpression().toString();
} else {
expressionString = ";;";
}
text = "for (" + expressionString + ")";
block = currentParent;
c = ISketchColorConstants.LOOP_FG;
bc = ISketchColorConstants.LOOP_BG;
break;
case ASTNode.TRY_STATEMENT:
text = "try";
block = currentParent;
c = ISketchColorConstants.ERROR_FG;
bc = ISketchColorConstants.ERROR_BG;
break;
case ASTNode.CATCH_CLAUSE:
text = "catch (" + ((CatchClause) currentParent).getException().toString() + ")";
block = currentParent;
c = ISketchColorConstants.ERROR_FG;
bc = ISketchColorConstants.ERROR_BG;
break;
case ASTNode.DO_STATEMENT:
text = "do while (" + ((DoStatement) currentParent).getExpression().toString() + ")";
block = currentParent;
c = ISketchColorConstants.LOOP_FG;
bc = ISketchColorConstants.LOOP_BG;
break;
}
if (text != null) {
MappedMessageGrouping grouping = groups.get(block);
if (grouping == null) {
grouping = new MappedMessageGrouping(activationElement, i, 1, text, block);
grouping.setBackground(bc);
grouping.setForeground(c);
groups.put(block, grouping);
} else {
int length = (i - grouping.getOffset()) + 1;
grouping.setLength(length);
}
}
currentParent = currentParent.getParent();
}
}
}
}
ArrayList<MappedMessageGrouping> groupList = new ArrayList<MappedMessageGrouping>(groups.values());
Collections.sort(groupList, new Comparator<MappedMessageGrouping>() {
public int compare(MappedMessageGrouping o1, MappedMessageGrouping o2) {
ASTNode n1 = (ASTNode) o1.getKey();
ASTNode n2 = (ASTNode) o2.getKey();
int diff = n1.getStartPosition() - n2.getStartPosition();
if (diff == 0) {
diff = (n1.getStartPosition() + n1.getLength()) - (n2.getStartPosition() + n2.getLength());
}
return diff;
}
});
return groupList.toArray(new IMessageGrouping[groupList.size()]);
}
Example 31
Project: eclipse-jmockit-master File: MockMethodCompletionProposal.java View source code |
@Override
protected final boolean updateReplacementString(final IDocument document, final char trigger, final int offset, final ImportRewrite importRw) throws CoreException, BadLocationException {
try {
Document recoveredDocument = new Document();
CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
initContext(offset, importRw, unit);
ASTNode node = NodeFinder.perform(unit, offset, 1);
AST ast = unit.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
CodeGenerationSettings settings = getCodeGenSettings();
MethodDeclaration stub = createMockMethodStub(ast, rewrite, settings);
String methodDeclarationText = generateMethodDeclaration(document, recoveredDocument, node, rewrite, settings, stub);
setReplacementString(methodDeclarationText);
} catch (Exception exception) {
Activator.log(exception);
}
return true;
}
Example 32
Project: FindBug-for-Domino-Designer-master File: CreateDoPrivilegedBlockResolution.java View source code |
protected void updateVariableReferences(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
Assert.isNotNull(rewrite);
Assert.isNotNull(classLoaderCreation);
MethodDeclaration method = findMethodDeclaration(classLoaderCreation);
if (method != null) {
final Set<String> variableReferences = findVariableReferences(classLoaderCreation.arguments());
if (!variableReferences.isEmpty()) {
updateMethodParams(rewrite, variableReferences, method.parameters());
updateLocalVariableDeclarations(rewrite, variableReferences, method.getBody());
}
}
}
Example 33
Project: findbugs-rcp-master File: CreateDoPrivilegedBlockResolution.java View source code |
protected void updateVariableReferences(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
assert rewrite != null;
assert classLoaderCreation != null;
MethodDeclaration method = findMethodDeclaration(classLoaderCreation);
if (method != null) {
final Set<String> variableReferences = findVariableReferences(classLoaderCreation.arguments());
if (!variableReferences.isEmpty()) {
updateMethodParams(rewrite, variableReferences, method.parameters());
updateLocalVariableDeclarations(rewrite, variableReferences, method.getBody());
}
}
}
Example 34
Project: flower-platform-3-master File: JavaModelAdapterFactorySet.java View source code |
@Override public void initialize(Resource astCache, String limitedPath, boolean useUIDs) { super.initialize(astCache, limitedPath, useUIDs); // right - AST rightFactory = new ModelAdapterFactory(); IFileAccessController fileAccessController = EditorPlugin.getInstance().getFileAccessController(); // folder adapter FolderModelAdapter folderModelAdapter = (FolderModelAdapter) createAstModelAdapter(new FolderModelAdapter()); folderModelAdapter.setLimitedPath(limitedPath); rightFactory.addModelAdapter(fileAccessController.getFileClass(), folderModelAdapter, "", CodeSyncPlugin.FOLDER); // java specific adapters JavaFileModelAdapter fileModelAdapter = (JavaFileModelAdapter) createAstModelAdapter(new JavaFileModelAdapter()); rightFactory.addModelAdapter(fileAccessController.getFileClass(), fileModelAdapter, CodeSyncCodeJavaPlugin.TECHNOLOGY, CodeSyncPlugin.FILE); rightFactory.addModelAdapter(AbstractTypeDeclaration.class, createAstModelAdapter(new JavaTypeModelAdapter()), JavaTypeModelAdapter.CLASS); rightFactory.addModelAdapter(FieldDeclaration.class, createAstModelAdapter(new JavaAttributeModelAdapter()), JavaAttributeModelAdapter.ATTRIBUTE); rightFactory.addModelAdapter(MethodDeclaration.class, createAstModelAdapter(new JavaOperationModelAdapter()), JavaOperationModelAdapter.OPERATION); rightFactory.addModelAdapter(SingleVariableDeclaration.class, createAstModelAdapter(new JavaParameterModelAdapter()), JavaParameterModelAdapter.PARAMETER); rightFactory.addModelAdapter(Annotation.class, createAstModelAdapter(new JavaAnnotationModelAdapter()), JavaAnnotationModelAdapter.ANNOTATION); rightFactory.addModelAdapter(Modifier.class, createAstModelAdapter(new JavaModifierModelAdapter()), JavaModifierModelAdapter.MODIFIER); rightFactory.addModelAdapter(MemberValuePair.class, createAstModelAdapter(new JavaMemberValuePairModelAdapter()), JavaMemberValuePairModelAdapter.MEMBER_VALUE_PAIR); rightFactory.addModelAdapter(EnumConstantDeclaration.class, createAstModelAdapter(new JavaEnumConstantDeclarationModelAdapter()), JavaEnumConstantDeclarationModelAdapter.ENUM_CONSTANT); rightFactory.addModelAdapter(AnnotationTypeMemberDeclaration.class, createAstModelAdapter(new JavaAnnotationTypeMemberDeclarationModelAdapter()), JavaAnnotationTypeMemberDeclarationModelAdapter.ANNOTATION_MEMBER); rightFactory.addModelAdapter(String.class, createAstModelAdapter(new StringModelAdapter()), "String"); // ancestor - CodeSyncElements this.ancestorFactory = createCodeSyncModelAdapterFactory(null, false); // left - CodeSyncElements leftFactory = createCodeSyncModelAdapterFactory(astCache, true); // feature providers CodeSyncElementFeatureProvider featureProvider = new CodeSyncElementFeatureProvider(); addFeatureProvider(fileAccessController.getFileClass(), featureProvider); addFeatureProvider(CodeSyncPlugin.FOLDER, featureProvider); addFeatureProvider(fileAccessController.getFileClass(), featureProvider); addFeatureProvider(CodeSyncPlugin.FILE, featureProvider); JavaTypeFeatureProvider typeFeatureProvider = new JavaTypeFeatureProvider(); addFeatureProvider(AbstractTypeDeclaration.class, typeFeatureProvider); addFeatureProvider(CLASS, typeFeatureProvider); addFeatureProvider(INTERFACE, typeFeatureProvider); addFeatureProvider(ENUM, typeFeatureProvider); addFeatureProvider(ANNOTATION, typeFeatureProvider); JavaAttributeFeatureProvider attributeFeatureProvider = new JavaAttributeFeatureProvider(); addFeatureProvider(FieldDeclaration.class, attributeFeatureProvider); addFeatureProvider(ATTRIBUTE, attributeFeatureProvider); JavaOperationFeatureProvider operationFeatureProvider = new JavaOperationFeatureProvider(); addFeatureProvider(MethodDeclaration.class, operationFeatureProvider); addFeatureProvider(OPERATION, operationFeatureProvider); JavaEnumConstantDeclarationFeatureProvider enumCtFeatureProvider = new JavaEnumConstantDeclarationFeatureProvider(); addFeatureProvider(EnumConstantDeclaration.class, enumCtFeatureProvider); addFeatureProvider(ENUM_CONSTANT, enumCtFeatureProvider); JavaAnnotationTypeMemberDeclarationFeatureProvider annotationMemberFeatureProvider = new JavaAnnotationTypeMemberDeclarationFeatureProvider(); addFeatureProvider(AnnotationTypeMemberDeclaration.class, annotationMemberFeatureProvider); addFeatureProvider(ANNOTATION_MEMBER, annotationMemberFeatureProvider); JavaAnnotationFeatureProvider annotationFeatureProvider = new JavaAnnotationFeatureProvider(); addFeatureProvider(Annotation.class, annotationFeatureProvider); addFeatureProvider(com.crispico.flower.mp.model.astcache.code.Annotation.class, annotationFeatureProvider); JavaMemberValuePairFeatureProvider annotationValueFeatureProvider = new JavaMemberValuePairFeatureProvider(); addFeatureProvider(MemberValuePair.class, annotationValueFeatureProvider); addFeatureProvider(AnnotationValue.class, annotationValueFeatureProvider); JavaModifierFeatureProvider modifierFeatureProvider = new JavaModifierFeatureProvider(); addFeatureProvider(Modifier.class, modifierFeatureProvider); addFeatureProvider(com.crispico.flower.mp.model.astcache.code.Modifier.class, modifierFeatureProvider); JavaParameterFeatureProvider parameterFeatureProvider = new JavaParameterFeatureProvider(); addFeatureProvider(SingleVariableDeclaration.class, parameterFeatureProvider); addFeatureProvider(Parameter.class, parameterFeatureProvider); addFeatureProvider(String.class, new StringFeatureProvider()); }
Example 35
Project: Green-UML-master File: RelationshipModel.java View source code |
/** * @return A representation of the cardinality. * * @throws JavaModelException * * @author Gene Wang */ @SuppressWarnings("boxing") public String getCardinality() throws JavaModelException { final String NPE = "Node is not a child of a MethodDeclaration or Initializer block."; final int INF = 999999; boolean isGeneric = false; int min = INF; int max = 0; int constructors = 0; int uConstructors = 0; Map<ASTNode, Integer> cardinality = new HashMap<ASTNode, Integer>(); RelationshipKind flags = PlugIn.getRelationshipGroup(getPartClass()).getFlags(); if (flags.equals(Single)) { return "1"; } if (flags.equals(Cumulative)) { for (Relationship relationship : _relationships) { ASTNode locator = relationship.getFeatures().get(0); while ((!(locator instanceof MethodDeclaration) && !(locator instanceof Initializer)) && locator != null) { locator = locator.getParent(); } if (locator == null) { //ever happen, so throw an NPE here just in case throw new NullPointerException(NPE); } if (locator.getNodeType() == METHOD_DECLARATION) { isGeneric = !((MethodDeclaration) locator).isConstructor(); } else if (locator.getNodeType() == INITIALIZER) { //cannot have higher cardinality return "1"; } } } for (IMethod method : _sourceType.getMethods()) { if (method.isConstructor()) { constructors++; } } for (Relationship relationship : _relationships) { ASTNode locator = relationship.getFeatures().get(0); int card; while ((!(locator instanceof MethodDeclaration) && !(locator instanceof Initializer)) && locator != null) { locator = locator.getParent(); } if (locator == null) { throw new NullPointerException(NPE); } if (cardinality.get(locator) == null) { card = 0; uConstructors++; } else { card = cardinality.get(locator); } if ((locator.getNodeType() == METHOD_DECLARATION) && ((MethodDeclaration) locator).isConstructor()) { if (relationship.isGeneric()) { isGeneric = true; cardinality.put(locator, card + relationship.getFeatures().size() - 2); } else { cardinality.put(locator, card + 1); } } } for (Integer card : cardinality.values()) { if (card < min) { min = card; } if (card > max) { max = card; } } if (uConstructors < constructors) { min = 0; } if (min == INF) { min = 0; } if (isGeneric) { return min + "..*"; } else if (min == max) { return "" + min; } else { return min + ".." + max; } }
Example 36
Project: groovy-eclipse-master File: CreateMethodOperation.java View source code |
/** * Returns the type signatures of the parameter types of the * current <code>MethodDeclaration</code> */ protected String[] convertASTMethodTypesToSignatures() { if (this.parameterTypes == null) { if (this.createdNode != null) { MethodDeclaration methodDeclaration = (MethodDeclaration) this.createdNode; List parameters = methodDeclaration.parameters(); int size = parameters.size(); this.parameterTypes = new String[size]; Iterator iterator = parameters.iterator(); // convert the AST types to signatures for (int i = 0; i < size; i++) { SingleVariableDeclaration parameter = (SingleVariableDeclaration) iterator.next(); String typeSig = Util.getSignature(parameter.getType()); int extraDimensions = parameter.getExtraDimensions(); if (methodDeclaration.isVarargs() && i == size - 1) extraDimensions++; this.parameterTypes[i] = Signature.createArraySignature(typeSig, extraDimensions); } } } return this.parameterTypes; }
Example 37
Project: mapstruct-eclipse-master File: PropertyNameProposalCollector.java View source code |
@Override
public void endVisit(MethodDeclaration node) {
if (!inMethod) {
return;
}
String pathWithoutLastElement = getPathWithoutLastElement(givenPrefix);
Deque<String> pathToProposedType;
if (pathWithoutLastElement.isEmpty()) {
pathToProposedType = new LinkedList<String>();
proposalPrefix = "";
} else {
pathToProposedType = new LinkedList<String>(Arrays.asList(pathWithoutLastElement.split("\\.")));
proposalPrefix = pathWithoutLastElement + ".";
}
String propertyPrefix = getLastPathElement(givenPrefix);
ITypeBinding proposalType = getTypeForPropertyProposals(node, pathToProposedType, propertyPrefix);
if (proposalType != null) {
proposePropertiesIfPrefixMatches(propertyPrefix, proposalType);
}
}
Example 38
Project: ofbiz-eclipse-project-explorer-master File: JavaHelper.java View source code |
@Override
public boolean visit(final MethodDeclaration node) {
final IMethodBinding resolveMethodBinding = node.resolveBinding();
if (resolveMethodBinding == null) {
return true;
}
String methodName = resolveMethodBinding.getName();
if (methodName.equals(invoke)) {
if (parameterNumber == -1 || parameterNumber == resolveMethodBinding.getParameterTypes().length) {
final IFile file = (IFile) findType.getResource();
hyperlinkMarkers.add(new HyperlinkMarker() {
@Override
public String getTypeLabel() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getHyperlinkText() {
StringBuilder types = new StringBuilder("");
int i = 0;
for (ITypeBinding type : resolveMethodBinding.getParameterTypes()) {
if (i != 0) {
types.append(", ");
}
types.append(type.getName());
i++;
}
return "Goto java: " + invoke + "parameters: (" + types.toString() + ")";
}
@Override
public void open() {
try {
IMarker marker = file.createMarker(Plugin.TEXT_MARKER);
marker.setAttribute(IMarker.LINE_NUMBER, parse.getLineNumber(node.getStartPosition()));
IDE.openEditor(GoToFile.getActiveWorkbenchPage(), marker);
} catch (CoreException e) {
}
}
@Override
public IRegion getHyperlinkRegion() {
try {
if (lineNumber == -1) {
return null;
}
return new Region(doc.getLineOffset(lineNumber) + offset - 1, length + 1);
} catch (BadLocationException e) {
e.printStackTrace();
}
return null;
}
});
}
}
return true;
}
Example 39
Project: org.revisionfilter-master File: CreateDoPrivilegedBlockResolution.java View source code |
protected void updateVariableReferences(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
assert rewrite != null;
assert classLoaderCreation != null;
MethodDeclaration method = findMethodDeclaration(classLoaderCreation);
if (method != null) {
final Set<String> variableReferences = findVariableReferences(classLoaderCreation.arguments());
if (!variableReferences.isEmpty()) {
updateMethodParams(rewrite, variableReferences, method.parameters());
updateLocalVariableDeclarations(rewrite, variableReferences, method.getBody());
}
}
}
Example 40
Project: platform_tools_motodev-master File: ContentProviderClass.java View source code |
/**
* Adds the delete method to the content provider class
*/
@SuppressWarnings("unchecked")
private void addDeleteMethod() {
final String SELECTION_PARAM = "selection";
final String SELECTION_ARGS_PARAM = "selectionArgs";
MethodDeclaration method = ast.newMethodDeclaration();
method.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
method.setReturnType2(ast.newPrimitiveType(PrimitiveType.INT));
method.setName(ast.newSimpleName(DELETE_METHOD_NAME));
addMethodParameter(method, getName(URI_CLASS).toLowerCase(), uriType());
addMethodParameter(method, SELECTION_PARAM, stringType());
addMethodParameter(method, SELECTION_ARGS_PARAM, stringArrayType());
addEmptyBlock(method);
classDecl.bodyDeclarations().add(method);
addComment(method, CodeUtilsNLS.MODEL_ContentProviderClass_DeleteMethodDescription);
addMethodReference(method, CP_SUPERCLASS, DELETE_METHOD_NAME, new Type[] { uriType(), stringType(), stringArrayType() });
}
Example 41
Project: substeps-eclipse-plugin-master File: JavaDocVisitor.java View source code |
@SuppressWarnings("unchecked") @Override public void endVisit(final MethodDeclaration node) { // TODO Auto-generated method stub super.endVisit(node); if (isCorrectMethod(node)) { final List<Object> parameterProperties = ((List<Object>) node.getStructuralProperty(MethodDeclaration.PARAMETERS_PROPERTY)); for (final Object prop : parameterProperties) { if (prop instanceof SingleVariableDeclaration) { this.parameterNames.add(((SingleVariableDeclaration) prop).getName().toString()); } } } }
Example 42
Project: tymore-master File: BindingsResolver.java View source code |
public void resolveBindings(ASTNode node) { if (node instanceof AbstractTypeDeclaration) resolveBindings((AbstractTypeDeclaration) node); else if (node instanceof AnnotationTypeMemberDeclaration) resolveBindings((AnnotationTypeMemberDeclaration) node); else if (node instanceof AnonymousClassDeclaration) resolveBindings((AnonymousClassDeclaration) node); else if (node instanceof EnumConstantDeclaration) resolveBindings((EnumConstantDeclaration) node); else if (node instanceof Expression) resolveBindings((Expression) node); else if (node instanceof FieldDeclaration) resolveBindings((FieldDeclaration) node); else if (node instanceof ImportDeclaration) resolveBindings((ImportDeclaration) node); else if (node instanceof MemberRef) resolveBindings((MemberRef) node); else if (node instanceof MethodDeclaration) resolveBindings((MethodDeclaration) node); else if (node instanceof MethodRef) resolveBindings((MethodRef) node); else if (node instanceof PackageDeclaration) resolveBindings((PackageDeclaration) node); else if (node instanceof Statement) resolveBindings((Statement) node); else if (node instanceof Type) resolveBindings((Type) node); else if (node instanceof TypeParameter) resolveBindings((TypeParameter) node); else if (node instanceof VariableDeclaration) resolveBindings((VariableDeclaration) node); }
Example 43
Project: EasyMPermission-master File: EclipsePatcher.java View source code |
private static void patchExtractInterface(ScriptManager sm) { /* Fix sourceEnding for generated nodes to avoid null pointer */ sm.addScript(ScriptBuilder.wrapMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.compiler.SourceElementNotifier", "notifySourceElementRequestor", "void", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.ImportReference")).methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.util.HashtableOfObjectToInt", "get", "int", "java.lang.Object")).wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getSourceEndFixed", "int", "int", "org.eclipse.jdt.internal.compiler.ast.ASTNode")).requestExtra(StackRequest.PARAM1).transplant().build()); /* Make sure the generated source element is found instead of the annotation */ sm.addScript(ScriptBuilder.wrapMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodDeclaration", "void", "org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite", "org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "org.eclipse.jdt.core.dom.AbstractTypeDeclaration", "org.eclipse.jdt.core.dom.MethodDeclaration")).methodToWrap(new Hook("org.eclipse.jface.text.IDocument", "get", "java.lang.String", "int", "int")).wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationSource", "java.lang.String", "java.lang.String", "java.lang.Object", "org.eclipse.jdt.core.dom.MethodDeclaration")).requestExtra(StackRequest.THIS, StackRequest.PARAM4).transplant().build()); /* get real generated node in stead of a random one generated by the annotation */ sm.addScript(ScriptBuilder.replaceMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMemberDeclarations")).target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComments")).methodToReplace(new Hook("org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil", "getMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")).replacementMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")).transplant().build()); /* Do not add @Override's for generated methods */ sm.addScript(ScriptBuilder.exitEarly().target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ListRewrite", "insertFirst")).decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isListRewriteOnGeneratedNode", "boolean", "org.eclipse.jdt.core.dom.rewrite.ListRewrite")).request(StackRequest.THIS).transplant().build()); /* Do not add comments for generated methods */ sm.addScript(ScriptBuilder.exitEarly().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComment")).decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")).request(StackRequest.PARAM2).transplant().build()); }
Example 44
Project: lombok-master File: EclipsePatcher.java View source code |
private static void patchExtractInterface(ScriptManager sm) { /* Fix sourceEnding for generated nodes to avoid null pointer */ sm.addScript(ScriptBuilder.wrapMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.compiler.SourceElementNotifier", "notifySourceElementRequestor", "void", "org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.ImportReference")).methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.util.HashtableOfObjectToInt", "get", "int", "java.lang.Object")).wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getSourceEndFixed", "int", "int", "org.eclipse.jdt.internal.compiler.ast.ASTNode")).requestExtra(StackRequest.PARAM1).transplant().build()); /* Make sure the generated source element is found instead of the annotation */ sm.addScript(ScriptBuilder.wrapMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodDeclaration", "void", "org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite", "org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "org.eclipse.jdt.core.dom.AbstractTypeDeclaration", "org.eclipse.jdt.core.dom.MethodDeclaration")).methodToWrap(new Hook("org.eclipse.jface.text.IDocument", "get", "java.lang.String", "int", "int")).wrapMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationSource", "java.lang.String", "java.lang.String", "java.lang.Object", "org.eclipse.jdt.core.dom.MethodDeclaration")).requestExtra(StackRequest.THIS, StackRequest.PARAM4).transplant().build()); /* get real generated node in stead of a random one generated by the annotation */ sm.addScript(ScriptBuilder.replaceMethodCall().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMemberDeclarations")).target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComments")).methodToReplace(new Hook("org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil", "getMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")).replacementMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "getRealMethodDeclarationNode", "org.eclipse.jdt.core.dom.MethodDeclaration", "org.eclipse.jdt.core.IMethod", "org.eclipse.jdt.core.dom.CompilationUnit")).transplant().build()); /* Do not add @Override's for generated methods */ sm.addScript(ScriptBuilder.exitEarly().target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ListRewrite", "insertFirst")).decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isListRewriteOnGeneratedNode", "boolean", "org.eclipse.jdt.core.dom.rewrite.ListRewrite")).request(StackRequest.THIS).transplant().build()); /* Do not add comments for generated methods */ sm.addScript(ScriptBuilder.exitEarly().target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor", "createMethodComment")).decisionMethod(new Hook("lombok.launch.PatchFixesHider$PatchFixes", "isGenerated", "boolean", "org.eclipse.jdt.core.dom.ASTNode")).request(StackRequest.PARAM2).transplant().build()); }
Example 45
Project: arquillian-eclipse-master File: ArquillianResourceHyperlinkDetector.java View source code |
@Override public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) { ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class); if (region == null || textEditor == null) return null; IEditorSite site = textEditor.getEditorSite(); if (site == null) return null; ITypeRoot javaElement = JavaUI.getEditorInputTypeRoot(textEditor.getEditorInput()); if (javaElement == null) return null; if (!ArquillianSearchEngine.isArquillianJUnitTest(javaElement.findPrimaryType(), false, false)) { return null; } CompilationUnit ast = SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null); if (ast == null) return null; ASTNode node = NodeFinder.perform(ast, region.getOffset(), 1); if (!(node instanceof StringLiteral)) return null; if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY) return null; ASTNode parent = node.getParent(); if (!(parent instanceof MethodInvocation)) { return null; } MethodInvocation methodInvocation = (MethodInvocation) parent; SimpleName name = methodInvocation.getName(); String methodName = name.getFullyQualifiedName(); if (!ArquillianUIUtil.ADD_AS_RESOURCE_METHOD.equals(methodName) && !ArquillianUIUtil.ADD_AS_MANIFEST_RESOURCE_METHOD.equals(methodName) && !ArquillianUIUtil.ADD_AS_WEB_INF_RESOURCE_METHOD.equals(methodName)) { return null; } while (parent != null) { parent = parent.getParent(); if (parent instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) parent; int modifiers = methodDeclaration.getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) { IMethodBinding binding = methodDeclaration.resolveBinding(); IMethod method = (IMethod) binding.getJavaElement(); try { String signature = method.getSignature(); if (!//$NON-NLS-1$ "()QArchive<*>;".equals(//$NON-NLS-1$ signature)) { break; } } catch (JavaModelException e) { ArquillianUIActivator.log(e); } IAnnotationBinding[] annotations = binding.getAnnotations(); for (IAnnotationBinding annotationBinding : annotations) { ITypeBinding typeBinding = annotationBinding.getAnnotationType(); if (ArquillianUtility.ORG_JBOSS_ARQUILLIAN_CONTAINER_TEST_API_DEPLOYMENT.equals(typeBinding.getQualifiedName())) { StringLiteral stringLiteral = (StringLiteral) node; String resource = stringLiteral.getLiteralValue(); IFile file = getFile(resource, javaElement); if (file != null) { int start = node.getStartPosition(); int length = node.getLength(); if (length > 2) { start++; length -= 2; } IRegion stringLiteralRegion = new Region(start, length); return new IHyperlink[] { new ArquillianResourceHyperlink(resource, stringLiteralRegion, file) }; } break; } } } } } return null; }
Example 46
Project: concurrencer-master File: AccessAnalyzerForAtomicLong.java View source code |
private boolean checkSynchronizedMethod(ASTNode node, Expression invocation, String accessType) { MethodDeclaration methodDecl = (MethodDeclaration) ASTNodes.getParent(node, MethodDeclaration.class); int modifiers = methodDecl.getModifiers(); if (Modifier.isSynchronized(modifiers)) { List methodBodyStatements = methodDecl.getBody().statements(); if (methodBodyStatements.size() == 1) { ModifierRewrite methodRewriter = ModifierRewrite.create(fRewriter, methodDecl); int synchronized1 = Modifier.SYNCHRONIZED; synchronized1 = ~synchronized1; int newModifiersWithoutSync = modifiers & synchronized1; methodRewriter.setModifiers(newModifiersWithoutSync, createGroupDescription(REMOVE_SYNCHRONIZED_MODIFIER)); } fRewriter.replace(node, invocation, createGroupDescription(accessType)); return true; } return false; }
Example 47
Project: eclipse-pmd-master File: UseUtilityClassQuickFix.java View source code |
@SuppressWarnings("unchecked") private void addPrivateConstructor(final TypeDeclaration typeDeclaration, final ASTRewrite rewrite) { final AST ast = typeDeclaration.getAST(); final MethodDeclaration constructor = (MethodDeclaration) ast.createInstance(MethodDeclaration.class); constructor.setConstructor(true); final Modifier modifier = (Modifier) ast.createInstance(Modifier.class); modifier.setKeyword(ModifierKeyword.PRIVATE_KEYWORD); constructor.modifiers().add(modifier); constructor.setName(ASTUtil.copy(typeDeclaration.getName())); final Block body = (Block) ast.createInstance(Block.class); constructor.setBody(body); final ListRewrite statementRewrite = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY); final ASTNode comment = rewrite.createStringPlaceholder("// hide constructor of utility class", ASTNode.EMPTY_STATEMENT); statementRewrite.insertFirst(comment, null); final int position = findConstructorPosition(typeDeclaration); final ListRewrite bodyDeclarationRewrite = rewrite.getListRewrite(typeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); bodyDeclarationRewrite.insertAt(constructor, position, null); }
Example 48
Project: Grindstone-master File: BindingTestCase.java View source code |
public void testMethodInInterface() throws Exception { String source = "interface Foo { void bar(); }" + "class Bar implements Foo { public void bar() {} }"; CompilationUnit ast = createAST(source); MethodDeclaration fooBar = getType(ast, "Foo").getMethods()[0]; MethodDeclaration barBar = getType(ast, "Bar").getMethods()[0]; assertMethodDefinition(fooBar, barBar); }
Example 49
Project: jbosstools-arquillian-master File: FixInvalidDeploymentMethodMarkerResolution.java View source code |
/* (non-Javadoc) * @see org.eclipse.ui.IMarkerResolution#run(org.eclipse.core.resources.IMarker) */ @Override public void run(IMarker marker) { CompilationUnit root = getAST(); final int markerStart = marker.getAttribute(IMarker.CHAR_START, 0); final int markerEnd = marker.getAttribute(IMarker.CHAR_END, 0); if (root == null || markerStart <= 0 || markerEnd <= markerStart) { ArquillianUIActivator.logWarning("Invalid Deployment method resolution"); return; } root.accept(new ASTVisitor() { @Override public boolean visit(MethodDeclaration node) { int startPosition = node.getStartPosition(); int length = node.getLength(); if (markerStart >= startPosition && markerEnd <= startPosition + length) { deploymentMethod = node; node.resolveBinding(); return false; } return true; } }); if (deploymentMethod == null) { ArquillianUIActivator.logWarning("Invalid Deployment method resolution"); return; } ASTRewrite rewriter = ASTRewrite.create(deploymentMethod.getAST()); MethodDeclaration newMethodDeclaration = (MethodDeclaration) rewriter.createCopyTarget(deploymentMethod); ModifierRewrite listRewrite = ModifierRewrite.create(rewriter, deploymentMethod); listRewrite.setModifiers(Modifier.PUBLIC | Modifier.STATIC, Modifier.PRIVATE | Modifier.PROTECTED, null); rewriter.replace(deploymentMethod, newMethodDeclaration, null); IDocumentProvider provider = new TextFileDocumentProvider(); try { provider.connect(file); IDocument doc = provider.getDocument(file); TextEdit edits = rewriter.rewriteAST(doc, icu.getJavaProject().getOptions(true)); edits.apply(doc); CodeFormatter formatter = ToolFactory.createCodeFormatter(icu.getJavaProject().getOptions(true)); TextEdit formatEdits = formatter.format(CodeFormatter.K_COMPILATION_UNIT, doc.get(), edits.getOffset(), edits.getLength(), 1, TextUtilities.getDefaultLineDelimiter(doc)); formatEdits.apply(doc); icu.save(new NullProgressMonitor(), true); if (save) { provider.saveDocument(new NullProgressMonitor(), file, doc, false); } } catch (IllegalArgumentException e) { ArquillianUIActivator.log(e); } catch (MalformedTreeException e) { ArquillianUIActivator.log(e); } catch (CoreException e) { ArquillianUIActivator.log(e); } catch (BadLocationException e) { ArquillianUIActivator.log(e); } finally { provider.disconnect(file); } }
Example 50
Project: KissMDA-master File: JdtHelperTest.java View source code |
@Test
public void testCreateReturnType() {
Map<String, String> javaTypes = createJavaTypes();
when(dataTypeUtils.getJavaTypes()).thenReturn(javaTypes);
TypeDeclaration td = ast.newTypeDeclaration();
MethodDeclaration md = ast.newMethodDeclaration();
String umlTypeName = "Collection";
String umlQualifiedTypeName = "Validation Profile::OCL Library::Collection";
String sourceDirectoryPackageName = "Data";
jdtHelper.createReturnType(ast, td, md, umlTypeName, umlQualifiedTypeName, sourceDirectoryPackageName);
assertEquals("java.util.Collection", md.getReturnType2().toString());
}
Example 51
Project: PerformanceHat-master File: CriticalLoopBuilderParticipant.java View source code |
/** * {@inheritDoc} */ @Override protected void buildFile(final FeedbackJavaProject project, final FeedbackJavaFile javaFile, final CompilationUnit astRoot) { astRoot.accept(new ASTVisitor() { private MethodDeclaration currentMethodDeclaration; @Override public boolean visit(final MethodDeclaration node) { currentMethodDeclaration = node; return true; } @Override public boolean visit(final EnhancedForStatement foreachStatement) { final Optional<CollectionSource> collectionSource = new CollectionSourceDetector().getSource(foreachStatement, currentMethodDeclaration); if (collectionSource.isPresent()) { final Procedure procedure = collectionSource.get().getProcedure(); final String[] arguments = procedure.getArguments().toArray(new String[procedure.getArguments().size()]); final Double averageSize = feedbackHandlerClient.collectionSize(project, procedure.getClassName(), procedure.getName(), arguments, collectionSource.get().getPosition()); final Map<Procedure, Double> procedureExecutionTimes = getProcedureExecutionTimes(foreachStatement); final Double avgExecTimePerIteration = getAverageExecutionTime(procedureExecutionTimes); if (averageSize != null && avgExecTimePerIteration != null) { final Double avgTotalExecTime = averageSize * avgExecTimePerIteration; final double threshold = project.getFeedbackProperties().getDouble(PerformanceFeedbackProperties.TRESHOLD__LOOPS, PerformanceConfigs.DEFAULT_THRESHOLD_LOOPS); if (avgTotalExecTime >= threshold) { final int startPosition = foreachStatement.getParameter().getStartPosition(); final Expression expression = foreachStatement.getExpression(); final int endPosition = expression.getStartPosition() + expression.getLength(); final int line = astRoot.getLineNumber(startPosition); final String avgIterationsText = new Double(Numbers.round(averageSize, DECIMAL_PLACES)).toString(); final String avgExecTimePerIterationText = TimeValues.toText(avgExecTimePerIteration, DECIMAL_PLACES); final String avgTotalExecTimeText = TimeValues.toText(avgTotalExecTime, DECIMAL_PLACES); final String msg = String.format(MESSAGE_PATTERN, avgTotalExecTimeText, avgIterationsText); final Map<String, Object> context = Maps.newHashMap(); context.put(AVG_TOTAL, avgTotalExecTimeText); context.put(AVG_INTERATIONS, avgIterationsText); context.put(AVG_TIME_PER_ITERATION, avgExecTimePerIterationText); context.put(PROCEDURE_EXECUTIONS, getProcedureExecutionData(procedureExecutionTimes)); final String desc = templateHandler.getContent(LOOP, context); final MarkerSpecification markerSpecification = MarkerSpecification.of(Ids.PERFORMANCE_MARKER, new MarkerPosition(line, startPosition, endPosition), IMarker.SEVERITY_WARNING, PerformanceMarkerTypes.COLLECTION_SIZE, msg).and(MarkerAttributes.DESCRIPTION, desc); addMarker(javaFile, markerSpecification); } } } return super.visit(foreachStatement); } @Override public boolean visit(final ForStatement forStatement) { // - node.updaters() return super.visit(forStatement); } private Map<Procedure, Double> getProcedureExecutionTimes(final EnhancedForStatement foreachStatement) { final List<Procedure> procedures = new ForLoopBodyVisitor().getProcedureInvocations(foreachStatement); final Map<Procedure, Double> procedureExecutionTimes = Maps.newHashMap(); for (final Procedure procedure : procedures) { final String[] arguments = procedure.getArguments().toArray(new String[procedure.getArguments().size()]); final Double avgExecTimeResponse = feedbackHandlerClient.avgExecTime(project, procedure.getClassName(), procedure.getName(), arguments); final double avgExecTime = avgExecTimeResponse != null ? avgExecTimeResponse : 0; procedureExecutionTimes.put(procedure, avgExecTime); } return procedureExecutionTimes; } private List<ProcedureExecutionData> getProcedureExecutionData(final Map<Procedure, Double> procedureExecutionTimes) { final List<ProcedureExecutionData> data = Lists.newArrayList(); for (final Map.Entry<Procedure, Double> entry : procedureExecutionTimes.entrySet()) { data.add(ProcedureExecutionData.of(entry.getKey(), entry.getValue())); } return data; } private Double getAverageExecutionTime(final Map<Procedure, Double> procedures) { double averageLoopTime = 0; for (final Entry<Procedure, Double> entry : procedures.entrySet()) { averageLoopTime += entry.getValue(); } return averageLoopTime; } }); }
Example 52
Project: process-master File: SourceUtils.java View source code |
public static List<Edit> preprocessAST(CompilationUnit cu) {
final List<Edit> edits = new ArrayList<>();
// Walk the tree
cu.accept(new ASTVisitor() {
@Override
public boolean visit(SimpleType node) {
// replace "color" with "int"
if ("color".equals(node.getName().toString())) {
edits.add(Edit.replace(node.getStartPosition(), node.getLength(), "int"));
}
return super.visit(node);
}
@Override
public boolean visit(NumberLiteral node) {
// add 'f' to floats
String s = node.getToken().toLowerCase();
if (FLOATING_POINT_LITERAL_VERIFIER.matcher(s).matches() && !s.endsWith("f") && !s.endsWith("d")) {
edits.add(Edit.insert(node.getStartPosition() + node.getLength(), "f"));
}
return super.visit(node);
}
@Override
public boolean visit(MethodDeclaration node) {
// add 'public' to methods with default visibility
int accessModifiers = node.getModifiers() & ACCESS_MODIFIERS_MASK;
if (accessModifiers == 0) {
edits.add(Edit.insert(node.getStartPosition(), "public "));
}
return super.visit(node);
}
});
return edits;
}
Example 53
Project: processing-master File: SourceUtils.java View source code |
public static List<Edit> preprocessAST(CompilationUnit cu) {
final List<Edit> edits = new ArrayList<>();
// Walk the tree
cu.accept(new ASTVisitor() {
@Override
public boolean visit(SimpleType node) {
// replace "color" with "int"
if ("color".equals(node.getName().toString())) {
edits.add(Edit.replace(node.getStartPosition(), node.getLength(), "int"));
}
return super.visit(node);
}
@Override
public boolean visit(NumberLiteral node) {
// add 'f' to floats
String s = node.getToken().toLowerCase();
if (FLOATING_POINT_LITERAL_VERIFIER.matcher(s).matches() && !s.endsWith("f") && !s.endsWith("d")) {
edits.add(Edit.insert(node.getStartPosition() + node.getLength(), "f"));
}
return super.visit(node);
}
@Override
public boolean visit(MethodDeclaration node) {
// add 'public' to methods with default visibility
int accessModifiers = node.getModifiers() & ACCESS_MODIFIERS_MASK;
if (accessModifiers == 0) {
edits.add(Edit.insert(node.getStartPosition(), "public "));
}
return super.visit(node);
}
});
return edits;
}
Example 54
Project: recommenders-master File: CallsApidocProvider.java View source code |
private void handle(final IJavaElement variable, final String elementName, final String typeSignature, final JavaElementSelectionEvent event, final Composite parent) {
final Optional<ASTNode> opt = event.getSelectedNode();
if (!opt.isPresent()) {
return;
}
final Optional<IType> varType = findVariableType(typeSignature, variable);
if (!varType.isPresent()) {
return;
}
receiverType = varType.get();
baseName = pcProvider.toUniqueName(receiverType).orNull();
if (baseName == null || !acquireModel()) {
return;
}
try {
final ASTNode node = opt.get();
final Optional<MethodDeclaration> optAstMethod = findEnclosingMethod(node);
final Optional<IMethod> optJdtMethod = resolveMethod(optAstMethod.orNull());
if (!optJdtMethod.isPresent()) {
return;
}
AstDefUseFinder defUse = new AstDefUseFinder(variable.getElementName(), optAstMethod.orNull());
IMethod findFirstDeclaration = JdtUtils.findFirstDeclaration(optJdtMethod.get());
IMethodName overrideContext = jdtResolver.toRecMethod(findFirstDeclaration).or(VmMethodName.NULL);
Set<IMethodName> calls = Sets.newHashSet(defUse.getCalls());
IMethodName definingMethod = defUse.getDefiningMethod().orNull();
DefinitionKind kind = defUse.getDefinitionKind();
// In the case of parameters we replace the defining method with the overridesContext
if (PARAM == kind) {
definingMethod = overrideContext;
}
if (kind == DefinitionKind.UNKNOWN) {
// the context and try.
if (definingMethod == null) {
kind = FIELD;
} else if (definingMethod.isInit()) {
kind = DefinitionKind.NEW;
} else {
kind = RETURN;
}
}
model.setObservedOverrideContext(overrideContext);
model.setObservedDefiningMethod(definingMethod);
model.setObservedCalls(calls);
model.setObservedDefinitionKind(kind);
Iterable<Recommendation<IMethodName>> methodCalls = sortByRelevance(Recommendations.filterRelevance(model.recommendCalls(), 0.01 / 100));
runSyncInUiThread(new CallRecommendationsRenderer(overrideContext, methodCalls, calls, variable.getElementName(), definingMethod, kind, parent));
} finally {
releaseModel();
}
}
Example 55
Project: tamiflex-master File: MethodResolver.java View source code |
private static void disambiguateMethodByLineNumber(String containerClassName, String methodName, IProject containerProject, int lineNumber) {
IJavaProject javaProject = JavaCore.create(containerProject);
try {
IType type = javaProject.findType(containerClassName, (IProgressMonitor) null);
ICompilationUnit compilationUnit = type.getCompilationUnit();
if (compilationUnit != null) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
final int linePosition = cu.getPosition(lineNumber, 0);
cu.accept(new ASTVisitor() {
public boolean visit(MethodDeclaration method) {
if (method.getStartPosition() <= linePosition && method.getStartPosition() + method.getLength() >= linePosition) {
//method is resolved
resolvedMethods.clear();
resolvedMethods.add((IMethod) method.resolveBinding().getJavaElement());
}
return false;
}
});
} else {
IClassFile classFile = type.getClassFile();
if (classFile != null) {
IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile, IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
for (IMethodInfo method : reader.getMethodInfos()) {
String currMethodName = new String(method.getName());
if (!currMethodName.equals(methodName))
continue;
ICodeAttribute codeAttribute = method.getCodeAttribute();
ILineNumberAttribute lineNumberAttribute = codeAttribute.getLineNumberAttribute();
if (lineNumberAttribute != null) {
int[][] lineNumberTable = lineNumberAttribute.getLineNumberTable();
if (lineNumberTable != null && lineNumberTable.length > 0) {
int startLine = Integer.MAX_VALUE;
int endLine = 0;
for (int[] entry : lineNumberTable) {
int line = entry[1];
startLine = Math.min(startLine, line);
endLine = Math.max(endLine, line);
}
if (startLine >= lineNumber && endLine <= lineNumber) {
char[][] parameterTypes = Signature.getParameterTypes(method.getDescriptor());
String[] parameterTypeNames = new String[parameterTypes.length];
int i = 0;
for (char[] cs : parameterTypes) {
parameterTypeNames[i] = new String(cs);
i++;
}
IMethod iMethod = type.getMethod(currMethodName, parameterTypeNames);
//method resolved
resolvedMethods.clear();
resolvedMethods.add(iMethod);
}
}
}
}
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
}
Example 56
Project: eclipse.jdt.debug-master File: JavaBreakpointImportParticipant.java View source code |
/** * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration) */ @Override public boolean visit(MethodDeclaration node) { SimpleName name = node.getName(); String typename = fTypeNameStack.peek(); if (!fTypename.equals(typename) && !fTypename.startsWith(typename)) { return false; } if (name != null && name.getFullyQualifiedName().equals(fName)) { String sig = getMethodSignatureFromNode(node); if (sig != null) { //$NON-NLS-1$ //$NON-NLS-2$ sig = sig.replaceAll("\\.", "/"); if (sig.equals(fSignature)) { IMarker marker = fBreakpoint.getMarker(); int currentstart = marker.getAttribute(IMarker.CHAR_START, -1); int charstart = name.getStartPosition(); if (currentstart != charstart) { try { marker.setAttribute(IMarker.CHAR_START, charstart); marker.setAttribute(IMarker.CHAR_END, charstart + name.getLength()); } catch (CoreException ce) { } } } } } // local type return fBreakpoint instanceof JavaClassPrepareBreakpoint; }
Example 57
Project: bundlemaker-master File: JdtAstVisitor.java View source code |
/* * (non-Javadoc) * * @seeorg.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom. MethodDeclaration) */ @SuppressWarnings("unchecked") @Override public boolean visit(MethodDeclaration node) { // declared method return type resolveType(node.getReturnType2(), false, false, false); // declared method argument types List<SingleVariableDeclaration> variableDeclarations = node.parameters(); for (SingleVariableDeclaration singleVariableDeclaration : variableDeclarations) { resolveType(singleVariableDeclaration.getType(), false, false, false); } // declared method exception types List<Name> exceptions = node.thrownExceptions(); for (Name name : exceptions) { resolveTypeName(name, false, false, false); } // visit the child nodes return true; }
Example 58
Project: ccvisu-master File: FactUtils.java View source code |
public static String getMethodFullName(MethodDeclaration md) {
assert md != null;
StringBuilder result = new StringBuilder();
if (md.getParent() instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration = (TypeDeclaration) md.getParent();
ITypeBinding typeBinding = typeDeclaration.resolveBinding();
IPackageBinding packageBinding = typeBinding.getPackage();
result.append(FactUtils.getPackageName(packageBinding));
result.append('.');
result.append(typeDeclaration.getName().getFullyQualifiedName());
result.append('.');
}
result.append(md.getName().getFullyQualifiedName()).append("()");
return result.toString();
}
Example 59
Project: com.idega.eclipse.ejbwizards-master File: BeanCreator.java View source code |
protected MethodDeclaration getMethodDeclaration(AST ast, IMethod method, String methodName, String returnType, Set imports, boolean addJavadoc) throws JavaModelException { String[] exceptions = method.getExceptionTypes(); String[] parameterTypes = method.getParameterTypes(); String[] parameterNames = method.getParameterNames(); MethodDeclaration methodConstructor = ast.newMethodDeclaration(); methodConstructor.setConstructor(false); methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC)); methodConstructor.setReturnType2(getType(ast, returnType)); methodConstructor.setName(ast.newSimpleName(methodName)); if (returnType != null) { imports.add(getImportSignature(returnType)); } for (int i = 0; i < exceptions.length; i++) { methodConstructor.thrownExceptions().add(ast.newSimpleName(Signature.getSignatureSimpleName(exceptions[i]))); imports.add(getImportSignature(Signature.toString(exceptions[i]))); } for (int i = 0; i < parameterTypes.length; i++) { String parameterType = getReturnType(parameterTypes[i]); SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE)); variableDeclaration.setType(getType(ast, parameterType)); variableDeclaration.setName(ast.newSimpleName(parameterNames[i])); methodConstructor.parameters().add(variableDeclaration); imports.add(getImportSignature(Signature.toString(parameterTypes[i]))); } if (addJavadoc) { methodConstructor.setJavadoc(getJavadoc(ast, method)); } return methodConstructor; }
Example 60
Project: Convert-For-Each-Loop-to-Lambda-Expression-Eclipse-Plugin-master File: ForeachLoopToLambdaRefactoring.java View source code |
// this method get the EnhancedForSrarement to check the precondition
private static Set<EnhancedForStatement> getEnhancedForStatements(IMethod method, IProgressMonitor pm) throws JavaModelException {
ICompilationUnit iCompilationUnit = method.getCompilationUnit();
// get the ASTParser of the method
CompilationUnit compilationUnit = RefactoringASTParser.parseWithASTProvider(iCompilationUnit, true, new SubProgressMonitor(pm, 1));
// get the method declaration ASTNode.
MethodDeclaration methodDeclarationNode = ASTNodeSearchUtil.getMethodDeclarationNode(method, compilationUnit);
final Set<EnhancedForStatement> statements = new LinkedHashSet<EnhancedForStatement>();
// extract all enhanced for loop statements in the method.
methodDeclarationNode.accept(new ASTVisitor() {
@Override
public boolean visit(EnhancedForStatement node) {
statements.add(node);
return super.visit(node);
}
});
return statements;
}
Example 61
Project: dot-emacs-master File: ASTUtils.java View source code |
/**
* Finds the node at the specified offset that matches up with the supplied
* IJavaElement.
*
* @param cu The CompilationUnit.
* @param offset The node offset in the compilation unit.
* @param element The IJavaElement to match.
* @return The node at the specified offset.
*/
public static ASTNode findNode(CompilationUnit cu, int offset, IJavaElement element) throws Exception {
ASTNode node = findNode(cu, offset);
if (node == null) {
return null;
}
if (element.getElementType() == IJavaElement.TYPE_PARAMETER) {
element = element.getParent();
}
switch(element.getElementType()) {
case IJavaElement.PACKAGE_DECLARATION:
node = resolveNode(node, PackageDeclaration.class);
break;
case IJavaElement.IMPORT_DECLARATION:
node = resolveNode(node, ImportDeclaration.class);
break;
case IJavaElement.TYPE:
node = resolveNode(node, AbstractTypeDeclaration.class);
break;
case IJavaElement.INITIALIZER:
node = resolveNode(node, Initializer.class);
break;
case IJavaElement.FIELD:
node = resolveNode(node, FieldDeclaration.class);
break;
case IJavaElement.METHOD:
node = resolveNode(node, MethodDeclaration.class);
break;
default:
logger.info("findNode(CompilationUnit,int,IJavaElement) - " + "unrecognized element type " + element.getElementType());
}
return node;
}
Example 62
Project: ecl-master File: ASTUtils.java View source code |
/**
* Finds the node at the specified offset that matches up with the supplied
* IJavaElement.
*
* @param cu The CompilationUnit.
* @param offset The node offset in the compilation unit.
* @param element The IJavaElement to match.
* @return The node at the specified offset.
*/
public static ASTNode findNode(CompilationUnit cu, int offset, IJavaElement element) throws Exception {
ASTNode node = findNode(cu, offset);
if (node == null) {
return null;
}
if (element.getElementType() == IJavaElement.TYPE_PARAMETER) {
element = element.getParent();
}
switch(element.getElementType()) {
case IJavaElement.PACKAGE_DECLARATION:
node = resolveNode(node, PackageDeclaration.class);
break;
case IJavaElement.IMPORT_DECLARATION:
node = resolveNode(node, ImportDeclaration.class);
break;
case IJavaElement.TYPE:
node = resolveNode(node, AbstractTypeDeclaration.class);
break;
case IJavaElement.INITIALIZER:
node = resolveNode(node, Initializer.class);
break;
case IJavaElement.FIELD:
node = resolveNode(node, FieldDeclaration.class);
break;
case IJavaElement.METHOD:
node = resolveNode(node, MethodDeclaration.class);
break;
default:
logger.info("findNode(CompilationUnit,int,IJavaElement) - " + "unrecognized element type " + element.getElementType());
}
return node;
}
Example 63
Project: eclim-master File: ASTUtils.java View source code |
/**
* Finds the node at the specified offset that matches up with the supplied
* IJavaElement.
*
* @param cu The CompilationUnit.
* @param offset The node offset in the compilation unit.
* @param element The IJavaElement to match.
* @return The node at the specified offset.
*/
public static ASTNode findNode(CompilationUnit cu, int offset, IJavaElement element) throws Exception {
ASTNode node = findNode(cu, offset);
if (node == null) {
return null;
}
if (element.getElementType() == IJavaElement.TYPE_PARAMETER) {
element = element.getParent();
}
switch(element.getElementType()) {
case IJavaElement.PACKAGE_DECLARATION:
node = resolveNode(node, PackageDeclaration.class);
break;
case IJavaElement.IMPORT_DECLARATION:
node = resolveNode(node, ImportDeclaration.class);
break;
case IJavaElement.TYPE:
node = resolveNode(node, AbstractTypeDeclaration.class);
break;
case IJavaElement.INITIALIZER:
node = resolveNode(node, Initializer.class);
break;
case IJavaElement.FIELD:
node = resolveNode(node, FieldDeclaration.class);
break;
case IJavaElement.METHOD:
node = resolveNode(node, MethodDeclaration.class);
break;
default:
logger.info("findNode(CompilationUnit,int,IJavaElement) - " + "unrecognized element type " + element.getElementType());
}
return node;
}
Example 64
Project: eclipse-tapestry5-plugin-master File: TapestryServiceConfigurationCapturingVisitor.java View source code |
@Override
public boolean visit(MethodDeclaration node) {
// Capture method arguments in a scope
declarations.enterScope();
for (Object arg : node.parameters()) {
if (arg instanceof SingleVariableDeclaration) {
SingleVariableDeclaration variableDeclaration = (SingleVariableDeclaration) arg;
String className = EclipseUtils.toClassName(tapestryModule.getEclipseProject(), variableDeclaration.getType());
if (StringUtils.isNotEmpty(className)) {
declarations.add(new Declaration(variableDeclaration, variableDeclaration.getName().getIdentifier(), className));
}
}
}
return super.visit(node);
}
Example 65
Project: hawk-drivers-master File: SService.java View source code |
private void extractJavaDoc(Class<?> clazz) { ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setSource(sourceCodeFetcher.get(clazz).toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { MethodDeclaration currentMethod = null; public boolean visit(Javadoc javaDoc) { if (currentMethod != null) { SMethod method = getSMethod(currentMethod.getName().getIdentifier()); if (method == null) { LOGGER.error("Method " + currentMethod.getName().getIdentifier() + " not found in class"); } else { for (Object tag : javaDoc.tags()) { if (tag instanceof TagElement) { TagElement tagElement = (TagElement) tag; String tagName = tagElement.getTagName() == null ? null : tagElement.getTagName().trim(); if ("@param".equals(tagName)) { SParameter parameter = null; for (int i = 0; i < tagElement.fragments().size(); i++) { Object fragment = tagElement.fragments().get(i); if (i == 0 && fragment instanceof SimpleName) { parameter = method.getParameter(((SimpleName) fragment).getIdentifier()); } else if (i == 1 && parameter != null && fragment instanceof TextElement) { parameter.setDoc(((TextElement) fragment).getText()); } } } else if ("@return".equals(tagName)) { method.setReturnDoc(extractFullText(tagElement)); } else if ("@throws".equals(tagName)) { } else { method.setDoc(extractFullText(tagElement)); } } } } } return super.visit(javaDoc); } @Override public boolean visit(MethodDeclaration node) { currentMethod = node; return super.visit(node); } @Override public void endVisit(MethodDeclaration node) { currentMethod = null; super.endVisit(node); } }); }
Example 66
Project: integrity-master File: JavadocUtil.java View source code |
private static MethodDeclaration getMethodDeclaration(JvmOperation aMethod, IJavaElementFinder anElementFinder) { IJavaElement tempSourceMethod = (IJavaElement) anElementFinder.findElementFor(aMethod); // no Javadoc anyway if (tempSourceMethod.getParent().getParent() instanceof ICompilationUnit) { ICompilationUnit tempCompilationUnit = (ICompilationUnit) tempSourceMethod.getParent().getParent(); AbstractTypeDeclaration tempType = parseCompilationUnit(tempCompilationUnit); if (tempType instanceof TypeDeclaration) { for (MethodDeclaration tempMethod : ((TypeDeclaration) tempType).getMethods()) { // required to be unique per class if (aMethod.getSimpleName().equals(tempMethod.getName().getFullyQualifiedName())) { return tempMethod; } } } } return null; }
Example 67
Project: jbosstools-hibernate-master File: Utils.java View source code |
public static String getFieldNameByGetter(MethodDeclaration node) {
if (node.parameters().size() != 0)
return null;
String methodName = node.getName().getIdentifier();
if (//$NON-NLS-1$
methodName.startsWith("get") && methodName.length() > 3) {
methodName = methodName.substring(3);
return Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1);
} else if (//$NON-NLS-1$
methodName.startsWith("is") && methodName.length() > 2) {
methodName = methodName.substring(2);
return Character.toLowerCase(methodName.charAt(0)) + methodName.substring(1);
}
return null;
}
Example 68
Project: jbosstools-javaee-master File: ComponentBuilder.java View source code |
void processFactories() { for (AnnotatedASTNode<MethodDeclaration> n : annotatedMethods) { Annotation a = findAnnotation(n, FACTORY_ANNOTATION_TYPE); if (a == null) continue; MethodDeclaration m = n.getNode(); ValueInfo factoryName = ValueInfo.getValueInfo(a, null); if (factoryName == null) { factoryName = new ValueInfo(); factoryName.setValue(toPropertyName(m.getName().getIdentifier(), "get")); factoryName.valueLength = m.getName().getLength(); factoryName.valueStartPosition = m.getName().getStartPosition(); } ValueInfo scope = ValueInfo.getValueInfo(a, ISeamXmlComponentDeclaration.SCOPE); //$NON-NLS-1$ ValueInfo autoCreate = ValueInfo.getValueInfo(a, "autoCreate"); SeamAnnotatedFactory factory = new SeamAnnotatedFactory(); factory.setParentDeclaration(component); IMethod im = findMethod(m); factory.setSourceMember(im); factory.setId(im); factory.setSourcePath(component.getSourcePath()); factory.setName(factoryName); if (autoCreate != null) factory.setAutoCreate(true); if (scope != null) { factory.setScope(scope); } ValueInfo _a = new ValueInfo(); _a.setValue(FACTORY_ANNOTATION_TYPE); _a.valueStartPosition = a.getStartPosition(); _a.valueLength = a.getLength(); factory.addAttribute(FACTORY_ANNOTATION_TYPE, _a); ds.getFactories().add(factory); } }
Example 69
Project: LEADT-master File: JDTCheckGenerator.java View source code |
/* METHOD DECLARATION PART */
@Override
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
List<MethodPathItem> inhMethods = new ArrayList<MethodPathItem>();
boolean foundInhMethods = initializeAndCollectInhData(binding, inhMethods);
if (foundInhMethods) {
handleInheritedAbstractMethodImplementation(node, binding, inhMethods);
handleOverridingRelationshipViolation(node, binding, inhMethods);
}
return super.visit(node);
}
Example 70
Project: pdt-master File: OverrideIndicatorManager.java View source code |
/* * @see * org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core * .dom.MethodDeclaration) */ @Override public boolean visit(MethodDeclaration node) { IMethodBinding binding = node.resolveMethodBinding(); if (binding != null) { IMethodBinding definingMethod = Bindings.findOverriddenMethod(binding, true); if (definingMethod != null) { ITypeBinding definingType = definingMethod.getDeclaringClass(); String qualifiedMethodName = //$NON-NLS-1$ [TODO definingType.getName() + "." + //$NON-NLS-1$ [TODO binding.getName(); // - // Use // definingType.getQualifiedName()] boolean isImplements = (Modifiers.AccAbstract & definingMethod.getModifiers()) != 0; String text; if (isImplements) text = Messages.format(PHPUIMessages.OverrideIndicatorManager_implements, // $NON-NLS-1$ qualifiedMethodName); else text = Messages.format(PHPUIMessages.OverrideIndicatorManager_overrides, // $NON-NLS-1$ qualifiedMethodName); Identifier name = node.getFunction().getFunctionName(); Position position = new Position(name.getStart(), name.getLength()); OverrideIndicator indicator = new OverrideIndicator(isImplements, text, definingMethod.getKey()); annotationMap.put(indicator, position); } } return true; }
Example 71
Project: quick-junit-master File: LeaningAST.java View source code |
// @Test // public void learning_addSource() throws Exception { // String source = "public class TestClass{\n" + // " /**\n" + // " * @see test.TestClass\n" + // " * @see org.junit.Test\n" + // " */\n" + // " @org.junit.Test\n" + // " public void do_test() throws Exception{\n" + // " }\n" + // "}\n"; // ASTParser parser = ASTParser.newParser(AST.JLS3); // parser.setSource(source.toCharArray()); // final ASTNode node = parser.createAST(null); // final List<String> actual = new ArrayList<String>(); // ASTVisitor visitor = new ASTVisitor(){ // public boolean visit(Javadoc doc){ // AST ast = doc.getAST(); // TagElement tag = ast.newTagElement(); // tag.setTagName(TagElement.TAG_SEE); // doc.tags().add(tag); // MethodRef method = ast.newMethodRef(); // tag.fragments().add(method); // SimpleName name = ast.newSimpleName("Test"); // method.setQualifier(ast.newQualifiedName(ast.newQualifiedName(ast.newName("org"), ast.newSimpleName("junit")), name)); // name = ast.newSimpleName("test"); // method.setName(name); // return super.visit(doc); // } // }; // node.accept(visitor); // System.out.println(node); // } @Test @Ignore public /* * resolveBindingsã?¯IProjectã?ªã?©å®Ÿéš›ã?®JavaModelã?¨é–¢é€£ä»˜ã?‘ã‚‹å¿…è¦?ã?Œã?‚る。 * ソースã? ã?‘ã?§ã?¯ä½•ã?¨ã‚‚出æ?¥ã?ªã?„ã?¿ã?Ÿã?„。 */ void learning_ASTRewrite_use_resolveBindings() throws Exception { String source = "public class TestClass{\n" + // " @org.junit.Test\n" + " public void do_test() throws Exception{\n" + " }\n" + "}\n"; Document doc = new Document(source); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); // set source parser.setSource(source.toCharArray()); // we need bindings later on parser.setResolveBindings(true); CompilationUnit cu = (CompilationUnit) parser.createAST(null); // List types = cu.structuralPropertiesForType(); for (Object o : cu.types()) { AbstractTypeDeclaration dec = (AbstractTypeDeclaration) o; List bodyDeclarations = dec.bodyDeclarations(); assertNotNull(dec.resolveBinding()); for (Object body : bodyDeclarations) { MethodDeclaration methodDec = (MethodDeclaration) body; IMethodBinding binding = methodDec.resolveBinding(); assertNotNull(binding); ASTNode node = cu.findDeclaringNode(binding); assertNotNull("can't find declaring node", node); System.out.println(node); } } // ASTRewrite rewriter = ASTRewrite.create(cu.getAST()); // ListRewrite listRewrite = rewriter.getListRewrite(cu, Javadoc.TAGS_PROPERTY); }
Example 72
Project: seam-forge-master File: MethodImpl.java View source code |
@Override
public Method<O> setBody(final String body) {
String stub = "public class Stub { public void method() {" + body + "} }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
List<Method<JavaClass>> methods = temp.getMethods();
Block block = ((MethodDeclaration) methods.get(0).getInternal()).getBody();
block = (Block) ASTNode.copySubtree(method.getAST(), block);
method.setBody(block);
return this;
}
Example 73
Project: stlipse-master File: BeanPropertyVisitor.java View source code |
@Override
public boolean visit(MethodDeclaration node) {
if (nestLevel != 1)
return false;
// Resolve binding first to support Lombok generated methods.
// node.getModifiers() returns incorrect access modifiers for them.
// https://github.com/harawata/stlipse/issues/2
IMethodBinding method = node.resolveBinding();
if (Modifier.isPublic(method.getModifiers())) {
final String methodName = node.getName().toString();
final int parameterCount = node.parameters().size();
final Type returnType = node.getReturnType2();
if (returnType == null) {
// Ignore constructor
} else if (isReturnVoid(returnType)) {
if (isSetter(methodName, parameterCount)) {
SingleVariableDeclaration param = (SingleVariableDeclaration) node.parameters().get(0);
String qualifiedName = getQualifiedNameFromType(param.getType());
String fieldName = getFieldNameFromAccessor(methodName);
writableFields.put(fieldName, qualifiedName);
}
} else {
if (isGetter(methodName, parameterCount)) {
String fieldName = getFieldNameFromAccessor(methodName);
String qualifiedName = getQualifiedNameFromType(returnType);
readableFields.put(fieldName, qualifiedName);
} else if (isEventHandler(returnType.toString(), parameterCount)) {
ITypeBinding binding = returnType.resolveBinding();
if (binding == null) {
Activator.log(Status.INFO, "Couldn't resolve binding for return type " + returnType.toString() + " of method " + methodName);
} else {
String qualifiedName = binding.getQualifiedName();
try {
if (TypeCache.isResolution(project, project.findType(qualifiedName))) {
Object annotationValue = null;
boolean isDefaultHandler = false;
boolean isInterceptor = false;
for (IAnnotationBinding annotation : method.getAnnotations()) {
String name = annotation.getName();
isInterceptor |= ("Before".equals(name) || "After".equals(name));
if (isInterceptor)
break;
isDefaultHandler |= "DefaultHandler".equals(name);
if ("HandlesEvent".equals(name)) {
IMemberValuePairBinding[] valuePairs = annotation.getAllMemberValuePairs();
for (IMemberValuePairBinding valuePair : valuePairs) {
if ("value".equals(valuePair.getName())) {
annotationValue = valuePair.getValue();
}
}
}
}
if (!isInterceptor) {
EventProperty eventProperty = new EventProperty();
eventProperty.setDefaultHandler(isDefaultHandler);
eventProperty.setMethodName(methodName);
String eventName = (String) (annotationValue == null ? methodName : annotationValue);
eventHandlers.put(eventName, eventProperty);
}
}
} catch (JavaModelException e) {
Activator.log(Status.WARNING, "Error occurred during event handler check", e);
}
}
}
}
}
return false;
}
Example 74
Project: XobotOS-master File: NativeBuilder.java View source code |
public NativeMethodBuilder registerNativeMethod(MethodDeclaration node, NativeMethod template, NativeHandleBuilder nativeHandle) {
final IMethodBinding binding = node.resolveBinding();
String prefix = _config.getFunctionPrefix();
if (prefix == null)
prefix = "";
String name;
if (template.getKind() == Kind.DESTRUCTOR)
name = "destructor";
else if (template.getName() != null)
name = template.getName();
else
name = binding.getName();
String nativeName = template.getNativeName();
if (nativeName == null)
nativeName = name;
String funcName = String.format("%s_%s_%s", prefix, binding.getDeclaringClass().getName(), name);
if (_nativeMethods.containsKey(funcName)) {
int index = 0;
while (_nativeMethods.containsKey(funcName + "_" + index)) index++;
funcName = funcName + "_" + index;
}
NativeMethodBuilder builder = new NativeMethodBuilder(this, node, template, nativeName, funcName, nativeHandle);
_nativeMethods.put(funcName, builder);
return builder;
}
Example 75
Project: eclipse3-master File: SyntaxTranslator.java View source code |
@Override
public void endVisit(SimpleName node) {
IBinding nameBinding = node.resolveBinding();
if (nameBinding instanceof org.eclipse.jdt.core.dom.IVariableBinding) {
org.eclipse.jdt.core.dom.IVariableBinding variableBinding = (org.eclipse.jdt.core.dom.IVariableBinding) nameBinding;
org.eclipse.jdt.core.dom.MethodDeclaration enclosingMethod = getEnclosingMethod(node);
if (!variableBinding.isField() && enclosingMethod != null && variableBinding.getDeclaringMethod() != enclosingMethod.resolveBinding() && addedParameters.add(variableBinding)) {
TypeName parameterTypeName = translateTypeName(variableBinding.getType());
String parameterName = variableBinding.getName();
SimpleIdentifier parameterNameNode = identifier(parameterName);
innerClass.getMembers().add(index++, fieldDeclaration(parameterTypeName, variableDeclaration(parameterNameNode)));
constructorParameters.add(fieldFormalParameter(null, null, parameterNameNode));
arguments.add(parameterNameNode);
context.putReference(parameterNameNode, variableBinding, null);
}
}
super.endVisit(node);
}
Example 76
Project: srcrepo-master File: JDTVisitor.java View source code |
@Override
public boolean visit(final org.eclipse.jdt.core.dom.MethodDeclaration node) {
AbstractMethodDeclaration element = null;
if (this.isINCREMENTALDISCOVERING && !(node.getParent() instanceof org.eclipse.jdt.core.dom.AnonymousClassDeclaration)) {
String qualifiedName = JDTVisitorUtils.getQualifiedName(node);
element = (AbstractMethodDeclaration) getGlobalBindings().getTarget(qualifiedName);
if (element != null) {
unSetProxy(element);
}
}
if (element == null) {
if (node.isConstructor()) {
element = this.factory.createConstructorDeclaration();
} else {
element = this.factory.createMethodDeclaration();
}
}
this.binding.put(node, element);
// anonymous class declared in a method body
if (getLocalBindings() == null) {
setLocalBindings(new BindingManager(this.factory));
}
return true;
}
Example 77
Project: iTrace-master File: AstManager.java View source code |
public boolean visit(MethodDeclaration node) {
SourceCodeEntity sce = new SourceCodeEntity();
sce.type = SCEType.METHOD;
sce.how = SCEHow.DECLARE;
sce.name = node.getName().getFullyQualifiedName();
determineSCEPosition(compileUnit, node, sce);
extractDataFromMethodBinding(node.resolveBinding(), sce);
sourceCodeEntities.add(sce);
return true;
}
Example 78
Project: blade.tools-master File: JavaFileChecker.java View source code |
@Override
public boolean visit(MethodDeclaration node) {
boolean sameParmSize = true;
String methodName = node.getName().toString();
List<?> parmsList = node.parameters();
if (name.equals(methodName) && params.length == parmsList.size()) {
for (int i = 0; i < params.length; i++) {
if (!(params[i].trim().equals(parmsList.get(i).toString().substring(0, params[i].trim().length())))) {
sameParmSize = false;
break;
}
}
} else {
sameParmSize = false;
}
if (sameParmSize) {
final int startLine = _ast.getLineNumber(node.getName().getStartPosition());
final int startOffset = node.getName().getStartPosition();
node.accept(new ASTVisitor() {
@Override
public boolean visit(Block node) {
// SimpleName parent can not be MarkerAnnotation and
// SimpleType
// SingleVariableDeclaration node contains the
// parms's type
int endLine = _ast.getLineNumber(node.getStartPosition());
int endOffset = node.getStartPosition();
searchResults.add(createSearchResult(startOffset, endOffset, startLine, endLine, true));
return false;
}
;
});
}
return false;
}
Example 79
Project: emf.texo-master File: ImportReferencesCollector.java View source code |
/* * @see ASTVisitor#visit(MethodDeclaration) */ @Override public boolean visit(final MethodDeclaration node) { doVisitNode(node.getJavadoc()); if (node.getAST().apiLevel() >= AST.JLS3) { doVisitChildren(node.modifiers()); doVisitChildren(node.typeParameters()); } if (!node.isConstructor()) { doVisitNode(node.getReturnType2()); } doVisitChildren(node.parameters()); Iterator<?> iter = node.thrownExceptions().iterator(); while (iter.hasNext()) { typeRefFound((Name) iter.next()); } doVisitNode(node.getBody()); return false; }
Example 80
Project: FastIbatis-master File: AbstractCodeBuilder.java View source code |
@SuppressWarnings("unchecked") private MethodDeclaration createMethodDeclaration(AST ast, TypeDeclaration type, FastIbatisConfig fc) { MethodDeclaration methodDeclaration = ast.newMethodDeclaration(); methodDeclaration.setConstructor(false); List modifiers = methodDeclaration.modifiers(); modifiers.add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); methodDeclaration.setName(ast.newSimpleName(fc.getMethodName())); String _str = fc.getReturnType(); if (_str == null || _str.equalsIgnoreCase("void")) methodDeclaration.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); else methodDeclaration.setReturnType2(ast.newSimpleType(ast.newSimpleName(_str))); SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration(); variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(fc.getParamType()))); variableDeclaration.setName(ast.newSimpleName("param")); methodDeclaration.parameters().add(variableDeclaration); return methodDeclaration; }
Example 81
Project: Hindsight-master File: OutCodeVisitor.java View source code |
// check if getter or setter
@Override
public boolean visit(MethodDeclaration methodDeclaration) {
methodMetrics(methodDeclaration);
if (methodDeclaration.isConstructor())
return true;
if (methodDeclaration.getBody() == null || methodDeclaration.getBody().statements().size() != 1)
return true;
if (methodDeclaration.getName().getIdentifier().startsWith("get")) {
Object object = methodDeclaration.getBody().statements().get(0);
if (!(object instanceof ReturnStatement))
return true;
else {
ReturnStatement returnStatement = (ReturnStatement) object;
Expression expression = returnStatement.getExpression();
if (expression == null)
// method name starts with get but returns
return true;
// null
if (isObjectFieldAccess(expression)) {
if (methodDeclaration != null) {
IMethodBinding methodBinding = methodDeclaration.resolveBinding();
if (methodBinding != null) {
Node method = db.createIJavaElementNode(methodBinding.getJavaElement(), commit, commitID, added, removed);
method.setProperty("get", true);
}
}
}
}
} else if (methodDeclaration.getName().getIdentifier().startsWith("set")) {
Object object = methodDeclaration.getBody().statements().get(0);
if (!(object instanceof Assignment) && !(object instanceof ExpressionStatement))
return true;
if (object instanceof ExpressionStatement)
object = ((ExpressionStatement) object).getExpression();
if (!(object instanceof Assignment))
return true;
Assignment assignment = (Assignment) object;
Expression leftExpression = assignment.getLeftHandSide();
if (isObjectFieldAccess(leftExpression) && isParameterAccess(assignment.getRightHandSide())) {
IMethodBinding methodBinding = methodDeclaration.resolveBinding();
if (methodBinding != null) {
IJavaElement methodJavaElement = methodBinding.getJavaElement();
if (methodJavaElement != null) {
Node method = db.createIJavaElementNode(methodJavaElement, commit, commitID, added, removed);
method.setProperty("get", true);
}
}
}
}
return true;
}
Example 82
Project: jenkins.py-master File: AbstractTypeDeclFinder.java View source code |
public boolean visit(MethodDeclaration node) {
Type returnType = node.getReturnType2();
if (returnType != null) {
if (returnType.isSimpleType()) {
node.setReturnType2(replaceType((SimpleType) returnType));
} else if (returnType.isParameterizedType()) {
node.setReturnType2(replaceType((ParameterizedType) returnType));
}
}
for (int i = 0; i < node.parameters().size(); i++) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) node.parameters().get(i);
Type varType = svd.getType();
if (varType.isSimpleType()) {
svd.setType(replaceType((SimpleType) varType));
} else if (varType.isParameterizedType()) {
svd.setType(replaceType((ParameterizedType) varType));
}
}
return false;
}
Example 83
Project: juniversal-master File: HeaderTypeDeclarationWriter.java View source code |
private void writeMethods() { ArrayList<MethodDeclaration> publicMethods = new ArrayList<>(); ArrayList<MethodDeclaration> protectedMethods = new ArrayList<>(); ArrayList<MethodDeclaration> privateMethods = new ArrayList<>(); for (Object bodyDeclaration : typeDeclaration.bodyDeclarations()) { if (bodyDeclaration instanceof MethodDeclaration) { MethodDeclaration MethodDeclaration = (MethodDeclaration) bodyDeclaration; AccessLevel accessLevel = ASTUtil.getAccessModifier(MethodDeclaration.modifiers()); if (accessLevel == AccessLevel.PUBLIC || accessLevel == AccessLevel.PACKAGE) publicMethods.add(MethodDeclaration); else if (accessLevel == AccessLevel.PROTECTED) protectedMethods.add(MethodDeclaration); else privateMethods.add(MethodDeclaration); } else if (!(bodyDeclaration instanceof FieldDeclaration || bodyDeclaration instanceof TypeDeclaration)) throw new JUniversalException("Unexpected bodyDeclaration type" + bodyDeclaration.getClass()); } writeMethodsForAccessLevel(publicMethods, AccessLevel.PUBLIC); writeMethodsForAccessLevel(protectedMethods, AccessLevel.PROTECTED); writeMethodsForAccessLevel(privateMethods, AccessLevel.PRIVATE); }
Example 84
Project: Manal-master File: SuspectSearch.java View source code |
private boolean createAST(IPackageFragment packageSearched, ApiDescriptor methodSearched) throws JavaModelException {
String className = methodSearched.getClassNameFromSoot();
if (className == null) {
System.err.println("Can't search. Class name is NULL.");
return false;
}
for (ICompilationUnit unit : packageSearched.getCompilationUnits()) {
String unitName = unit.getElementName();
if ((unitName != null) && unitName.contains(className)) {
// now create the AST for the ICompilationUnits
final CompilationUnit parse = parse(unit);
methodSearched.setCompilationUnit(parse);
return true;
// MethodVisitor visitor = new MethodVisitor();
// parse.accept(visitor);
//
// for (MethodDeclaration method : visitor.getMethods()) {
// System.out.print("Method name: " + method.getName()
// + " Return type: " + method.getReturnType2());
// extractStatements(parse, method, methodSearched);
// }
}
}
return false;
}
Example 85
Project: perconik-master File: CompilationUnitDifferencer.java View source code |
private static boolean isSimilar(final ASTNode original, final ASTNode revised) {
if (original instanceof AbstractTypeDeclaration) {
return isSimilar((AbstractTypeDeclaration) original, revised);
}
switch(NodeType.valueOf(original)) {
case ANNOTATION_TYPE_MEMBER_DECLARATION:
return isSimilar((AnnotationTypeMemberDeclaration) original, revised);
case ENUM_CONSTANT_DECLARATION:
return isSimilar((EnumConstantDeclaration) original, revised);
case FIELD_DECLARATION:
return isSimilar((FieldDeclaration) original, revised);
case INITIALIZER:
return isSimilar((Initializer) original, revised);
case METHOD_DECLARATION:
return isSimilar((MethodDeclaration) original, revised);
default:
return false;
}
}
Example 86
Project: ptii-master File: SortMembersUtility.java View source code |
private int compareNodeType(BodyDeclaration bodyDeclaration1, BodyDeclaration bodyDeclaration2) { int typeCode1 = getNodeTypeCode(bodyDeclaration1); int typeCode2 = getNodeTypeCode(bodyDeclaration2); if (typeCode1 != typeCode2) { return typeCode1 - typeCode2; } else { switch(bodyDeclaration1.getNodeType()) { case ASTNode.METHOD_DECLARATION: MethodDeclaration method1 = (MethodDeclaration) bodyDeclaration1; MethodDeclaration method2 = (MethodDeclaration) bodyDeclaration2; if (method1.isConstructor() && !method2.isConstructor()) { return -1; } else if (!method1.isConstructor() && method2.isConstructor()) { return 1; } String methodName1 = method1.getName().getIdentifier(); String methodName2 = method2.getName().getIdentifier(); // method declarations (constructors) are sorted by name int nameResult = methodName1.compareTo(methodName2); if (nameResult != 0) { return nameResult; } // if names equal, sort by parameter types List<?> parameters1 = method1.parameters(); List<?> parameters2 = method2.parameters(); int length1 = parameters1.size(); int length2 = parameters2.size(); int minLength = Math.min(length1, length2); for (int i = 0; i < minLength; i++) { SingleVariableDeclaration param1i = (SingleVariableDeclaration) parameters1.get(i); SingleVariableDeclaration param2i = (SingleVariableDeclaration) parameters2.get(i); int paramResult = buildSignature(param1i.getType()).compareTo(buildSignature(param2i.getType())); if (paramResult != 0) { return paramResult; } } if (length1 != length2) { return length1 - length2; } return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); case ASTNode.FIELD_DECLARATION: FieldDeclaration field1 = (FieldDeclaration) bodyDeclaration1; FieldDeclaration field2 = (FieldDeclaration) bodyDeclaration2; String fieldName1 = ((VariableDeclarationFragment) field1.fragments().get(0)).getName().getIdentifier(); String fieldName2 = ((VariableDeclarationFragment) field2.fragments().get(0)).getName().getIdentifier(); return compareNames(bodyDeclaration1, bodyDeclaration2, fieldName1, fieldName2); case ASTNode.INITIALIZER: return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); case ASTNode.TYPE_DECLARATION: case ASTNode.ENUM_DECLARATION: case ASTNode.ANNOTATION_TYPE_DECLARATION: AbstractTypeDeclaration type1 = (AbstractTypeDeclaration) bodyDeclaration1; AbstractTypeDeclaration type2 = (AbstractTypeDeclaration) bodyDeclaration2; String typeName1 = type1.getName().getIdentifier(); String typeName2 = type2.getName().getIdentifier(); return compareNames(bodyDeclaration1, bodyDeclaration2, typeName1, typeName2); case ASTNode.ENUM_CONSTANT_DECLARATION: EnumConstantDeclaration enum1 = (EnumConstantDeclaration) bodyDeclaration1; EnumConstantDeclaration enum2 = (EnumConstantDeclaration) bodyDeclaration2; String enumName1 = enum1.getName().getIdentifier(); String enumName2 = enum2.getName().getIdentifier(); return compareNames(bodyDeclaration1, bodyDeclaration2, enumName1, enumName2); case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: AnnotationTypeMemberDeclaration annotation1 = (AnnotationTypeMemberDeclaration) bodyDeclaration1; AnnotationTypeMemberDeclaration annotation2 = (AnnotationTypeMemberDeclaration) bodyDeclaration2; String annotationName1 = annotation1.getName().getIdentifier(); String annotationName2 = annotation2.getName().getIdentifier(); return compareNames(bodyDeclaration1, bodyDeclaration2, annotationName1, annotationName2); default: return preserveRelativeOrder(bodyDeclaration1, bodyDeclaration2); } } }
Example 87
Project: swtbot-master File: Recorder.java View source code |
/**
* Adds a new line of code to the currently selected method and the editor
* which contains this method.
*
* @param code
* The code to append.
*/
private void insertInEditor(String code) {
ICompilationUnit methodCompilationUnit = selectedMethod.getCompilationUnit();
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(methodCompilationUnit);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
ASTNode rootNode = parser.createAST(null);
CompilationUnit compilationUnit = (CompilationUnit) rootNode;
// Create a visitor which finds all method declarations
MethodDeclarationVisitor methodDeclarationVisitor = new MethodDeclarationVisitor();
compilationUnit.accept(methodDeclarationVisitor);
// Search for the method declaration corresponding to selectedMethod
MethodDeclaration method = methodDeclarationVisitor.findMethodDeclaration(selectedMethod);
final ASTRewrite rewrite = ASTRewrite.create(rootNode.getAST());
ListRewrite listRewrite = rewrite.getListRewrite(method.getBody(), Block.STATEMENTS_PROPERTY);
Statement statement = (Statement) rewrite.createStringPlaceholder(code + ";", ASTNode.EMPTY_STATEMENT);
listRewrite.insertLast(statement, null);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
TextEdit edits = rewrite.rewriteAST();
try {
edits.apply(selectedMethodDocument);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
} catch (JavaModelException e1) {
e1.printStackTrace();
} catch (IllegalArgumentException e1) {
e1.printStackTrace();
}
}
;
});
}
Example 88
Project: TBLips-master File: ASTMethodExplorer.java View source code |
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
if (binding != null) {
ITypeBinding[] params = binding.getParameterTypes();
String paramString = "(";
for (int i = 0; i < params.length; i++) {
paramString += params[i].getName();
if (i < params.length - 1)
paramString += ",";
}
paramString += ")";
String key = binding.getDeclaringClass().getName() + "." + binding.getName() + paramString;
ITypeBinding declaredClassBinding = binding.getDeclaringClass();
// overrides super method
ITypeBinding superClassBinding = declaredClassBinding.getSuperclass();
boolean skip = checkSuperClass(binding, superClassBinding);
// is implementation of interface
ITypeBinding[] interfaceBindings = declaredClassBinding.getInterfaces();
skip = skip || checkInterfaces(binding, interfaceBindings);
if (superClassBinding != null) {
// classDependencies
classDependencies.put(declaredClassBinding.getName(), superClassBinding.getName());
// WOComponent && title()
boolean isWOComponent = superClassBinding.getName().equals("WOComponent");
skip = skip || (isWOComponent && binding.getName().equals("title"));
}
// DirectAction.Action()
boolean isDirectAction = declaredClassBinding.getName().equals("DirectAction");
skip = skip || (isDirectAction && (binding.getName().endsWith("Action") || binding.getName().equals("performActionNamed")));
// app || logic && Constructor
IPackageBinding packageBinding = declaredClassBinding.getPackage();
String[] comps = packageBinding.getNameComponents();
if (comps.length > 0) {
String comp = comps[comps.length - 1];
skip = skip || ((comp.equals("app") || comp.equals("logic")) && binding.isConstructor());
}
if (!usedMethods.containsKey(key)) {
List<String> value = new ArrayList<String>();
value.add(iCompUnit.getHandleIdentifier());
value.add(binding.getName());
value.add(binding.getReturnType().getName());
value.add(skip + "");
declaredMethods.put(key, value);
}
}
return true;
}
Example 89
Project: UML-Designer-master File: JavaReverseCUVisitor.java View source code |
/* * (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration) */ @Override public boolean visit(MethodDeclaration node) { boolean ret = false; entryNodeMap = new HashMap<Statement, ActivityNode>(); exitNodeMap = new HashMap<Statement, ActivityNode>(); innerExitMap = new HashMap<Statement, ActivityNode>(); innerEntryMap = new HashMap<Statement, ActivityNode>(); choiceMap = new HashMap<Statement, ActivityNode>(); choiceThenFMap = new HashMap<Statement, Statement>(); choiceElseFMap = new HashMap<Statement, Statement>(); choiceThenMap = new HashMap<Statement, Statement>(); choiceElseMap = new HashMap<Statement, Statement>(); choiceOutMap = new HashMap<Statement, ActivityNode>(); parentStatements = new ArrayList<Statement>(); // add activity to current class String methodname = node.getName().toString(); TypeDeclaration classnode = null; String classname = ""; NamedElement specObject = null; if (node.getParent() instanceof TypeDeclaration) { classnode = (TypeDeclaration) node.getParent(); classname = classnode.getName().toString(); specObject = packageObject.getOwnedMember(classname); } if (specObject != null && specObject instanceof Class) { List<SingleVariableDeclaration> params = node.parameters(); List<String> paramTypeNames = new ArrayList<String>(); EList<Parameter> pset = null; for (SingleVariableDeclaration p : params) { paramTypeNames.add(p.getType().toString()); } if (paramTypeNames.size() == 0) { paramTypeNames = null; } BehavioralFeature op = ((Class) specObject).getOwnedOperation(methodname, null, null); // check parameters if (op != null) { pset = op.getOwnedParameters(); // parameters names boolean pnok = ctrlParamTypes(paramTypeNames, pset); List<Operation> ops2 = ((Class) specObject).getOperations(); List<Operation> ops = new ArrayList<Operation>(); for (Operation oo : ops2) { if (oo.getName().toString().equals(methodname)) { ops.add(oo); } } while (!pnok && ops.size() > 1) { ops.remove(op); op = ops.get(0); pset = op.getOwnedParameters(); pnok = ctrlParamTypes(paramTypeNames, pset); } if (!pnok) { op = null; } } if (op == null) { op = ((Class) specObject).getOwnedReception(methodname, null, null); if (op != null) { List<Reception> ops2 = ((Class) specObject).getOwnedReceptions(); List<Reception> ops = new ArrayList<Reception>(); for (Reception oo : ops2) { if (oo.getName().toString().equals(methodname)) { ops.add(oo); } } pset = op.getOwnedParameters(); boolean pnok = ctrlParamTypes(paramTypeNames, pset); while (!pnok && ops.size() > 1) { ops.remove(op); op = ops.get(0); pset = op.getOwnedParameters(); pnok = ctrlParamTypes(paramTypeNames, pset); } if (!pnok) { op = null; } } } // process only methods annotated @activity if (op != null && isAnnotatedOnly) { // list of modifiers and annotations List<IExtendedModifier> modifiers = node.modifiers(); if (modifiers.isEmpty()) { op = null; } else { // list of annotations names List<String> flags = new ArrayList<String>(); for (IExtendedModifier flag : modifiers) { if (flag.isAnnotation()) { flags.add(flag.toString()); } } // check annotation if (!flags.contains(ANNOTATION_ACTIVITY)) { op = null; } } } if (op != null) { currentActivity = UMLFactory.eINSTANCE.createActivity(); currentActivity.setName(node.getName().toString()); LogUtils.logEntering(currentActivity, "Activity for " + methodname); currentActivity.setSpecification(op); ((BehavioredClassifier) specObject).getOwnedBehaviors().add(currentActivity); for (Parameter paramOp : pset) { ActivityParameterNode paramu = UMLFactory.eINSTANCE.createActivityParameterNode(); paramu.setName(paramOp.getName()); paramu.setActivity(currentActivity); paramu.setType(paramOp.getType()); paramu.setParameter(paramOp); } initNode = UMLFactory.eINSTANCE.createInitialNode(); initNode.setName("InitNode"); initNode.setActivity(currentActivity); // create Final node (connections later) finalNode = UMLFactory.eINSTANCE.createActivityFinalNode(); finalNode.setName("FinalNode"); finalNode.setActivity(currentActivity); ret = true; } } return ret; }
Example 90
Project: Virgo-Tooling-master File: ArtifactAnalyserTypeVisitor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
if (binding == null) {
return true;
}
// return value
if (binding.getReturnType() != null) {
String fqn = binding.getReturnType().getQualifiedName();
if (!"void".equals(fqn)) {
recordTypeBinding(binding.getReturnType());
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(binding.getReturnType());
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
// throws clause
if (binding.getExceptionTypes() != null) {
for (ITypeBinding exceptionBinding : binding.getExceptionTypes()) {
recordTypeBinding(exceptionBinding);
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(exceptionBinding);
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
// parameter
if (binding.getParameterTypes() != null) {
for (ITypeBinding parameterBinding : binding.getParameterTypes()) {
recordTypeBinding(parameterBinding);
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(parameterBinding);
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
return true;
}
Example 91
Project: virgo.ide-master File: ArtifactAnalyserTypeVisitor.java View source code |
/**
* {@inheritDoc}
*/
@Override
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
if (binding == null) {
return true;
}
// return value
if (binding.getReturnType() != null) {
String fqn = binding.getReturnType().getQualifiedName();
if (!"void".equals(fqn)) {
recordTypeBinding(binding.getReturnType());
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(binding.getReturnType());
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
// throws clause
if (binding.getExceptionTypes() != null) {
for (ITypeBinding exceptionBinding : binding.getExceptionTypes()) {
recordTypeBinding(exceptionBinding);
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(exceptionBinding);
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
// parameter
if (binding.getParameterTypes() != null) {
for (ITypeBinding parameterBinding : binding.getParameterTypes()) {
recordTypeBinding(parameterBinding);
if (!Modifier.isPrivate(node.getModifiers())) {
IPackageBinding packageBinding = getPackageBinding(parameterBinding);
if (packageBinding != null) {
this.partialManifest.recordUsesPackage(this.typePackage, packageBinding.getName());
}
}
}
}
return true;
}
Example 92
Project: webtools.javaee-master File: CreateJavaEEArtifactTemplateModel.java View source code |
public List<Constructor> getConstructors() { List<Constructor> constrs = new ArrayList<Constructor>(); String superclass = dataModel.getStringProperty(SUPERCLASS); if (superclass != null && superclass.length() > 0) { IProject p = (IProject) dataModel.getProperty(PROJECT); IJavaProject javaProject = JavaCore.create(p); if (javaProject != null) { try { IType type = javaProject.findType(superclass); if (type != null) { if (type.isBinary()) { IMethod[] methods = type.getMethods(); for (IMethod method : methods) { if (method.isConstructor()) constrs.add(new BinaryConstructor(method)); } } else { ICompilationUnit compilationUnit = type.getCompilationUnit(); TypeDeclaration declarationFromType = getTypeDeclarationFromType(superclass, compilationUnit); if (declarationFromType != null) { MethodDeclaration[] methods = declarationFromType.getMethods(); for (MethodDeclaration method : methods) { if (method.isConstructor()) constrs.add(new SourceConstructor(method)); } } } } } catch (JavaModelException e) { J2EEPlugin.logError(e); } } } return constrs; }
Example 93
Project: Wol-master File: ASTMethodExplorer.java View source code |
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
if (binding != null) {
ITypeBinding[] params = binding.getParameterTypes();
String paramString = "(";
for (int i = 0; i < params.length; i++) {
paramString += params[i].getName();
if (i < params.length - 1)
paramString += ",";
}
paramString += ")";
String key = binding.getDeclaringClass().getName() + "." + binding.getName() + paramString;
ITypeBinding declaredClassBinding = binding.getDeclaringClass();
// overrides super method
ITypeBinding superClassBinding = declaredClassBinding.getSuperclass();
boolean skip = checkSuperClass(binding, superClassBinding);
// is implementation of interface
ITypeBinding[] interfaceBindings = declaredClassBinding.getInterfaces();
skip = skip || checkInterfaces(binding, interfaceBindings);
if (superClassBinding != null) {
// classDependencies
classDependencies.put(declaredClassBinding.getName(), superClassBinding.getName());
// WOComponent && title()
boolean isWOComponent = superClassBinding.getName().equals("WOComponent");
skip = skip || (isWOComponent && binding.getName().equals("title"));
}
// DirectAction.Action()
boolean isDirectAction = declaredClassBinding.getName().equals("DirectAction");
skip = skip || (isDirectAction && (binding.getName().endsWith("Action") || binding.getName().equals("performActionNamed")));
// app || logic && Constructor
IPackageBinding packageBinding = declaredClassBinding.getPackage();
String[] comps = packageBinding.getNameComponents();
if (comps.length > 0) {
String comp = comps[comps.length - 1];
skip = skip || ((comp.equals("app") || comp.equals("logic")) && binding.isConstructor());
}
if (!usedMethods.containsKey(key)) {
List<String> value = new ArrayList<String>();
value.add(iCompUnit.getHandleIdentifier());
value.add(binding.getName());
value.add(binding.getReturnType().getName());
value.add(skip + "");
declaredMethods.put(key, value);
}
}
return true;
}
Example 94
Project: wolips-master File: ASTMethodExplorer.java View source code |
public boolean visit(MethodDeclaration node) {
IMethodBinding binding = node.resolveBinding();
if (binding != null) {
ITypeBinding[] params = binding.getParameterTypes();
String paramString = "(";
for (int i = 0; i < params.length; i++) {
paramString += params[i].getName();
if (i < params.length - 1)
paramString += ",";
}
paramString += ")";
String key = binding.getDeclaringClass().getName() + "." + binding.getName() + paramString;
ITypeBinding declaredClassBinding = binding.getDeclaringClass();
// overrides super method
ITypeBinding superClassBinding = declaredClassBinding.getSuperclass();
boolean skip = checkSuperClass(binding, superClassBinding);
// is implementation of interface
ITypeBinding[] interfaceBindings = declaredClassBinding.getInterfaces();
skip = skip || checkInterfaces(binding, interfaceBindings);
if (superClassBinding != null) {
// classDependencies
classDependencies.put(declaredClassBinding.getName(), superClassBinding.getName());
// WOComponent && title()
boolean isWOComponent = superClassBinding.getName().equals("WOComponent");
skip = skip || (isWOComponent && binding.getName().equals("title"));
}
// DirectAction.Action()
boolean isDirectAction = declaredClassBinding.getName().equals("DirectAction");
skip = skip || (isDirectAction && (binding.getName().endsWith("Action") || binding.getName().equals("performActionNamed")));
// app || logic && Constructor
IPackageBinding packageBinding = declaredClassBinding.getPackage();
String[] comps = packageBinding.getNameComponents();
if (comps.length > 0) {
String comp = comps[comps.length - 1];
skip = skip || ((comp.equals("app") || comp.equals("logic")) && binding.isConstructor());
}
if (!usedMethods.containsKey(key)) {
List<String> value = new ArrayList<String>();
value.add(iCompUnit.getHandleIdentifier());
value.add(binding.getName());
value.add(binding.getReturnType().getName());
value.add(skip + "");
declaredMethods.put(key, value);
}
}
return true;
}
Example 95
Project: Aorm-Eclipse-Plugin-master File: SourceGenerator.java View source code |
private static void merge(CompilationUnit unit, String pkgName, String typeName, String auth, String dbName, List<String> tableCreators) {
unit.recordModifications();
AST ast = unit.getAST();
TypeDeclaration type = (TypeDeclaration) unit.types().get(0);
ImportDeclaration id = ast.newImportDeclaration();
id.setName(ast.newName("cn.ieclipse.aorm.Session"));
unit.imports().add(id);
id = ast.newImportDeclaration();
id.setName(ast.newName("android.content.UriMatcher"));
unit.imports().add(id);
id = ast.newImportDeclaration();
id.setName(ast.newName("android.database.sqlite.SQLiteDatabase"));
unit.imports().add(id);
id = ast.newImportDeclaration();
id.setName(ast.newName("android.database.sqlite.SQLiteOpenHelper"));
unit.imports().add(id);
id = ast.newImportDeclaration();
id.setName(ast.newName("java.net.Uri"));
unit.imports().add(id);
id = ast.newImportDeclaration();
id.setName(ast.newName("android.content.ContentValue"));
unit.imports().add(id);
VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
vdf.setName(ast.newSimpleName("AUTH"));
StringLiteral sl = ast.newStringLiteral();
sl.setLiteralValue(auth);
vdf.setInitializer(sl);
FieldDeclaration fd = ast.newFieldDeclaration(vdf);
fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
fd.setType(ast.newSimpleType(ast.newSimpleName("String")));
int i = 0;
type.bodyDeclarations().add(i++, fd);
// URI = Uri.parse("content://" + AUTH);
vdf = ast.newVariableDeclarationFragment();
vdf.setName(ast.newSimpleName("URI"));
MethodInvocation mi = ast.newMethodInvocation();
mi.setExpression(ast.newSimpleName("Uri"));
mi.setName(ast.newSimpleName("parse"));
InfixExpression fix = ast.newInfixExpression();
fix.setOperator(InfixExpression.Operator.PLUS);
sl = ast.newStringLiteral();
sl.setLiteralValue("content://");
fix.setLeftOperand(sl);
fix.setRightOperand(ast.newSimpleName("AUTH"));
mi.arguments().add(fix);
vdf.setInitializer(mi);
fd = ast.newFieldDeclaration(vdf);
fd.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL)));
fd.setType(ast.newSimpleType(ast.newSimpleName("Uri")));
type.bodyDeclarations().add(i++, fd);
// private mOpenHelper;
vdf = ast.newVariableDeclarationFragment();
vdf.setName(ast.newSimpleName("mOpenHelper"));
fd = ast.newFieldDeclaration(vdf);
fd.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD));
fd.setType(ast.newSimpleType(ast.newName("SQLiteOpenHelper")));
type.bodyDeclarations().add(i++, fd);
// private static session;
vdf = ast.newVariableDeclarationFragment();
vdf.setName(ast.newSimpleName("session"));
fd = ast.newFieldDeclaration(vdf);
fd.modifiers().addAll(ast.newModifiers((Modifier.PRIVATE | Modifier.STATIC)));
fd.setType(ast.newSimpleType(ast.newName("Session")));
type.bodyDeclarations().add(i++, fd);
// public static Session getSession(){
// return session;
// }
MethodDeclaration md = ast.newMethodDeclaration();
md.modifiers().addAll(ast.newModifiers((Modifier.PUBLIC | Modifier.STATIC)));
md.setReturnType2(ast.newSimpleType(ast.newName("Session")));
md.setName(ast.newSimpleName("getSession"));
Block methodBlock = ast.newBlock();
ReturnStatement returnStmt = ast.newReturnStatement();
returnStmt.setExpression(ast.newSimpleName("session"));
methodBlock.statements().add(returnStmt);
md.setBody(methodBlock);
type.bodyDeclarations().add(i, md);
// modify onCreate
rewriteOnCreate(unit, dbName, tableCreators);
}
Example 96
Project: Bracketeer-master File: ClosingBracketHintVisitor.java View source code |
@Override
public boolean visit(MethodDeclaration node) {
// starting a function empties the stack... (which should already be empty on good flow)
_scopeStack.clear();
StringBuffer hint = new StringBuffer();
hint.append(node.getName().getIdentifier());
/* TODO: specific params: exclude function parameters (show only the name) */
//$NON-NLS-1$
hint.append("( ");
for (@SuppressWarnings("rawtypes") Iterator iterator = node.parameters().iterator(); iterator.hasNext(); ) {
SingleVariableDeclaration param = (SingleVariableDeclaration) iterator.next();
hint.append(param.getName());
if (iterator.hasNext())
//$NON-NLS-1$
hint.append(", ");
}
//$NON-NLS-1$
hint.append(" )");
int startLoc = node.getName().getStartPosition();
int endLoc = node.getStartPosition() + node.getLength() - 1;
try {
//$NON-NLS-1$
_container.add(new Hint("function", startLoc, endLoc, hint.toString()));
} catch (BadLocationException e) {
_cancelProcessing.set(true);
}
return shouldContinue();
}
Example 97
Project: eclipse-i18ntools-master File: ResourceBundleWrapper.java View source code |
/** * Refactors the source code to replace selected source by literal. * * @param nodeFinder * @param literalName * @param resolver * @return */ @SuppressWarnings("unchecked") private boolean effectiveAddLiteral(final ASTNodeFinder nodeFinder, final String literalName, final ASTExpressionResolver resolver) { final ASTNode parent = nodeFinder.getParentNode(); final AST ast = parent.getAST(); final MethodInvocation replacement = ast.newMethodInvocation(); replacement.setExpression(ast.newName(this.resourceBundleName + "." + literalName)); replacement.setName(ast.newSimpleName("value")); final EnumDeclaration enumDeclaration = (EnumDeclaration) this.enumDomCompilationUnit.types().get(0); final EnumConstantDeclaration enumConstantDeclaration = enumDeclaration.getAST().newEnumConstantDeclaration(); enumConstantDeclaration.setName(enumDeclaration.getAST().newSimpleName(literalName)); enumDeclaration.enumConstants().add(enumConstantDeclaration); boolean hasMessageKeyConstructor = false; for (final Iterator<Object> iterator = enumDeclaration.bodyDeclarations().iterator(); iterator.hasNext() && !hasMessageKeyConstructor; ) { final Object next = iterator.next(); if (next instanceof MethodDeclaration) { final MethodDeclaration methodDeclaration = (MethodDeclaration) next; if (methodDeclaration.isConstructor() && methodDeclaration.parameters().size() > 0) { hasMessageKeyConstructor = true; } } } if (hasMessageKeyConstructor) { final StringLiteral literal = enumDeclaration.getAST().newStringLiteral(); literal.setLiteralValue(literalName); enumConstantDeclaration.arguments().add(literal); } StructuralPropertyDescriptor locationInParent = null; if (nodeFinder.getFoundNode() != null) { locationInParent = nodeFinder.getFoundNode().getLocationInParent(); } else { // TODO return false; } ResourceBundleWrapper.addImportToCompilationUnitIfMissing(nodeFinder.getParentNode(), this.packageName + "." + this.resourceBundleName); if (locationInParent.isChildListProperty()) { final List<Object> list = (List<Object>) parent.getStructuralProperty(locationInParent); final int index = list.indexOf(nodeFinder.getFoundNode()); list.remove(nodeFinder.getFoundNode()); list.add(index, replacement); } else { parent.setStructuralProperty(locationInParent, replacement); } for (final Expression parameter : resolver.getMessageParameters()) { final Expression newParameter = ASTTreeCloner.clone(parameter); replacement.arguments().add(newParameter); } String messagePattern = resolver.getMessagePattern(); if (this.prefixMessageByKey) { messagePattern = String.format("[%s] %s", literalName, messagePattern); } this.properties.put(literalName, messagePattern); return true; }
Example 98
Project: j2objc-master File: TreeConverter.java View source code |
private static TreeNode convertInner(ASTNode jdtNode) {
switch(jdtNode.getNodeType()) {
case ASTNode.ANNOTATION_TYPE_DECLARATION:
return convertAnnotationTypeDeclaration((org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) jdtNode);
case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
return convertAnnotationTypeMemberDeclaration((org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) jdtNode);
case ASTNode.ARRAY_ACCESS:
return convertArrayAccess((org.eclipse.jdt.core.dom.ArrayAccess) jdtNode);
case ASTNode.ARRAY_CREATION:
return convertArrayCreation((org.eclipse.jdt.core.dom.ArrayCreation) jdtNode);
case ASTNode.ARRAY_INITIALIZER:
return convertArrayInitializer((org.eclipse.jdt.core.dom.ArrayInitializer) jdtNode);
case ASTNode.ARRAY_TYPE:
return convertArrayType((org.eclipse.jdt.core.dom.ArrayType) jdtNode);
case ASTNode.ASSERT_STATEMENT:
return convertAssertStatement((org.eclipse.jdt.core.dom.AssertStatement) jdtNode);
case ASTNode.ASSIGNMENT:
return convertAssignment((org.eclipse.jdt.core.dom.Assignment) jdtNode);
case ASTNode.BLOCK:
return convertBlock((org.eclipse.jdt.core.dom.Block) jdtNode);
case ASTNode.BLOCK_COMMENT:
return new BlockComment();
case ASTNode.BOOLEAN_LITERAL:
return convertBooleanLiteral((org.eclipse.jdt.core.dom.BooleanLiteral) jdtNode);
case ASTNode.BREAK_STATEMENT:
return convertBreakStatement((org.eclipse.jdt.core.dom.BreakStatement) jdtNode);
case ASTNode.CAST_EXPRESSION:
return convertCastExpression((org.eclipse.jdt.core.dom.CastExpression) jdtNode);
case ASTNode.CATCH_CLAUSE:
return convertCatchClause((org.eclipse.jdt.core.dom.CatchClause) jdtNode);
case ASTNode.CHARACTER_LITERAL:
return convertCharacterLiteral((org.eclipse.jdt.core.dom.CharacterLiteral) jdtNode);
case ASTNode.CLASS_INSTANCE_CREATION:
return convertClassInstanceCreation((org.eclipse.jdt.core.dom.ClassInstanceCreation) jdtNode);
case ASTNode.CONDITIONAL_EXPRESSION:
return convertConditionalExpression((org.eclipse.jdt.core.dom.ConditionalExpression) jdtNode);
case ASTNode.CONSTRUCTOR_INVOCATION:
return convertConstructorInvocation((org.eclipse.jdt.core.dom.ConstructorInvocation) jdtNode);
case ASTNode.CONTINUE_STATEMENT:
return convertContinueStatement((org.eclipse.jdt.core.dom.ContinueStatement) jdtNode);
case ASTNode.CREATION_REFERENCE:
return convertCreationReference((org.eclipse.jdt.core.dom.CreationReference) jdtNode);
case ASTNode.DIMENSION:
return convertDimension((org.eclipse.jdt.core.dom.Dimension) jdtNode);
case ASTNode.DO_STATEMENT:
return convertDoStatement((org.eclipse.jdt.core.dom.DoStatement) jdtNode);
case ASTNode.EMPTY_STATEMENT:
return new EmptyStatement();
case ASTNode.ENHANCED_FOR_STATEMENT:
return convertEnhancedForStatement((org.eclipse.jdt.core.dom.EnhancedForStatement) jdtNode);
case ASTNode.ENUM_CONSTANT_DECLARATION:
return convertEnumConstantDeclaration((org.eclipse.jdt.core.dom.EnumConstantDeclaration) jdtNode);
case ASTNode.ENUM_DECLARATION:
return convertEnumDeclaration((org.eclipse.jdt.core.dom.EnumDeclaration) jdtNode);
case ASTNode.EXPRESSION_METHOD_REFERENCE:
return convertExpressionMethodReference((org.eclipse.jdt.core.dom.ExpressionMethodReference) jdtNode);
case ASTNode.EXPRESSION_STATEMENT:
return convertExpressionStatement((org.eclipse.jdt.core.dom.ExpressionStatement) jdtNode);
case ASTNode.FIELD_ACCESS:
return convertFieldAccess((org.eclipse.jdt.core.dom.FieldAccess) jdtNode);
case ASTNode.FIELD_DECLARATION:
return convertFieldDeclaration((org.eclipse.jdt.core.dom.FieldDeclaration) jdtNode);
case ASTNode.FOR_STATEMENT:
return convertForStatement((org.eclipse.jdt.core.dom.ForStatement) jdtNode);
case ASTNode.IF_STATEMENT:
return convertIfStatement((org.eclipse.jdt.core.dom.IfStatement) jdtNode);
case ASTNode.INFIX_EXPRESSION:
return convertInfixExpression((org.eclipse.jdt.core.dom.InfixExpression) jdtNode);
case ASTNode.INTERSECTION_TYPE:
return convertIntersectionType((org.eclipse.jdt.core.dom.IntersectionType) jdtNode);
case ASTNode.INITIALIZER:
return convertInitializer((org.eclipse.jdt.core.dom.Initializer) jdtNode);
case ASTNode.INSTANCEOF_EXPRESSION:
return convertInstanceofExpression((org.eclipse.jdt.core.dom.InstanceofExpression) jdtNode);
case ASTNode.JAVADOC:
return convertJavadoc((org.eclipse.jdt.core.dom.Javadoc) jdtNode);
case ASTNode.LABELED_STATEMENT:
return convertLabeledStatement((org.eclipse.jdt.core.dom.LabeledStatement) jdtNode);
case ASTNode.LAMBDA_EXPRESSION:
return convertLambdaExpression((org.eclipse.jdt.core.dom.LambdaExpression) jdtNode);
case ASTNode.LINE_COMMENT:
return new LineComment();
case ASTNode.MARKER_ANNOTATION:
return convertMarkerAnnotation((org.eclipse.jdt.core.dom.MarkerAnnotation) jdtNode);
case ASTNode.MEMBER_VALUE_PAIR:
return convertMemberValuePair((org.eclipse.jdt.core.dom.MemberValuePair) jdtNode);
case ASTNode.METHOD_DECLARATION:
return convertMethodDeclaration((org.eclipse.jdt.core.dom.MethodDeclaration) jdtNode);
case ASTNode.METHOD_INVOCATION:
return convertMethodInvocation((org.eclipse.jdt.core.dom.MethodInvocation) jdtNode);
case ASTNode.NAME_QUALIFIED_TYPE:
return convertNameQualifiedType((org.eclipse.jdt.core.dom.NameQualifiedType) jdtNode);
case ASTNode.NORMAL_ANNOTATION:
return convertNormalAnnotation((org.eclipse.jdt.core.dom.NormalAnnotation) jdtNode);
case ASTNode.NULL_LITERAL:
return new NullLiteral(BindingConverter.NULL_TYPE);
case ASTNode.NUMBER_LITERAL:
return convertNumberLiteral((org.eclipse.jdt.core.dom.NumberLiteral) jdtNode);
case ASTNode.PACKAGE_DECLARATION:
return convertPackageDeclaration((org.eclipse.jdt.core.dom.PackageDeclaration) jdtNode);
case ASTNode.PARAMETERIZED_TYPE:
return convertParameterizedType((org.eclipse.jdt.core.dom.ParameterizedType) jdtNode);
case ASTNode.PARENTHESIZED_EXPRESSION:
return convertParenthesizedExpression((org.eclipse.jdt.core.dom.ParenthesizedExpression) jdtNode);
case ASTNode.POSTFIX_EXPRESSION:
return convertPostfixExpression((org.eclipse.jdt.core.dom.PostfixExpression) jdtNode);
case ASTNode.PREFIX_EXPRESSION:
return convertPrefixExpression((org.eclipse.jdt.core.dom.PrefixExpression) jdtNode);
case ASTNode.PRIMITIVE_TYPE:
return convertPrimitiveType((org.eclipse.jdt.core.dom.PrimitiveType) jdtNode);
case ASTNode.QUALIFIED_NAME:
return convertQualifiedName((org.eclipse.jdt.core.dom.QualifiedName) jdtNode);
case ASTNode.QUALIFIED_TYPE:
return convertQualifiedType((org.eclipse.jdt.core.dom.QualifiedType) jdtNode);
case ASTNode.RETURN_STATEMENT:
return convertReturnStatement((org.eclipse.jdt.core.dom.ReturnStatement) jdtNode);
case ASTNode.SIMPLE_NAME:
return convertSimpleName((org.eclipse.jdt.core.dom.SimpleName) jdtNode);
case ASTNode.SIMPLE_TYPE:
return convertSimpleType((org.eclipse.jdt.core.dom.SimpleType) jdtNode);
case ASTNode.SINGLE_MEMBER_ANNOTATION:
return convertSingleMemberAnnotation((org.eclipse.jdt.core.dom.SingleMemberAnnotation) jdtNode);
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return convertSingleVariableDeclaration((org.eclipse.jdt.core.dom.SingleVariableDeclaration) jdtNode);
case ASTNode.STRING_LITERAL:
return convertStringLiteral((org.eclipse.jdt.core.dom.StringLiteral) jdtNode);
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
return convertSuperConstructorInvocation((org.eclipse.jdt.core.dom.SuperConstructorInvocation) jdtNode);
case ASTNode.SUPER_FIELD_ACCESS:
return convertSuperFieldAccess((org.eclipse.jdt.core.dom.SuperFieldAccess) jdtNode);
case ASTNode.SUPER_METHOD_INVOCATION:
return convertSuperMethodInvocation((org.eclipse.jdt.core.dom.SuperMethodInvocation) jdtNode);
case ASTNode.SUPER_METHOD_REFERENCE:
return convertSuperMethodReference((org.eclipse.jdt.core.dom.SuperMethodReference) jdtNode);
case ASTNode.SWITCH_CASE:
return convertSwitchCase((org.eclipse.jdt.core.dom.SwitchCase) jdtNode);
case ASTNode.SWITCH_STATEMENT:
return convertSwitchStatement((org.eclipse.jdt.core.dom.SwitchStatement) jdtNode);
case ASTNode.SYNCHRONIZED_STATEMENT:
return convertSynchronizedStatement((org.eclipse.jdt.core.dom.SynchronizedStatement) jdtNode);
case ASTNode.TAG_ELEMENT:
return convertTagElement((org.eclipse.jdt.core.dom.TagElement) jdtNode);
case ASTNode.TEXT_ELEMENT:
return convertTextElement(((org.eclipse.jdt.core.dom.TextElement) jdtNode).getText());
case ASTNode.THIS_EXPRESSION:
return convertThisExpression((org.eclipse.jdt.core.dom.ThisExpression) jdtNode);
case ASTNode.THROW_STATEMENT:
return convertThrowStatement((org.eclipse.jdt.core.dom.ThrowStatement) jdtNode);
case ASTNode.TRY_STATEMENT:
return convertTryStatement((org.eclipse.jdt.core.dom.TryStatement) jdtNode);
case ASTNode.TYPE_DECLARATION:
return convertTypeDeclaration((org.eclipse.jdt.core.dom.TypeDeclaration) jdtNode);
case ASTNode.TYPE_DECLARATION_STATEMENT:
return convertTypeDeclarationStatement((org.eclipse.jdt.core.dom.TypeDeclarationStatement) jdtNode);
case ASTNode.TYPE_LITERAL:
return convertTypeLiteral((org.eclipse.jdt.core.dom.TypeLiteral) jdtNode);
case ASTNode.TYPE_METHOD_REFERENCE:
return convertTypeMethodReference((org.eclipse.jdt.core.dom.TypeMethodReference) jdtNode);
case ASTNode.UNION_TYPE:
return convertUnionType((org.eclipse.jdt.core.dom.UnionType) jdtNode);
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return convertVariableDeclarationExpression((org.eclipse.jdt.core.dom.VariableDeclarationExpression) jdtNode);
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
return convertVariableDeclarationFragment((org.eclipse.jdt.core.dom.VariableDeclarationFragment) jdtNode);
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return convertVariableDeclarationStatement((org.eclipse.jdt.core.dom.VariableDeclarationStatement) jdtNode);
case ASTNode.WHILE_STATEMENT:
return convertWhileStatement((org.eclipse.jdt.core.dom.WhileStatement) jdtNode);
// information from their subtree so we just convert them to TextElement.
case ASTNode.MEMBER_REF:
case ASTNode.METHOD_REF:
case ASTNode.METHOD_REF_PARAMETER:
return convertTextElement(jdtNode.toString());
case ASTNode.COMPILATION_UNIT:
throw new AssertionError("CompilationUnit must be converted using convertCompilationUnit()");
default:
throw new AssertionError("Unknown node type: " + jdtNode.getClass().getName());
}
}
Example 99
Project: platform_sdk-master File: AddSuppressAnnotation.java View source code |
/** * Adds any applicable suppress lint fix resolutions into the given list * * @param marker the marker to create fixes for * @param id the issue id * @param resolutions a list to add the created resolutions into, if any */ public static void createFixes(IMarker marker, String id, List<IMarkerResolution> resolutions) { ITextEditor textEditor = AdtUtils.getActiveTextEditor(); IDocumentProvider provider = textEditor.getDocumentProvider(); IEditorInput editorInput = textEditor.getEditorInput(); IDocument document = provider.getDocument(editorInput); if (document == null) { return; } IWorkingCopyManager manager = JavaUI.getWorkingCopyManager(); ICompilationUnit compilationUnit = manager.getWorkingCopy(editorInput); int offset = 0; int length = 0; int start = marker.getAttribute(IMarker.CHAR_START, -1); int end = marker.getAttribute(IMarker.CHAR_END, -1); offset = start; length = end - start; CompilationUnit root = SharedASTProvider.getAST(compilationUnit, SharedASTProvider.WAIT_YES, null); if (root == null) { return; } int api = -1; if (id.equals(ApiDetector.UNSUPPORTED.getId())) { String message = marker.getAttribute(IMarker.MESSAGE, null); if (message != null) { //$NON-NLS-1$ Pattern pattern = Pattern.compile("\\s(\\d+)\\s"); Matcher matcher = pattern.matcher(message); if (matcher.find()) { api = Integer.parseInt(matcher.group(1)); } } } Issue issue = EclipseLintClient.getRegistry().getIssue(id); boolean isClassDetector = issue != null && issue.getScope().contains(Scope.CLASS_FILE); // Don't offer to suppress (with an annotation) the annotation checks if (issue == AnnotationDetector.ISSUE) { return; } NodeFinder nodeFinder = new NodeFinder(root, offset, length); ASTNode coveringNode; if (offset <= 0) { // Error added on the first line of a Java class: typically from a class-based // detector which lacks line information. Map this to the top level class // in the file instead. coveringNode = root; if (root.types() != null && root.types().size() > 0) { Object type = root.types().get(0); if (type instanceof ASTNode) { coveringNode = (ASTNode) type; } } } else { coveringNode = nodeFinder.getCoveringNode(); } for (ASTNode body = coveringNode; body != null; body = body.getParent()) { if (body instanceof BodyDeclaration) { BodyDeclaration declaration = (BodyDeclaration) body; String target = null; if (body instanceof MethodDeclaration) { //$NON-NLS-1$ target = ((MethodDeclaration) body).getName().toString() + "()"; } else if (body instanceof FieldDeclaration) { target = "field"; FieldDeclaration field = (FieldDeclaration) body; if (field.fragments() != null && field.fragments().size() > 0) { ASTNode first = (ASTNode) field.fragments().get(0); if (first instanceof VariableDeclarationFragment) { VariableDeclarationFragment decl = (VariableDeclarationFragment) first; target = decl.getName().toString(); } } } else if (body instanceof AnonymousClassDeclaration) { target = "anonymous class"; } else if (body instanceof TypeDeclaration) { target = ((TypeDeclaration) body).getName().toString(); } else { target = body.getClass().getSimpleName(); } // and on classes, not on variable declarations if (isClassDetector && !(body instanceof MethodDeclaration || body instanceof TypeDeclaration || body instanceof AnonymousClassDeclaration || body instanceof FieldDeclaration)) { continue; } String desc = String.format("Add @SuppressLint '%1$s\' to '%2$s'", id, target); resolutions.add(new AddSuppressAnnotation(id, marker, declaration, desc, null)); if (api != -1 && // @TargetApi is only valid on methods and classes, not fields etc (body instanceof MethodDeclaration || body instanceof TypeDeclaration)) { String apiString = AdtUtils.getBuildCodes(api); if (apiString == null) { apiString = Integer.toString(api); } desc = String.format("Add @TargetApi(%1$s) to '%2$s'", apiString, target); resolutions.add(new AddSuppressAnnotation(id, marker, declaration, desc, apiString)); } } } }
Example 100
Project: rascal-master File: SourceConverter.java View source code |
public void endVisit(MethodDeclaration node) {
ownValue = scopeManager.pop();
ASTNode parent = node.getParent();
if (parent instanceof TypeDeclaration) {
// TODO: why can this node.resolveBinding sometimes be null?
fillOverrides(node.resolveBinding(), ((TypeDeclaration) parent).resolveBinding());
} else if (parent instanceof AnonymousClassDeclaration) {
fillOverrides(node.resolveBinding(), ((AnonymousClassDeclaration) parent).resolveBinding());
}
IConstructor type = bindingsResolver.resolveType(node.resolveBinding(), true);
insert(types, ownValue, type);
}
Example 101
Project: swt-javafx-master File: Check64CompilationParticipant.java View source code |
void createBadOverwrittenMethodProblems(IJavaProject project, String root) throws CoreException { if (sources == null) return; IProject proj = project.getProject(); HashMap<String, TypeDeclaration> cache = new HashMap<String, TypeDeclaration>(); for (Iterator<String> iterator = sources.iterator(); iterator.hasNext(); ) { String path = iterator.next(); IResource resource = getResourceWithoutErrors(proj, path, false); if (resource == null) continue; TypeDeclaration type = loadType(cache, path); MethodDeclaration[] methods = type.getMethods(); List<TypeDeclaration> superclasses = new ArrayList<TypeDeclaration>(); TypeDeclaration temp = type; while (true) { Type supertype = temp.getSuperclassType(); if (supertype == null) break; TypeDeclaration stype = loadType(cache, resolvePath(path, supertype.toString())); if (stype == null) break; superclasses.add(stype); temp = stype; } for (int i = 0; i < methods.length; i++) { MethodDeclaration method = methods[i]; for (Iterator<TypeDeclaration> iterator2 = superclasses.iterator(); iterator2.hasNext(); ) { TypeDeclaration supertype = iterator2.next(); MethodDeclaration[] supermethods = supertype.getMethods(); for (int j = 0; j < supermethods.length; j++) { MethodDeclaration supermethod = supermethods[j]; if (method.getName().getIdentifier().equals(supermethod.getName().getIdentifier()) && method.parameters().size() == supermethod.parameters().size()) { List<SingleVariableDeclaration> mParams = method.parameters(); List<SingleVariableDeclaration> sParams = supermethod.parameters(); for (int k = 0; k < sParams.size(); k++) { SingleVariableDeclaration p1 = mParams.get(k); SingleVariableDeclaration p2 = sParams.get(k); String r1 = p1.getType().toString(); String r2 = p2.getType().toString(); if (is64Type(r1) && is64Type(r2)) { if (!r1.equals(r2) && p1.getName().getIdentifier().equals(p2.getName().getIdentifier())) { String message = "\"" + p1.getName().getIdentifier() + "\" parameter type does not match super declaration"; createProblem(resource, message, p1.getStartPosition(), p1.getStartPosition() + p1.toString().length()); } } } } } } } } }