use of org.eclipse.jdt.core.dom.ImportDeclaration in project AutoRefactor by JnRouvignac.
the class TypeNameDecider method getImportedTypes.
private static TreeSet<String> getImportedTypes(final CompilationUnit cu) {
TreeSet<String> results = new TreeSet<>();
for (ImportDeclaration importDecl : (List<ImportDeclaration>) cu.imports()) {
Name importName = importDecl.getName();
results.add(importName.getFullyQualifiedName());
}
return results;
}
use of org.eclipse.jdt.core.dom.ImportDeclaration in project flow by vaadin.
the class CodeTest method gwtGenerics.
private static void gwtGenerics(File file) throws IOException {
ASTParser parser = ASTParser.newParser(AST.JLS8);
String value = FileUtils.readFileToString(file, UTF_8);
parser.setSource(value.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.accept(new ASTVisitor() {
Set<String> imports = new HashSet<>();
String packageName;
@Override
public boolean visit(PackageDeclaration node) {
packageName = node.getName().toString();
return false;
}
@Override
public boolean visit(ImportDeclaration node) {
imports.add(node.getName().toString());
return false;
}
@Override
public boolean visit(VariableDeclarationStatement node) {
for (Object frament : node.fragments()) {
if (frament instanceof VariableDeclarationFragment) {
VariableDeclarationFragment variableDeclaration = (VariableDeclarationFragment) frament;
Expression expression = variableDeclaration.getInitializer();
if (expression instanceof ClassInstanceCreation) {
ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
Class<?> typeClass = getClass(node.getType());
Class<?> instanceClass = getClass(classInstanceCreation.getType());
if (typeClass != instanceClass && typeClass.isAssignableFrom(instanceClass)) {
fail("Variable type must be the specific implementation in " + node + " in " + file.getName());
}
}
}
}
return false;
}
private Class<?> getClass(Type type) {
if (type instanceof ArrayType) {
type = ((ArrayType) type).getElementType();
}
if (type instanceof ParameterizedType) {
type = ((ParameterizedType) type).getType();
}
String className = type.toString();
if (className.indexOf('.') == -1) {
String dotPrefix = '.' + className;
for (String i : imports) {
if (i.endsWith(dotPrefix)) {
className = i;
break;
}
}
}
Class<?> clas = getClass(className);
if (clas != null) {
return clas;
}
clas = getClass("java.lang." + className);
if (clas != null) {
return clas;
}
try {
String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
if (fileName.equals(className)) {
return Class.forName(packageName + '.' + fileName);
}
clas = getClass(packageName + '.' + className);
if (clas != null) {
return clas;
}
return Class.forName(packageName + '.' + fileName + '$' + className);
} catch (ClassNotFoundException e) {
fail("Could not load class " + e);
return null;
}
}
private Class<?> getClass(String className) {
try {
return ClassUtils.getClass(className);
} catch (ClassNotFoundException e) {
return null;
}
}
});
}
use of org.eclipse.jdt.core.dom.ImportDeclaration in project eap-additional-testsuite by jboss-set.
the class MethodInfo method parse.
public static void parse(String str) throws IOException {
types.clear();
fields.clear();
methods.clear();
classInstanceCreations.clear();
typesNotResolved.clear();
methodsNotResolved.clear();
methodInvocations.clear();
imports.clear();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(readFileToString(str).toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
HashMap<String, String> declarations = new HashMap();
cu.accept(new ASTVisitor() {
Set names = new HashSet();
int blockCount = 0;
public boolean visit(FieldDeclaration node) {
String name = node.fragments().get(0).toString().split("=")[0].trim();
String type = node.getType().toString();
declarations.put(name, type);
if (!node.modifiers().toString().contains("private")) {
fields.put(name, type);
}
ArrayList<String> types0 = new ArrayList<>();
String type2 = null;
do {
if (type.contains("[")) {
type = type.replaceAll("\\[\\]", "");
if (type.contains("[")) {
type = type.substring(0, type.indexOf("["));
}
}
if (type.contains("<")) {
String type3 = type;
type = type.substring(0, type.indexOf("<"));
if (type3.substring(type3.indexOf("<") + 1).startsWith("<>") || type3.substring(type.indexOf("<") + 1).startsWith("<T>")) {
type2 = null;
} else {
type2 = type3.substring(type3.indexOf("<") + 1, type3.lastIndexOf(">"));
if (type2.contains(",")) {
if (type2.substring(0, type2.indexOf(",")).contains("<")) {
types0.add(type2);
} else {
types0.add(type2.substring(0, type2.indexOf(",")));
types0.add(type2.substring(type2.indexOf(",") + 1));
}
} else {
types0.add(type2);
}
}
}
types.addAll(Arrays.asList(type.split(" extends ")));
if (types0.size() != 0) {
type = types0.remove(0);
} else {
type = null;
}
} while (type != null);
return false;
}
public boolean visit(EnumConstantDeclaration node) {
String type = node.getName().toString();
// System.out.println("ccccc : " + type);
List<String> constants = node.arguments();
for (String f : constants) {
// System.out.println("ccccc : " + type + "." + f);
declarations.put(type + "." + f, type);
if (!node.modifiers().toString().contains("private")) {
fields.put(type + "." + f, type);
}
}
return false;
}
public boolean visit(MethodDeclaration node) {
if (node.getName().getIdentifier() != null) {
String returnType = null;
if (node.getReturnType2() == null) {
returnType = "";
} else {
returnType = node.getReturnType2().toString();
}
HashMap<String, String> bDeclarations = new HashMap();
bDeclarations.putAll(importedClassFields);
bDeclarations.putAll(declarations);
methods.put(node.getName().toString() + "_Return_Type", new String[] { returnType });
String[] methodParams = new String[node.parameters().size()];
List params = node.parameters();
int i = 0;
for (Object s : params) {
String type = ((SingleVariableDeclaration) s).getType().toString();
bDeclarations.put(((SingleVariableDeclaration) s).getName().toString(), type);
ArrayList<String> types0 = new ArrayList<>();
String type2 = null;
String typeF = null;
do {
if (type.contains("[")) {
type = type.replaceAll("\\[\\]", "");
if (type.contains("[")) {
type = type.substring(0, type.indexOf("["));
}
} else if (type.contains("<")) {
String type3 = type;
type = type.substring(0, type.indexOf("<"));
if (type3.substring(type3.indexOf("<") + 1).startsWith("<>") || type3.substring(type.indexOf("<") + 1).startsWith("<T>")) {
type2 = null;
} else {
type2 = type3.substring(type3.indexOf("<") + 1, type3.lastIndexOf(">"));
if (type2.contains(",")) {
if (type2.substring(0, type2.indexOf(",")).contains("<")) {
types0.add(type2);
} else {
types0.add(type2.substring(0, type2.indexOf(",")));
types0.add(type2.substring(type2.indexOf(",") + 1));
}
} else {
types0.add(type2);
}
}
}
types.addAll(Arrays.asList(type.split(" extends ")));
if (types0.size() != 0) {
type = types0.remove(0);
typeF = type;
} else {
type = null;
}
} while (type != null);
methodParams[i++] = typeF;
}
methods.put(node.getName().toString() + "_Return_Type", methodParams);
Block block = node.getBody();
blockIterate(block, cu, bDeclarations);
}
return false;
}
public boolean visit(ImportDeclaration node) {
imports.add(node.getName().toString());
if (DependencyTreeMethods.jarClassPaths.containsKey(node.getName().toString())) {
importedClassFields = DependencyTreeMethods.listFieldsOfJarClass(DependencyTreeMethods.jarClassPaths.get(node.getName().toString()), node.getName().toString());
fields.putAll(importedClassFields);
}
return false;
}
public boolean visit(PackageDeclaration node) {
packageName = node.getName().toString();
return true;
}
});
}
use of org.eclipse.jdt.core.dom.ImportDeclaration in project evosuite by EvoSuite.
the class TestExtensionJob method run.
@Override
protected IStatus run(IProgressMonitor monitor) {
IStatus status = super.run(monitor);
newTests.clear();
IJavaElement element = JavaCore.create(target);
if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
ICompilationUnit compilationUnit = (ICompilationUnit) element;
CodeFormatter formatter = ToolFactory.createCodeFormatter(null);
try {
if (compilationUnit.getTypes().length == 0) {
System.out.println("The compilation unit is empty :|");
return status;
}
IType classType = compilationUnit.getTypes()[0];
// new tests
loadTestSuiteContent(getTestClassName());
for (ImportDeclaration newImport : newImports) {
if (!hasImport(compilationUnit, newImport)) {
int flag = newImport.isStatic() ? Flags.AccStatic : Flags.AccDefault;
String strImport = newImport.getName().toString();
// Names of onDemand import declarations do not contain the '*'
if (newImport.isOnDemand())
strImport += ".*";
compilationUnit.createImport(strImport, null, flag, null);
}
}
for (MethodDeclaration newMethod : newMethods) {
if (hasMethod(classType, newMethod.getName().toString())) {
System.out.println("Test suite already contains method called: " + newMethod.getName());
int num = 1;
newMethod.setName(newMethod.getAST().newSimpleName(newMethod.getName().toString() + "_" + num));
while (hasMethod(classType, newMethod.getName().toString())) {
num += 1;
String name = newMethod.getName().toString();
newMethod.setName(newMethod.getAST().newSimpleName(name.substring(0, name.length() - 2) + "_" + num));
}
}
String testContent = newMethod.toString();
IMethod methodToAdd = classType.createMethod(testContent, null, false, new NullProgressMonitor());
ISourceRange range = methodToAdd.getSourceRange();
TextEdit indent_edit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, classType.getCompilationUnit().getSource(), range.getOffset(), range.getLength(), 0, null);
classType.getCompilationUnit().applyTextEdit(indent_edit, null);
newTests.add(newMethod.getName().toString());
}
classType.getCompilationUnit().commitWorkingCopy(false, null);
// write markers
writeMarkersExtendedTestSuite();
} catch (JavaModelException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return status;
}
use of org.eclipse.jdt.core.dom.ImportDeclaration in project evosuite by EvoSuite.
the class ResolutionMarkerEvoIgnoreForClass method run.
@Override
public void run(IMarker marker) {
IResource res = marker.getResource();
try {
CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
if (position == 0) {
int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
position = compunit.getPosition(line, 0);
}
AST ast = compunit.getAST();
ASTRewrite rewriter = ASTRewrite.create(ast);
Annotation annotation = ast.newNormalAnnotation();
annotation.setTypeName(ast.newName("EvoIgnore"));
ImportDeclaration id = ast.newImportDeclaration();
id.setName(ast.newName("org.evosuite.quickfixes.annotations.EvoIgnore"));
ListRewrite lr = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
// lr.insertFirst(annotation, null);
lr.insertAt(annotation, 0, null);
lr.insertAt(id, 0, null);
ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
IPath path = compunit.getJavaElement().getPath();
try {
bm.connect(path, null, null);
ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
IDocument document = textFileBuffer.getDocument();
TextEdit edits = rewriter.rewriteAST(document, null);
edits.apply(document);
textFileBuffer.commit(null, false);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedTreeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bm.disconnect(path, null, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// (4)
}
System.out.println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
} catch (JavaModelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
marker.delete();
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Aggregations