Advertisement
Oifan

KZTG Utils.java

Mar 16th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 5.14 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.lang.reflect.Field;
  4. import java.net.MalformedURLException;
  5. import java.net.URL;
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.EnumSet;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.Map;
  12.  
  13. /**
  14.  * @author Oifan
  15.  *
  16.  */
  17. public class Utils {
  18.  
  19.     /**
  20.      * There is no reason to instantiate class containing <b>only static</b> methods.
  21.      */
  22.     private Utils() {
  23.         throw new UnsupportedOperationException("Instantiation of 'STATIC' class is not allowed");
  24.     }
  25.  
  26.     /**
  27.      * Tries to convert <code>fileName</code> to URL - first on filesystem, then via ClassLoader as
  28.      * a resource.
  29.      *
  30.      * @param fileName
  31.      * @return
  32.      */
  33.     public static URL fileOrResourceToURL(final String fileName) {
  34.         try {
  35.             final File file = new File(fileName);
  36.             return (file.exists() ? file.toURI().toURL() : Utils.class.getClassLoader().getResource(fileName));
  37.         } catch (MalformedURLException e) {
  38.             throw new RuntimeException(e);
  39.         }
  40.     }
  41.  
  42.     /**
  43.      * Copies from List <code>data</code> only elements flagged as <b>true</b> in
  44.      * <code>allowedIdx</code> into <code>result</code>.
  45.      *
  46.      * @param data
  47.      * @param allowedIdx
  48.      * @param result
  49.      */
  50.     public static <T> void filterList(List<T> data, boolean[] allowedIdx, List<T> result) {
  51.         final int len = Math.min(data.size(), allowedIdx.length);
  52.         for (int i = 0; i < len; ++i) {
  53.             if (allowedIdx[i])
  54.                 result.add(data.get(i));
  55.         }
  56.     }
  57.  
  58.     /**
  59.      * Retrieves the last non-empty token (part) of '/'-delimited path.
  60.      * @param path
  61.      * '/'-delimited path
  62.      * @return
  63.      * last non-empty path token or <code>path</code> if no '/' was found
  64.      */
  65.     public static String getLastTokenFromPath(String path) {
  66.         String[] tokens = path.split("\\/");
  67.         return (tokens.length > 0 ? tokens[tokens.length - 1] : path);
  68.     }
  69.  
  70.     /**
  71.      * Tries to locate / create <code>file</code>.
  72.      *
  73.      * @param file
  74.      * @throws IOException
  75.      */
  76.     public static void initFile(File file) throws IOException {
  77.         final String logPrefix = "initFile: ";
  78.         if (!file.createNewFile()) {
  79.             if (!file.isFile()) {
  80.                 throw new IllegalStateException(String.format("%sCannot create file '%s', since it is NOT a FILE!", logPrefix,
  81.                         file.getAbsolutePath()));
  82.             }
  83.             if (!file.canWrite()) {
  84.                 throw new IllegalStateException(String.format("%sCannot write to file '%s'!", logPrefix, file
  85.                         .getAbsolutePath()));
  86.             }
  87.         }
  88.     }
  89.  
  90.     /**
  91.      * Tries to locate / create <code>folder</code>.
  92.      *
  93.      * @param folder
  94.      * @throws IllegalStateException
  95.      */
  96.     public static void initFolder(File folder) throws IllegalStateException {
  97.         final String logPrefix = "initFolder: ";
  98.         if (folder.exists()) {
  99.             // check whether it is a directory
  100.             if (!folder.isDirectory()) {
  101.                 throw new IllegalStateException(String.format(
  102.                         "%sCannot enter folder '%s', since it is a FILE - cannot write files in there!", logPrefix,
  103.                         folder.getAbsolutePath()));
  104.             }
  105.         } else {
  106.             // create folder since it does not exist
  107.             if (!folder.mkdirs()) {
  108.                 // creating folder failed - abort
  109.                 throw new IllegalStateException(String.format("%sCould not create folder '%s' - cannot write files in there!",
  110.                         logPrefix, folder.getAbsolutePath()));
  111.             }
  112.         }
  113.     }
  114.  
  115.     /**
  116.      * Tries to create <b>destination folder</b>, which is composed from destParentFolder and
  117.      * <code>child</code>.
  118.      *
  119.      * @param destParentFolder
  120.      *            can be null, in which case no folder will be created and null will be returned
  121.      * @param child
  122.      * @throws IllegalStateException
  123.      * @returns <b>destination folder</b> if created / exists, null otherwise
  124.      */
  125.     public static File createDestFolder(File destParentFolder, String child)
  126.             throws IllegalStateException {
  127.         if (destParentFolder != null) {
  128.             final File destFolder = new File(destParentFolder, child);
  129.             Utils.initFolder(destFolder);
  130.             return destFolder;
  131.         } else {
  132.             return null;
  133.         }
  134.     }
  135.  
  136.     /**
  137.      * Uses {@link ServiceLoader} to load all implementations of given API <code>api</code>.<br>
  138.      * For this to work, you have to write a list of implementations (fully qualified class names
  139.      * w/o ".class") into file <code>META-INF/services/&lt;T></code> (containing 1 implementation
  140.      * per line).
  141.      *
  142.      * @param <T>
  143.      *            type of {@link Interface} to find
  144.      * @param apiClazz
  145.      *            {@link Interface} of the Service
  146.      * @return List of found Service implementations
  147.      */
  148.     public static <T> List<T> loadServices(Class<T> apiClazz) {
  149.         final List<T> result = new ArrayList<T>();
  150.         for (T loadedImpl : ServiceLoader.load(apiClazz)) {
  151.             result.add(loadedImpl);
  152.         }
  153.         return result;
  154.     }
  155.  
  156.     /**
  157.      * Builds unmodifiable lookup-Map for an {@link Enum} - useful for Enums modified by
  158.      * {@link #setEnumOrdinal(Enum, int)}.
  159.      *
  160.      * @param <E>
  161.      * @param enumClazz
  162.      * @return Unmodifiable Map
  163.      */
  164.     public static <E extends Enum<E>> Map<Integer, E> lookupMap(Class<E> enumClazz) {
  165.         final Map<Integer, E> lookup = new HashMap<Integer, E>();
  166.         for (E element : EnumSet.allOf(enumClazz)) {
  167.             lookup.put(element.ordinal(), element);
  168.         }
  169.         return Collections.unmodifiableMap(lookup);
  170.     }
  171. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement