List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:org.apache.drill.yarn.core.TestConfig.java
private DoYTestConfig initConfig(String configName) throws IOException, DoyConfigException { File tempDir = new File(System.getProperty("java.io.tmpdir")); File configDir = new File(tempDir, "config"); if (configDir.exists()) { FileUtils.forceDelete(configDir); }/*from w w w . j av a 2 s . c o m*/ configDir.mkdirs(); configDir.deleteOnExit(); InputStream in = getClass().getResourceAsStream("/" + configName); File dest = new File(configDir, "drill-on-yarn.conf"); Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING); in = getClass().getResourceAsStream("/test-doy-distrib.conf"); dest = new File(configDir, "doy-distrib.conf"); Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING); System.setProperty(DrillOnYarnConfig.YARN_QUEUE, "sys-queue"); TestClassLoader cl = new TestClassLoader(this.getClass().getClassLoader(), configDir); assertNotNull(cl.getResource(DrillOnYarnConfig.DISTRIB_FILE_NAME)); return new DoYTestConfig(cl, configDir); }
From source file:at.alladin.rmbt.controlServer.QualityOfServiceExportResource.java
@Get public Representation request(final String entity) { //Before doing anything => check if a cached file already exists and is new enough String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); final File generatingFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); if (cachedFile.exists()) { //check if file has been recently created OR a file is currently being created if (((cachedFile.lastModified() + cacheThresholdMs) > (new Date()).getTime()) || (generatingFile.exists() && (generatingFile.lastModified() + cacheThresholdMs) > (new Date()).getTime())) { //if so, return the cached file instead of a cost-intensive new one final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override/*from www . java 2s.c o m*/ public void write(OutputStream out) throws IOException { InputStream is = new FileInputStream(cachedFile); IOUtils.copy(is, out); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; } } //final List<String> data = new ArrayList<String>(); final StringBuilder sb = new StringBuilder(); QoSTestObjectiveDao nnObjectiveDao = new QoSTestObjectiveDao(conn); QoSTestDescDao nnDescDao = new QoSTestDescDao(conn, null); try { Map<String, List<QoSTestObjective>> map = nnObjectiveDao.getAllToMap(); Iterator<String> keys = map.keySet().iterator(); sb.append("<h1>Contents:</h1>"); sb.append("<ol>"); sb.append("<li><a href=\"#table1\">qos_test_objective</a></li>"); sb.append("<li><a href=\"#table2\">qos_test_desc</a></li>"); sb.append("</ol><br>"); sb.append("<h1 id=\"table1\">Test objectives table (qos_test_objective)</h1>"); while (keys.hasNext()) { String testType = keys.next(); List<QoSTestObjective> list = map.get(testType); sb.append("<h2>Test group: " + testType.toUpperCase() + "</h2><ul>"); //data.add("<h2>Test group: " + testType.toUpperCase() + "</h2>"); for (QoSTestObjective item : list) { //data.add(item.toHtml()); sb.append("<li>"); sb.append(item.toHtml()); sb.append("</li>"); } sb.append("</ul>"); } Map<String, List<QoSTestDesc>> descMap = nnDescDao.getAllToMapIgnoreLang(); keys = descMap.keySet().iterator(); sb.append("<h1 id=\"table2\">Language table (qos_test_desc)</h1><ul>"); while (keys.hasNext()) { String descKey = keys.next(); List<QoSTestDesc> list = descMap.get(descKey); sb.append("<li><h4 id=\"" + descKey.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">KEY (column: desc_key): <i>" + descKey + "</i></h4><ul>"); //data.add("<h3>KEY: <i>" + descKey + "</i></h3><ul>"); for (QoSTestDesc item : list) { sb.append("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); //data.add("<li><i>" + item.getLang() + "</i>: " + item.getValue() + "</li>"); } sb.append("</ul></li>"); //data.add("</ul>"); } sb.append("</ul>"); } catch (final SQLException e) { e.printStackTrace(); return null; } final OutputRepresentation result = new OutputRepresentation( zip ? MediaType.APPLICATION_ZIP : MediaType.TEXT_HTML) { @Override public void write(OutputStream out) throws IOException { //cache in file => create temporary temporary file (to // handle errors while fulfilling a request) String property = System.getProperty("java.io.tmpdir"); final File cachedFile = new File( property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML) + "_tmp"); OutputStream outf = new FileOutputStream(cachedFile); if (zip) { final ZipOutputStream zos = new ZipOutputStream(outf); final ZipEntry zeLicense = new ZipEntry("LIZENZ.txt"); zos.putNextEntry(zeLicense); final InputStream licenseIS = getClass().getResourceAsStream("DATA_LICENSE.txt"); IOUtils.copy(licenseIS, zos); licenseIS.close(); final ZipEntry zeCsv = new ZipEntry(FILENAME_HTML); zos.putNextEntry(zeCsv); outf = zos; } try (OutputStreamWriter osw = new OutputStreamWriter(outf)) { osw.write(sb.toString()); osw.flush(); } if (zip) outf.close(); //if we reach this code, the data is now cached in a temporary tmp-file //so, rename the file for "production use2 //concurrency issues should be solved by the operating system File newCacheFile = new File(property + File.separator + ((zip) ? FILENAME_ZIP : FILENAME_HTML)); Files.move(cachedFile.toPath(), newCacheFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); FileInputStream fis = new FileInputStream(newCacheFile); IOUtils.copy(fis, out); fis.close(); out.close(); } }; if (zip) { final Disposition disposition = new Disposition(Disposition.TYPE_ATTACHMENT); disposition.setFilename(FILENAME_ZIP); result.setDisposition(disposition); } return result; }
From source file:divconq.tool.Updater.java
static public boolean tryUpdate() { @SuppressWarnings("resource") final Scanner scan = new Scanner(System.in); FuncResult<RecordStruct> ldres = Updater.loadDeployed(); if (ldres.hasErrors()) { System.out.println("Error reading deployed.json file: " + ldres.getMessage()); return false; }//from w w w.j a v a2s . c om RecordStruct deployed = ldres.getResult(); String ver = deployed.getFieldAsString("Version"); String packfolder = deployed.getFieldAsString("PackageFolder"); String packprefix = deployed.getFieldAsString("PackagePrefix"); if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) { System.out.println("Error reading deployed.json file: Missing Version or PackageFolder"); return false; } if (StringUtil.isEmpty(packprefix)) packprefix = "DivConq"; System.out.println("Current Version: " + ver); Path packpath = Paths.get(packfolder); if (!Files.exists(packpath) || !Files.isDirectory(packpath)) { System.out.println("Error reading PackageFolder - it may not exist or is not a folder."); return false; } File pp = packpath.toFile(); RecordStruct deployment = null; File matchpack = null; for (File f : pp.listFiles()) { if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip")) continue; System.out.println("Checking: " + f.getName()); // if not a match before, clear this deployment = null; try { ZipFile zf = new ZipFile(f); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.getName().equals("deployment.json")) { //System.out.println("crc: " + entry.getCrc()); FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry)); if (pres.hasErrors()) { System.out.println("Error reading deployment.json file"); break; } deployment = (RecordStruct) pres.getResult(); break; } } zf.close(); } catch (IOException x) { System.out.println("Error reading deployment.json file: " + x); } if (deployment != null) { String fndver = deployment.getFieldAsString("Version"); String fnddependson = deployment.getFieldAsString("DependsOn"); if (ver.equals(fnddependson)) { System.out.println("Found update: " + fndver); matchpack = f; break; } } } if ((matchpack == null) || (deployment == null)) { System.out.println("No updates found!"); return false; } String fndver = deployment.getFieldAsString("Version"); String umsg = deployment.getFieldAsString("UpdateMessage"); if (StringUtil.isNotEmpty(umsg)) { System.out.println("========================================================================"); System.out.println(umsg); System.out.println("========================================================================"); } System.out.println(); System.out.println("Do you want to install? (y/n)"); System.out.println(); String p = scan.nextLine().toLowerCase(); if (!p.equals("y")) return false; System.out.println(); System.out.println("Intalling: " + fndver); Set<String> ignorepaths = new HashSet<>(); ListStruct iplist = deployment.getFieldAsList("IgnorePaths"); if (iplist != null) { for (Struct df : iplist.getItems()) ignorepaths.add(df.toString()); } ListStruct dflist = deployment.getFieldAsList("DeleteFiles"); // deleting if (dflist != null) { for (Struct df : dflist.getItems()) { Path delpath = Paths.get(".", df.toString()); if (Files.exists(delpath)) { System.out.println("Deleting: " + delpath.toAbsolutePath()); try { Files.delete(delpath); } catch (IOException x) { System.out.println("Unable to Delete: " + x); } } } } // copying updates System.out.println("Checking for updated files: "); try { @SuppressWarnings("resource") ZipFile zf = new ZipFile(matchpack); Enumeration<ZipArchiveEntry> entries = zf.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String entryname = entry.getName().replace('\\', '/'); boolean xfnd = false; for (String exculde : ignorepaths) if (entryname.startsWith(exculde)) { xfnd = true; break; } if (xfnd) continue; System.out.print("."); Path localpath = Paths.get(".", entryname); if (entry.isDirectory()) { if (!Files.exists(localpath)) Files.createDirectories(localpath); } else { boolean hashmatch = false; if (Files.exists(localpath)) { String local = null; String update = null; try (InputStream lin = Files.newInputStream(localpath)) { local = HashUtil.getMd5(lin); } try (InputStream uin = zf.getInputStream(entry)) { update = HashUtil.getMd5(uin); } hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update) && local.equals(update)); } if (!hashmatch) { System.out.print("[" + entryname + "]"); try (InputStream uin = zf.getInputStream(entry)) { Files.createDirectories(localpath.getParent()); Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING); } catch (Exception x) { System.out.println("Error updating: " + entryname + " - " + x); return false; } } } } zf.close(); } catch (IOException x) { System.out.println("Error reading update package: " + x); } // updating local config deployed.setField("Version", fndver); OperationResult svres = Updater.saveDeployed(deployed); if (svres.hasErrors()) { System.out.println("Intalled: " + fndver + " but could not update deployed.json. Repair the file before continuing.\nError: " + svres.getMessage()); return false; } System.out.println("Intalled: " + fndver); return true; }
From source file:com.yahoo.parsec.gradle.utils.FileUtils.java
/** * Un-TarZip a tgz file./*from www .j a v a 2 s .co m*/ * * @param resourcePath resource path * @param outputPath output path * @param overwrite overwrite flag * @throws IOException IOException */ public void unTarZip(String resourcePath, String outputPath, boolean overwrite) throws IOException { try (InputStream inputStream = getClass().getResourceAsStream(resourcePath); GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(inputStream); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream( gzipCompressorInputStream);) { TarArchiveEntry tarArchiveEntry; logger.info("Extracting tgz file to " + outputPath); while ((tarArchiveEntry = tarArchiveInputStream.getNextTarEntry()) != null) { final File outputFile = new File(outputPath, tarArchiveEntry.getName()); if (!overwrite && outputFile.exists()) { continue; } if (tarArchiveEntry.isDirectory()) { outputFile.mkdirs(); } else { Files.copy(tarArchiveInputStream, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } catch (IOException e) { throw e; } }
From source file:dialog.DialogFunctionUser.java
private void actionAddUser() { if (!isValidData()) { return;/* www .j av a2s . com*/ } if (isExistUsername(tfUsername.getText())) { JOptionPane.showMessageDialog(null, "Username tn ti", "Error", JOptionPane.ERROR_MESSAGE); return; } String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); int role = cbRole.getSelectedIndex(); User objUser; if (mAvatar != null) { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } } else { objUser = new User(UUID.randomUUID().toString(), username, password, fullname, role, new Date(System.currentTimeMillis()), ""); } if (mControllerUser.addItem(objUser)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Thm thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Thm tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } this.dispose(); }
From source file:it.greenvulcano.configuration.BaseConfigurationManager.java
@Override public void deploy(String name) throws XMLConfigException, FileNotFoundException { Path configurationArchivePath = getConfigurationPath(name); Path current = Paths.get(XMLConfig.getBaseConfigPath()); Path staging = current.getParent().resolve("deploy"); Path destination = current.getParent().resolve(name); if (LOCK.tryLock()) { if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) { try { ZipInputStream configurationArchive = new ZipInputStream( Files.newInputStream(configurationArchivePath, StandardOpenOption.READ)); LOG.debug("Starting deploy of configuration " + name); ZipEntry zipEntry = null; for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) { if (!Files.isDirectory(cfgFile)) { Path target = staging.resolve(current.relativize(cfgFile)); Files.createDirectories(target); Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING); }/*w w w.j a v a2s . c o m*/ } LOG.debug("Staging new config " + name); while ((zipEntry = configurationArchive.getNextEntry()) != null) { Path entryPath = staging.resolve(zipEntry.getName()); LOG.debug("Adding resource: " + entryPath); if (zipEntry.isDirectory()) { entryPath.toFile().mkdirs(); } else { Path parent = entryPath.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING); } } //**** Deleting old config dir LOG.debug("Removing old config: " + current); Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); LOG.debug("Deploy new config " + name + " in path " + destination); Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE); setXMLConfigBasePath(destination.toString()); LOG.debug("Deploy complete"); deployListeners.forEach(l -> l.onDeploy(destination)); } catch (Exception e) { if (Objects.nonNull(staging) && Files.exists(staging)) { LOG.error("Deploy failed, rollback to previous configuration", e); try { Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(java.nio.file.Path::toFile).forEach(File::delete); setXMLConfigBasePath(current.toString()); } catch (IOException | InvalidSyntaxException rollbackException) { LOG.error("Failed to delete old configuration", e); } } else { LOG.error("Deploy failed", e); } throw new XMLConfigException("Deploy failed", e); } finally { LOCK.unlock(); } } else { throw new FileNotFoundException(configurationArchivePath.toString()); } } else { throw new IllegalStateException("A deploy is already in progress"); } }
From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java
@Override public void move(DavResource dest) throws DavException { final Path src = ResourcePathUtils.getPhysicalPath(this); final Path dst = ResourcePathUtils.getPhysicalPath(dest); try {/* w ww. j av a 2s . c om*/ // check for conflicts: if (Files.exists(dst) && Files.getLastModifiedTime(dst).toMillis() > Files.getLastModifiedTime(src).toMillis()) { throw new DavException(DavServletResponse.SC_CONFLICT, "File at destination already exists: " + dst.toString()); } // move: try { Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { Files.move(src, dst, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { LOG.error("Error moving file from " + src.toString() + " to " + dst.toString()); throw new IORuntimeException(e); } }
From source file:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java
/** * Take custom screen shot./* w w w . j av a 2 s . co m*/ * @param fileNames the file names */ @Override public void takeCustomScreenShot(final String... fileNames) { try { smallWait(); final String dir = System.getProperty("user.dir"); final Path screenshot = ((TakesScreenshot) getDeviceDriver()).getScreenshotAs(OutputType.FILE).toPath(); smallWait(); final String folders = arrayToStringDelimited(fileNames, "/"); final Path screenShotDir = Paths.get(dir, "target", folders.indexOf('/') == -1 ? "" : folders.substring(0, folders.lastIndexOf('/'))); Files.createDirectories(screenShotDir); LOGGER.debug("screenShotDir: " + screenShotDir.toString() + "; folders: " + folders); final Path screenShotFile = Paths.get(dir, "target", folders + ".png"); Files.copy(screenshot, screenShotFile, StandardCopyOption.REPLACE_EXISTING); if (Files.exists(screenShotFile)) { LOGGER.info("Saved custom screenshot for " + fileNames + AT_STRING + screenShotFile); } else { LOGGER.info("Unable to save custom screenshot for " + fileNames + AT_STRING + screenShotFile); } } catch (WebDriverException | IOException e) { LOGGER.error("Error taking custom screenshot for " + fileNames, e); } }
From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java
@Override public void copy(UrlTreeMetaData<InputStream> metadata, String dstDir, UrlTreeContext ctx) throws BadContentException { String srcPathName = metadata.getAbsolutePath(); Path srcPath = this.generateFileObj(srcPathName); Path dstPath = this.generateFileObj(dstDir); logger.debug("copy: " + srcPath.toAbsolutePath() + " to " + dstPath.toAbsolutePath()); try {//from ww w . ja v a 2 s . c o m Files.copy(srcPath, dstPath.resolve(srcPath.getFileName()), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new GenericResourceException("cannot copy file", e); } }
From source file:org.apache.flink.runtime.security.SecurityContext.java
private static void populateSystemSecurityProperties(Configuration configuration) { Preconditions.checkNotNull(configuration, "The supplied configuation was null"); //required to be empty for Kafka but we will override the property //with pseudo JAAS configuration file if SASL auth is enabled for ZK System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, ""); boolean disableSaslClient = configuration.getBoolean(HighAvailabilityOptions.ZOOKEEPER_SASL_DISABLE); if (disableSaslClient) { LOG.info("SASL client auth for ZK will be disabled"); //SASL auth is disabled by default but will be enabled if specified in configuration System.setProperty(ZOOKEEPER_SASL_CLIENT, "false"); return;//ww w. jav a2 s.c om } // load Jaas config file to initialize SASL final File jaasConfFile; try { Path jaasConfPath = Files.createTempFile(JAAS_CONF_FILENAME, ""); InputStream jaasConfStream = SecurityContext.class.getClassLoader() .getResourceAsStream(JAAS_CONF_FILENAME); Files.copy(jaasConfStream, jaasConfPath, StandardCopyOption.REPLACE_EXISTING); jaasConfFile = jaasConfPath.toFile(); jaasConfFile.deleteOnExit(); jaasConfStream.close(); } catch (IOException e) { throw new RuntimeException( "SASL auth is enabled for ZK but unable to " + "locate pseudo Jaas config provided with Flink", e); } LOG.info("Enabling {} property with pseudo JAAS config file: {}", JAVA_SECURITY_AUTH_LOGIN_CONFIG, jaasConfFile.getAbsolutePath()); //ZK client module lookup the configuration to handle SASL. //https://github.com/sgroschupf/zkclient/blob/master/src/main/java/org/I0Itec/zkclient/ZkClient.java#L900 System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, jaasConfFile.getAbsolutePath()); System.setProperty(ZOOKEEPER_SASL_CLIENT, "true"); String zkSaslServiceName = configuration.getValue(HighAvailabilityOptions.ZOOKEEPER_SASL_SERVICE_NAME); if (!StringUtils.isBlank(zkSaslServiceName)) { LOG.info("ZK SASL service name: {} is provided in the configuration", zkSaslServiceName); System.setProperty(ZOOKEEPER_SASL_CLIENT_USERNAME, zkSaslServiceName); } }