List of usage examples for java.nio.file FileSystems newFileSystem
public static FileSystem newFileSystem(Path path, Map<String, ?> env) throws IOException
From source file:fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.java
/** * Unzip a jar file/*from w w w. j av a 2 s. c o m*/ * @param jarFile Jar file url like file:/path/to/foo.jar * @param destination Directory where we want to extract the content to * @throws IOException In case of any IO problem */ public static void unzip(String jarFile, Path destination) throws IOException { Map<String, String> zipProperties = new HashMap<>(); /* We want to read an existing ZIP File, so we set this to false */ zipProperties.put("create", "false"); zipProperties.put("encoding", "UTF-8"); URI zipFile = URI.create("jar:" + jarFile); try (FileSystem zipfs = FileSystems.newFileSystem(zipFile, zipProperties)) { Path rootPath = zipfs.getPath("/"); Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetPath = destination.resolve(rootPath.relativize(dir).toString()); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, destination.resolve(rootPath.relativize(file).toString()), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } }); } }
From source file:org.schedulesdirect.grabber.Grabber.java
private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException { Set<String> completedListings = new HashSet<String>(); LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads())); pool = createThreadPoolExecutor();//w w w . ja v a 2 s. c o m start = System.currentTimeMillis(); File dest = grabOpts.getTarget(); cachedSeriesIds = new HashSet<String>(); boolean rmDest = false; if (dest.exists()) { ZipEpgClient zipClnt = null; try { zipClnt = new ZipEpgClient(dest); if (!zipClnt.getUserStatus().getLastServerRefresh() .before(clnt.getUserStatus().getLastServerRefresh())) { LOG.info( "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server."); boolean force = grabOpts.isForce(); if (!force) return; else LOG.warn("Forcing an update of data with the server due to user request!"); } } catch (Exception e) { if (grabOpts.isKeep()) { LOG.error("Existing cache is invalid, keeping by user request!", e); return; } else { LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!", e); rmDest = true; } } finally { if (zipClnt != null) try { zipClnt.close(); } catch (IOException e) { } if (rmDest && !dest.delete()) throw new IOException("Unable to delete " + dest); } } freshZip = !dest.exists(); try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())), Collections.singletonMap("create", "true"))) { if (freshZip) { Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE); Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET)); } ProgramCache progCache = ProgramCache.get(vfs); Path lineups = vfs.getPath("lineups.txt"); Files.deleteIfExists(lineups); Path scheds = vfs.getPath("/schedules/"); if (!Files.isDirectory(scheds)) Files.createDirectory(scheds); Path maps = vfs.getPath("/maps/"); PathUtils.removeDirectory(maps); Files.createDirectory(maps); Path progs = vfs.getPath("/programs/"); if (!Files.isDirectory(progs)) Files.createDirectory(progs); Path logos = vfs.getPath("/logos/"); if (!Files.isDirectory(logos)) Files.createDirectory(logos); Path md5s = vfs.getPath("/md5s/"); if (!Files.isDirectory(md5s)) Files.createDirectory(md5s); Path cache = vfs.getPath(LOGO_CACHE); if (Files.exists(cache)) { String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET); logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class); } else logoCache = new JSONObject(); Path seriesInfo = vfs.getPath("/seriesInfo/"); if (!Files.isDirectory(seriesInfo)) Files.createDirectories(seriesInfo); loadSeriesInfoIds(seriesInfo); missingSeriesIds = Collections.synchronizedSet(new HashSet<String>()); loadRetryIds(vfs.getPath(SERIES_INFO_DATA)); JSONObject resp = Config.get().getObjectMapper().readValue( factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); if (!JsonResponseUtils.isErrorResponse(resp)) Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); else LOG.error("Received error response when requesting lineup data!"); for (Lineup l : clnt.getLineups()) { buildStationList(); JSONObject o = Config.get().getObjectMapper() .readValue( factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))), o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); JSONArray stations = o.getJSONArray("stations"); JSONArray ids = new JSONArray(); for (int i = 0; i < stations.length(); ++i) { JSONObject obj = stations.getJSONObject(i); String sid = obj.getString("stationID"); if (stationList != null && !stationList.contains(sid)) LOG.debug(String.format("Skipped %s; not listed in station file", sid)); else if (completedListings.add(sid)) { ids.put(sid); if (!grabOpts.isNoLogos()) { if (logoCacheInvalid(obj)) pool.execute(new LogoTask(obj, vfs, logoCache)); else if (LOG.isDebugEnabled()) LOG.debug(String.format("Skipped logo for %s; already cached!", obj.optString("callsign", null))); } else if (!logosWarned) { logosWarned = true; LOG.warn("Logo downloads disabled by user request!"); } } else LOG.debug(String.format("Skipped %s; already downloaded.", sid)); //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory! if (ids.length() == grabOpts.getMaxSchedChunk()) { pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); ids = new JSONArray(); } } if (ids.length() > 0) pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); } pool.shutdown(); try { LOG.debug("Waiting for SchedLogoExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) LOG.debug("SchedLogoExecutor: Terminated successfully."); else { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE); ScheduleTask.commit(vfs); pool = createThreadPoolExecutor(); //pool.setMaximumPoolSize(5); // Again, we've got memory problems String[] dirtyPrograms = progCache.getDirtyIds(); progCache.markAllClean(); progCache = null; LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length)); Collection<String> progIds = new ArrayList<String>(); for (String progId : dirtyPrograms) { progIds.add(progId); if (progIds.size() == grabOpts.getMaxProgChunk()) { pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); progIds.clear(); } } if (progIds.size() > 0) pool.execute( new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); pool.shutdown(); try { LOG.debug("Waiting for ProgramExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) { LOG.debug("ProgramExecutor: Terminated successfully."); Iterator<String> itr = missingSeriesIds.iterator(); while (itr.hasNext()) { String id = itr.next(); if (cachedSeriesIds.contains(id)) itr.remove(); } if (missingSeriesIds.size() > 0) { LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size())); Set<String> retrySet = new HashSet<>(); try { new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo", retrySet, true).run(); } catch (RuntimeException e) { LOG.error("SeriesInfo task failed!", e); Grabber.failedTask = true; } Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA); if (retrySet.size() > 0) { StringBuilder sb = new StringBuilder(); for (String id : retrySet) sb.append(id + "\n"); Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } else if (Files.exists(seriesInfoData)) Files.delete(seriesInfoData); } } else { failedTask = true; LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } String userData = clnt.getUserStatus().toJson(); if (failedTask) { LOG.error("One or more tasks failed! Resetting last data refresh timestamp to zero."); SimpleDateFormat fmt = Config.get().getDateTimeFormat(); String exp = fmt.format(new Date(0L)); JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class); o.put("lastDataUpdate", exp); userData = o.toString(2); } Path p = vfs.getPath(USER_DATA); Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); removeIgnoredStations(vfs); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } finally { Runtime rt = Runtime.getRuntime(); LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s", FileUtils.byteCountToDisplaySize(rt.freeMemory()), FileUtils.byteCountToDisplaySize(rt.totalMemory()), FileUtils.byteCountToDisplaySize(rt.maxMemory()))); } }
From source file:net.minecraftforge.common.crafting.CraftingHelper.java
private static void loadFactories(ModContainer mod) { FileSystem fs = null;/*from w ww. j a v a 2s. com*/ BufferedReader reader = null; try { JsonContext ctx = new JsonContext(mod.getModId()); Path fPath = null; if (mod.getSource().isFile()) { fs = FileSystems.newFileSystem(mod.getSource().toPath(), null); fPath = fs.getPath("/assets/" + ctx.getModId() + "/recipes/_factories.json"); } else if (mod.getSource().isDirectory()) { fPath = mod.getSource().toPath().resolve("assets/" + ctx.getModId() + "/recipes/_factories.json"); } if (fPath != null && Files.exists(fPath)) { reader = Files.newBufferedReader(fPath); JsonObject json = JsonUtils.fromJson(GSON, reader, JsonObject.class); loadFactories(json, ctx); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(fs); IOUtils.closeQuietly(reader); } }
From source file:net.minecraftforge.common.crafting.CraftingHelper.java
public static boolean findFiles(ModContainer mod, String base, Function<Path, Boolean> preprocessor, BiFunction<Path, Path, Boolean> processor) { FileSystem fs = null;/*from w w w . j a va 2 s. c o m*/ try { File source = mod.getSource(); if ("minecraft".equals(mod.getModId()) && DEBUG_LOAD_MINECRAFT) { try { URI tmp = CraftingManager.class.getResource("/assets/.mcassetsroot").toURI(); source = new File(tmp.resolve("..").getPath()); } catch (URISyntaxException e) { FMLLog.log.error("Error finding Minecraft jar: ", e); return false; } } Path root = null; if (source.isFile()) { try { fs = FileSystems.newFileSystem(source.toPath(), null); root = fs.getPath("/" + base); } catch (IOException e) { FMLLog.log.error("Error loading FileSystem from jar: ", e); return false; } } else if (source.isDirectory()) { root = source.toPath().resolve(base); } if (root == null || !Files.exists(root)) return false; if (preprocessor != null) { Boolean cont = preprocessor.apply(root); if (cont == null || !cont.booleanValue()) return false; } if (processor != null) { Iterator<Path> itr = null; try { itr = Files.walk(root).iterator(); } catch (IOException e) { FMLLog.log.error("Error iterating filesystem for: {}", mod.getModId(), e); return false; } while (itr != null && itr.hasNext()) { Boolean cont = processor.apply(root, itr.next()); if (cont == null || !cont.booleanValue()) return false; } } return true; } finally { IOUtils.closeQuietly(fs); } }
From source file:org.olat.ims.qti.qpool.QTIImportProcessor.java
private List<DocInfos> traverseZip_nio(File file) throws IOException { List<DocInfos> docInfos = new ArrayList<>(); Path fPath = FileSystems.newFileSystem(file.toPath(), null).getPath("/"); if (fPath != null) { DocInfosVisitor visitor = new DocInfosVisitor(); Files.walkFileTree(fPath, visitor); List<Path> xmlFiles = visitor.getXmlFiles(); for (Path xmlFile : xmlFiles) { InputStream in = Files.newInputStream(xmlFile); Document doc = readXml(in); if (doc != null) { DocInfos d = new DocInfos(); d.setDocument(doc);/*from w w w. j a v a 2 s . c o m*/ d.setRoot(xmlFile.getParent()); d.setFilename(xmlFile.getFileName().toString()); docInfos.add(d); } } } return docInfos; }
From source file:org.owasp.benchmark.score.BenchmarkScore.java
private static TestResults readActualResults(File fileToParse) throws Exception { String filename = fileToParse.getName(); TestResults tr = null;// w w w .java2s . c o m if (filename.endsWith(".ozasmt")) { tr = new AppScanSourceReader().parse(fileToParse); } else if (filename.endsWith(".json")) { String line1 = getLine(fileToParse, 0); String line2 = getLine(fileToParse, 1); if (line2.contains("Coverity") || line2.contains("formatVersion")) { tr = new CoverityReader().parse(fileToParse); } } else if (filename.endsWith(".txt")) { String line1 = getLine(fileToParse, 0); if (line1.startsWith("Possible ")) { tr = new SourceMeterReader().parse(fileToParse); } } else if (filename.endsWith(".xml")) { // Handle XML results file where the 2nd line indicates the tool type String line1 = getLine(fileToParse, 0); String line2 = getLine(fileToParse, 1); if (line2.startsWith("<pmd")) { tr = new PMDReader().parse(fileToParse); } else if (line2.startsWith("<FusionLiteInsight")) { tr = new FusionLiteInsightReader().parse(fileToParse); } else if (line2.startsWith("<XanitizerFindingsList")) { tr = new XanitizerReader().parse(fileToParse); } else if (line2.startsWith("<BugCollection")) { tr = new FindbugsReader().parse(fileToParse); // change the name of the tool if the filename contains findsecbugs if (fileToParse.getName().contains("findsecbugs")) { tr.setTool("FBwFindSecBugs"); } } else if (line2.startsWith("<ResultsSession")) { tr = new ParasoftReader().parse(fileToParse); } else if (line2.startsWith("<detailedreport")) { tr = new VeracodeReader().parse(fileToParse); } else if (line1.startsWith("<total")) { tr = new SonarQubeReader().parse(fileToParse); } else if (line1.contains("<OWASPZAPReport") || line2.contains("<OWASPZAPReport")) { tr = new ZapReader().parse(fileToParse); } else if (line2.startsWith("<CxXMLResults")) { tr = new CheckmarxReader().parse(fileToParse); } else if (line2.startsWith("<report")) { tr = new ArachniReader().parse(fileToParse); } else if (line2.startsWith("<analysisReportResult")) { tr = new JuliaReader().parse(fileToParse); } else { // Handle XML where we have to look for a specific node to identify the tool type Document doc = getXMLDocument(fileToParse); Node root = doc.getDocumentElement(); if (root.getNodeName().equals("issues")) { tr = new BurpReader().parse(root); } else if (root.getNodeName().equals("XmlReport")) { tr = new AppScanDynamicReader().parse(root); } else if (root.getNodeName().equals("noisycricket")) { tr = new NoisyCricketReader().parse(root); } else if (root.getNodeName().equals("Scan")) { tr = new WebInspectReader().parse(root); } else if (root.getNodeName().equals("ScanGroup")) { tr = new AcunetixReader().parse(root); } else if (root.getNodeName().equals("VulnSummary")) { tr = new Rapid7Reader().parse(root); } else if (root.getNodeName().equals("netsparker")) { tr = new NetsparkerReader().parse(root); } } // end else } // end if endsWith ".xml" else if (filename.endsWith(".fpr")) { // .fpr files are really .zip files. So we have to extract the .fvdl file out of it to process it Path path = Paths.get(fileToParse.getPath()); FileSystem fileSystem = FileSystems.newFileSystem(path, null); File outputFile = File.createTempFile(filename, ".fvdl"); Path source = fileSystem.getPath("audit.fvdl"); Files.copy(source, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); tr = new FortifyReader().parse(outputFile); outputFile.delete(); // Check to see if the results are regular Fortify or Fortify OnDemand results // To check, you have to look at the filtertemplate.xml file inside the .fpr archive // and see if that file contains: "Fortify-FOD-Template" outputFile = File.createTempFile(filename + "-filtertemplate", ".xml"); source = fileSystem.getPath("filtertemplate.xml"); // In older versions of Fortify, like 4.1, the filtertemplate.xml file doesn't exist // So only check it if it exists try { Files.copy(source, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedReader br = new BufferedReader(new FileReader(outputFile)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // Only read the first 3 lines and the answer is near the top of the file. int i = 1; while (line != null && i++ <= 3) { sb.append(line); line = br.readLine(); } if (sb.indexOf("Fortify-FOD-") > -1) { tr.setTool(tr.getTool() + "-OnDemand"); } } finally { br.close(); } } catch (NoSuchFileException e) { // Do nothing if the filtertemplate.xml file doesn't exist in the .fpr archive } finally { outputFile.delete(); } } else if (filename.endsWith(".log")) { tr = new ContrastReader().parse(fileToParse); } // If the version # of the tool is specified in the results file name, extract it, and set it. // For example: Benchmark-1.1-Coverity-results-v1.3.2661-6720.json (the version # is 1.3.2661 in this example). // This code should also handle: Benchmark-1.1-Coverity-results-v1.3.2661.xml (where the compute time '-6720' isn't specified) int indexOfVersionMarker = filename.lastIndexOf("-v"); if (indexOfVersionMarker != -1) { String restOfFileName = filename.substring(indexOfVersionMarker + 2); int endIndex = restOfFileName.lastIndexOf('-'); if (endIndex == -1) endIndex = restOfFileName.lastIndexOf('.'); String version = restOfFileName.substring(0, endIndex); tr.setToolVersion(version); } return tr; }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
private boolean saveXml2Package(String xml, String uuid) throws IOException { uuid = UuidUtil.removeCurlies(uuid); //xml file//from w w w. j a v a2 s.c om String folder = Constant.UPLOAD_FOLDER; File temp = new File(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME); InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)); //InputStream in = doc.newInputStream(); Path a = temp.toPath(); Files.copy(in, a, java.nio.file.StandardCopyOption.REPLACE_EXISTING); //copy xml file into zip file Map<String, String> env = new HashMap<>(); env.put("create", "true"); Path path = null; path = Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_ZIP_NAME); URI uri = URI.create("jar:" + path.toUri()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { Files.copy(Paths.get(folder + File.separator + uuid + File.separator + Constant.XML_OUTPUT_FILE_NAME), fs.getPath(Constant.XML_OUTPUT_FILE_NAME), StandardCopyOption.REPLACE_EXISTING); } return true; }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Cleans the Workspace of the AUT and creates a demo Project. * /*from w w w . j a v a2s. c om*/ * @throws IOException * on reset the workspace. * @throws URISyntaxException * on reset the workspace. */ private void prepareAUTWorkspace() throws IOException, URISyntaxException { File wsPathFile = new File(getWorkspacePath()); Path wsPath = wsPathFile.toPath(); if (wsPathFile.exists()) { Files.walkFileTree(wsPath, getDeleteFileVisitor()); LOGGER.info("Removed AUT_WS: " + getWorkspacePath()); } Files.createDirectory(wsPath); Map<String, String> env = new HashMap<String, String>(); env.put("create", "true"); FileSystem fs = FileSystems.newFileSystem(getClass().getResource("/DemoWebTests.zip").toURI(), env); Iterable<Path> rootDirectories = fs.getRootDirectories(); for (Path root : rootDirectories) { DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root); for (Path path : directoryStream) { if (path.getFileName().startsWith("DemoWebTests.zip")) { LOGGER.info("Found DemoWebTest."); Files.copy(path, Paths.get(wsPath.toString(), "DemoWebTests.zip")); URI uriDemoZip = new URI("jar:" + Paths.get(wsPath.toString(), "/DemoWebTests.zip").toUri()); LOGGER.info(uriDemoZip); FileSystem zipFs = FileSystems.newFileSystem(uriDemoZip, env); copyFolder(zipFs.getPath("/"), Paths.get(getWorkspacePath())); zipFs.close(); } } } fs.close(); LOGGER.info("Created Demoproject in: " + getWorkspacePath()); }
From source file:org.schedulesdirect.grabber.Grabber.java
/** * Execute the grabber app/*from w w w.ja v a2 s . c o m*/ * @param args The command line args * @throws IOException Thrown on any unexpected IO error * @throws InvalidCredentialsException Thrown if the login attempt to Schedules Direct failed * @return {@link GrabberReturnCodes#OK OK} on success, one of the other constants in the interface otherwise; typically one would return this value back to the OS level caller * @see GrabberReturnCodes */ public int execute(String[] args) throws IOException, InvalidCredentialsException { if (!parseArgs(args)) return ARGS_PARSE_ERR; else if (parser.getParsedCommand() == null) { parser.usage(); return NO_CMD_ERR; } NetworkEpgClient clnt = null; try { if (!parser.getParsedCommand().equals("audit")) { try { clnt = new NetworkEpgClient(globalOpts.getUsername(), globalOpts.getPassword(), globalOpts.getUserAgent(), globalOpts.getUrl().toString(), true, factory); LOG.debug(String.format("Client details: %s", clnt.getUserAgent())); } catch (ServiceOfflineException e) { LOG.error("Web service is offline! Please try again later."); return SERVICE_OFFLINE_ERR; } } action = Action.valueOf(parser.getParsedCommand().toUpperCase()); int rc = CMD_FAILED_ERR; switch (action) { case LIST: if (!listOpts.isHelp()) { listLineups(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case GRAB: if (!grabOpts.isHelp()) { updateZip(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case ADD: if (!addOpts.isHelp()) addLineup(clnt); else parser.usage(action.toString().toLowerCase()); break; case DELETE: if (!delOpts.isHelp()) rc = removeHeadend(clnt) ? OK : CMD_FAILED_ERR; else parser.usage(action.toString().toLowerCase()); break; case INFO: if (!infoOpts.isHelp()) { dumpAccountInfo(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case SEARCH: if (!searchOpts.isHelp()) { listLineupsForZip(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case AUDIT: if (!auditOpts.isHelp()) { Auditor a = new Auditor(auditOpts); a.run(); if (!a.isFailed()) rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case LISTMSGS: if (!listMsgsOpts.isHelp()) { listAllMessages(clnt); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case DELMSG: if (!delMsgsOpts.isHelp()) { if (deleteMessages(clnt, clnt.getUserStatus().getSystemMessages()) < delMsgsOpts.getIds() .size()) deleteMessages(clnt, clnt.getUserStatus().getUserMessages()); rc = OK; } else parser.usage(action.toString().toLowerCase()); break; case AVAILABLE: if (!availOpts.isHelp()) { String type = availOpts.getType(); if (type == null) listAvailableThings(clnt); else listAvailableThings(clnt, type); // TODO: change rc = OK; } else parser.usage(action.toString().toLowerCase()); break; } return rc; } catch (ParameterException e) { System.out.println(e.getMessage()); parser.usage(); return ARGS_PARSE_ERR; } catch (JSONException e) { throw new RuntimeException(e); } finally { if (clnt != null) clnt.close(); if (grabOpts.getTarget().exists() && action == Action.GRAB) { FileSystem target; try { target = FileSystems.newFileSystem( new URI(String.format("jar:%s", grabOpts.getTarget().toURI())), Collections.<String, Object>emptyMap()); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } if (action == Action.GRAB && !grabOpts.isHelp() && grabOpts.isPurge() && !freshZip) { LOG.warn("Performing a cache cleanup, this will take a few minutes!"); try { removeExpiredSchedules(target); } catch (JSONException e) { throw new IOException(e); } removeUnusedPrograms(target); } target.close(); if (action == Action.GRAB && !grabOpts.isHelp()) LOG.info(String.format("Created '%s' successfully! [%dms]", target, System.currentTimeMillis() - start)); } if (globalOpts.isSaveCreds()) { String user = globalOpts.getUsername(); String pwd = globalOpts.getPassword(); if (user != null && user.length() > 0 && pwd != null && pwd.length() > 0) { Properties props = new Properties(); props.setProperty("user", globalOpts.getUsername()); props.setProperty("password", globalOpts.getPassword()); Writer w = new FileWriter(OPTS_FILE); props.store(w, "Generated by sdjson-grabber"); w.close(); LOG.info(String.format("Credentials saved for future use in %s!", OPTS_FILE.getAbsoluteFile())); } } } }
From source file:org.tinymediamanager.core.Utils.java
/** * Creates (or adds) a file to a ZIP/*from www. j av a 2 s . c om*/ * * @param zipFile * Path of zip file * @param toBeAdded * Path to be added * @param internalPath * the location inside the ZIP like /aa/a.txt */ public static void createZip(Path zipFile, Path toBeAdded, String internalPath) { Map<String, String> env = new HashMap<>(); try { // check if file exists env.put("create", String.valueOf(!Files.exists(zipFile))); // use a Zip filesystem URI URI fileUri = zipFile.toUri(); // here URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null); // System.out.println(zipUri); // URI uri = URI.create("jar:file:"+zipLocation); // here creates the // zip // try with resource try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) { // Create internal path in the zipfs Path internalTargetPath = zipfs.getPath(internalPath); if (!Files.exists(internalTargetPath.getParent())) { // Create directory Files.createDirectory(internalTargetPath.getParent()); } // copy a file into the zip file Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING); } } catch (Exception e) { LOGGER.error("Failed to create zip file!" + e.getMessage()); } }