List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
From source file:org.dspace.app.itemimport.ItemImport.java
public static void main(String[] argv) throws Exception { DSIndexer.setBatchProcessingMode(true); Date startTime = new Date(); int status = 0; try {/*from w ww.java 2s .c o m*/ // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("a", "add", false, "add items to DSpace"); options.addOption("b", "add-bte", false, "add items to DSpace via Biblio-Transformation-Engine (BTE)"); options.addOption("r", "replace", false, "replace items in mapfile"); options.addOption("d", "delete", false, "delete items listed in mapfile"); options.addOption("i", "inputtype", true, "input type in case of BTE import"); options.addOption("s", "source", true, "source of items (directory)"); options.addOption("z", "zip", true, "name of zip file"); options.addOption("c", "collection", true, "destination collection(s) Handle or database ID"); options.addOption("m", "mapfile", true, "mapfile items in mapfile"); options.addOption("e", "eperson", true, "email of eperson doing importing"); options.addOption("w", "workflow", false, "send submission through collection's workflow"); options.addOption("n", "notify", false, "if sending submissions through the workflow, send notification emails"); options.addOption("t", "test", false, "test run - do not actually import items"); options.addOption("p", "template", false, "apply template"); options.addOption("R", "resume", false, "resume a failed import (add only)"); options.addOption("q", "quiet", false, "don't display metadata"); options.addOption("h", "help", false, "help"); CommandLine line = parser.parse(options, argv); String command = null; // add replace remove, etc String bteInputType = null; //ris, endnote, tsv, csv, bibtex String sourcedir = null; String mapfile = null; String eperson = null; // db ID or email String[] collections = null; // db ID or handles if (line.hasOption('h')) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp("ItemImport\n", options); System.out.println( "\nadding items: ItemImport -a -e eperson -c collection -s sourcedir -m mapfile"); System.out.println( "\nadding items from zip file: ItemImport -a -e eperson -c collection -s sourcedir -z filename.zip -m mapfile"); System.out .println("replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("deleting items: ItemImport -d -e eperson -m mapfile"); System.out.println( "If multiple collections are specified, the first collection will be the one that owns the item."); System.exit(0); } if (line.hasOption('a')) { command = "add"; } if (line.hasOption('r')) { command = "replace"; } if (line.hasOption('d')) { command = "delete"; } if (line.hasOption('b')) { command = "add-bte"; } if (line.hasOption('i')) { bteInputType = line.getOptionValue('i'); ; } if (line.hasOption('w')) { useWorkflow = true; if (line.hasOption('n')) { useWorkflowSendEmail = true; } } if (line.hasOption('t')) { isTest = true; System.out.println("**Test Run** - not actually importing items."); } if (line.hasOption('p')) { template = true; } if (line.hasOption('s')) // source { sourcedir = line.getOptionValue('s'); } if (line.hasOption('m')) // mapfile { mapfile = line.getOptionValue('m'); } if (line.hasOption('e')) // eperson { eperson = line.getOptionValue('e'); } if (line.hasOption('c')) // collections { collections = line.getOptionValues('c'); } if (line.hasOption('R')) { isResume = true; System.out.println("**Resume import** - attempting to import items not already imported"); } if (line.hasOption('q')) { isQuiet = true; } boolean zip = false; String zipfilename = ""; String ziptempdir = ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir"); if (line.hasOption('z')) { zip = true; zipfilename = sourcedir + System.getProperty("file.separator") + line.getOptionValue('z'); } // now validate // must have a command set if (command == null) { System.out.println( "Error - must run with either add, replace, or remove (run with -h flag for details)"); System.exit(1); } else if ("add".equals(command) || "replace".equals(command)) { if (sourcedir == null) { System.out.println("Error - a source directory containing items must be set"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (mapfile == null) { System.out.println("Error - a map file to hold importing results must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (eperson == null) { System.out.println("Error - an eperson to do the importing must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (collections == null) { System.out.println("Error - at least one destination collection must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } } else if ("add-bte".equals(command)) { if (sourcedir == null) { System.out.println("Error - a source file containing items must be set"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (mapfile == null) { System.out.println("Error - a map file to hold importing results must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (eperson == null) { System.out.println("Error - an eperson to do the importing must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (collections == null) { System.out.println("Error - at least one destination collection must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } if (bteInputType == null) { System.out.println( "Error - an input type (tsv, csv, ris, endnote, bibtex or any other type you have specified in BTE Spring XML configuration file) must be specified"); System.out.println(" (run with -h flag for details)"); System.exit(1); } } else if ("delete".equals(command)) { if (eperson == null) { System.out.println("Error - an eperson to do the importing must be specified"); System.exit(1); } if (mapfile == null) { System.out.println("Error - a map file must be specified"); System.exit(1); } } // can only resume for adds if (isResume && !"add".equals(command)) { System.out.println("Error - resume option only works with --add command"); System.exit(1); } // do checks around mapfile - if mapfile exists and 'add' is selected, // resume must be chosen File myFile = new File(mapfile); if (!isResume && "add".equals(command) && myFile.exists()) { System.out.println("Error - the mapfile " + mapfile + " already exists."); System.out.println("Either delete it or use --resume if attempting to resume an aborted import."); System.exit(1); } // does the zip file exist and can we write to the temp directory if (zip) { File zipfile = new File(sourcedir); if (!zipfile.canRead()) { System.out.println("Zip file '" + sourcedir + "' does not exist, or is not readable."); System.exit(1); } if (ziptempdir == null) { System.out.println( "Unable to unzip import file as the key 'org.dspace.app.itemexport.work.dir' is not set in dspace.cfg"); System.exit(1); } zipfile = new File(ziptempdir); if (!zipfile.isDirectory()) { System.out.println("'" + ConfigurationManager.getProperty("org.dspace.app.itemexport.work.dir") + "' as defined by the key 'org.dspace.app.itemexport.work.dir' in dspace.cfg " + "is not a valid directory"); System.exit(1); } File tempdir = new File(ziptempdir); if (!tempdir.exists() && !tempdir.mkdirs()) { log.error("Unable to create temporary directory"); } sourcedir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z"); ziptempdir = ziptempdir + System.getProperty("file.separator") + line.getOptionValue("z") + System.getProperty("file.separator"); } ItemImport myloader = new ItemImport(); // create a context Context c = new Context(); // find the EPerson, assign to context EPerson myEPerson = null; if (eperson.indexOf('@') != -1) { // @ sign, must be an email myEPerson = EPerson.findByEmail(c, eperson); } else { myEPerson = EPerson.find(c, Integer.parseInt(eperson)); } if (myEPerson == null) { System.out.println("Error, eperson cannot be found: " + eperson); System.exit(1); } c.setCurrentUser(myEPerson); // find collections Collection[] mycollections = null; // don't need to validate collections set if command is "delete" if (!"delete".equals(command)) { System.out.println("Destination collections:"); mycollections = new Collection[collections.length]; // validate each collection arg to see if it's a real collection for (int i = 0; i < collections.length; i++) { // is the ID a handle? if (collections[i].indexOf('/') != -1) { // string has a / so it must be a handle - try and resolve // it mycollections[i] = (Collection) HandleManager.resolveToObject(c, collections[i]); // resolved, now make sure it's a collection if ((mycollections[i] == null) || (mycollections[i].getType() != Constants.COLLECTION)) { mycollections[i] = null; } } // not a handle, try and treat it as an integer collection // database ID else if (collections[i] != null) { mycollections[i] = Collection.find(c, Integer.parseInt(collections[i])); } // was the collection valid? if (mycollections[i] == null) { throw new IllegalArgumentException("Cannot resolve " + collections[i] + " to collection"); } // print progress info String owningPrefix = ""; if (i == 0) { owningPrefix = "Owning "; } System.out.println(owningPrefix + " Collection: " + mycollections[i].getMetadata("name")); } } // end of validating collections try { // If this is a zip archive, unzip it first if (zip) { ZipFile zf = new ZipFile(zipfilename); ZipEntry entry; Enumeration<? extends ZipEntry> entries = zf.entries(); while (entries.hasMoreElements()) { entry = entries.nextElement(); if (entry.isDirectory()) { if (!new File(ziptempdir + entry.getName()).mkdir()) { log.error("Unable to create contents directory"); } } else { System.out.println("Extracting file: " + entry.getName()); int index = entry.getName().lastIndexOf('/'); if (index == -1) { // Was it created on Windows instead? index = entry.getName().lastIndexOf('\\'); } if (index > 0) { File dir = new File(ziptempdir + entry.getName().substring(0, index)); if (!dir.mkdirs()) { log.error("Unable to create directory"); } } byte[] buffer = new byte[1024]; int len; InputStream in = zf.getInputStream(entry); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(ziptempdir + entry.getName())); while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } } c.turnOffAuthorisationSystem(); if ("add".equals(command)) { myloader.addItems(c, mycollections, sourcedir, mapfile, template); } else if ("replace".equals(command)) { myloader.replaceItems(c, mycollections, sourcedir, mapfile, template); } else if ("delete".equals(command)) { myloader.deleteItems(c, mapfile); } else if ("add-bte".equals(command)) { myloader.addBTEItems(c, mycollections, sourcedir, mapfile, template, bteInputType); } // complete all transactions c.complete(); } catch (Exception e) { // abort all operations if (mapOut != null) { mapOut.close(); } mapOut = null; c.abort(); e.printStackTrace(); System.out.println(e); status = 1; } // Delete the unzipped file try { if (zip) { System.gc(); System.out.println("Deleting temporary zip directory: " + ziptempdir); ItemImport.deleteDirectory(new File(ziptempdir)); } } catch (Exception ex) { System.out.println("Unable to delete temporary zip archive location: " + ziptempdir); } if (mapOut != null) { mapOut.close(); } if (isTest) { System.out.println("***End of Test Run***"); } } finally { DSIndexer.setBatchProcessingMode(false); Date endTime = new Date(); System.out.println("Started: " + startTime.getTime()); System.out.println("Ended: " + endTime.getTime()); System.out.println("Elapsed time: " + ((endTime.getTime() - startTime.getTime()) / 1000) + " secs (" + (endTime.getTime() - startTime.getTime()) + " msecs)"); } System.exit(status); }
From source file:com.adobe.aem.demomachine.communities.Loader.java
public static void main(String[] args) { String hostname = null;//from ww w .j av a 2 s. co m String port = null; String altport = null; String csvfile = null; String analytics = null; String adminPassword = "admin"; boolean reset = false; boolean configure = false; boolean minimize = false; boolean noenablement = true; int maxretries = MAXRETRIES; // Command line options for this tool Options options = new Options(); options.addOption("h", true, "Hostname"); options.addOption("p", true, "Port"); options.addOption("a", true, "Alternate Port"); options.addOption("f", true, "CSV file"); options.addOption("r", false, "Reset"); options.addOption("u", true, "Admin Password"); options.addOption("c", false, "Configure"); options.addOption("m", false, "Minimize"); options.addOption("e", false, "No Enablement"); options.addOption("s", true, "Analytics Endpoint"); options.addOption("t", false, "Analytics"); options.addOption("w", false, "Retry"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { hostname = cmd.getOptionValue("h"); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } if (cmd.hasOption("a")) { altport = cmd.getOptionValue("a"); } if (cmd.hasOption("f")) { csvfile = cmd.getOptionValue("f"); } if (cmd.hasOption("u")) { adminPassword = cmd.getOptionValue("u"); } if (cmd.hasOption("t")) { if (cmd.hasOption("s")) { analytics = cmd.getOptionValue("s"); } } if (cmd.hasOption("r")) { reset = true; } if (cmd.hasOption("w")) { maxretries = Integer.parseInt(cmd.getOptionValue("w")); } if (cmd.hasOption("c")) { configure = true; } if (cmd.hasOption("m")) { minimize = true; } if (cmd.hasOption("e")) { noenablement = false; } if (csvfile == null || port == null || hostname == null) { System.out.println( "Request parameters: -h hostname -p port -a alternateport -u adminPassword -f path_to_CSV_file -r (true|false, delete content before import) -c (true|false, post additional properties)"); System.exit(-1); } } catch (ParseException ex) { logger.error(ex.getMessage()); } logger.debug("AEM Demo Loader: Processing file " + csvfile); try { // Reading and processing the CSV file, stand alone or as part of a ZIP file if (csvfile != null && csvfile.toLowerCase().endsWith(".zip")) { ZipFile zipFile = new ZipFile(csvfile); ZipInputStream stream = new ZipInputStream(new FileInputStream(csvfile)); ZipEntry zipEntry; while ((zipEntry = stream.getNextEntry()) != null) { if (!zipEntry.isDirectory() && zipEntry.getName().toLowerCase().endsWith(".csv")) { InputStream is = zipFile.getInputStream(zipEntry); BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset, configure, minimize, noenablement, csvfile, maxretries); } } try { stream.close(); zipFile.close(); } catch (IOException ioex) { //omitted. } } else if (csvfile.toLowerCase().endsWith(".csv")) { Reader in = new FileReader(csvfile); processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset, configure, minimize, noenablement, csvfile, maxretries); } } catch (IOException e) { logger.error(e.getMessage()); } }
From source file:Main.java
public static InputStream inputStream(ZipFile zipFile, ZipEntry entry) { try {/* ww w. ja v a 2 s .c o m*/ return zipFile.getInputStream(entry); } catch (final FileNotFoundException e) { throw new IllegalArgumentException("File " + zipFile + " not found.", e); } catch (final IOException e) { throw new RuntimeException("File " + zipFile + " not found.", e); } }
From source file:Main.java
public static java.io.InputStream upZip(String zipFilePath, String fileString) throws Exception { java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(zipFilePath); java.util.zip.ZipEntry zipEntry = zipFile.getEntry(fileString); return zipFile.getInputStream(zipEntry); }
From source file:brut.util.BrutIO.java
public static void copy(ZipFile inputFile, ZipOutputStream outputFile, ZipEntry entry) throws IOException { try (InputStream is = inputFile.getInputStream(entry)) { IOUtils.copy(is, outputFile);//from w ww .j ava2 s . c om } }
From source file:net.fabricmc.installer.installer.ServerInstaller.java
public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar) throws IOException { progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0); String[] split = version.split("-"); String mcVer = split[0];/* w ww . ja v a 2 s .c o m*/ String fabricVer = split[1]; File mcJar = new File(mcDir, "minecraft_server." + mcVer + ".jar"); if (!mcJar.exists()) { progress.updateProgress(Translator.getString("install.server.downloadVersionList"), 10); JsonObject versionList = Utils .loadRemoteJSON(new URL("https://launchermeta.mojang.com/mc/game/version_manifest.json")); String url = null; for (JsonElement element : versionList.getAsJsonArray("versions")) { JsonObject object = element.getAsJsonObject(); if (object.get("id").getAsString().equals(mcVer)) { url = object.get("url").getAsString(); break; } } if (url == null) { throw new RuntimeException(Translator.getString("install.server.error.noVersion")); } progress.updateProgress(Translator.getString("install.server.downloadServerInfo"), 12); JsonObject serverInfo = Utils.loadRemoteJSON(new URL(url)); url = serverInfo.getAsJsonObject("downloads").getAsJsonObject("server").get("url").getAsString(); progress.updateProgress(Translator.getString("install.server.downloadServer"), 15); FileUtils.copyURLToFile(new URL(url), mcJar); } File libs = new File(mcDir, "libs"); ZipFile fabricZip = new ZipFile(fabricJar); InstallerMetadata metadata; try (InputStream inputStream = fabricZip .getInputStream(fabricZip.getEntry(Reference.INSTALLER_METADATA_FILENAME))) { metadata = new InstallerMetadata(inputStream); } List<InstallerMetadata.LibraryEntry> fabricDeps = metadata.getLibraries("server", "common"); for (int i = 0; i < fabricDeps.size(); i++) { InstallerMetadata.LibraryEntry dep = fabricDeps.get(i); File depFile = new File(libs, dep.getFilename()); if (depFile.exists()) { depFile.delete(); } progress.updateProgress("Downloading " + dep.getFilename(), 20 + (i * 70 / fabricDeps.size())); FileUtils.copyURLToFile(new URL(dep.getFullURL()), depFile); } progress.updateProgress(Translator.getString("install.success"), 100); }
From source file:com.shazam.fork.model.InstrumentationInfo.java
/** * Parse key information from an instrumentation APK's manifest. * @param apkTestFile the instrumentation APK * @return the instrumentation info instance *//*from w w w . j a v a2 s. co m*/ @Nonnull public static InstrumentationInfo parseFromFile(File apkTestFile) { InputStream is = null; try { ZipFile zip = new ZipFile(apkTestFile); ZipEntry entry = zip.getEntry("AndroidManifest.xml"); is = zip.getInputStream(entry); AXMLParser parser = new AXMLParser(is); int eventType = parser.getType(); String appPackage = null; String testPackage = null; String testRunnerClass = null; while (eventType != AXMLParser.END_DOCUMENT) { if (eventType == AXMLParser.START_TAG) { String parserName = parser.getName(); boolean isManifest = "manifest".equals(parserName); boolean isInstrumentation = "instrumentation".equals(parserName); if (isManifest || isInstrumentation) { for (int i = 0; i < parser.getAttributeCount(); i++) { String parserAttributeName = parser.getAttributeName(i); if (isManifest && "package".equals(parserAttributeName)) { testPackage = parser.getAttributeValueString(i); } else if (isInstrumentation && "targetPackage".equals(parserAttributeName)) { appPackage = parser.getAttributeValueString(i); } else if (isInstrumentation && "name".equals(parserAttributeName)) { testRunnerClass = parser.getAttributeValueString(i); } } } } eventType = parser.next(); } checkNotNull(testPackage, "Could not find test application package."); checkNotNull(appPackage, "Could not find application package."); checkNotNull(testRunnerClass, "Could not find test runner class."); // Support relative declaration of instrumentation test runner. if (testRunnerClass.startsWith(".")) { testRunnerClass = testPackage + testRunnerClass; } else if (!testRunnerClass.contains(".")) { testRunnerClass = testPackage + "." + testRunnerClass; } return new InstrumentationInfo(appPackage, testPackage, testRunnerClass); } catch (IOException e) { throw new RuntimeException("Unable to parse test app AndroidManifest.xml.", e); } finally { IOUtils.closeQuietly(is); } }
From source file:Main.java
public static byte[] readZipEntry(File zfile, ZipEntry entry) throws ZipException, IOException { Log.d("file3: ", zfile.toString()); Log.d("zipEntry3: ", entry.toString()); ZipFile zipFile = new ZipFile(zfile); if (entry != null && !entry.isDirectory()) { byte[] barr = new byte[(int) entry.getSize()]; int read = 0; int len = 0; InputStream is = zipFile.getInputStream(entry); BufferedInputStream bis = new BufferedInputStream(is); int length = barr.length; while ((len = bis.read(barr, read, length - read)) != -1) { read += len;/* w w w . ja v a 2 s.c o m*/ } bis.close(); is.close(); zipFile.close(); return barr; } else { zipFile.close(); return new byte[0]; } }
From source file:b2s.idea.mavenize.JarCombiner.java
private static byte[] contentsOf(ZipEntry entry, ZipFile file) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); InputStream input = null;/*from w ww . j av a 2 s . co m*/ try { input = file.getInputStream(entry); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); } return output.toByteArray(); }
From source file:Main.java
/** * Uncompresses zipped files// ww w . j a va2 s . c o m * @param zippedFile The file to uncompress * @param destinationDir Where to put the files * @return list of unzipped files * @throws java.io.IOException thrown if there is a problem finding or writing the files */ public static List<File> unzip(File zippedFile, File destinationDir) throws IOException { int buffer = 2048; List<File> unzippedFiles = new ArrayList<File>(); BufferedOutputStream dest; BufferedInputStream is; ZipEntry entry; ZipFile zipfile = new ZipFile(zippedFile); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; File destFile; if (destinationDir != null) { destFile = new File(destinationDir, entry.getName()); } else { destFile = new File(entry.getName()); } FileOutputStream fos = new FileOutputStream(destFile); dest = new BufferedOutputStream(fos, buffer); try { while ((count = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, count); } unzippedFiles.add(destFile); } finally { dest.flush(); dest.close(); is.close(); } } return unzippedFiles; }