Java Examples for org.zeroturnaround.zip.ZipUtil
The following java examples will help you to understand the usage of org.zeroturnaround.zip.ZipUtil. These source code samples are taken from different open source projects.
Example 1
| Project: zt-zip-master File: ReplaceEntryExample.java View source code |
public static void replaceEntry() throws Exception {
// lets unpack a file
File zipArchive = new File("src/test/resources/demo.zip");
File resultingFile = new File("foo.txt");
ZipUtil.unpackEntry(zipArchive, "foo.txt", resultingFile);
// lets work with the file a bit
FileWriter fw = new FileWriter(resultingFile);
fw.write("Hello World!\n");
fw.close();
ZipUtil.replaceEntry(zipArchive, "foo.txt", resultingFile);
}Example 2
| Project: motherbrain-master File: CompressUtils.java View source code |
/****
*
* @param root
* @throws IOException
*/
public static byte[] compress(File root) throws IOException {
if (root.exists()) {
File zip = new File(Files.createTempDir(), "data.zip");
ZipUtil.pack(root, zip, new NameMapper() {
@Override
public String map(String name) {
// Filter out the socket files...
if (name.endsWith(".sock"))
return null;
else
return name;
}
});
byte[] data = Files.toByteArray(zip);
zip.delete();
return data;
} else {
_log.warn("no data to compress: " + root.toString());
return new byte[] {};
}
}Example 3
| Project: bytecode-viewer-master File: CFRDecompiler.java View source code |
@Override
public void decompileToZip(String zipName) {
try {
Path outputDir = Files.createTempDirectory("cfr_output");
Path tempJar = Files.createTempFile("cfr_input", ".jar");
File output = new File(zipName);
try {
JarUtils.saveAsJar(BytecodeViewer.getLoadedBytes(), tempJar.toAbsolutePath().toString());
Options options = new GetOptParser().parse(generateMainMethod(), OptionsImpl.getFactory());
ClassFileSourceImpl classFileSource = new ClassFileSourceImpl(options);
DCCommonState dcCommonState = new DCCommonState(options, classFileSource);
doJar(dcCommonState, tempJar.toAbsolutePath(), outputDir.toAbsolutePath());
ZipUtil.pack(outputDir.toFile(), output);
} catch (Exception e) {
handleException(e);
} finally {
try {
FileUtils.deleteDirectory(outputDir.toFile());
} catch (IOException e) {
handleException(e);
}
try {
Files.delete(tempJar);
} catch (IOException e) {
handleException(e);
}
}
} catch (Exception e) {
handleException(e);
}
}Example 4
| Project: olca-app-master File: DbImportWizard.java View source code |
private IDatabase connectToFolder() {
File zipFile = config.file;
File tempDir = new File(System.getProperty("java.io.tmpdir"));
tempDbFolder = new File(tempDir, UUID.randomUUID().toString());
tempDbFolder.mkdirs();
log.trace("unpack zolca file to {}", tempDbFolder);
ZipUtil.unpack(zipFile, tempDbFolder);
return new DerbyDatabase(tempDbFolder);
}Example 5
| Project: TadpoleForDBTools-master File: ZipUtils.java View source code |
/**
*
* @param base_dir
* @param zipFile
* @return
* @throws Exception
*/
public static String pack(String base_dir, String zipFile) throws Exception {
String zipFullPath = PublicTadpoleDefine.TEMP_DIR + zipFile + ".zip";
ZipUtil.pack(new File(base_dir), new File(zipFullPath), new NameMapper() {
public String map(String name) {
try {
if (!StringUtils.equals(name, StringEscapeUtils.escapeJava(name))) {
name = "download_files" + StringUtils.substring(name, StringUtils.lastIndexOf(name, '.'));
}
name = new String(name.getBytes(), "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error("zip pack", e);
}
return name;
}
});
return zipFullPath;
}Example 6
| Project: Web-Karma-master File: AbstractFileDistributionStrategy.java View source code |
@Override
public void prepare(@SuppressWarnings("rawtypes") Map globalConfig) {
try {
tempDirPath = Files.createTempDirectory("karma_home", new FileAttribute[0]);
File tempDir = tempDirPath.toFile();
tempDir.deleteOnExit();
InputStream serializedFileStream = getStream();
if (isZipped) {
ZipUtil.unpack(serializedFileStream, tempDir);
materializedFilePath = FileSystems.getDefault().getPath(tempDir.getAbsolutePath(), "karma");
} else {
Path filePath = FileSystems.getDefault().getPath(tempDir.getAbsolutePath(), fileName);
Files.copy(serializedFileStream, filePath, new CopyOption[0]);
materializedFilePath = filePath;
}
LOG.info("Materialized file at: " + materializedFilePath.toAbsolutePath());
} catch (Exception e) {
LOG.error("Unable to materialize file: " + fileName, e);
}
}Example 7
| Project: bonita-ui-designer-master File: Unzipper.java View source code |
public Path unzipInTempDir(InputStream is, String tempDirPrefix) throws IOException {
Path tempDirectory = Files.createTempDirectory(temporaryZipPath, tempDirPrefix);
Path zipFile = writeInDir(is, tempDirectory);
try {
ZipUtil.unpack(zipFile.toFile(), tempDirectory.toFile());
} catch (org.zeroturnaround.zip.ZipException e) {
throw new ZipException(e.getMessage());
} finally {
FileUtils.deleteQuietly(zipFile.toFile());
}
return tempDirectory;
}Example 8
| Project: elasticsearch-maven-plugin-master File: ResolveElasticsearchStep.java View source code |
@Override
public void execute(InstanceConfiguration config) {
Log log = config.getClusterConfiguration().getLog();
File unpackDirectory = null;
try {
String version = config.getClusterConfiguration().getVersion();
ElasticsearchArtifact artifact = new ElasticsearchArtifact(version);
log.debug("Resolving " + artifact.toString());
File resolvedArtifact = config.getClusterConfiguration().getArtifactResolver().resolveArtifact(artifact.getArtifactCoordinates());
unpackDirectory = getUnpackDirectory();
ZipUtil.unpack(resolvedArtifact, unpackDirectory);
File baseDir = new File(config.getBaseDir());
moveToElasticsearchDirectory(unpackDirectory, baseDir);
String pathConf = config.getClusterConfiguration().getPathConf();
if (pathConf != null && !pathConf.isEmpty()) {
// Merge the user-defined config directory with the default one
// This allows user to omit some configuration files (jvm.options for instance)
FileUtils.copyDirectory(new File(pathConf), new File(baseDir, "config"));
}
} catch (ResolutionExceptionIOException | e) {
throw new RuntimeException(e);
} finally {
if (unpackDirectory != null) {
try {
FileUtils.deleteDirectory(unpackDirectory);
} catch (IOException e) {
log.error(String.format("Could not delete Elasticsearch upack directory : ", unpackDirectory.getAbsolutePath()), e);
}
}
}
}Example 9
| Project: p2-bridge-master File: PackedEclipseLocation.java View source code |
public File get() {
if (!extracted) {
try {
if (!reuseExisting) {
if (location.exists()) {
FileUtils.deleteDirectory(location);
if (location.exists()) {
throw new RuntimeException(String.format("Cannot delete existing eclipse location %s", location.getAbsolutePath()));
}
}
location.mkdirs();
ZipUtil.unpack(eclipseArchive, location.getParentFile());
}
extracted = true;
} catch (final Exception e) {
throw new RuntimeException("Cannot unpack Eclipse", e);
}
}
return location;
}Example 10
| Project: DroidFix-master File: ClassInject.java View source code |
private static void repackJar() {
File src = new File(Configure.getInstance().getTransformedClassDir());
File target = new File(Configure.getInstance().getTransformedClassDir() + ".jar");
ZipUtil.pack(src, target);
try {
FileUtils.deleteDirectory(src);
} catch (IOException e) {
e.printStackTrace();
}
}Example 11
| Project: oj_web-master File: Problem.java View source code |
public File problemZipFile() throws IOException {
String problemId = "problem_" + id;
Logger.info("Create problem zip package named " + problemId);
Path tempDirectory = Files.createTempDirectory(problemId);
// Write problem data file.
File problemFile = new File(tempDirectory.toFile(), "data.json");
PrintWriter writer = new PrintWriter(problemFile, "UTF-8");
writer.println(toJson());
writer.close();
// Copy files.
FileCopy.copyDirectory(getResourcesPath(), tempDirectory.resolve("resources"));
FileCopy.copyDirectory(getAssetPath(), tempDirectory.resolve("assets"));
// Create zip package.
File zip = File.createTempFile(problemId + "_", ".zip");
ZipUtil.pack(tempDirectory.toFile(), zip);
return zip;
}Example 12
| Project: baker-android-refactor-master File: ExtractIssueJob.java View source code |
@Override
public void onRun() throws Throwable {
// Send zero progress event
EventBus.getDefault().post(new ExtractIssueProgressEvent(issue, 0));
// Delete directory if exists
if (outputDirectory.exists() && outputDirectory.isDirectory()) {
FileUtils.deleteDirectory(outputDirectory);
}
// Prepare progress
FileInputStream zipFileInputStream = new MonitorFileInputStream(zipFile);
// Unzip file
ZipUtil.unpack(zipFileInputStream, outputDirectory);
// Delete zip file
if (!this.zipFile.delete()) {
throw new Exception("Unable to remove issue hpub file");
}
// Post complete event
completed = true;
Log.i("ExtractZipJob", "completed");
EventBus.getDefault().post(new ExtractIssueCompleteEvent(issue));
}Example 13
| Project: dg-toolkit-master File: DerbyDatabaseBackupService.java View source code |
/**
* Backup the On-Line Derby database. This temporarily locks the db in
* readonly mode
*
* Invokes SYSCS_BACKUP_DATABASE and dumps the database to the temporary
* directory Use {@link ZipUtil#pack(File, File)} to zip the directory
* Deletes the temporary directory
*
* @see #createBackupURL(String)
*/
private void backupDerbyDatabase() {
lastBackupURL = createBackupURL();
CallableStatement cs = null;
try {
cs = datasource.getConnection().prepareCall("CALL SYSCS_UTIL.SYSCS_BACKUP_DATABASE(?)");
cs.setString(1, lastBackupURL);
cs.execute();
} catch (SQLException e) {
LOGGER.error("Cannot perform database backup!", e);
return;
} finally {
try {
cs.close();
} catch (SQLException e) {
LOGGER.error("Error closing backup connection ", e);
return;
}
}
File backupURLFile = new File(lastBackupURL);
// zip the contents and delete the dir
ZipUtil.pack(backupURLFile, new File(lastBackupURL + ARCHIVE_SUFFIX));
// delete the backup directory that we just zipped
try {
FileUtils.deleteDirectory(backupURLFile);
} catch (IOException e) {
LOGGER.error("Cannot delete temporary backup directory", e);
}
LOGGER.info("Backed up database to " + lastBackupURL + ARCHIVE_SUFFIX);
}Example 14
| Project: ankush-master File: AbstractMonitor.java View source code |
public void downloadlogs() {
final String component = (String) parameterMap.get(com.impetus.ankush2.constant.Constant.Keys.COMPONENT);
if (component == null || component.isEmpty()) {
this.addAndLogError("Invalid Log request: Please specify a component.");
return;
}
try {
ArrayList<String> nodes = (ArrayList) parameterMap.get(Constant.JsonKeys.Logs.NODES);
if (nodes == null || nodes.isEmpty()) {
nodes = new ArrayList<String>(this.clusterConf.getComponents().get(component).getNodes().keySet());
}
ArrayList<String> roles = (ArrayList) parameterMap.get(Constant.JsonKeys.Logs.ROLES);
Serviceable serviceableObj = ObjectFactory.getServiceObject(component);
if (roles == null || roles.isEmpty()) {
roles = new ArrayList<String>(serviceableObj.getServiceList(this.clusterConf));
}
String clusterResourcesLogsDir = AppStoreWrapper.getClusterResourcesPath() + "logs/";
String clusterLogsDirName = "Logs_" + this.clusterConf.getName() + "_" + System.currentTimeMillis();
String clusterLogsArchiveName = clusterLogsDirName + ".zip";
final String cmpLogsDirPathOnServer = clusterResourcesLogsDir + clusterLogsDirName + "/" + component + "/";
if (!FileUtils.ensureFolder(cmpLogsDirPathOnServer)) {
this.addAndLogError("Could not create log directory for " + component + " on server.");
return;
}
final Semaphore semaphore = new Semaphore(nodes.size());
final ArrayList<String> rolesObj = new ArrayList<String>(roles);
try {
for (final String host : nodes) {
semaphore.acquire();
AppStoreWrapper.getExecutor().execute(new Runnable() {
@Override
public void run() {
NodeConfig nodeConfig = clusterConf.getNodes().get(host);
SSHExec connection = SSHUtils.connectToNode(host, clusterConf.getAuthConf());
if (connection == null) {
// TODO: handle Error
logger.error("Could not fetch log files - Connection not initialized", component, host);
}
Serviceable serviceableObj = null;
try {
serviceableObj = ObjectFactory.getServiceObject(component);
for (String role : rolesObj) {
if (nodeConfig.getRoles().get(component).contains(role)) {
String tmpLogsDirOnServer = cmpLogsDirPathOnServer + "/" + role + "/" + host + "/";
if (!FileUtils.ensureFolder(tmpLogsDirOnServer)) {
// this role
continue;
}
String nodeLogsDirPath = FileUtils.getSeparatorTerminatedPathEntry(serviceableObj.getLogDirPath(clusterConf, host, role));
String logFilesRegex = serviceableObj.getLogFilesRegex(clusterConf, host, role, null);
String outputTarArchiveName = role + "_" + +System.currentTimeMillis() + ".tar.gz";
try {
List<String> logsFilesList = AnkushUtils.listFilesInDir(connection, host, nodeLogsDirPath, logFilesRegex);
AnkushTask ankushTask = new CreateTarArchive(nodeLogsDirPath, nodeLogsDirPath + outputTarArchiveName, logsFilesList);
if (connection.exec(ankushTask).rc != 0) {
// role
continue;
}
connection.downloadFile(nodeLogsDirPath + outputTarArchiveName, tmpLogsDirOnServer + outputTarArchiveName);
ankushTask = new Remove(nodeLogsDirPath + outputTarArchiveName);
connection.exec(ankushTask);
ankushTask = new UnTarArchive(tmpLogsDirOnServer + outputTarArchiveName, tmpLogsDirOnServer);
Runtime.getRuntime().exec(ankushTask.getCommand()).waitFor();
ankushTask = new Remove(tmpLogsDirOnServer + outputTarArchiveName);
Runtime.getRuntime().exec(ankushTask.getCommand()).waitFor();
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
} catch (Exception e) {
return;
} finally {
if (semaphore != null) {
semaphore.release();
}
if (connection != null) {
connection.disconnect();
}
}
}
});
}
semaphore.acquire(nodes.size());
} catch (Exception e) {
}
ZipUtil.pack(new File(clusterResourcesLogsDir + clusterLogsDirName), new File(clusterResourcesLogsDir + clusterLogsArchiveName), true);
org.apache.commons.io.FileUtils.deleteDirectory(new File(clusterResourcesLogsDir + clusterLogsDirName));
result.put(com.impetus.ankush2.constant.Constant.Keys.DOWNLOADPATH, clusterResourcesLogsDir + clusterLogsArchiveName);
} catch (Exception e) {
this.addAndLogError("Could not download logs for " + component + ".");
logger.error(e.getMessage(), component, e);
}
}Example 15
| Project: Crimson-master File: Generator.java View source code |
private GenReport.Builder genJar(ClientConfig ic, int cvid) throws IOException {
GenReport.Builder gReport = GenReport.newBuilder();
Date start = new Date();
gReport.setGenDate(start.getTime());
File clientJar = new File(temp.getAbsolutePath() + "/installer.jar");
File clientDB = new File(temp.getAbsolutePath() + "/client.db");
File internal = new File(temp.getAbsolutePath() + "/internal.txt");
// create a database for the client
try {
BasicDatabase database = new BasicDatabase("", clientDB);
database.initSql();
database.resetClient();
database.store("cvid", cvid);
database.store("ic", new String(B64Util.encode(ic.toByteArray())));
if (ic.getAuthType() == AuthType.GROUP) {
database.store("auth.group", Authentication.getGroup(ic.getGroupName()));
}
database.close();
} catch (Exception e) {
e.printStackTrace();
gReport.setComment("Failed to create client database: " + e.getMessage());
gReport.setResult(false);
return gReport;
}
// copy the client jar out
JarUtil.extract("com/subterranean_security/crimson/server/res/bin/client.jar", clientJar.getAbsolutePath());
// add client database to jar
ZipUtil.addEntry(clientJar, "com/subterranean_security/crimson/client/res/bin/client.db", clientDB);
// add libraries to jar
File tmpZip = new File(temp.getAbsolutePath() + "/clib.zip");
tmpZip.mkdir();
new File(tmpZip.getAbsolutePath() + "/java").mkdirs();
// add jar files
for (String lib : Universal.getInstancePrerequisites(Universal.Instance.CLIENT)) {
if (lib.equals("c19") && !ic.getKeylogger()) {
continue;
}
FileUtil.copy(new File(Common.Directories.base.getAbsolutePath() + "/lib/java/" + lib + ".jar"), new File(tmpZip.getAbsolutePath() + "/java/" + lib + ".jar"));
}
// selectively add native libraries
if (ic.hasPathWin()) {
File jniOut = new File(tmpZip.getAbsolutePath() + "/jni/win");
jniOut.mkdirs();
for (File f : new File(Common.Directories.base.getAbsolutePath() + "/lib/jni/win").listFiles()) {
FileUtil.copy(f, new File(jniOut.getAbsolutePath() + "/" + f.getName()));
}
}
if (ic.hasPathLin()) {
File jniOut = new File(tmpZip.getAbsolutePath() + "/jni/lin");
jniOut.mkdirs();
for (File f : new File(Common.Directories.base.getAbsolutePath() + "/lib/jni/lin").listFiles()) {
FileUtil.copy(f, new File(jniOut.getAbsolutePath() + "/" + f.getName()));
}
}
if (ic.hasPathOsx()) {
File jniOut = new File(tmpZip.getAbsolutePath() + "/jni/osx");
jniOut.mkdirs();
for (File f : new File(Common.Directories.base.getAbsolutePath() + "/lib/jni/osx").listFiles()) {
FileUtil.copy(f, new File(jniOut.getAbsolutePath() + "/" + f.getName()));
}
}
if (ic.hasPathSol()) {
File jniOut = new File(tmpZip.getAbsolutePath() + "/jni/sol");
jniOut.mkdirs();
for (File f : new File(Common.Directories.base.getAbsolutePath() + "/lib/jni/sol").listFiles()) {
FileUtil.copy(f, new File(jniOut.getAbsolutePath() + "/" + f.getName()));
}
}
if (ic.hasPathBsd()) {
File jniOut = new File(tmpZip.getAbsolutePath() + "/jni/bsd");
jniOut.mkdirs();
for (File f : new File(Common.Directories.base.getAbsolutePath() + "/lib/jni/bsd").listFiles()) {
FileUtil.copy(f, new File(jniOut.getAbsolutePath() + "/" + f.getName()));
}
}
ZipUtil.unexplode(tmpZip);
ZipUtil.addEntry(clientJar, "com/subterranean_security/crimson/client/res/bin/lib.zip", tmpZip);
// create and add the internal.txt
internal.createNewFile();
PrintWriter pw = new PrintWriter(internal);
pw.println(B64Util.encode(ic.toByteArray()));
pw.close();
ZipUtil.addEntry(clientJar, "com/subterranean_security/crimson/client/internal.txt", internal);
// delete jars
// CUtil.Files.delete(clientJar);
gReport.setHashMd5(FileUtil.getHash(clientJar.getAbsolutePath(), "MD5"));
gReport.setHashSha256(FileUtil.getHash(clientJar.getAbsolutePath(), "SHA-256"));
gReport.setFileSize((int) clientJar.length());
gReport.setResult(true);
gReport.setGenTime((int) (new Date().getTime() - start.getTime()));
log.info("Generated jar in {} ms", gReport.getGenTime());
return gReport;
}Example 16
| Project: gitools-master File: ZipResourceLocatorAdaptor.java View source code |
@Override
public OutputStream openOutputStream(IProgressMonitor monitor) throws IOException {
// Create a temporal folder
tmpFolder = createTemporalFolder(getURL());
// Extract all the files
monitor.title("Extracting to temporal folder...");
try {
ZipUtil.unpack(getParentLocator().openInputStream(new NullProgressMonitor()), tmpFolder);
// Check if we are doing a 'Save as...'
if (!getWriteFile().equals(getReadFile())) {
// Rename all entries
String inName = getReadFile().getName().replace("." + getExtension() + ".zip", "");
String toName = getBaseName();
renameAll(getTemporalFolder(), inName, toName);
}
} catch (FileNotFoundException e) {
}
monitor.title("Copying files...");
return new FileOutputStream(new File(tmpFolder, entryName));
}Example 17
| Project: packr-master File: PackrReduce.java View source code |
static void minimizeJre(PackrOutput output, PackrConfig config) throws IOException {
if (config.minimizeJre == null) {
return;
}
System.out.println("Minimizing JRE ...");
JsonObject minimizeJson = readMinimizeProfile(config);
if (minimizeJson != null) {
if (config.verbose) {
System.out.println(" # Removing files and directories in profile '" + config.minimizeJre + "' ...");
}
JsonArray reduceArray = minimizeJson.get("reduce").asArray();
for (JsonValue reduce : reduceArray) {
String path = reduce.asObject().get("archive").asString();
File file = new File(output.resourcesFolder, path);
if (!file.exists()) {
if (config.verbose) {
System.out.println(" # No file or directory '" + file.getPath() + "' found, skipping");
}
continue;
}
boolean needsUnpack = !file.isDirectory();
File fileNoExt = needsUnpack ? new File(output.resourcesFolder, path.contains(".") ? path.substring(0, path.lastIndexOf('.')) : path) : file;
if (needsUnpack) {
if (config.verbose) {
System.out.println(" # Unpacking '" + file.getPath() + "' ...");
}
ZipUtil.unpack(file, fileNoExt);
}
JsonArray removeArray = reduce.asObject().get("paths").asArray();
for (JsonValue remove : removeArray) {
File removeFile = new File(fileNoExt, remove.asString());
if (removeFile.exists()) {
if (removeFile.isDirectory()) {
FileUtils.deleteDirectory(removeFile);
} else {
PackrFileUtils.delete(removeFile);
}
} else {
if (config.verbose) {
System.out.println(" # No file or directory '" + removeFile.getPath() + "' found");
}
}
}
if (needsUnpack) {
if (config.verbose) {
System.out.println(" # Repacking '" + file.getPath() + "' ...");
}
long beforeLen = file.length();
PackrFileUtils.delete(file);
ZipUtil.pack(fileNoExt, file);
FileUtils.deleteDirectory(fileNoExt);
long afterLen = file.length();
if (config.verbose) {
System.out.println(" # " + beforeLen / 1024 + " kb -> " + afterLen / 1024 + " kb");
}
}
}
JsonArray removeArray = minimizeJson.get("remove").asArray();
for (JsonValue remove : removeArray) {
String platform = remove.asObject().get("platform").asString();
if (!matchPlatformString(platform, config)) {
continue;
}
JsonArray removeFilesArray = remove.asObject().get("paths").asArray();
for (JsonValue removeFile : removeFilesArray) {
removeFileWildcard(output.resourcesFolder, removeFile.asString(), config);
}
}
}
}Example 18
| Project: resource-manager-master File: VFSZipperZIPTest.java View source code |
private void assertZipWithFileHierarchy(Path archivePath) {
final int[] nbEntries = { 0 };
// Reads ZIP content using a third-party library
ZipUtil.iterate(archivePath.toFile(), new ZipEntryCallback() {
@Override
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
nbEntries[0]++;
}
});
assertThat(nbEntries[0]).isEqualTo(HIERARCHY_DEPTH + 1);
}Example 19
| Project: rhq-agent-plugin-plugin-master File: SetupTestPluginContainerMojo.java View source code |
private void copySigarLibs(final File libDirectory, File sigarDistributionFile) throws MojoExecutionException {
try {
ZipUtil.iterate(sigarDistributionFile, new ZipEntryCallback() {
@Override
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
String zipEntryName = zipEntry.getName();
if (zipEntryName.contains("sigar-bin/lib") && !zipEntryName.endsWith("/")) {
String compressedFileName = zipEntryName.substring(zipEntryName.lastIndexOf("/") + 1);
if (compressedFileName.endsWith(".so") || compressedFileName.endsWith(".dll") || compressedFileName.endsWith(".sl") || compressedFileName.endsWith(".dylib") || compressedFileName.equals("sigar.jar")) {
File destinationFile = new File(libDirectory, compressedFileName);
copyStreamToFile(new RawInputStreamFacade(in), destinationFile);
}
}
}
});
} catch (Exception e) {
throw new MojoExecutionException("Could not unpack Sigar file " + sigarDistributionFile.getAbsolutePath(), e);
}
}Example 20
| Project: scheduling-master File: VFSZipperZIPTest.java View source code |
private void assertZipWithFileHierarchy(Path archivePath) {
final int[] nbEntries = { 0 };
// Reads ZIP content using a third-party library
ZipUtil.iterate(archivePath.toFile(), new ZipEntryCallback() {
@Override
public void process(InputStream in, ZipEntry zipEntry) throws IOException {
nbEntries[0]++;
}
});
assertThat(nbEntries[0]).isEqualTo(HIERARCHY_DEPTH + 1);
}Example 21
| Project: robovm-idea-master File: AndroidBundledSetupDialog.java View source code |
private void downloadAndroidSdk(final String sdkDir, final JProgressBar progressBar, final JLabel label, final BooleanFlag cancel) throws IOException {
// download the SDK zip to a temporary location
File destination = File.createTempFile("android-sdk", ".zip");
destination.deleteOnExit();
URL url = new URL(ANDROID_SDK_URL);
URLConnection con = url.openConnection();
final long length = con.getContentLengthLong();
byte[] buffer = new byte[1024 * 100];
try (InputStream in = con.getInputStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream(destination))) {
int read = in.read(buffer);
long total = read;
while (read != -1) {
out.write(buffer, 0, read);
read = in.read(buffer);
total += read;
final int percentage = (int) (((double) total / (double) length) * 100);
final long totalRead = total;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(Math.min(100, percentage));
label.setText("Downloading Android SDK (" + (totalRead / 1024 / 1024) + "/" + (length / 1024 / 1024) + "MB)");
}
});
if (cancel.getValue()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
installAndroidSdkButton.setText("Install Android SDK");
for (ActionListener listener : installAndroidSdkButton.getActionListeners()) {
installAndroidSdkButton.removeActionListener(listener);
}
installAndroidSdkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
installAndroidSdk();
}
});
installPanel.removeAll();
installPanel.revalidate();
nextButton.setEnabled(true);
}
});
return;
}
}
}
// unpack the SDK zip, then rename the extracted
// folder
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("Unpacking SDK to " + sdkDir);
installAndroidSdkButton.setEnabled(false);
nextButton.setEnabled(false);
}
});
final File outputDir = new File(sdkDir);
File tmpOutputDir = new File(outputDir.getParent());
if (!tmpOutputDir.exists()) {
if (!tmpOutputDir.mkdirs()) {
throw new RuntimeException("Couldn't create output directory");
}
}
if (ANDROID_SDK_URL.endsWith("zip")) {
ZipUtil.unpack(destination, tmpOutputDir, new NameMapper() {
@Override
public String map(String s) {
int idx = s.indexOf("/");
s = outputDir.getName() + s.substring(idx);
final String file = s;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("Unpacking " + file.substring(0, Math.min(50, file.length() - 1)) + " ...");
}
});
return s;
}
});
} else {
TarArchiveInputStream in = null;
try {
in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(destination)));
TarArchiveEntry entry = null;
while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) {
File f = new File(tmpOutputDir, entry.getName());
if (entry.isDirectory()) {
f.mkdirs();
} else {
f.getParentFile().mkdirs();
OutputStream out = null;
try {
out = new FileOutputStream(f);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(out);
}
if ((entry.getMode() & 0100) != 0) {
f.setExecutable(true);
}
}
final String fileName = entry.getName();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
label.setText("Unpacking " + fileName.substring(0, Math.min(50, fileName.length() - 1)) + " ...");
}
});
}
} catch (Throwable t) {
} finally {
IOUtils.closeQuietly(in);
}
}
// ziputils doesn't preserve file permissions
for (File file : new File(outputDir, "tools").listFiles()) {
if (file.isFile()) {
file.setExecutable(true);
}
}
for (File file : new File(outputDir, "platform-tools").listFiles()) {
if (file.isFile()) {
file.setExecutable(true);
}
}
for (File file : new File(outputDir, "tools/proguard/bin").listFiles()) {
if (file.isFile()) {
file.setExecutable(true);
}
}
}Example 22
| Project: SyncthingAndroid-master File: SyncthingUtils.java View source code |
public static void exportConfig(Context context) {
File configDir = getConfigDirectory(context);
if (!configDir.exists()) {
Toast.makeText(context, R.string.no_config_found, Toast.LENGTH_LONG).show();
return;
}
File zipFile = new File(Environment.getExternalStorageDirectory(), context.getPackageName() + "-export-" + DateTime.now().toString("yyyy-MM-dd--HH-mm-ss") + ".zip");
if (zipFile.exists()) {
//Double click or something. just ignore
return;
}
File tmpDir = new File(context.getApplicationContext().getCacheDir(), randomString(6));
try {
//copy the files we care about into tmp location
File[] files = configDir.listFiles(( dir, filename) -> filename.endsWith(".xml") || filename.endsWith(".pem"));
for (File f : files) {
FileUtils.copyFileToDirectory(f, tmpDir);
}
ZipUtil.pack(tmpDir, zipFile);
new AlertDialog.Builder(context).setTitle(R.string.archive_created).setMessage(context.getString(R.string.archive_at_location, zipFile.getAbsolutePath())).setPositiveButton(android.R.string.ok, null).show();
} catch (IOExceptionRuntimeException | e) {
FileUtils.deleteQuietly(zipFile);
Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show();
Timber.e("Failed to export", e);
} finally {
FileUtils.deleteQuietly(tmpDir);
}
}Example 23
| Project: TheSceneryAlong-master File: TrackUtil.java View source code |
/**
* @description: 压缩并返回zip路径
* @author: chenshiqiang E-mail:csqwyyx@163.com
* @param track
* @return
*/
public static String zipPack(Track track) {
if (createXml(track) != null) {
String trackPath = PathConstants.getTrackpath() + File.separator + track.getUniqueMack();
String zipPath = PathConstants.getExportpath() + File.separator + StringUtils.filterIllegalWords(track.getName()) + ".tsa";
ZipUtil.pack(new File(trackPath), new File(zipPath), true);
return zipPath;
}
return null;
}Example 24
| Project: robovm-master File: ConfigTest.java View source code |
private File createMergeConfig(File tmpDir, String dir, String id, OS os, Arch arch, boolean jar) throws Exception {
File p = new File(tmpDir, dir);
for (OS os2 : OS.values()) {
for (Arch arch2 : Arch.values()) {
File root = new File(p, "META-INF/robovm/" + os2 + "/" + arch2);
root.mkdirs();
if (!new File(root, "robovm.xml").exists()) {
new Config.Builder().write(new File(root, "robovm.xml"));
}
}
}
File root = new File(p, "META-INF/robovm/" + os + "/" + arch);
new Config.Builder().addExportedSymbol(id.toUpperCase() + "*").addForceLinkClass("com." + id.toLowerCase() + ".**").addFrameworkPath(new File(root, id.toLowerCase() + "/bar")).addFramework(id).addLib(new Lib(id.toLowerCase(), true)).addLib(new Lib(new File(root, "lib" + id.toLowerCase() + ".a").getAbsolutePath(), true)).addResource(new Resource(new File(root, "resources"))).addWeakFramework("Weak" + id).write(new File(root, "robovm.xml"));
if (jar) {
File jarFile = new File(tmpDir, p.getName() + ".jar");
ZipUtil.pack(p, jarFile);
FileUtils.deleteDirectory(p);
return jarFile;
} else {
return p;
}
}Example 25
| Project: spring-boot-master File: RepackagerTests.java View source code |
@Test
public void existingSourceEntriesTakePrecedenceOverStandardLibraries() throws Exception {
TestJarFile nested = new TestJarFile(this.temporaryFolder);
nested.addClass("a/b/C.class", ClassWithoutMainMethod.class);
final File nestedFile = nested.getFile();
this.testJarFile.addFile("BOOT-INF/lib/" + nestedFile.getName(), nested.getFile());
this.testJarFile.addClass("A.class", ClassWithMainMethod.class);
File file = this.testJarFile.getFile();
Repackager repackager = new Repackager(file);
long sourceLength = nestedFile.length();
repackager.repackage(new Libraries() {
@Override
public void doWithLibraries(LibraryCallback callback) throws IOException {
nestedFile.delete();
File toZip = RepackagerTests.this.temporaryFolder.newFile();
ZipUtil.packEntry(toZip, nestedFile);
callback.library(new Library(nestedFile, LibraryScope.COMPILE));
}
});
JarFile jarFile = new JarFile(file);
try {
assertThat(jarFile.getEntry("BOOT-INF/lib/" + nestedFile.getName()).getSize()).isEqualTo(sourceLength);
} finally {
jarFile.close();
}
}Example 26
| Project: alfresco-sdk-master File: AbstractRunMojo.java View source code |
/**
* If we are in Alfresco version 4.2 or younger the Solr 1.0 WAR is not available as Maven artifact, just
* as part of a ZIP file, so install it locally so we can deploy from embedded tomcat
*
* @throws MojoExecutionException
*/
protected void installSolr10InLocalRepo() throws MojoExecutionException {
if (isPlatformVersionLtOrEqTo42()) {
getLog().info("Installing Solr 1.0 WAR in local Maven repo");
File solrWarSource = new File(solrHome + "/apache-solr-1.4.1.war");
File outputDir = new File(project.getBuild().getDirectory() + "/solr");
if (outputDir.exists()) {
getLog().info("Solr build dir: " + outputDir + " already exists, not rebuilding");
return;
}
ZipUtil.unpack(solrWarSource, outputDir);
// Comment out SSL/security requirements
executeMojo(plugin(groupId("com.google.code.maven-replacer-plugin"), artifactId("replacer"), version(MAVEN_REPLACER_PLUGIN_VERSION)), goal("replace"), configuration(element(name("regex"), "false"), element(name("includes"), element(name("include"), outputDir + "/WEB-INF/web.xml")), element(name("replacements"), element(name("replacement"), element(name("token"), "<!-- <security-constraint>"), element(name("value"), "<security-constraint>")), element(name("replacement"), element(name("token"), "</security-role> -->"), element(name("value"), "</security-role>")), element(name("replacement"), element(name("token"), "<security-constraint>"), element(name("value"), "<!-- <security-constraint>")), element(name("replacement"), element(name("token"), "</security-role>"), element(name("value"), "</security-role> -->")))), execEnv);
executeMojo(plugin(groupId("com.coderplus.maven.plugins"), artifactId("copy-rename-maven-plugin"), version("1.0")), goal("copy"), configuration(element(name("sourceFile"), solrHome + "/log4j-solr.properties"), element(name("destinationFile"), outputDir + "/WEB-INF/classes/log4j.properties")), execEnv);
executeMojo(plugin(groupId("org.apache.maven.plugins"), artifactId("maven-resources-plugin"), version(MAVEN_RESOURCE_PLUGIN_VERSION)), goal("copy-resources"), configuration(element(name("outputDirectory"), outputDir + "/WEB-INF/lib"), element(name("resources"), element(name("resource"), element(name("directory"), solrHome + "/lib"), element(name("includes"), element(name("include"), "*org.springframework*")), element(name("filtering"), "false")))), execEnv);
ZipUtil.pack(outputDir, new File(solrHome + "/apache-solr-1.4.1.war"));
// Install the Solr 1.0 war file in local maven repo
executeMojo(plugin(groupId("org.apache.maven.plugins"), artifactId("maven-install-plugin"), version(MAVEN_INSTALL_PLUGIN_VERSION)), goal("install-file"), configuration(element(name("file"), solrHome + "/apache-solr-1.4.1.war"), element(name("groupId"), "${project.groupId}"), element(name("artifactId"), getSolrArtifactId()), element(name("version"), "${project.version}"), element(name("packaging"), "war")), execEnv);
}
}Example 27
| Project: sandboxes-master File: Artifact.java View source code |
public boolean contains(String location) {
return ZipUtil.containsEntry(file, location);
}Example 28
| Project: Europeana-Cloud-master File: FolderCompressor.java View source code |
public static void compress(String folderPath, String zipFolderPath) throws ZipException {
File folder = new File(folderPath);
ZipUtil.pack(folder, new File(zipFolderPath));
}Example 29
| Project: jb-filemanager-master File: ZipBuilder.java View source code |
@Override
public void build(List<String> strings) {
super.build(strings);
//external lib because it is very boring impl recursive zipping
ZipUtil.pack(new File(DIR_FOR_TEST_TREE), new File(ZIP_NAME));
}Example 30
| Project: apigee-proxy-coverage-master File: ProxyZipFileHandler.java View source code |
static File expandZipFile(File zipFile) throws IOException {
final Path tempDirectory = Files.createTempDirectory(zipFile.getName());
ZipUtil.unpack(zipFile, tempDirectory.toFile());
return tempDirectory.toFile();
}Example 31
| Project: griffin-master File: Initializer.java View source code |
private void unzipStructure(Path path) throws IOException {
ZipUtil.unpack(new File(zipp + File.separator + "scaffold.zip"), path.toFile());
}Example 32
| Project: cello-master File: ScriptCommands.java View source code |
public void makeZIP(String directory, String zipname) {
org.zeroturnaround.zip.ZipUtil.pack(new File(directory), new File(directory + zipname), true);
}