Refine search
private TypeDeclaration getOuterClass (CompilationUnit unit) { for (TypeDeclaration type : unit.getTypes()) { if (type instanceof ClassOrInterfaceDeclaration || type instanceof EnumDeclaration) return type; } throw new RuntimeException("Couldn't find class, is your java file empty?"); }
private static void organiseImports(CompilationUnit cu) { List<ImportDeclaration> importDecls = new ArrayList<>(); for (ImportDeclaration importDeclaration : cu.getImports()) { if (importDeclaration.getNameAsString().startsWith("org.jctools.util.Unsafe")) { continue; } importDecls.add(importDeclaration); } cu.getImports().clear(); for (ImportDeclaration importDecl : importDecls) { cu.addImport(importDecl); } cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongFieldUpdater")); cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicReferenceArray")); cu.addImport(importDeclaration("java.util.concurrent.atomic.AtomicLongArray")); }
CompilationUnit newClazz = JavaParser.parse(code); Map<String, FieldDeclaration> oldFields = old .findAll(FieldDeclaration.class) .stream() .collect(Collectors.toMap(declaration -> declaration.getVariable(0).getNameAsString(), Function.identity())); .findAll(MethodDeclaration.class) .stream() .collect(Collectors.toMap(NodeWithSimpleName::getNameAsString, Function.identity())); newClazz.findAll(FieldDeclaration.class).forEach(declaration -> { String name = declaration.getVariable(0).getNameAsString(); if (oldFields.get(name) == null) { VariableDeclarator declarator = declaration.getVariable(0); FieldDeclaration newField = old.getType(0) .addField(declarator.getType(), declarator.getNameAsString(), declaration.getModifiers().toArray(new Modifier[]{})); newClazz.findAll(MethodDeclaration.class).forEach(declaration -> { String name = declaration.getNameAsString(); if (oldMethod.get(name) == null) { MethodDeclaration newMethod = old.getType(0) .addMethod(name, declaration.getModifiers().toArray(new Modifier[]{})); code = old.toString();
static String getPackageName(Node container) { if (container instanceof CompilationUnit) { Optional<PackageDeclaration> p = ((CompilationUnit) container).getPackageDeclaration(); if (p.isPresent()) { return p.get().getName().toString(); } } else if (container != null) { return getPackageName(container.getParentNode().orElse(null)); } return ""; }
public void calculate(ClassOrInterfaceDeclaration classOrInterfaceDeclaration, CompilationUnit compilationUnit) { List<ClassOrInterfaceType> extendedTypes = classOrInterfaceDeclaration.getExtendedTypes(); for (ClassOrInterfaceType extendedType : extendedTypes) { String extendedTypeName = extendedType.getNameAsString(); String extendedTypePackageName = extendedType .findCompilationUnit() .flatMap(CompilationUnit::getPackageDeclaration) .flatMap(pkg -> Optional.of(pkg.getNameAsString())).orElse("???"); if (typeDao.exist(extendedTypeName, extendedTypePackageName)) { // JDK interfaces are not indexed int extendedInterfaceId = typeDao.getId(extendedTypeName, extendedTypePackageName); int interfaceId = typeDao.getId(classOrInterfaceDeclaration.getNameAsString(), compilationUnit.getPackageDeclaration().get().getNameAsString()); extendsDao.save(new Extends(interfaceId, extendedInterfaceId)); } } } }
public SymbolReference<ResolvedTypeDeclaration> solve(ThisExpr node) { // If 'this' is prefixed by a class eg. MyClass.this if (node.getClassExpr().isPresent()) { // Get the class name String className = node.getClassExpr().get().toString(); // Attempt to resolve using a typeSolver SymbolReference<ResolvedReferenceTypeDeclaration> clazz = typeSolver.tryToSolveType(className); if (clazz.isSolved()) { return SymbolReference.solved(clazz.getCorrespondingDeclaration()); } // Attempt to resolve locally in Compilation unit Optional<CompilationUnit> cu = node.findAncestor(CompilationUnit.class); if (cu.isPresent()) { Optional<ClassOrInterfaceDeclaration> classByName = cu.get().getClassByName(className); if (classByName.isPresent()) { return SymbolReference.solved(getTypeDeclaration(classByName.get())); } } } return SymbolReference.solved(getTypeDeclaration(findContainingTypeDeclOrObjectCreationExpr(node))); }
public static Optional<TypeDeclaration<?>> findType(CompilationUnit cu, String qualifiedName) { if (cu.getTypes().isEmpty()) { return Optional.empty(); } final String typeName = getOuterTypeName(qualifiedName); Optional<TypeDeclaration<?>> type = cu.getTypes().stream().filter((t) -> t.getName().getId().equals(typeName)).findFirst(); final String innerTypeName = getInnerTypeName(qualifiedName); if (type.isPresent() && !innerTypeName.isEmpty()) { return findType(type.get(), innerTypeName); } return type; }
@Override public SymbolReference<ResolvedMethodDeclaration> solveMethod(String name, List<ResolvedType> argumentsTypes, boolean staticOnly, TypeSolver typeSolver) { for (ImportDeclaration importDecl : wrappedNode.getImports()) { if(importDecl.isStatic()){ if(importDecl.isAsterisk()){ String importString = importDecl.getNameAsString(); if (this.wrappedNode.getPackageDeclaration().isPresent() && this.wrappedNode.getPackageDeclaration().get().getName().getIdentifier().equals(packageName(importString)) && this.wrappedNode.getTypes().stream().anyMatch(it -> it.getName().getIdentifier().equals(toSimpleName(importString)))) {
@Test public void issue257() throws FileNotFoundException { String pathToSourceFile = adaptPath("src/test/resources/issue257/A.java.txt"); CompilationUnit cu = JavaParser.parse(new File(pathToSourceFile)); Statement statement = cu.getClassByName("A").get().getMethodsByName("run").get(0).getBody().get().getStatement(0); ExpressionStmt expressionStmt = (ExpressionStmt)statement; Expression expression = expressionStmt.getExpression(); JavaParserFacade.get(typeSolver).getType(expression); }
@Override protected String getTypeName(CompilationUnit compilationUnit, int index) { ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) compilationUnit.getType(0); NodeList<ClassOrInterfaceType> extendedTypes = type.getExtendedTypes(); ClassOrInterfaceType extendedType = extendedTypes.get(index); String typeSimpleName = extendedType.getName().getIdentifier(); Optional<ClassOrInterfaceType> scope = extendedType.getScope(); String typeName; if (scope.isPresent()) { String typePackageName = scope.get().toString(); typeName = String.format("%s.%s", typePackageName, typeSimpleName); } else { typeName = typeSimpleName; } return typeName; }
TestEngine.select(project).ifPresent(testEngine -> { args.addAll(List.of("--add-reads", moduleName + "=" + testEngine.moduleName)); for (var sourceFile : testSourceSet.getJava()) { try { Optional<PackageDeclaration> optionalPackageDeclaration = JavaParser.parse(sourceFile).getPackageDeclaration(); if (optionalPackageDeclaration.isPresent()) { PackageDeclaration packageDeclaration = optionalPackageDeclaration.get(); testPackages.add(packageDeclaration.getNameAsString());
@Override public DocTag converter(String comment) { DocTag docTag = super.converter(comment); String path = ClassMapperUtils.getPath((String) docTag.getValues()); if (StringUtils.isBlank(path)) { return null; } Class<?> returnClassz; CompilationUnit cu; try (FileInputStream in = new FileInputStream(path)) { cu = JavaParser.parse(in); if (cu.getTypes().size() <= 0) { return null; } returnClassz = Class.forName(cu.getPackageDeclaration().get().getNameAsString() + "." + cu.getTypes().get(0).getNameAsString()); } catch (Exception e) { log.warn("读取java原文件失败:{}", path, e.getMessage()); return null; } String text = cu.getComment().isPresent() ? CommentUtils.parseCommentText(cu.getComment().get().getContent()) : ""; Map<String, String> commentMap = this.analysisFieldComments(returnClassz); List<FieldInfo> fields = this.analysisFields(returnClassz, commentMap); ObjectInfo objectInfo = new ObjectInfo(); objectInfo.setType(returnClassz); objectInfo.setFieldInfos(fields); objectInfo.setComment(text); return new SeeTagImpl(docTag.getTagName(), objectInfo); }
@Test public void constructorDeclarationResolve() throws IOException { File f = adaptPath(new File("src/test/resources/javaparser_new_src/javaparser-core/com/github/javaparser/ast/CompilationUnit.java")); CompilationUnit cu = parseWithSymbolResolution(f); ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)cu.getType(0); ConstructorDeclaration constructorDeclaration = classOrInterfaceDeclaration.getDefaultConstructor().get(); ResolvedConstructorDeclaration resolvedConstructorDeclaration = constructorDeclaration.resolve(); } @Test
public void index(com.github.javaparser.ast.CompilationUnit compilationUnit, String fileName) { String packageName = compilationUnit.getPackageDeclaration().map(NodeWithName::getNameAsString).orElse(""); io.github.benas.jql.model.CompilationUnit cu = new io.github.benas.jql.model.CompilationUnit(fileName, packageName); int cuId = compilationUnitDao.save(cu); List<TypeDeclaration<?>> types = compilationUnit.getTypes(); for (TypeDeclaration<?> type : types) { typeIndexer.index(type, cuId); } }
PrintStream s = new PrintStream(bytes); String newPkg = cu.getPackageDeclaration() // .map(p -> p.getName().toString()) // .orElse("") + ".immutable"; s.format("package %s;\n\n", newPkg); s.format("<IMPORTS>\n"); Map<String, String> imports; NodeList<ImportDeclaration> n = cu.getImports(); if (n != null) { imports = new HashMap<>(n.stream() // for (Node n : cu.getChildNodes()) { if (n instanceof ClassOrInterfaceDeclaration) { ClassOrInterfaceDeclaration c = (ClassOrInterfaceDeclaration) n;
info.setCompilationUnit(JavaParser.parse(file)); info.setPackageName(info.getCompilationUnit() .getPackageDeclaration() .map(PackageDeclaration::getNameAsString) .orElse(null)); info.setClassName(info.getSourceFile().getName().replaceAll(".java", "")); .getClassByName(info.getClassName()) .map(declaration -> declaration.getImplementedTypes() .stream() .map(ClassOrInterfaceType::getName)
@SuppressWarnings("PMD.SimplifyBooleanReturns") private boolean isImported(CompilationUnit compilationUnit, String typeSimpleName) { if (StringUtils.isBlank(typeSimpleName) || typeSimpleName.contains(".")) { throw new IllegalArgumentException("Invalid type simple name"); } // If the specified type is part of the JDK, // then it won't need need an explicit import statement if (specifiedTypePackageName.startsWith("java.lang")) { return true; } // Check if the compilation unit has an explicit import declaration whose // type name matches the specified type simple name String importClass; for (ImportDeclaration importDeclaration : compilationUnit.getImports()) { importClass = importDeclaration.getName().getIdentifier(); if (importClass.equals(typeSimpleName)) { return true; } } // Check if the annotation is declared // at the same package where the class is if (compilationUnit.getPackageDeclaration().get().getNameAsString().equals(specifiedTypePackageName)) { return true; } return false; }
@Override @edu.umd.cs.findbugs.annotations.SuppressFBWarnings (value="NP_ALWAYS_NULL_EXCEPTION") protected TUExecutionResult execution(File transformedAppFolder, TransformationContext transformationContext) { File javaClassFile = getAbsoluteFile(transformedAppFolder, transformationContext); FileInputStream fileInputStream = null; TUExecutionResult result = null; // TODO // Add a validation here simply checking if the file name ends with .java try { fileInputStream = new FileInputStream(javaClassFile); CompilationUnit compilationUnit = JavaParser.parse(fileInputStream); Optional<PackageDeclaration> packageDeclaration = compilationUnit.getPackageDeclaration(); result = TUExecutionResult.value(this, packageDeclaration.get().getNameAsString()); } catch (Exception e) { TransformationUtilityException tue = new TransformationUtilityException("An error happened when trying to read and parse the specified Java file " + getRelativePath(transformedAppFolder, javaClassFile), e); result = TUExecutionResult.error(this, tue); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { result.addWarning(e); } } return result; }
@Override public List<ResolvedFieldDeclaration> fieldsExposedToChild(Node child) { List<ResolvedFieldDeclaration> res = new LinkedList<>(); // Consider the static imports for static fields for (ImportDeclaration importDeclaration : wrappedNode.getImports()) { if (importDeclaration.isStatic()) { Name typeNameAsNode = importDeclaration.isAsterisk() ? importDeclaration.getName() : importDeclaration.getName().getQualifier().get(); String typeName = typeNameAsNode.asString(); ResolvedReferenceTypeDeclaration typeDeclaration = typeSolver.solveType(typeName); res.addAll(typeDeclaration.getAllFields().stream() .filter(f -> f.isStatic()) .filter(f -> importDeclaration.isAsterisk() || importDeclaration.getName().getIdentifier().equals(f.getName())) .collect(Collectors.toList())); } } return res; }
public FieldImp parse(final String signature) { final StringBuilder sb = new StringBuilder(); sb.append("class A {\n"); sb.append(signature.endsWith(";") ? signature : signature.concat(";")); sb.append("\n}"); final FieldImp field = new FieldImp("NOT_DEFINED", null); final CompilationUnit compilationUnit = JavaParser.parse(sb.toString()); compilationUnit.getClassByName("A").ifPresent(clazz -> { clazz.getFields().forEach(fd -> { field.name(fd.getVariables().get(0).toString()); field.type(this.getType(fd)); field.visibility(this.getVisibility(fd)); field.modifiers(this.getModifiers(fd)); fd.getAnnotations().forEach(an -> this.getAnnotationField(an) .ifPresent(x -> field.annotation(x))); }); }); return field; }