com.github.javaparser.ParseException Java Examples

The following examples show how to use com.github.javaparser.ParseException. 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: EntitySourceAnalyzer.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
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 #2
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: CodeValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #5
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: SourceDaoTest.java    From vaadinator with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnumeration() throws ParseException {
	BeanDescription desc = daoUnderTest.processJavaInput(getClass().getResourceAsStream("Anreden.javainput"));
	assertEquals("Anreden", desc.getClassName());
	assertTrue(desc.isEnumeration());
	assertEquals(3, desc.getEnumValues().size());
	assertNull(desc.getEnumValue("gibtesnicht"));
	assertNotNull(desc.getEnumValue("HERR"));
	assertEquals("HERR", desc.getEnumValue("HERR").getValue());
	assertEquals("Herr", desc.getEnumValue("HERR").getEffectiveCaption());
	assertNotNull(desc.getEnumValue("FRAU"));
	assertEquals("FRAU", desc.getEnumValue("FRAU").getValue());
	assertEquals("Frau", desc.getEnumValue("FRAU").getEffectiveCaption());
	assertNotNull(desc.getEnumValue("FROLLEIN"));
	assertEquals("FROLLEIN", desc.getEnumValue("FROLLEIN").getValue());
	assertEquals("Fräulein", desc.getEnumValue("FROLLEIN").getCaptionText());
	assertEquals("Fräulein", desc.getEnumValue("FROLLEIN").getEffectiveCaption());
	assertFalse(desc.isDisplayed());
	assertFalse(desc.isMapped());
	assertFalse(desc.isWrapped());
}
 
Example #9
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@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 File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #11
Source File: Reverser.java    From android-reverse-r with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #12
Source File: CompilationUnitMerger.java    From dolphin with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #13
Source File: AbstractWisdomSourceWatcherMojo.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassImplementingController() throws IOException, ParseException {
    File file = new File("src/test/java/sample/MyController.java");
    final CompilationUnit declaration = JavaParser.parse(file);
    final Boolean isController = visitor.visit(declaration, null);
    assertThat(isController).isTrue();
}
 
Example #15
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: ClassSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: CodeValidator.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getMD5FromText(String code) {
    // Parse the code and output the string without the comment.
    // This string should be already normalized
    try {
        return org.apache.commons.codec.digest.DigestUtils
                .md5Hex(getCompilationUnitFromText(code).toString( new PrettyPrinterConfiguration().setPrintComments(false)));
    } catch ( IOException | ParseException e) {
        // Ignore this
    }
    // if the code does not compile there's no point to try to remove the comments
    return org.apache.commons.codec.digest.DigestUtils.md5Hex(code);
}
 
Example #21
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #23
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: ControllerSourceVisitorTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@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 #25
Source File: JavaFileAnalyzer.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
private Optional<CompilationUnit> handleThrowable(File file, Throwable t) {
    String message = "Failed to parse [" + file + "]!";
    if ((TokenMgrError.class.isInstance(t) || ParseException.class.isInstance(t))
            && ignoreParsingErrors) {
        logger.debug(message, t);
        return absent();
    }
    if (Error.class.isInstance(t) && !TokenMgrError.class.isInstance(t)) {
        throw Error.class.cast(t);
    }
    throw new RuntimeException(message, t);
}
 
Example #26
Source File: A_Nodes.java    From deadcode4j with Apache License 2.0 5 votes vote down vote up
@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 #27
Source File: ExtendsTest.java    From butterfly with MIT License 5 votes vote down vote up
@Test
public void negateTest() throws ParseException {
    String resourceName = "/test-app/src/main/java/com/testapp/JavaLangSubclass.java";
    InputStream resourceAsStream = this.getClass().getResourceAsStream(resourceName);
    CompilationUnit compilationUnit = StaticJavaParser.parse(resourceAsStream);
    Extends extendsObj = new Extends(Throwable.class).setNegate(true);
    Assert.assertFalse(extendsObj.evaluate(compilationUnit));
}
 
Example #28
Source File: AnnotatedWithTest.java    From butterfly with MIT License 4 votes vote down vote up
@Test
public void simpleNameStringTest() throws ParseException {
    AnnotatedWith annotatedWith = new AnnotatedWith("org.springframework.context.annotation.ComponentScan");
    Assert.assertTrue(annotatedWith.evaluate(compilationUnit));
}
 
Example #29
Source File: ExtendsTest.java    From butterfly with MIT License 4 votes vote down vote up
@Test
public void fqdnTest() throws ParseException {
    test("/test-app/src/main/java/com/testapp/FqdnSubclass.java", Logger.class, true);
}
 
Example #30
Source File: ExtendsTest.java    From butterfly with MIT License 4 votes vote down vote up
@Test
public void simpleNameTest() throws ParseException {
    test("/test-app/src/main/java/com/testapp/SimpleNameSubclass.java", Logger.class, true);
}