2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.yang2sources.plugin;
11 import java.util.Collection;
14 import org.apache.commons.io.FileUtils;
16 import com.google.common.base.Function;
17 import com.google.common.collect.Collections2;
18 import com.google.common.collect.Maps;
22 static final String YANG_SUFFIX = "yang";
24 // Cache for listed directories and found yang files. Typically yang files
25 // are utilized twice. First: code is generated during generate-sources
26 // phase Second: yang files are copied as resources during
27 // generate-resources phase. This cache ensures that yang files are listed
29 private static Map<String, Collection<File>> cache = Maps
30 .newHashMapWithExpectedSize(10);
33 * List files recursively and return as array of String paths. Use cache of
36 static Collection<File> listFiles(String rootDir) {
38 if (cache.get(rootDir) != null)
39 return cache.get(rootDir);
41 Collection<File> yangFiles = FileUtils.listFiles(new File(rootDir),
42 new String[] { YANG_SUFFIX }, true);
44 toCache(rootDir, yangFiles);
48 static String[] listFilesAsArrayOfPaths(String rootDir) {
49 String[] filesArray = new String[] {};
50 Collection<File> yangFiles = listFiles(rootDir);
52 // If collection is empty, return empty array [] rather then [null]
53 // array, that is created by default
54 return yangFiles.isEmpty() ? filesArray : Collections2.transform(
55 yangFiles, new Function<File, String>() {
58 public String apply(File input) {
59 return input.getPath();
61 }).toArray(filesArray);
64 private static void toCache(final String rootDir,
65 final Collection<File> yangFiles) {
66 cache.put(rootDir, yangFiles);
70 * Instantiate object from fully qualified class name
72 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType)
73 throws ClassNotFoundException, InstantiationException,
74 IllegalAccessException {
75 return baseType.cast(resolveClass(codeGeneratorClass, baseType)
79 private static Class<?> resolveClass(String codeGeneratorClass,
80 Class<?> baseType) throws ClassNotFoundException {
81 Class<?> clazz = Class.forName(codeGeneratorClass);
83 if (!isImplemented(baseType, clazz))
84 throw new IllegalArgumentException("Code generator " + clazz
85 + " has to implement " + baseType);
89 private static boolean isImplemented(Class<?> expectedIface,
91 for (Class<?> iface : byClazz.getInterfaces()) {
92 if (iface.equals(expectedIface))
98 static String message(String message, String logPrefix, Object... args) {
99 String innerMessage = String.format(message, args);
100 return String.format("%s %s", logPrefix, innerMessage);