org.nuiton.eugene.java.ServiceLoaderUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of eugene-core Show documentation
Show all versions of eugene-core Show documentation
Efficient Universal Generator.
package org.nuiton.eugene.java;
/*-
* #%L
* EUGene :: EUGene Core
* %%
* Copyright (C) 2004 - 2017 Code Lutin, Ultreia.io
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* .
* #L%
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
/**
* Created by tchemit on 05/12/17.
*
* @author Tony Chemit - [email protected]
*/
public class ServiceLoaderUtil {
public static List load(Path classPathDirectory, Class> type) {
Path filePath = getServiceLoaderFile(classPathDirectory, type);
try {
return Files.exists(filePath) ? Files.readAllLines(filePath) : Collections.emptyList();
} catch (IOException e) {
throw new IllegalStateException("Can't load service loader file at: " + filePath, e);
}
}
public static boolean store(Path classPathDirectory, Class> type, List implementations) {
List load = load(classPathDirectory, type);
if (load.equals(implementations)) {
// file is up to date
return false;
}
Path filePath = getServiceLoaderFile(classPathDirectory, type);
try {
if (!Files.exists(filePath.getParent())) {
Files.createDirectories(filePath.getParent());
}
Files.write(filePath, implementations);
return true;
} catch (IOException e) {
throw new IllegalStateException("Can't store service loader file at: " + filePath, e);
}
}
public static Path getServiceLoaderFile(Path classPathDirectory, Class> type) {
return classPathDirectory.resolve("META-INF").resolve("services").resolve(type.getName());
}
}