com.github.javaparser.ParseProblemException Java Examples
The following examples show how to use
com.github.javaparser.ParseProblemException.
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: 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 #2
Source File: TestUtils.java From openapi-generator with Apache License 2.0 | 5 votes |
public static void assertValidJavaSourceCode(String javaSourceCode, String filename) { try { CompilationUnit compilation = StaticJavaParser.parse(javaSourceCode); assertTrue(compilation.getTypes().size() > 0, "File: " + filename); } catch (ParseProblemException ex) { fail("Java parse problem: " + filename, ex); } }
Example #3
Source File: ParseUtil.java From SnowGraph with 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 #4
Source File: EntityIndexer.java From jql with MIT License | 5 votes |
public void indexFiles(Collection<File> files) { int totalFiles = files.size(); int fileIndex = 1; for (File file : files) { try { CompilationUnit cu = parse(file); compilationUnitIndexer.index(cu, file.getName()); } catch (ParseProblemException | IOException e) { System.err.println("Error while parsing " + file.getAbsolutePath()); } System.out.print("\rIndexing entities: " + getPercent(fileIndex, totalFiles) + "% " + ("(" + fileIndex + "/" + totalFiles + ")")); fileIndex++; } }
Example #5
Source File: RelationCalculator.java From jql with MIT License | 5 votes |
public void calculateRelations(Collection<File> files) { System.out.println(); int totalFiles = files.size(); int fileIndex = 1; for (File file : files) { try { CompilationUnit cu = parse(file); NodeList<TypeDeclaration<?>> types = cu.getTypes(); for (TypeDeclaration<?> type : types) { boolean isInterface = type instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) type).isInterface(); boolean isAnnotation = type instanceof AnnotationDeclaration; boolean isEnumeration = type instanceof EnumDeclaration; boolean isClass = !isAnnotation && !isEnumeration && !isInterface; if (isInterface) { // check if this interface extends another interface and persist relation in EXTENDS table ClassOrInterfaceDeclaration interfaceDeclaration = (ClassOrInterfaceDeclaration) type; extendsRelationCalculator.calculate(interfaceDeclaration, cu); } if (isClass) { ClassOrInterfaceDeclaration classDeclaration = (ClassOrInterfaceDeclaration) type; // check if this class implements an interface and persist relation in IMPLEMENTS table implementsRelationCalculator.calculate(classDeclaration, cu); // check if this class extends another class and persist relation in EXTENDS table extendsRelationCalculator.calculate(classDeclaration, cu); } if (isClass || isInterface) { annotatedWithCalculator.calculate((ClassOrInterfaceDeclaration) type, cu); } } } catch (ParseProblemException | IOException e) { System.err.println("Error while parsing " + file.getAbsolutePath()); } System.out.print("\rCalculating relations: " + getPercent(fileIndex, totalFiles) + "% " + ("(" + fileIndex + "/" + totalFiles + ")")); fileIndex++; } System.out.println(); }
Example #6
Source File: CodeValidator.java From CodeDefenders with 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 #7
Source File: BaseModelTest.java From jeddict with Apache License 2.0 | 4 votes |
private void testClass(JavaClass javaClass, ClassGenerator generator, EntityMappings entityMappings, String fileName) throws Exception { PrettyPrinter prettyPrinter = new PrettyPrinter(); String existingSource; CompilationUnit existingUnit; String newSource = null; CompilationUnit newUnit; try (InputStream existingSourceStream = this.getClass().getResourceAsStream(javaClass.getClazz() + JAVA_EXT_SUFFIX)) { existingSource = readString(existingSourceStream); existingUnit = new JavaParser().parse(existingSource).getResult().get(); assertNotNull(existingUnit); existingSource = prettyPrinter.print(existingUnit); } JavaClassSyncHandler .getInstance(javaClass) .syncExistingSnippet(existingUnit); if (fileName == null) { fileName = wrap("Reverse Engineering", FG_DARK_MAGENTA); } else { fileName = wrap(fileName, FG_DARK_BLUE); } try { ClassDefSnippet classDef = generator.getClassDef(); classDef.setJaxbSupport(entityMappings.getJaxbSupport()); newSource = classDef.getSnippet(); assertNotNull(newSource); newUnit = new JavaParser().parse(newSource).getResult().get(); assertNotNull(newUnit); newSource = prettyPrinter.print(newUnit); // System.out.println("newSource " + newSource); try (BufferedReader existingSourceReader = new BufferedReader(new StringReader(existingSource)); BufferedReader newSourceReader = new BufferedReader(new StringReader(newSource));) { String existingSourceLine; String newSourceLine; int lineNumber = 0; while ((existingSourceLine = existingSourceReader.readLine()) != null && (newSourceLine = newSourceReader.readLine()) != null) { ++lineNumber; assertEquals(existingSourceLine, newSourceLine, '\n' + wrap("Failed : " + javaClass.getFQN() + " [" + fileName + "]", FG_DARK_RED, BOLD) + '\n' + wrap("Line number : " + lineNumber, FG_RED, BOLD) + '\n' + wrap("existingSourceLine : " + existingSourceLine, FG_DARK_RED) + '\n' + wrap("newSourceLine : " + newSourceLine, FG_DARK_RED) + '\n' + newSource ); } } System.out.println(wrap("Passed : ", FG_DARK_GREEN, BOLD) + wrap(javaClass.getFQN(), FG_DARK_CYAN) + " [" + fileName + "]" ); } catch (ParseProblemException ex) { fail(wrap( "Compilation Failed : " + javaClass.getFQN() + " [" + fileName + "]" + '\n' + "---------------------" + '\n' + newSource + '\n' + "---------------------" + ex.getMessage() + "---------------------", FG_RED )); } }
Example #8
Source File: ClassCodeAnalyser.java From CodeDefenders with GNU Lesser General Public License v3.0 | 3 votes |
/** * Iterates through a java class code to extract following information in a {@link CodeAnalysisResult}: * <ul> * <li>Strings of imports</li> * <li>Lines of compile time constants</li> * <li>Lines of non coverable code</li> * <li>Lines of not initialized fields</li> * <li>{@link Range Ranges} of methods signatures</li> * <li>{@link Range Ranges} of methods</li> * <li>{@link Range Ranges} if-condition statements and their bracket pair</li> * </ul> * * @param className The name of the visited class. * @param sourceCode the source code of the visited class. * @return a result, may be empty, but never {@code null}. */ public static CodeAnalysisResult visitCode(String className, String sourceCode) { final CodeAnalysisResult result = new CodeAnalysisResult(); try { final CompilationUnit cu = JavaParser.parse(sourceCode); resultVisitor.visit(cu, result); } catch (ParseProblemException e) { logger.warn("Failed to parse {}. Aborting code visit.", className); } return result; }