Example usage for com.liferay.portal.kernel.util ClassUtil getClasses

List of usage examples for com.liferay.portal.kernel.util ClassUtil getClasses

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util ClassUtil getClasses.

Prototype

public static Set<String> getClasses(Reader reader, String className) throws IOException 

Source Link

Usage

From source file:com.liferay.tools.sourceformatter.JavaSourceProcessor.java

License:Open Source License

public static String stripJavaImports(String content, String packageDir, String className) throws IOException {

    Matcher matcher = _importsPattern.matcher(content);

    if (!matcher.find()) {
        return content;
    }/* w  w w  .  j  a va 2s .  c  o m*/

    String imports = matcher.group();

    Set<String> classes = ClassUtil.getClasses(new UnsyncStringReader(content), className);

    StringBundler sb = new StringBundler();

    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(new UnsyncStringReader(imports));

    String line = null;

    while ((line = unsyncBufferedReader.readLine()) != null) {
        if (!line.contains("import ")) {
            continue;
        }

        int importX = line.indexOf(" ");
        int importY = line.lastIndexOf(".");

        String importPackage = line.substring(importX + 1, importY);

        if (importPackage.equals(packageDir) || importPackage.equals("java.lang")) {

            continue;
        }

        String importClass = line.substring(importY + 1, line.length() - 1);

        if (importClass.equals("*") || classes.contains(importClass)) {
            sb.append(line);
            sb.append("\n");
        }
    }

    ImportsFormatter importsFormatter = new JavaImportsFormatter();

    imports = importsFormatter.format(sb.toString());

    content = content.substring(0, matcher.start()) + imports + content.substring(matcher.end());

    // Ensure a blank line exists between the package and the first import

    content = content.replaceFirst("(?m)^[ \t]*(package .*;)\\s*^[ \t]*import", "$1\n\nimport");

    // Ensure a blank line exists between the last import (or package if
    // there are no imports) and the class comment

    content = content.replaceFirst("(?m)^[ \t]*((?:package|import) .*;)\\s*^[ \t]*/\\*\\*", "$1\n\n/**");

    return content;
}