use of java.util.jar.JarOutputStream in project spring-boot by spring-projects.
the class ApplicationBuilder method createResourcesJar.
private File createResourcesJar() throws IOException, FileNotFoundException {
File resourcesJar = new File(this.temp.getRoot(), "resources.jar");
if (resourcesJar.exists()) {
return resourcesJar;
}
JarOutputStream resourcesJarStream = new JarOutputStream(new FileOutputStream(resourcesJar));
resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/"));
resourcesJarStream.closeEntry();
resourcesJarStream.putNextEntry(new ZipEntry("META-INF/resources/nested-meta-inf-resource.txt"));
resourcesJarStream.write("nested".getBytes());
resourcesJarStream.closeEntry();
resourcesJarStream.close();
return resourcesJar;
}
use of java.util.jar.JarOutputStream in project flink by apache.
the class JarFileCreator method createJarFile.
/**
* Creates a jar file which contains the previously added class. The content of the jar file is written to
* <code>outputFile</code> which has been provided to the constructor. If <code>outputFile</code> already exists, it
* is overwritten by this operation.
*
* @throws IOException
* thrown if an error occurs while writing to the output file
*/
public synchronized void createJarFile() throws IOException {
//Retrieve dependencies automatically
addDependencies();
// Temporary buffer for the stream copy
final byte[] buf = new byte[128];
// Check if output file is valid
if (this.outputFile == null) {
throw new IOException("Output file is null");
}
// If output file already exists, delete it
if (this.outputFile.exists()) {
this.outputFile.delete();
}
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(this.outputFile), new Manifest())) {
final Iterator<Class<?>> it = this.classSet.iterator();
while (it.hasNext()) {
final Class<?> clazz = it.next();
final String entry = clazz.getName().replace('.', '/') + CLASS_EXTENSION;
jos.putNextEntry(new JarEntry(entry));
String name = clazz.getName();
int n = name.lastIndexOf('.');
String className = null;
if (n > -1) {
className = name.substring(n + 1, name.length());
}
//Using the part after last dot instead of class.getSimpleName() could resolve the problem of inner class.
final InputStream classInputStream = clazz.getResourceAsStream(className + CLASS_EXTENSION);
int num = classInputStream.read(buf);
while (num != -1) {
jos.write(buf, 0, num);
num = classInputStream.read(buf);
}
classInputStream.close();
jos.closeEntry();
}
}
}
use of java.util.jar.JarOutputStream in project hadoop by apache.
the class FileUtil method createJarWithClassPath.
/**
* Create a jar file at the given path, containing a manifest with a classpath
* that references all specified entries.
*
* Some platforms may have an upper limit on command line length. For example,
* the maximum command line length on Windows is 8191 characters, but the
* length of the classpath may exceed this. To work around this limitation,
* use this method to create a small intermediate jar with a manifest that
* contains the full classpath. It returns the absolute path to the new jar,
* which the caller may set as the classpath for a new process.
*
* Environment variable evaluation is not supported within a jar manifest, so
* this method expands environment variables before inserting classpath entries
* to the manifest. The method parses environment variables according to
* platform-specific syntax (%VAR% on Windows, or $VAR otherwise). On Windows,
* environment variables are case-insensitive. For example, %VAR% and %var%
* evaluate to the same value.
*
* Specifying the classpath in a jar manifest does not support wildcards, so
* this method expands wildcards internally. Any classpath entry that ends
* with * is translated to all files at that path with extension .jar or .JAR.
*
* @param inputClassPath String input classpath to bundle into the jar manifest
* @param pwd Path to working directory to save jar
* @param targetDir path to where the jar execution will have its working dir
* @param callerEnv Map<String, String> caller's environment variables to use
* for expansion
* @return String[] with absolute path to new jar in position 0 and
* unexpanded wild card entry path in position 1
* @throws IOException if there is an I/O error while writing the jar file
*/
public static String[] createJarWithClassPath(String inputClassPath, Path pwd, Path targetDir, Map<String, String> callerEnv) throws IOException {
// Replace environment variables, case-insensitive on Windows
@SuppressWarnings("unchecked") Map<String, String> env = Shell.WINDOWS ? new CaseInsensitiveMap(callerEnv) : callerEnv;
String[] classPathEntries = inputClassPath.split(File.pathSeparator);
for (int i = 0; i < classPathEntries.length; ++i) {
classPathEntries[i] = StringUtils.replaceTokens(classPathEntries[i], StringUtils.ENV_VAR_PATTERN, env);
}
File workingDir = new File(pwd.toString());
if (!workingDir.mkdirs()) {
// If mkdirs returns false because the working directory already exists,
// then this is acceptable. If it returns false due to some other I/O
// error, then this method will fail later with an IOException while saving
// the jar.
LOG.debug("mkdirs false for " + workingDir + ", execution will continue");
}
StringBuilder unexpandedWildcardClasspath = new StringBuilder();
// Append all entries
List<String> classPathEntryList = new ArrayList<String>(classPathEntries.length);
for (String classPathEntry : classPathEntries) {
if (classPathEntry.length() == 0) {
continue;
}
if (classPathEntry.endsWith("*")) {
// Append all jars that match the wildcard
List<Path> jars = getJarsInDirectory(classPathEntry);
if (!jars.isEmpty()) {
for (Path jar : jars) {
classPathEntryList.add(jar.toUri().toURL().toExternalForm());
}
} else {
unexpandedWildcardClasspath.append(File.pathSeparator);
unexpandedWildcardClasspath.append(classPathEntry);
}
} else {
// Append just this entry
File fileCpEntry = null;
if (!new Path(classPathEntry).isAbsolute()) {
fileCpEntry = new File(targetDir.toString(), classPathEntry);
} else {
fileCpEntry = new File(classPathEntry);
}
String classPathEntryUrl = fileCpEntry.toURI().toURL().toExternalForm();
// created yet, but will definitely be created before running.
if (classPathEntry.endsWith(Path.SEPARATOR) && !classPathEntryUrl.endsWith(Path.SEPARATOR)) {
classPathEntryUrl = classPathEntryUrl + Path.SEPARATOR;
}
classPathEntryList.add(classPathEntryUrl);
}
}
String jarClassPath = StringUtils.join(" ", classPathEntryList);
// Create the manifest
Manifest jarManifest = new Manifest();
jarManifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
jarManifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), jarClassPath);
// Write the manifest to output JAR file
File classPathJar = File.createTempFile("classpath-", ".jar", workingDir);
FileOutputStream fos = null;
BufferedOutputStream bos = null;
JarOutputStream jos = null;
try {
fos = new FileOutputStream(classPathJar);
bos = new BufferedOutputStream(fos);
jos = new JarOutputStream(bos, jarManifest);
} finally {
IOUtils.cleanup(LOG, jos, bos, fos);
}
String[] jarCp = { classPathJar.getCanonicalPath(), unexpandedWildcardClasspath.toString() };
return jarCp;
}
use of java.util.jar.JarOutputStream in project flink by apache.
the class JarHelper method jarDir.
// ========================================================================
// Public methods
/**
* Jars a given directory or single file into a JarOutputStream.
*/
public void jarDir(File dirOrFile2Jar, File destJar) throws IOException {
if (dirOrFile2Jar == null || destJar == null) {
throw new IllegalArgumentException();
}
mDestJarName = destJar.getCanonicalPath();
FileOutputStream fout = new FileOutputStream(destJar);
JarOutputStream jout = new JarOutputStream(fout);
//jout.setLevel(0);
try {
jarDir(dirOrFile2Jar, jout, null);
} catch (IOException ioe) {
throw ioe;
} finally {
jout.close();
fout.close();
}
}
use of java.util.jar.JarOutputStream in project byte-buddy by raphw.
the class AndroidClassLoadingStrategy method load.
@Override
public Map<TypeDescription, Class<?>> load(ClassLoader classLoader, Map<TypeDescription, byte[]> types) {
DexProcessor.Conversion conversion = dexProcessor.create();
for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) {
conversion.register(entry.getKey().getName(), entry.getValue());
}
File jar = new File(privateDirectory, randomString.nextString() + JAR_FILE_EXTENSION);
try {
if (!jar.createNewFile()) {
throw new IllegalStateException("Cannot create " + jar);
}
JarOutputStream zipOutputStream = new JarOutputStream(new FileOutputStream(jar));
try {
zipOutputStream.putNextEntry(new JarEntry(DEX_CLASS_FILE));
conversion.drainTo(zipOutputStream);
zipOutputStream.closeEntry();
} finally {
zipOutputStream.close();
}
return doLoad(classLoader, types.keySet(), jar);
} catch (IOException exception) {
throw new IllegalStateException("Cannot write to zip file " + jar, exception);
} finally {
if (!jar.delete()) {
Logger.getLogger("net.bytebuddy").warning("Could not delete " + jar);
}
}
}
Aggregations