com.github.javaparser.JavaParser Java Examples
The following examples show how to use
com.github.javaparser.JavaParser.
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 File: MyShellCallback.java From mapper-generator-javafx with 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 File: StaticScanner.java From gauge-java with 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 #3
Source File: CodeValidator.java From CodeDefenders with 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 #4
Source File: ControllerSourceVisitorTest.java From wisdom with 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 #5
Source File: ControllerSourceVisitorTest.java From wisdom with 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 #6
Source File: JavaClassSyncHandler.java From jeddict with 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 File: ControllerSourceVisitorTest.java From wisdom with 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 #8
Source File: ControllerSourceVisitorTest.java From wisdom with 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 #9
Source File: ControllerSourceVisitorTest.java From wisdom with 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 #10
Source File: ControllerSourceVisitorTest.java From wisdom with 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 #11
Source File: EntitySourceAnalyzer.java From enkan with 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 #12
Source File: Parser.java From SimFix with 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 #13
Source File: FinalRClassBuilder.java From Briefness with 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 #14
Source File: JavaFileAnalyzer.java From deadcode4j with 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 #15
Source File: JavaParsingAtomicQueueGenerator.java From JCTools with 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 File: ModuleName.java From gradle-modules-plugin with 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 #17
Source File: ControllerSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testEmptyController() throws IOException, ParseException { File file = new File("src/test/java/controller/EmptyController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); assertThat(model.getRoutes()).isEmpty(); }
Example #18
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testClassExtendingDefaultController() throws IOException, ParseException { File file = new File("src/test/java/sample/MyDefaultController.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isTrue(); }
Example #19
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testClassAnnotatedWithController() throws IOException, ParseException { File file = new File("src/test/java/sample/MyAnnotatedController.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isTrue(); }
Example #20
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testABasicClass() throws IOException, ParseException { File file = new File("src/test/java/sample/MyClass.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isFalse(); }
Example #21
Source File: A_Nodes.java From deadcode4j with Apache License 2.0 | 5 votes |
@Test public void calculatesTypeNames() throws IOException, ParseException { CompilationUnit compilationUnit = JavaParser.parse( FileLoader.getFile("de/is24/javaparser/TypeNameTestClass.java")); compilationUnit.accept(new VoidVisitorAdapter<Void>() { @Override public void visit(StringLiteralExpr n, Void arg) { assertThat("Name of anonymous class is invalid!", Nodes.getTypeName(n), is(n.getValue())); } }, null); }
Example #22
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testAnInterfaceClass() throws IOException, ParseException { File file = new File("src/test/java/sample/MyInterface.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isFalse(); }
Example #23
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testAnEnum() throws IOException, ParseException { File file = new File("src/test/java/sample/MyEnum.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isFalse(); }
Example #24
Source File: ClassSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testAnAnnotation() throws IOException, ParseException { File file = new File("src/test/java/sample/MyAnnotation.java"); final CompilationUnit declaration = JavaParser.parse(file); final Boolean isController = visitor.visit(declaration, null); assertThat(isController).isFalse(); }
Example #25
Source File: SourceCodeProcessHandler.java From molicode with 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 #26
Source File: ControllerSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testParameters() throws IOException, ParseException { File file = new File("src/test/java/controller/ParameterizedController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model, "/params/1"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); RouteParamModel param = (RouteParamModel) Iterables.get(route.getParams(), 0); assertThat(param.getName()).isEqualTo("hello"); assertThat(param.getParamType()).isEqualTo(RouteParamModel.ParamType.FORM); assertThat(param.getDefaultValue()).isNull(); assertThat(param.getValueType()).isEqualTo(String.class.getSimpleName()); route = getModelByPath(model, "/params/2/{hello}"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(1); param = (RouteParamModel) Iterables.get(route.getParams(), 0); assertThat(param.getName()).isEqualTo("hello"); assertThat(param.getParamType()).isEqualTo(RouteParamModel.ParamType.PATH_PARAM); assertThat(param.getDefaultValue()).isNull(); assertThat(param.getValueType()).isEqualTo(String.class.getSimpleName()); route = getModelByPath(model, "/params/3/{hello}"); assertThat(route).isNotNull(); assertThat(route.getParams()).hasSize(2); param = getParamByName(route.getParams(), "hello"); assertThat(param.getParamType()).isEqualTo(RouteParamModel.ParamType.PATH_PARAM); assertThat(param.getDefaultValue()).isNull(); assertThat(param.getValueType()).isEqualTo(String.class.getSimpleName()); param = getParamByName(route.getParams(), "name"); assertThat(param.getParamType()).isEqualTo(RouteParamModel.ParamType.FORM); assertThat(param.getDefaultValue()).isEqualTo("wisdom"); assertThat(param.getValueType()).isEqualTo(String.class.getSimpleName()); }
Example #27
Source File: ControllerSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testBody() throws IOException, ParseException { File file = new File("src/test/java/controller/ParameterizedController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model, "/params/4"); assertThat(route.getParams()).hasSize(1); final RouteParamModel o = (RouteParamModel) Iterables.get(route.getParams(), 0); assertThat(o.getParamType()).isEqualTo(RouteParamModel.ParamType.BODY); assertThat(o.getName()).isEqualTo("body"); // Special value. assertThat(o.getValueType()).isEqualTo(String.class.getSimpleName()); }
Example #28
Source File: ControllerSourceVisitorTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testFileItem() throws IOException, ParseException { File file = new File("src/test/java/controller/ParameterizedController.java"); final CompilationUnit declaration = JavaParser.parse(file); ControllerModel model = new ControllerModel(); visitor.visit(declaration, model); ControllerRouteModel route = getModelByPath(model, "/params/5"); assertThat(route.getParams()).hasSize(1); final RouteParamModel o = (RouteParamModel) Iterables.get(route.getParams(), 0); assertThat(o.getParamType()).isEqualTo(RouteParamModel.ParamType.FORM); assertThat(o.getName()).isEqualTo("file"); assertThat(o.getValueType()).isEqualTo(FileItem.class.getSimpleName()); }
Example #29
Source File: TraceVisitor.java From JCTools with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { for (String file : args) { System.out.println("Opening " + file); CompilationUnit cu = new JavaParser().parse(new File(file)).getResult().get(); new TraceVisitor(System.out, false).visit(cu, null); System.out.println(); System.out.println(); System.out.println(); } }
Example #30
Source File: AbstractWisdomSourceWatcherMojo.java From wisdom with 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); }