com.cpjit.swagger4j.util.ReflectUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.cpjit.swagger4j.util.ReflectUtils.java

Source

/*
 * Copyright 2011-2017 CPJIT Group.
 * 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package com.cpjit.swagger4j.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

/**
 * ??
 * 
 * @author yonghaun
 * @since 1.2.2
 */
public final class ReflectUtils {
    private ReflectUtils() {
        throw new AssertionError("?? " + ReflectUtils.class.getName());
    }

    /**
     * ???
     * 
     * @param packNames
     *            ??
     * @return ??null
     *       0
     *       <li>?packNames0</li>
     *       <li>?</li>
     * 
     * @throws FileNotFoundException ?
     * @throws IllegalArgumentException ??? 
     * @throws ClassNotFoundException ?
     * 
     * @since 1.0.0
     */
    public static List<Class<?>> scanClazzs(List<String> packNames)
            throws FileNotFoundException, IllegalArgumentException, ClassNotFoundException {
        if (packNames.size() < 1) { // ??
            return Collections.emptyList();
        }

        Set<Class<?>> clazzs = new HashSet<Class<?>>();
        for (String packName : packNames) {
            List<String> clazzNames = scanClazzName(packName);
            for (String clazzName : clazzNames) { // ?
                Class<?> clazz = Class.forName(clazzName);
                clazzs.add(clazz);
            }
        }
        if (clazzs.size() < 1) { // ?
            return Collections.emptyList();
        }
        return new ArrayList<Class<?>>(clazzs);
    }

    /**
     * ???
     * 
     * @param packageNames
     *            ??
     * @param recursion
     *            ????
     * @return ??null
     *       0
     *       <li>?packageNames0</li>
     *       <li>?recursionfalse?</li>
     *       <li>?recursiontrue???</li>
     * 
     * @throws FileNotFoundException ?
     * @throws IllegalArgumentException ???
     * @throws ClassNotFoundException ?
     * 
     * @since 1.0.0
     */
    public static List<Class<?>> scanClazzs(List<String> packageNames, boolean recursion)
            throws FileNotFoundException, IllegalArgumentException, ClassNotFoundException {
        if (packageNames.size() < 1) { // ??
            return Collections.emptyList();
        }
        List<String> packNames = scanPackages(packageNames, recursion).stream().map(pkg -> pkg.getName())
                .collect(Collectors.toList());
        return scanClazzs(packNames);
    }

    /**
     * ????
     * 
     * @param basePackage
     * @param recursion
     *            ????
     * @return    ???null
     *          0
     *          <li>?</li>
     *          <li>package-info.java?</li>
     *          <li>?basePackage</li>
     * @since 1.0.0
     */
    public static List<Package> scanPackage(final String basePackage, boolean recursion) {
        if (StringUtils.isBlank(basePackage)) {
            return Collections.emptyList();
        }

        Set<Package> packages = new HashSet<Package>();
        String pack2path = basePackage.replaceAll("\\.", "/");
        URL url = ResourceUtil.getResource(pack2path);
        if (url == null) { // ?
            return Collections.emptyList();
        }

        Path pkFile = null;
        try {
            pkFile = Paths.get(url.toURI());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(basePackage + "????", e);
        }
        if (!Files.isDirectory(pkFile)) {
            throw new IllegalArgumentException(basePackage + "????");
        }

        Package pk = null;
        try {
            pk = getPackage(basePackage);
        } catch (Exception e) {
        }
        if (pk != null) {
            packages.add(pk);
        }

        if (recursion && StringUtils.isNotBlank(basePackage)) { // ???
            try (DirectoryStream<Path> childs = Files.newDirectoryStream(pkFile)) {
                childs.forEach(child -> {
                    if (Files.isDirectory(child)) {
                        String childPackage = basePackage + "." + child.getFileName().toString();
                        if (StringUtils.isBlank(basePackage)) { // 
                            childPackage = child.getFileName().toString();
                        }
                        packages.addAll(scanPackage(childPackage, true));
                    }
                });
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
        if (packages.size() < 1) { // ??
            return Collections.emptyList();
        }

        return new ArrayList<Package>(packages);
    }

    /**
     * ???????
     * 
     * @param packageName
     * @return    ???null
     *          0
     *          <li>?</li>
     *          <li>package-info.java?</li>
     *          <li>?basePackage</li>
     * @since 1.0.0
     */
    public static List<Package> scanPackage(final String packageName) {
        return scanPackage(packageName, false);
    }

    /**
     * ??????
     * 
     * @param packageNames
     * @return    ???null
     *          0
     *          <li>?</li>
     *          <li>package-info.java?</li>
     *          <li>?basePackage</li>
     * @since 1.0.0
     */
    public static List<Package> scanPackages(List<String> packageNames) {
        return scanPackages(packageNames, false);
    }

    /**
     * ??????
     * 
     * @param packageNames
     * @param recursion
     *            ????
     * @return    ???null
     *          0
     *          <li>?</li>
     *          <li>package-info.java?</li>
     *          <li>?basePackage</li>
     * @since 1.0.0
     */
    public static List<Package> scanPackages(List<String> packageNames, boolean recursion) {
        if (packageNames == null || packageNames.size() < 1) { // ??
            return Collections.emptyList();
        }
        return packageNames.stream().flatMap(packName -> scanPackage(packName, recursion).stream())
                .collect(Collectors.toList());
    }

    /**
     * ????
     * 
     * @param packageName
     * @return ????null
     *       0
     *       <li>?packNames0</li>
     *       <li>??</li>
     * @throws FileNotFoundException ?
     * @throws IllegalArgumentException ???
     * @since 1.0.0
     */
    public static List<String> scanClazzName(String packageName)
            throws FileNotFoundException, IllegalArgumentException {
        String pack2path = packageName.replaceAll("\\.", "/");
        if (StringUtils.isBlank(packageName)) {
            pack2path = "";
        }

        URL fullPath = ResourceUtil.getResource(pack2path);
        if (fullPath == null) {
            throw new FileNotFoundException("[" + packageName + "]?");
        }
        Path pack;
        try {
            pack = Paths.get(fullPath.toURI());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
        if (!Files.isDirectory(pack)) {
            throw new IllegalArgumentException("[" + packageName + "]????");
        }

        Set<String> clazzNames = new HashSet<String>();
        String prefix = StringUtils.isBlank(packageName) ? "" : packageName + ".";
        // ?Java?
        try (DirectoryStream<Path> clazzs = Files.newDirectoryStream(pack, "*.class");) {
            clazzs.forEach(clazz -> { // ???
                String clazzName = prefix + clazz.getFileName().toString().replace(".class", "");
                clazzNames.add(clazzName);
            });
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        if (clazzNames.size() < 1) { // ?
            return Collections.emptyList();
        }
        return new ArrayList<String>(clazzNames);
    }

    /**
     * ?????
     * <p>
     * package-info.java?{@code null}
     * </p>
     * @since 1.2.2
     */
    private static Package getPackage(final String packageName)
            throws FileNotFoundException, IllegalArgumentException {
        Package pkg = Package.getPackage(packageName);
        if (pkg == null) { // ?package-info.class
            pkg = scanClazzName(packageName).stream().map(clazzName -> {
                try {
                    return Class.forName(clazzName).getPackage();
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }).filter(pk -> pk != null).findFirst().get();
        }
        return pkg;
    }
}