com.redhat.ceylon.compiler.java.tools.MetaInfServices Maven / Gradle / Ivy
package com.redhat.ceylon.compiler.java.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class MetaInfServices {
/**
* Parse the contents of a {@code META-INF/services/...}
* file being read from the given stream, returning the
* class names in a set.
*/
public static Set parseMetaInfServices(InputStream is)
throws UnsupportedEncodingException, IOException {
Set impls = new HashSet(1);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
String line = inputStream.readLine();
while (line != null) {
int index = line.indexOf('#');
if (index != -1) {
line = line.substring(0, index);
}
if (!line.isEmpty()) {
impls.add(line);
}
line = inputStream.readLine();
}
} finally {
inputStream.close();
}
return impls;
}
public static Map> parseAllServices(File carFile) throws IOException, UnsupportedEncodingException {
Map> result;
result = new HashMap>();
JarFile jarFile = new JarFile(carFile);
try {
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("META-INF/services/")
&& !entry.isDirectory()) {
String serviceBinaryName = entry.getName().substring("META-INF/services/".length());
result.put(serviceBinaryName, MetaInfServices.parseMetaInfServices(jarFile.getInputStream(entry)));
}
}
} finally {
jarFile.close();
}
return result;
}
public static void writeAllServices(File outputFolder, Map> previousServices) {
for (Map.Entry> serviceEntry : previousServices.entrySet()) {
String serviceInterface = serviceEntry.getKey();
Set serviceClasses = serviceEntry.getValue();
try (Writer writer = new OutputStreamWriter(new FileOutputStream(
new File(outputFolder, "META-INF/services/"+serviceInterface)),
"UTF-8")){
for (String impl : serviceClasses) {
writer.append(impl).append('\n');
}
writer.flush();
}
catch(IOException e) {
// TODO : log to the right place
}
}
}
}