use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.
the class JavaParserModule method parseJavaFilesAndSolveTypes.
private void parseJavaFilesAndSolveTypes(final Folder folder) {
if (ignoreTests && "test".equals(folder.getName())) {
return;
}
for (final File file : folder.getFiles()) {
if (file.getContentType().equals("text/x-java")) {
final String javaFileName = file.getName();
if (javaFileName.equals("package-info.java") || javaFileName.equals("testPackage-info.java")) {
} else {
final String javaContent = file.getFavoriteContent();
ClassOrInterface clsOrIface = null;
CompilationUnit cu = null;
try {
cu = JavaParser.parse(javaContent);
for (final TypeDeclaration type : cu.findAll(TypeDeclaration.class)) {
SymbolReference<? extends ResolvedValueDeclaration> decl = facade.solve(type.getName());
if (type.isClassOrInterfaceDeclaration()) {
org.structr.javaparser.entity.Package pkg = null;
if (cu.getPackageDeclaration().isPresent()) {
pkg = handlePackage(cu.getPackageDeclaration().get());
}
clsOrIface = handleClassOrInterface(type, pkg);
}
}
for (final BodyDeclaration t : cu.findAll(BodyDeclaration.class)) {
if (t instanceof CallableDeclaration) {
final CallableDeclaration callable = t.asCallableDeclaration();
if (t instanceof ConstructorDeclaration) {
// final ConstructorDeclaration cd = t.asConstructorDeclaration();
// logger.info("Constructor found: " + cd.getNameAsString());
//
// final SymbolReference<ResolvedReferenceTypeDeclaration> constructorRef = typeSolver.tryToSolveType(cd.getNameAsString());
// if (constructorRef.isSolved()) {
//
// logger.info("Solved constructor: " + cd.getNameAsString());
// //final ResolvedReferenceTypeDeclaration decl = constructorRef.getCorrespondingDeclaration();
// }
} else if (t instanceof MethodDeclaration) {
final MethodDeclaration md = t.asMethodDeclaration();
final String methodName = md.getNameAsString();
logger.info("Method found: " + methodName);
// Create methods and link to class
final PropertyMap identifyingMethodProperties = new PropertyMap();
identifyingMethodProperties.put(Method.name, methodName);
final PropertyMap methodProperties = new PropertyMap();
methodProperties.putAll(identifyingMethodProperties);
methodProperties.put(Method.classOrInterface, clsOrIface);
methodProperties.put(Method.declaration, md.getDeclarationAsString());
final Optional<BlockStmt> block = md.getBody();
if (block.isPresent()) {
methodProperties.put(Method.body, block.get().toString());
}
final String symbolName = StringUtils.substringAfterLast(clsOrIface.getName(), ".") + "." + md.getNameAsString();
try {
final SymbolReference<? extends ResolvedValueDeclaration> methodRef = facade.solve(md.getName());
if (methodRef.isSolved()) {
final ResolvedValueDeclaration decl = methodRef.getCorrespondingDeclaration();
if (decl.isMethod()) {
final String mName = decl.asMethod().getName();
final String signature = decl.asMethod().getSignature();
logger.info("Solved method: " + methodRef.toString() + ", signature: " + signature);
methodProperties.put(Method.resolved, true);
}
}
} catch (final UnsolvedSymbolException ignore) {
}
getOrCreate(Method.class, identifyingMethodProperties, methodProperties);
logger.info("Created (or found) method " + symbolName);
}
// final NodeList<Parameter> parameters = callable.getParameters();
//
// List<JsonResult> parameterList = new ArrayList<>();
//
// parameters.forEach((p) -> {
//
// JsonResult param = new JsonResult();
//
// param.addName(p);
// param.addType(p.getType());
// param.addModifiers(p);
//
// parameterList.add(param);
// });
}
}
} catch (Throwable ignore) {
}
}
}
}
}
use of com.github.javaparser.ast.body.TypeDeclaration in project structr by structr.
the class JavaParserModule method toJson.
private JsonResult toJson(final CompilationUnit cu) {
final JsonResult jsonResult = new JsonResult();
final NodeList<TypeDeclaration<?>> types = cu.getTypes();
if (types.isEmpty()) {
return jsonResult;
}
final TypeDeclaration<?> type = types.get(0);
jsonResult.addName(type);
jsonResult.addModifiers(type);
final Optional<PackageDeclaration> pkg = cu.getPackageDeclaration();
if (pkg.isPresent()) {
jsonResult.addPackage(pkg.get());
}
final List<BodyDeclaration<?>> members = type.getMembers();
final List<JsonResult> membersList = new ArrayList<>();
members.forEach((t) -> {
final JsonResult member = new JsonResult();
if (t instanceof FieldDeclaration) {
final FieldDeclaration fd = t.asFieldDeclaration();
member.addName(fd.getVariable(0));
member.addType(fd.getVariable(0).getType());
member.addModifiers(fd);
} else if (t instanceof CallableDeclaration) {
final CallableDeclaration callable = t.asCallableDeclaration();
if (t instanceof ConstructorDeclaration) {
final ConstructorDeclaration cd = t.asConstructorDeclaration();
member.addName(cd);
member.isConstructor();
member.addModifiers(cd);
} else if (t instanceof MethodDeclaration) {
final MethodDeclaration md = t.asMethodDeclaration();
member.addName(md);
member.isMethod();
member.addReturnType(md.getType());
member.addModifiers(md);
member.addBody(md);
}
final NodeList<Parameter> parameters = callable.getParameters();
List<JsonResult> parameterList = new ArrayList<>();
parameters.forEach((p) -> {
JsonResult param = new JsonResult();
param.addName(p);
param.addType(p.getType());
param.addModifiers(p);
parameterList.add(param);
});
member.addParameters(parameterList);
}
membersList.add(member);
});
jsonResult.addMembers(membersList);
return jsonResult;
}
use of com.github.javaparser.ast.body.TypeDeclaration in project AndroidLife by CaMnter.
the class FinalRClassBuilder method brewJava.
/**
* JavaPoet 生成 R2
*
* @param rFile R.java File
* @param outputDir R2.java 输出文件夹
* @param packageName 包名
* @param className R2 name
* @throws Exception
*/
public static void brewJava(File rFile, File outputDir, String packageName, String className) throws Exception {
/*
* JavaParser 解析 R.java File
* 获取到 TypeDeclaration
*/
CompilationUnit compilationUnit = JavaParser.parse(rFile);
TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
/*
* 定义 R2.java class
*/
TypeSpec.Builder result = TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);
/*
* 遍历 R.java File 的每一个节点( 内部类或者接口 --> ClassOrInterfaceDeclaration )
* 添加到 R2.java 内
* 这里是给 TypeSpec 添加生成 内部类 的 语句
*/
for (Node node : resourceClass.getChildNodes()) {
if (node instanceof ClassOrInterfaceDeclaration) {
addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node);
}
}
JavaFile finalR = JavaFile.builder(packageName, result.build()).addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!").build();
finalR.writeTo(outputDir);
}
use of com.github.javaparser.ast.body.TypeDeclaration in project cloud-sea-towerman by huadahuang1983.
the class JavaFileMergerJaxp method mergerFile.
public String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit) {
StringBuilder sb = new StringBuilder(newCompilationUnit.getPackageDeclaration().get().toString());
newCompilationUnit.removePackageDeclaration();
// 合并imports
NodeList<ImportDeclaration> imports = newCompilationUnit.getImports();
imports.addAll(existingCompilationUnit.getImports());
Set<ImportDeclaration> importSet = new HashSet<ImportDeclaration>();
importSet.addAll(imports);
NodeList<ImportDeclaration> newImports = new NodeList<>();
newImports.addAll(importSet);
newCompilationUnit.setImports(newImports);
for (ImportDeclaration i : newCompilationUnit.getImports()) {
sb.append(i.toString());
}
newLine(sb);
NodeList<TypeDeclaration<?>> types = newCompilationUnit.getTypes();
NodeList<TypeDeclaration<?>> oldTypes = existingCompilationUnit.getTypes();
for (int i = 0; i < types.size(); i++) {
// 截取Class
String classNameInfo = types.get(i).toString().substring(0, types.get(i).toString().indexOf("{") + 1);
sb.append(classNameInfo);
newLine(sb);
newLine(sb);
// 合并fields
List<FieldDeclaration> fields = types.get(i).getFields();
List<FieldDeclaration> oldFields = oldTypes.get(i).getFields();
List<FieldDeclaration> newFields = new ArrayList<>();
Set<FieldDeclaration> fieldDeclarations = new LinkedHashSet<>();
fieldDeclarations.addAll(fields);
fieldDeclarations.addAll(oldFields);
newFields.addAll(fieldDeclarations);
for (FieldDeclaration f : newFields) {
sb.append("\t" + f.toString());
newLine(sb);
newLine(sb);
}
// 合并methods
List<MethodDeclaration> methods = types.get(i).getMethods();
List<MethodDeclaration> existingMethods = oldTypes.get(i).getMethods();
Set<MethodDeclaration> methodDeclarations = new LinkedHashSet<>();
methodDeclarations.addAll(methods);
methodDeclarations.addAll(existingMethods);
for (MethodDeclaration f : methodDeclarations) {
String res = f.toString().replaceAll("\r\n", "\r\n\t");
sb.append("\t" + res);
newLine(sb);
newLine(sb);
}
// 判断是否有内部类
types.get(i).getChildNodes();
for (Node n : types.get(i).getChildNodes()) {
if (n.toString().contains("static class")) {
sb.append(n.toString());
}
}
}
return sb.append(System.getProperty("line.separator") + "}").toString();
}
use of com.github.javaparser.ast.body.TypeDeclaration in project meghanada-server by mopemope.
the class LocationSearcher method searchLocationFromFile.
private static Location searchLocationFromFile(final SearchContext ctx, final String fqcn, final File targetFile) throws IOException {
final CompilationUnit compilationUnit = JavaParser.parse(targetFile, StandardCharsets.UTF_8);
final List<TypeDeclaration<?>> types = compilationUnit.getTypes();
for (final TypeDeclaration<?> type : types) {
if (ctx.kind.equals(SearchKind.CLASS)) {
final SimpleName simpleName = type.getName();
final String typeName = simpleName.getIdentifier();
final String name = ClassNameUtils.getSimpleName(fqcn);
final Optional<Position> begin = simpleName.getBegin();
if (typeName.equals(name) && begin.isPresent()) {
final Position position = begin.get();
return new Location(targetFile.getCanonicalPath(), position.line, position.column);
}
}
final List<BodyDeclaration<?>> members = type.getMembers();
ConstructorDeclaration constructor = null;
MethodDeclaration method = null;
for (final BodyDeclaration<?> member : members) {
if (member instanceof FieldDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.FIELD)) {
final Location variable = getFieldLocation(ctx, targetFile, (FieldDeclaration) member);
if (variable != null) {
return variable;
}
} else if (member instanceof ConstructorDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.METHOD)) {
final ConstructorDeclaration declaration = (ConstructorDeclaration) member;
final SimpleName simpleName = declaration.getName();
final String name = simpleName.getIdentifier();
final Optional<Position> begin = simpleName.getBegin();
if (name.equals(ctx.name) && begin.isPresent()) {
final Position position = begin.get();
final List<Parameter> parameters = declaration.getParameters();
// TODO check FQCN types
if (ctx.arguments.size() == parameters.size()) {
return new Location(targetFile.getCanonicalPath(), position.line, position.column);
} else {
if (constructor == null) {
constructor = declaration;
}
}
}
} else if (member instanceof MethodDeclaration && ctx.name != null && ctx.kind.equals(SearchKind.METHOD)) {
final MethodDeclaration declaration = (MethodDeclaration) member;
final SimpleName simpleName = declaration.getName();
final String name = simpleName.getIdentifier();
final Optional<Position> begin = simpleName.getBegin();
if (name.equals(ctx.name) && begin.isPresent()) {
final Position position = begin.get();
final List<Parameter> parameters = declaration.getParameters();
if (ctx.arguments.size() == parameters.size()) {
return new Location(targetFile.getCanonicalPath(), position.line, position.column);
} else {
if (method == null) {
method = declaration;
}
}
}
}
}
if (constructor != null) {
final Position pos = constructor.getName().getBegin().get();
return new Location(targetFile.getCanonicalPath(), pos.line, pos.column);
}
if (method != null) {
final Position pos = method.getName().getBegin().get();
return new Location(targetFile.getCanonicalPath(), pos.line, pos.column);
}
}
return null;
}
Aggregations