Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
Danny van Bruggen
@matozoid
(One reason I quit is because I felt I was scaring contributors off with my behvaiour :-D )
MarcosCosmos
@MarcosCosmos
Yeah... that checks out.
tpavel-aspose
@tpavel-aspose
Hi. Can I normalize braces? Per line. And restore missing braces.
2 replies
andrey49
@andrey49
Hi. I try to format the signature of the method according to the template as follows method.getSignature().getParameterTypes()
.forEach(type -> {
type.setData(Node.LINE_SEPARATOR_KEY, LineSeparator.CRLF);
});, but it does not work. I will be grateful if you help or tell me how to do it.
The template that should come out looks like this: method (
String str,
Integer i,
Double d
) {
4 replies
fahd
@debbicce_gitlab
Navigator.findNodeOfGivenClass is this deprecated ? it does not seem so in the documentation, is there an alternative ?
2 replies
jean pierre Lerbscher
@jlerbsc

Navigator.findNodeOfGivenClass is this deprecated ? it does not seem so in the documentation, is there an alternative ?

Depending of what you want to do you can use for example cu.findFirst/findAll(<your expression or class>)

sunilhyd
@sunilhyd
I was trying to print out a Whole Java Program using the Void visitor. I was getting errors. Does anyone have a sample to print out a Java program with comments? Kindly share. Thanks
2 replies
tpavel-aspose
@tpavel-aspose
I need it to keep code convention in review code
sunilhyd
@sunilhyd
Same idea, to refactor code, not just pretty print. Some modification to method signatures at times.
johnicesea
@johnicesea
how can i get the parameter type full name?
3 replies
Danny van Bruggen
@matozoid
To apply a set of formatting rules to code after a change, a tool like Spotless is useful: https://github.com/diffplug/spotless/
lossend
@lossend
how can i get parametertypes from a method declaration string, for example, a method declaration string:"enrichAtmosphereIcon(CartItemComponentInput input,final ICartItemResultCO iCartItemResultCO)", i wish the result is "enrichAtmosphereIcon(CartItemComponentInput,ICartItemResultCO)"
1 reply
NARASIMHA RAO
@_sunkara_twitter
HI am using Static Java parser and in method visitor would like omit the method parameters from methodexpr ( example : entityStatuses.get(i).getDataSourceTimeStamp().get(dataSource) --> entityStatuses.get.getDataSourceTimeStamp.get ) is it possibel ?
5 replies
Danny van Bruggen
@matozoid
Hey, happy holidays, christmas, new year, and everything everone!
Federico Tomassetti
@ftomassetti
Happy holidays to everyone!
NARASIMHA RAO
@_sunkara_twitter
Hi which expression catches this kind of statement -- vCatType.getId() == 4 ? cGSTINN : vGSTINN
2 replies
jean pierre Lerbscher
@jlerbsc
Merry christmas to everyone
Ryan Warren
@ryantbwarren
Hi everyone, I hope you are all having a wonderful holidays :) I am new here (both to gitter and the JavaParser community) so I do apologise if this has been asked before.. I wanted to know if there is any way to see how many potential compilation units exist within each SourceRoot for a given ProjectRoot before parsing them? The ProjectRoot I have contains 26 SourceRoots but I can't seem to figure out how to check how many potential compilation units there will be other than potentially performing an addition parse to collect the compilation units first, however I'd rather avoid having to do this as there are many compilation units in the projects and caching all of them might not be a possibility? Any advice is greatly appreciated!
3 replies
greggers123
@greggers123

Hi, Happy New Year everyone - I think I've found a new issue, I tried searching but didn't find anything that looked similar.

I encountered this when running against some code that makes use of log4j and has a call like this - logger.traceEntry("" + fee) - The fee variable is a double.

The log4j library has two trace methods that take a String and optional values, in this scenario javaparser throws an IndexOutOfBoundsException.

I've created a simple test - this class throws the exception:
`
public class AParserTest {

public void log() {
    double fee = 0.1;

    doSomething("" + fee);
}

private void doSomething(String string, Supplier<?>... supplier) {

}

private void doSomething(String format, Object... params) {

}

}
This doesn't:
public class AParserTest {

public void log() {
    double fee = 0.1;

    doSomething("" + fee);
}

private void doSomething(String string, Supplier<?>... supplier) {

}

}
`
Javaparser is expecting to find a second argument in MethodResolutionLogic.isExactMatch but doesn't find one, because it's optional. I'm not doing anything fancy in the javaparser call, just calling resolve() on the MethodCallExpr.

2 replies
Roger Howell
@MysterAitch
Wow, @jlerbsc is on a roll with the super fast turnarounds on bug fixes!! 😵😵😵
Danny van Bruggen
@matozoid
If @jlerbsc has a kofi account, I'll buy him a coffee :-)
Danny van Bruggen
@matozoid
greggers123
@greggers123

Hi all - I think I have found an issue... java.io.File contains the overloaded method 'listFiles', one takes a FileFilter and the other a FilenameFilter, both of which are functional interfaces, the former taking a single File argument and the later taking File and String arguments.

When the parser sees a call like this, it struggles to work out which method is being called and throws a MethodAmbiguityException:

File[] newFilesToRegister = directory.listFiles((dir, name) -> {
...
}

The two arguments in the argument list for the lambda expression should allow the parser to determine which method is being called.

I see a closed issue #2775 that talks of a similar thing but was deployed in 3.16.2 - I'm using 3.18

2 replies
jean pierre Lerbscher
@jlerbsc

If @jlerbsc has a kofi account, I'll buy him a coffee :-)

If @jlerbsc has a kofi account, I'll buy him a coffee :-)

Thank you. I'm just using JP in my work and I'm just trying here to spend some time to get to the community what this project brings. I think that's the spirit of open source. For the moment I am spending a few days of family vacation in Martinique (in the sun). I'm going to do a little pose ;-)

Danny van Bruggen
@matozoid
Yes, I think that is the spirit too. Good of you to follow it! Enjoy the island :-)
kauron
@kauron:matrix.org
[m]
Does anyone here know how to turn a ResolvedReferenceTypeDeclaration into a ResolvedReferenceType or viceversa? If this question is more suitable as an issue, I can file one.
kauron
@kauron:matrix.org
[m]
my current approach is new ReferenceTypeImpl(resolvedReferenceTypeDeclaration, typeSolver), where typeSolver is the CombinedTypeSolver used to setup javaparser's configuration
1 reply
melond
@melond
Hi all. Is there any way to count the number of read operation in statement? (including file input and user input)
7 replies
Denis
@dencns
Hi, I am using VoidVisitorAdapter and using visit method on IfStmt nodes on a file that I am parsing with CompilationUnit. I want to check if an IfStmt exists which I have done and now I want to check if there are any nulls values within an if statement condition. I am making another visitor method on NullLiteralExpr, how can I link the two?
2 replies
Diamantis Sellis
@sellisd
with my limited java I am trying to extract some descriptive statistics from java source code (number of classes/methods and their size per file). I am using the powerful javaparser code here but there is one simple detail that I can't figure out how to implement. I am using the VoidVisitorAdapter to visit recursively multiple files and for each file print the relevant information. However, within the visit method I would like to have access to the string of the file name so I can keep track of which file I am processing (add a column with file name in the output). In the github link above is the script and I also paste here the relevant part of code in case someone can help:
@Command(name = "CodeSeq", version = "1.0.1", mixinStandardHelpOptions = true)
public class CodeSeq implements Runnable{
    @Option(names = { "-o", "--output"}, description = "Output File and path.")
    String outputFilePath = "./java_data.tsv";
    @Option(names = { "-i", "--input"}, description = "Input Path to be recursively searched for .java files")
    String RootPath = "/mnt/Data/scratch/";
    @Override
    public void run(){
        try{
            FileWriter outputFile = new FileWriter(outputFilePath);
            outputFile.write("class\tclass_lines\tmethod\tmethod_lines\n");
            try(Stream<Path> walk = Files.walk(Paths.get(RootPath))){
                List<String> result = walk.map(x -> x.toString()).filter(f -> f.endsWith(".java")).collect(Collectors.toList());
                for (String fileName : result) {
                    Path fileNamePath = Paths.get(fileName);
                    if (!Files.isRegularFile(fileNamePath)) {
                        continue;
                    }
                    FileInputStream f = new FileInputStream(fileName);
                    try {
                        CompilationUnit cu = StaticJavaParser.parse(f);
                        VoidVisitor<FileWriter> methodNamePrinter = new MethodNamePrinter();
                        methodNamePrinter.visit(cu, outputFile);
                    } catch (ParseProblemException e) {
                        System.out.println("Skipping file: " + fileName);
                    }
                }
                outputFile.close();
            } catch(IOException e){
                e.printStackTrace();
            }
        }catch(IOException ex){
            System.out.println("Error writing to file");
            ex.printStackTrace();
        }
    }
    public static void main(String[] args){
        int exitCode = new CommandLine(new CodeSeq()).execute(args);
        System.exit(exitCode);
    }
    private static class MethodNamePrinter extends VoidVisitorAdapter<FileWriter> {
        @Override
        public void visit(ClassOrInterfaceDeclaration cl, FileWriter arg) {
            super.visit(cl, arg);
            Range class_range = cl.getRange().get();
            int class_loc = Math.max(class_range.begin.line, class_range.end.line) - Math.min(class_range.begin.line, class_range.end.line) + 1;
            for (MethodDeclaration method : cl.getMethods()) {
                Range r = method.getRange().get();
                int loc = Math.max(r.begin.line, r.end.line) - Math.min(r.begin.line, r.end.line) + 1;
                try{
                    arg.write(cl.getName() + "\t" + class_loc + "\t" + method.getName() + "\t" + loc + "\n");
                }catch(IOException ex){
                    System.out.println("Error writing to file");
                }
            }
        }
    }

}
3 replies
uvaisTrivecta
@uvaisTrivecta
Hi , How can i get fields those has annotations alone?
uvaisTrivecta
@uvaisTrivecta

Hi , How can i get fields those has annotations alone?

Finally was able to get it .Sharing the code here, may be useful for some one or please correct if anything is wrong

for (TypeDeclaration<?> typeDec : cu.getTypes()) {
                    for (BodyDeclaration<?> member : typeDec.getMembers()) {
                        member.toFieldDeclaration().ifPresent(field -> {
                            if(field.getAnnotations() != null && field.getAnnotations().size() > 0) {
                                System.out.println(field);

                            }
                        });
                    }
                }

`
Shreyansh Gupta
@kawaiifoxx

Hello Guys,
I am new to this library and I was trying to use CombinedTypeSolver to get method declarations from java source code,
but instead I got UnsuportedOperationException.

So here's what I did:

  1. I traversed through the source directory for each java file, then using VoidVistorAdapter<List<String>>, I saved the fully qualified class names to a list as I traverse through each ast.
  2. Then, I used a TypeSolver to get a List of ResolvedDeclaration for each class in List<String>, which I got from traversing through ast. I passed fullyQualified ClassName to solveType() method of TypeSolver class, to recieve a ResolvedDeclaration for corresponding className.
  3. Then, for each resolvedDeclaration, I used resolvedDeclaration.asType().asReferenceType().getDeclaredMethods().
  4. After this, I got a List of ResolvedMethodDeclaration, and then for each of these ResolvedMethodDeclaration, I used resolvedMethodDeclaration.asMethod().getSignature() <- Right here I got UnsupportedOperationException.

Here are some relevent code snippets:

This is where I call all the methods

@SpringBootTest
class SourceComponentTest {

    @Autowired
    private Parser parser;
    private SourceComponent sourceComponent;
    private static final String MULTIPLE_FILES_PATH = "src/test/testSources/JavaParserFacadeTests/testParserClass/MultipleFileTest/multipleFilesTest";

    @BeforeEach
    void setUp() {
        var resolvedTypeList = parser.getAllResolvedDeclarations(MULTIPLE_FILES_PATH);

        sourceComponent = new SourceComponent(resolvedTypeList);
    }

    //TODO: FINISH THIS!
    @Test
    public void TestToString() {
        System.out.println(sourceComponent);
        fail();
    }

}

This How I parse each file.

@Bean
    public DirExplorer dirExplorer(@Autowired VoidVisitor<List<String>> visitor) {
        return new DirExplorer((level, path, file) -> file.getName().endsWith(".java"), (level, path, file, state) -> {
            try {
                JavaParser javaParser = javaParser();
                CompilationUnit cu = javaParser.parse(file).getResult().get();
                visitor.visit(cu, state);
            } catch (FileNotFoundException e) {
                throw new RuntimeException("[DirExplorer.FileHandler] File not found at: " + file.getAbsolutePath());
            }
        });
    }
3 replies

this returns a list of ResolvedDeclaraion.

public List<ResolvedDeclaration> getAllResolvedDeclarations(String PATH) {
        CombinedTypeSolver typeSolver = new CombinedTypeSolver();
        typeSolver.add(new JavaParserTypeSolver(PATH));
        typeSolver.add(new ReflectionTypeSolver());

        javaParser.getParserConfiguration()
        .setSymbolResolver(new JavaSymbolSolver(typeSolver));

        var classList = parseClasses(PATH);

        List<ResolvedDeclaration> resolvedDeclarationList = new ArrayList<>();

        classList.forEach(k -> resolvedDeclarationList.add(typeSolver.solveType(k)));

        return resolvedDeclarationList;
    }

This is where I get all the ResolvedMethodDeclarations.

 private void generateParsedClassOrInterfaceComponentFromResolvedDecl(ResolvedDeclaration resolvedDeclaration,
                                                                         ParsedComponent parsedComponent) {

        if (resolvedDeclaration.isType() && parsedComponent.isParsedClassOrInterfaceComponent()) {
            var typeDeclaration = resolvedDeclaration.asType().asReferenceType();
            //noinspection OptionalGetWithoutIsPresent
            var classOrInterfaceComponent = parsedComponent.asParsedClassOrInterfaceComponent().get();
            var fieldList = typeDeclaration.getDeclaredFields();

            fieldList.forEach(e ->
                    classOrInterfaceComponent
                            .addChild(new ParsedFieldComponent(classOrInterfaceComponent, e)));

            var methodList = typeDeclaration.getDeclaredMethods();
            var constructorList = typeDeclaration.getConstructors();

            constructorList.forEach(e ->
                    classOrInterfaceComponent
                            .addChild(new ParsedConstructorComponent(classOrInterfaceComponent, e)));

            methodList.forEach(e -> {
                    classOrInterfaceComponent
                            .addChild(new ParsedMethodComponent(classOrInterfaceComponent, e));
            });

        }
    }

This where the exception occurs

public ParsedConstructorComponent(ParsedComponent parent, ResolvedDeclaration resolvedDeclaration) {
        this.resolvedDeclaration = resolvedDeclaration;
        this.parent = parent;
        this.printableName = resolvedDeclaration.asMethod().getSignature(); // <--- Exception Occurs here
    }

Stack trace

java.lang.UnsupportedOperationException: JavaParserMethodDeclaration{wrappedNode=@Override
public String toString() {
    return lineNumber + "|" + type + "|" + isOrphan + "|" + text.replaceAll("\\n", "").trim();
}, typeSolver=com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver@6206b4a7} is not a MethodDeclaration
at com.github.javaparser.resolution.declarations.ResolvedDeclaration.asMethod(ResolvedDeclaration.java:119)
    at org.java2uml.java2umlapi.umlComponenets.ParsedMethodComponent.<init>(ParsedMethodComponent.java:27)
    at org.java2uml.java2umlapi.umlComponenets.SourceComponent.lambda$generateParsedClassOrInterfaceComponentFromResolvedDecl$3(SourceComponent.java:104)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.java2uml.java2umlapi.umlComponenets.SourceComponent.generateParsedClassOrInterfaceComponentFromResolvedDecl(SourceComponent.java:103)
    at org.java2uml.java2umlapi.umlComponenets.SourceComponent.<init>(SourceComponent.java:34)
    at org.java2uml.java2umlapi.umlComponenets.SourceComponentTest.setUp(SourceComponentTest.java:24)
    <not relevant after this.>

Please Help Me!

1 reply
konaui
@konaui
"In a.<String>bb(15); a is the scope, String is a type argument, bb is the name and 15 is an argument." I am visiting MethodCallExpr using VoidVisitor, if scope was instantiated with a null value, how can I detect whether scope is null or not? Any tips/hints pls?
2 replies
N Jaya krishna
@jayanitw_twitter
Hi all, I'm new to using this library. I tried the examples present in the GitHub. I want to understand whether my use case could be accomplished by using javaparser. My use case is to rename classes with names matching a particular regex. So my doubt is whether it is possible to rename the references as well.
6 replies
konaui
@konaui
Hi, is there a way to detect whether an expression node exists inside the body of an if statement and not outside?
4 replies
Tsvetan Tsvetkov
@zekardo_gitlab
Hi guys, I'm new to JavaParser but find it very nice. I plan to use it for a executing java code (with just the very basic java syntax) taken from a text field. I plan to write a basic interpreter that executes just very basic java (declarations, if/else and for loops). Do you think that is a good idea? Has anybody done something like that?
3 replies
Tsvetan Tsvetkov
@zekardo_gitlab

Hi,
I'm trying as a newbie to write some very simple custom java interpreter. I wouldn't want to begin from the start with a wrong approach so I decided to ask for little help here. Here's my question (I hope it's not too basic for you guys):

I wanted to start from the simple stuff and decided to just implement an addition(for integers). I created a visitor for Integer Literals:

public class IntegerLiteralVisitor extends GenericVisitorAdapter<Integer, Void> {
    @Override
    public Integer visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
        super.visit(integerLiteralExpr, arg);
        return Integer.parseInt(integerLiteralExpr.getValue());
    }
}

So I guess my next step would be to write a visitor for the BinaryExpression. I want to check if the BinaryExpr.getOperator().equals(BinaryExpr.Operator.PLUS)
and if it is - just add the left and the right side of the BinaryExpression.

How can I technically do that? The left and the right side of a BinaryExpression are from type Expression and i'm having a little trouble putting the whole thing together.
Could someone maybe give me some advice or tell me if I'm approaching this the wrong way?

4 replies
mdproctor
@mdproctor
Does anyone have any idea on perf difference - when you both read in, mutate and write out - compared to Eclipse JDT.
2 replies
gogatagogata
@gogatagogata
Hi, does anyone know if it would be possible to fork the javaparser project and use it as a module in a gwt application?
1 reply
dirkaudaz
@dirkaudaz
Hi Everyone. Just starting playing with Javaparser but I would like to ask if this is the right tool for the task I need to accomplish. I need to be able to query for some type of visitable node and build a directed graph/sequence while backtracking up to the root. The idea is to identify the paths affected by a change in the queried node.
2 replies
dirkaudaz
@dirkaudaz
Where should we report issues/bugs found in the book?
1 reply
Jonathan Locke
@jonathanlocke
hello, anyone home? :)
i'm wondering if anyone knows what happened to JreTypeSolver
it doesn't seem to be in the latest javaparser-symbol-solver-core
4 replies
Danny van Bruggen
@matozoid
Wicket! I knew I heard your name before @jonathanlocke :-)
Jonathan Locke
@jonathanlocke
Guilty as charged :)
Jonathan Locke
@jonathanlocke
BTW, thanks for JavaParser, it's really making this job a lot easier.