@Override public String updateAndGetCompilationUnitContents( final String fileIdentifier, final ClassOrInterfaceTypeDetails cid) { // Validate parameters Validate.notBlank(fileIdentifier, "Oringinal unit path required"); Validate.notNull(cid, "Type details required"); // Load original compilation unit from file final File file = new File(fileIdentifier); String fileContents = ""; try { fileContents = FileUtils.readFileToString(file); } catch (final IOException ignored) { } if (StringUtils.isBlank(fileContents)) { return getCompilationUnitContents(cid); } CompilationUnit compilationUnit; try { compilationUnit = JavaParser.parse(new ByteArrayInputStream(fileContents.getBytes())); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final ParseException e) { throw new IllegalStateException(e); } // Load new compilation unit from cid information final String cidContents = getCompilationUnitContents(cid); CompilationUnit cidCompilationUnit; try { cidCompilationUnit = JavaParser.parse(new ByteArrayInputStream(cidContents.getBytes())); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final ParseException e) { throw new IllegalStateException(e); } // Update package if (!compilationUnit .getPackage() .getName() .getName() .equals(cidCompilationUnit.getPackage().getName().getName())) { compilationUnit.setPackage(cidCompilationUnit.getPackage()); } // Update imports UpdateCompilationUnitUtils.updateCompilationUnitImports(compilationUnit, cidCompilationUnit); // Update types UpdateCompilationUnitUtils.updateCompilationUnitTypes(compilationUnit, cidCompilationUnit); // Return new contents return compilationUnit.toString(); }
@Override public ClassOrInterfaceTypeDetails getTypeFromString( final String fileContents, final String declaredByMetadataId, final JavaType typeName) { if (StringUtils.isBlank(fileContents)) { return null; } Validate.notBlank(declaredByMetadataId, "Declaring metadata ID required"); Validate.notNull(typeName, "Java type to locate required"); try { final CompilationUnit compilationUnit = JavaParser.parse(new ByteArrayInputStream(fileContents.getBytes())); final TypeDeclaration typeDeclaration = JavaParserUtils.locateTypeDeclaration(compilationUnit, typeName); if (typeDeclaration == null) { return null; } return JavaParserClassOrInterfaceTypeDetailsBuilder.getInstance( compilationUnit, null, typeDeclaration, declaredByMetadataId, typeName, metadataService, typeLocationService) .build(); } catch (final IOException e) { throw new IllegalStateException(e); } catch (final ParseException e) { throw new IllegalStateException("Failed to parse " + typeName + " : " + e.getMessage()); } }