Java Code Examples for com.github.javaparser.JavaParser
The following examples show how to use
com.github.javaparser.JavaParser.
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 Author: alansun2 File: MyShellCallback.java License: Apache License 2.0 | 6 votes |
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: gradle-modules-plugin Author: java9-modularity File: ModuleName.java License: MIT License | 6 votes |
private Optional<String> findModuleName(Path moduleInfoJava, String projectPath) { try { JavaParser parser = new JavaParser(); parser.getParserConfiguration().setLanguageLevel(ParserConfiguration.LanguageLevel.JAVA_11); Optional<CompilationUnit> compilationUnit = parser.parse(moduleInfoJava).getResult(); if (compilationUnit.isEmpty()) { LOGGER.debug("Project {} => compilation unit is empty", projectPath); return Optional.empty(); } Optional<ModuleDeclaration> module = compilationUnit.get().getModule(); if (module.isEmpty()) { LOGGER.warn("Project {} => module-info.java found, but module name could not be parsed", projectPath); return Optional.empty(); } String name = module.get().getName().toString(); LOGGER.lifecycle("Project {} => '{}' Java module", projectPath, name); return Optional.of(name); } catch (IOException e) { LOGGER.error("Project {} => error opening module-info.java at {}", projectPath, moduleInfoJava); return Optional.empty(); } }
Example #3
Source Project: Briefness Author: hacknife File: FinalRClassBuilder.java License: Apache License 2.0 | 6 votes |
public static void brewJava(File rFile, File outputDir, String packageName, String className, boolean useLegacyTypes) throws Exception { CompilationUnit compilationUnit = JavaParser.parse(rFile); TypeDeclaration resourceClass = compilationUnit.getTypes().get(0); TypeSpec.Builder result = TypeSpec.classBuilder(className) .addModifiers(PUBLIC, FINAL); for (Node node : resourceClass.getChildNodes()) { if (node instanceof ClassOrInterfaceDeclaration) { addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node, useLegacyTypes); } } JavaFile finalR = JavaFile.builder(packageName, result.build()) .addFileComment("Generated code from Butter Knife gradle plugin. Do not modify!") .build(); finalR.writeTo(outputDir); }
Example #4
Source Project: SimFix Author: xgdsmileboy File: Parser.java License: GNU General Public License v2.0 | 6 votes |
/** * * @throws Exception */ public void parse() throws Exception { // creates an input stream for the file to be parsed FileInputStream in = new FileInputStream(this.sourceName); CompilationUnit cu; try { // parse the file cu = JavaParser.parse(in); } finally { in.close(); } // explore tree explore(" ", cu); /*for (Integer statement : this.statements.keySet()) { System.out.println(statement + " -> " + this.statements.get(statement).toString()); }*/ }
Example #5
Source Project: enkan Author: kawasima File: EntitySourceAnalyzer.java License: Eclipse Public License 1.0 | 6 votes |
public List<EntityField> analyze(File source) throws IOException, ParseException { List<EntityField> entityFields = new ArrayList<>(); CompilationUnit cu = JavaParser.parse(source); cu.accept(new VoidVisitorAdapter<List<EntityField>>() { @Override public void visit(FieldDeclaration fd, List<EntityField> f) { if (fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Column"))) { Class<?> type = null; switch (fd.getType().toString()) { case "String": type = String.class; break; case "Long": type = Long.class; break; case "Integer": type = Integer.class; break; case "boolean": type = boolean.class; break; } if (type == null) return; f.add(new EntityField( fd.getVariables().get(0).getId().getName(), type, fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Id")))); } } }, entityFields); return entityFields; }
Example #6
Source Project: jeddict Author: jeddict File: JavaClassSyncHandler.java License: Apache License 2.0 | 6 votes |
private void syncHeader(Comment comment) { String value = comment.toString(); if (javaClass.getRootElement() .getSnippets(BEFORE_PACKAGE) .stream() .filter(snip -> { Optional<CompilationUnit> parsed = new JavaParser().parse(snip.getValue()).getResult(); return (parsed.isPresent()&& compareNonWhitespaces(parsed.get().toString(), value)) || compareNonWhitespaces(snip.getValue(), value); }) .findAny() .isPresent()) { return; } if (javaClass.getSnippets(BEFORE_PACKAGE) .stream() .filter(snip -> compareNonWhitespaces(snip.getValue(), value)) .findAny() .isPresent()) { return; } javaClass.addRuntimeSnippet(new ClassSnippet(value, BEFORE_PACKAGE)); }
Example #7
Source Project: CodeDefenders Author: CodeDefenders File: CodeValidator.java License: GNU Lesser General Public License v3.0 | 6 votes |
private static CompilationUnit getCompilationUnitFromText(String code) throws ParseException, IOException { try (InputStream inputStream = new ByteArrayInputStream(code.getBytes())) { try { return JavaParser.parse(inputStream); } catch (ParseProblemException error) { throw new ParseException(error.getMessage()); } } }
Example #8
Source Project: gauge-java Author: getgauge File: StaticScanner.java License: Apache License 2.0 | 6 votes |
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 #9
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testHttpVerbs() throws IOException, ParseException { File file = new File("src/test/java/controller/SimpleController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); final Collection<ControllerRouteModel> routes = (Collection<ControllerRouteModel>) model.getRoutes().get("/simple"); assertThat(routes).isNotNull(); assertThat(routes).hasSize(6); for (ControllerRouteModel route : routes) { assertThat(route.getHttpMethod().name()).isEqualToIgnoringCase(route.getMethodName()); assertThat(route.getParams()).isEmpty(); assertThat(route.getPath()).isEqualToIgnoringCase("/simple"); } }
Example #10
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testNotNullContraints() throws IOException, ParseException{ File file = new File("src/test/java/controller/ControllerWithConstraints.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model,"/superman"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); RouteParamModel param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with NotNull constraints assertThat(param.getName()).isEqualTo("clark"); assertThat(param.isMandatory()).isTrue(); route = getModelByPath(model,"/batman"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with NotNull constraints that contains a message assertThat(param.getName()).isEqualTo("bruce"); assertThat(param.isMandatory()).isTrue(); }
Example #11
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testMinContraints() throws IOException, ParseException{ File file = new File("src/test/java/controller/ControllerWithConstraints.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model,"/spiderman"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); RouteParamModel param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with Min constraint assertThat(param.getName()).isEqualTo("peter"); assertThat(param.getMin()).isEqualTo(1962); route = getModelByPath(model,"/chameleon"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with Min constraints that contains a message assertThat(param.getName()).isEqualTo("dmitri"); assertThat(param.getMin()).isEqualTo(1963); }
Example #12
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testMaxContraints() throws IOException, ParseException{ File file = new File("src/test/java/controller/ControllerWithConstraints.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model,"/rahan"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); RouteParamModel param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with Max constraint assertThat(param.getName()).isEqualTo("son"); assertThat(param.getMax()).isEqualTo(2010); route = getModelByPath(model,"/crao"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); param = (RouteParamModel) Iterables.get(route.getParams(), 0); //Annotated with Max constraints that contains a message assertThat(param.getName()).isEqualTo("father"); assertThat(param.getMax()).isEqualTo(2010); }
Example #13
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testControllerUsingPath() throws IOException, ParseException { File file = new File("src/test/java/controller/ControllerWithPath.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); System.out.println(model.getRoutesAsMultiMap()); ControllerRouteModel route = getModelByFullPath(model, "/root/simple"); assertThat(route).isNotNull(); route = getModelByFullPath(model, "/root/"); assertThat(route).isNotNull(); route = getModelByFullPath(model, "/root"); assertThat(route).isNotNull(); route = getModelByFullPath(model, "/rootstuff"); assertThat(route).isNotNull(); }
Example #14
Source Project: wisdom Author: wisdom-framework File: ControllerSourceVisitorTest.java License: Apache License 2.0 | 6 votes |
@Test public void testReferencingConstant() throws IOException, ParseException { File file = new File("src/test/java/controller/ControllerReferencingConstant.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); final Collection<ControllerRouteModel> routes = (Collection<ControllerRouteModel>) model.getRoutes().get("/constant"); assertThat(routes).isNotNull(); assertThat(routes).hasSize(3); for (ControllerRouteModel route : routes) { assertThat(route.getHttpMethod().name()).isEqualToIgnoringCase(route.getMethodName()); assertThat(route.getParams()).isEmpty(); assertThat(route.getPath()).isEqualToIgnoringCase("/constant"); } }
Example #15
Source Project: JCTools Author: JCTools File: JavaParsingAtomicQueueGenerator.java License: Apache License 2.0 | 6 votes |
static void main(Class<? extends JavaParsingAtomicQueueGenerator> generatorClass, String[] args) throws Exception { if (args.length < 2) { throw new IllegalArgumentException("Usage: outputDirectory inputSourceFiles"); } File outputDirectory = new File(args[0]); for (int i = 1; i < args.length; i++) { File file = new File(args[i]); System.out.println("Processing " + file); CompilationUnit cu = new JavaParser().parse(file).getResult().get(); JavaParsingAtomicQueueGenerator generator = buildGenerator(generatorClass, file.getName()); generator.visit(cu, null); generator.organiseImports(cu); String outputFileName = generator.translateQueueName(file.getName().replace(".java", "")) + ".java"; try (FileWriter writer = new FileWriter(new File(outputDirectory, outputFileName))) { writer.write(cu.toString()); } System.out.println("Saved to " + outputFileName); } }
Example #16
Source Project: deadcode4j Author: Scout24 File: JavaFileAnalyzer.java License: Apache License 2.0 | 6 votes |
@Nonnull @Override @SuppressWarnings("PMD.AvoidCatchingThrowable") // unfortunately, JavaParser throws an Error when parsing fails public LoadingCache<File, Optional<CompilationUnit>> apply(@Nonnull final AnalysisContext analysisContext) { return SequentialLoadingCache.createSingleValueCache(toFunction(new NonNullFunction<File, Optional<CompilationUnit>>() { @Nonnull @Override @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "The MavenProject does not provide the proper encoding") public Optional<CompilationUnit> apply(@Nonnull File file) { Reader reader = null; try { reader = analysisContext.getModule().getEncoding() != null ? new InputStreamReader(new FileInputStream(file), analysisContext.getModule().getEncoding()) : new FileReader(file); return of(JavaParser.parse(reader, false)); } catch (Throwable t) { return handleThrowable(file, t); } finally { closeQuietly(reader); } } })); }
Example #17
Source Project: molicode Author: cn2oo8 File: SourceCodeProcessHandler.java License: Apache License 2.0 | 5 votes |
@Override public void doHandle(MoliCodeContext context) { String content = context.getDataString(MoliCodeConstant.CTX_KEY_SRC_CONTENT); if (StringUtils.isEmpty(content)) { return; } JavaSourceCodeDto sourceCodeDto = new JavaSourceCodeDto(); CompilationUnit compilationUnit = JavaParser.parse(content); compilationUnit.accept(new JavaSourceCodeVisitor(sourceCodeDto), null); context.put(MoliCodeConstant.CTX_KEY_DEF_DATA, sourceCodeDto); }
Example #18
Source Project: genDoc Author: easycodingnow File: ParseHelper.java License: Apache License 2.0 | 5 votes |
static Comment parseComment(Node node) { if (node.getComment().isPresent()) { Javadoc javadoc = JavaParser.parseJavadoc(node.getComment().get().getContent()); Comment comment = new Comment(); comment.setDescription(javadoc.getDescription().toText()); List<JavadocBlockTag> javadocBlockTags = javadoc.getBlockTags(); if (javadocBlockTags != null && javadocBlockTags.size() > 0) { List<Comment.Tag> tags = new ArrayList<Comment.Tag>(); for (JavadocBlockTag javadocBlockTag : javadocBlockTags) { Comment.Tag tag = new Comment.Tag(); tag.setTagName(javadocBlockTag.getTagName()); tag.setName(javadocBlockTag.getName().orElse(null)); tag.setContent(javadocBlockTag.getContent().toText()); tags.add(tag); } comment.setTags(tags); } return comment; } return null; }
Example #19
Source Project: SnowGraph Author: linzeqipku File: ParseUtil.java License: Apache License 2.0 | 5 votes |
public static List<String> parseFileContent(String code) { try { CompilationUnit cu = JavaParser.parse(code); List<MethodDeclaration> methods = cu.findAll(MethodDeclaration.class); count += methods.size(); return methods.stream() .map(MethodDeclaration::toString) .collect(Collectors.toList()); } catch (ParseProblemException e) { logger.warn("Could not parse code: "); logger.warn(code); return new ArrayList<>(); } }
Example #20
Source Project: Siamese Author: UCL-CREST File: JavaMethodParser.java License: GNU General Public License v3.0 | 5 votes |
public void printMethods(String javaFile) throws IOException { FileInputStream in = new FileInputStream(javaFile); CompilationUnit cu; cu = JavaParser.parse(in); new MethodVisitor().visit(cu, null); new ConstructorVisitor().visit(cu, null); in.close(); }
Example #21
Source Project: android-reverse-r Author: justingarrick File: Reverser.java License: Apache License 2.0 | 5 votes |
/** * Parses the R.java file(s) and creates a mapping of ids to fully qualified strings. * * @param rFiles the set of r.java files */ private void createTransform(Set<Path> rFiles) { ClassVisitor visitor = new ClassVisitor(); rFiles.stream().forEach(path -> { try { CompilationUnit unit = JavaParser.parse(path.toFile()); visitor.visit(unit, null); } catch (ParseException | IOException e) { System.err.println("Unable to parse " + path.getFileName() + ": " + e.getMessage()); } }); }
Example #22
Source Project: jaxrs-analyzer Author: sdaschner File: JavaDocAnalyzer.java License: Apache License 2.0 | 5 votes |
private static void parseJavaDoc(Path path, JavaDocParserVisitor visitor) { try { CompilationUnit cu = JavaParser.parse(path.toFile()); cu.accept(visitor, null); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } }
Example #23
Source Project: dolphin Author: beihaifeiwu File: CompilationUnitMerger.java License: Apache License 2.0 | 5 votes |
/** * Util method to make source merge more convenient * * @param first merge params, specifically for the existing source * @param second merge params, specifically for the new source * @return merged result * @throws ParseException cannot parse the input params */ public static String merge(String first, String second) throws ParseException { JavaParser.setDoNotAssignCommentsPreceedingEmptyLines(false); CompilationUnit cu1 = JavaParser.parse(new StringReader(first), true); CompilationUnit cu2 = JavaParser.parse(new StringReader(second), true); AbstractMerger<CompilationUnit> merger = AbstractMerger.getMerger(CompilationUnit.class); CompilationUnit result = merger.merge(cu1, cu2); return result.toString(); }
Example #24
Source Project: jeddict Author: jeddict File: SourceExplorer.java License: Apache License 2.0 | 5 votes |
public SourceExplorer( FileObject sourceRoot, EntityMappings entityMappings, Set<String> selectedClasses, boolean includeReference) { this.sourceRoot = sourceRoot; this.entityMappings = entityMappings; this.includeReference = includeReference; this.selectedClasses = selectedClasses.stream().map(JavaIdentifiers::unqualify).collect(toSet()); this.javaParser = new JavaParser(); configureJavaParser(sourceRoot); }
Example #25
Source Project: sundrio Author: sundrio File: Sources.java License: Apache License 2.0 | 5 votes |
public CompilationUnit apply(String resource) { InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream(resource); return JavaParser.parse(is); } catch (Exception ex) { throw new RuntimeException("Failed to load resource: [" + resource + "] from classpath."); } finally { IOUtils.closeQuietly(is); } }
Example #26
Source Project: sundrio Author: sundrio File: Sources.java License: Apache License 2.0 | 5 votes |
public CompilationUnit apply(InputStream is) { try { return JavaParser.parse(is); } catch (Exception ex) { throw new RuntimeException("Failed to parse stream.", ex); } finally { IOUtils.closeQuietly(is); } }
Example #27
Source Project: CodeDefenders Author: CodeDefenders File: CodeValidator.java License: GNU Lesser General Public License v3.0 | 5 votes |
private static ValidationMessage validInsertion(String diff, CodeValidatorLevel level) { try { BlockStmt blockStmt = JavaParser.parseBlock("{ " + diff + " }"); // TODO Should this called always and not only for checking if there's validInsertion ? MutationVisitor visitor = new MutationVisitor(level); visitor.visit(blockStmt, null); if (!visitor.isValid()) { return visitor.getMessage(); } } catch ( ParseProblemException ignored) { // TODO: Why is ignoring this acceptable? // Phil: I don't know, but otherwise some tests would fail, since they cannot be parsed. } // remove whitespaces String diff2 = diff.replaceAll("\\s+", ""); if (level != CodeValidatorLevel.RELAXED && containsAny(diff2, PROHIBITED_CONTROL_STRUCTURES)) { return ValidationMessage.MUTANT_VALIDATION_CALLS; } if (level != CodeValidatorLevel.RELAXED && containsAny(diff2, COMMENT_TOKENS)) { return ValidationMessage.MUTANT_VALIDATION_COMMENT; } if (containsAny(diff2, PROHIBITED_CALLS)) { return ValidationMessage.MUTANT_VALIDATION_OPERATORS; } // If bitshifts are used if (level == CodeValidatorLevel.STRICT && containsAny(diff2, PROHIBITED_BITWISE_OPERATORS)) { return ValidationMessage.MUTANT_VALIDATION_OPERATORS; } return ValidationMessage.MUTANT_VALIDATION_SUCCESS; }
Example #28
Source Project: gauge-java Author: getgauge File: StubImplementationCodeProcessor.java License: Apache License 2.0 | 5 votes |
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 #29
Source Project: gauge-java Author: getgauge File: JavaParseWorker.java License: Apache License 2.0 | 5 votes |
public void run() { try { Optional<CompilationUnit> result = new JavaParser().parse(javaFile).getResult(); result.ifPresent(value -> compilationUnit = value); } catch (Exception e) { Logger.error("Unable to parse file " + javaFile.getName()); } }
Example #30
Source Project: wisdom Author: wisdom-framework File: AbstractWisdomSourceWatcherMojo.java License: Apache License 2.0 | 5 votes |
/** * Parse the source file of a wisdom Controller and create a model from it. * Call {@link #controllerParsed(File, ControllerModel)}. * * @param file the controller source file. * @throws WatchingException */ public void parseController(File file) throws WatchingException{ ControllerModel<T> controllerModel = new ControllerModel<>(); //Populate the controller model by visiting the File try { JavaParser.parse(file).accept(CONTROLLER_VISITOR,controllerModel); } catch (ParseException |IOException e) { throw new WatchingException("Cannot parse "+file.getName(), e); } //Call children once the controller has been parsed controllerParsed(file, controllerModel); }