Java Code Examples for com.github.javaparser.ParseResult

The following examples show how to use com.github.javaparser.ParseResult. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mapper-generator-javafx   Source File: MyShellCallback.java    License: Apache License 2.0 6 votes vote down vote up
private String getNewJavaFile(String newFileSource, String existingFileFullPath) throws FileNotFoundException {
    JavaParser javaParser = new JavaParser();
    ParseResult<CompilationUnit> newCompilationUnitParse = javaParser.parse(newFileSource);
    CompilationUnit newCompilationUnit;
    if (newCompilationUnitParse.isSuccessful() && newCompilationUnitParse.getResult().isPresent()) {
        newCompilationUnit = newCompilationUnitParse.getResult().get();
    } else {
        log.error("解析 newFileSource 失败, {}", newCompilationUnitParse.getProblem(0).toString());
        return newFileSource;
    }

    ParseResult<CompilationUnit> existingCompilationUnitParse = javaParser.parse(new File(existingFileFullPath));
    CompilationUnit existingCompilationUnit;
    if (existingCompilationUnitParse.isSuccessful() && existingCompilationUnitParse.getResult().isPresent()) {
        existingCompilationUnit = existingCompilationUnitParse.getResult().get();
    } else {
        log.error("解析 existingFileFullPath 失败, {}", existingCompilationUnitParse.getProblem(0).toString());
        return newFileSource;
    }
    return mergerFile(newCompilationUnit, existingCompilationUnit);
}
 
Example 2
Source Project: apigcc   Source File: Apigcc.java    License: MIT License 6 votes vote down vote up
/**
 * 解析源代码
 *
 * @return
 */
public Project parse() {
    for (Path source : this.context.getSources()) {
        SourceRoot root = new SourceRoot(source, parserConfiguration);
        try {
            for (ParseResult<CompilationUnit> result : root.tryToParse()) {
                if (result.isSuccessful() && result.getResult().isPresent()) {
                    result.getResult().get().accept(visitorParser, project);
                }
            }
        } catch (IOException e) {
            log.warn("parse root {} error {}", source, e.getMessage());
        }
    }
    return project;
}
 
Example 3
Source Project: gauge-java   Source File: StaticScanner.java    License: Apache License 2.0 6 votes vote down vote up
public void addStepsFromFileContents(String file, String contents) {
    StringReader reader = new StringReader(contents);
    ParseResult<CompilationUnit> result = new JavaParser().parse(reader);
    boolean shouldScan = result.getResult().map(this::shouldScan).orElse(false);
    if (!shouldScan) {
        return;
    }
    RegistryMethodVisitor methodVisitor = new RegistryMethodVisitor(stepRegistry, file);
    methodVisitor.visit(result.getResult().get(), null);
}
 
Example 4
Source Project: Recaf   Source File: JavaResource.java    License: MIT License 5 votes vote down vote up
/**
 * Analyzes attached sources.
 * This also allows workspace-wide name lookups for better type-resolving.
 *
 * @param workspace
 * 		Context to analyze in. Allows application of a workspace-scoped type resolver.
 *
 * @return Map of class names to their parse result. If an
 * {@link SourceCodeException} occured during analysis of a class
 * then it's result may have {@link com.github.javaparser.ParseResult#isSuccessful()} be {@code false}.
 */
public Map<String, ParseResult<CompilationUnit>> analyzeSource(Workspace workspace) {
	Map<String,ParseResult<CompilationUnit>> copy = new HashMap<>();
	classSource.forEach((name, value) -> {
		try {
			copy.put(name, value.analyze(workspace));
		} catch(SourceCodeException ex) {
			error(ex, "Failed to parse source: {}", name);
			copy.put(name, ex.getResult());
		}
	});
	return copy;
}
 
Example 5
Source Project: flow   Source File: OpenApiObjectGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("squid:S1172")
private SourceRoot.Callback.Result process(Path localPath,
        Path absolutePath, ParseResult<CompilationUnit> result) {
    result.ifSuccessful(compilationUnit -> compilationUnit.getPrimaryType()
            .filter(BodyDeclaration::isClassOrInterfaceDeclaration)
            .map(BodyDeclaration::asClassOrInterfaceDeclaration)
            .filter(classOrInterfaceDeclaration -> !classOrInterfaceDeclaration
                    .isInterface())
            .map(this::appendNestedClasses).orElse(Collections.emptyList())
            .forEach(classOrInterfaceDeclaration -> this.parseClass(
                    classOrInterfaceDeclaration, compilationUnit)));
    pathItems.forEach((pathName, pathItem) -> openApiModel.getPaths()
            .addPathItem(pathName, pathItem));
    return SourceRoot.Callback.Result.DONT_SAVE;
}
 
Example 6
Source Project: jeddict   Source File: SourceExplorer.java    License: Apache License 2.0 5 votes vote down vote up
public Optional<CompilationUnit> createCompilationUnit(FileObject classFile) throws FileNotFoundException {
    if (classFile != null) {
        ParseResult<CompilationUnit> parseResult = javaParser.parse(FileUtil.toFile(classFile));
        return parseResult.getResult();
    }
    return Optional.empty();
}
 
Example 7
private Messages.FileDiff implementInExistingClass(ProtocolStringList stubs, File file) {
    try {

        JavaParser javaParser = new JavaParser();
        ParseResult<CompilationUnit> compilationUnit = javaParser.parse(file);
        String contents = String.join(NEW_LINE, stubs);
        int lastLine;
        int column;
        MethodVisitor methodVisitor = new MethodVisitor();
        methodVisitor.visit(compilationUnit.getResult().get(), null);
        if (!methodDeclarations.isEmpty()) {
            MethodDeclaration methodDeclaration = methodDeclarations.get(methodDeclarations.size() - 1);
            lastLine = methodDeclaration.getRange().get().end.line - 1;
            column = methodDeclaration.getRange().get().end.column + 1;
            contents = NEW_LINE + contents;
        } else {
            new ClassVisitor().visit(compilationUnit.getResult().get(), null);
            lastLine = classRange.end.line - 1;
            column = 0;
            contents = contents + NEW_LINE;
        }
        Spec.Span.Builder span = Spec.Span.newBuilder()
                .setStart(lastLine)
                .setStartChar(column)
                .setEnd(lastLine)
                .setEndChar(column);
        Messages.TextDiff textDiff = Messages.TextDiff.newBuilder().setSpan(span).setContent(contents).build();
        return Messages.FileDiff.newBuilder().setFilePath(file.toString()).addTextDiffs(textDiff).build();

    } catch (IOException e) {
        Logger.error("Unable to implement method", e);
    }
    return null;
}
 
Example 8
Source Project: Recaf   Source File: SourceCodeException.java    License: MIT License 4 votes vote down vote up
/**
 * @param result Result returned as a parse failure.
 */
public SourceCodeException(ParseResult<CompilationUnit> result) {
	this.result = result;
}
 
Example 9
Source Project: Recaf   Source File: SourceCodeException.java    License: MIT License 4 votes vote down vote up
/**
 * @return Failing parse result.
 */
public ParseResult<CompilationUnit> getResult() {
	return result;
}
 
Example 10
Source Project: Recaf   Source File: DeferringResource.java    License: MIT License 4 votes vote down vote up
@Override
public Map<String, ParseResult<CompilationUnit>> analyzeSource(Workspace workspace) {
	return backing.analyzeSource(workspace);
}
 
Example 11
Source Project: Recaf   Source File: Workspace.java    License: MIT License 2 votes vote down vote up
/**
 * Analyzes attached sources of all resources.
 * This also allows workspace-wide name lookups for better type-resolving.
 *
 * @return Map of class names to their parse result. If an
 * {@link SourceCodeException} occured during analysis of a class
 * then it's result may have {@link com.github.javaparser.ParseResult#isSuccessful()} be {@code false}.
 */
public Map<String, ParseResult<CompilationUnit>> analyzeSources() {
	return Stream.concat(Stream.of(primary), libraries.stream())
			.flatMap(resource -> resource.analyzeSource(this).entrySet().stream())
			.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}