List of usage examples for java.nio.file Files copy
public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
From source file:dialog.DialogFunctionUser.java
private void actionAddUser() { if (!isValidData()) { return;/* ww w .jav a 2 s .c o m*/ } 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); }//from w w w . ja v a 2 s .c om } 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:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java
/** * Take custom screen shot./* www . j ava 2s . c om*/ * @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:it.baeyens.arduino.managers.Manager.java
/** * This method takes a json boards file url and downloads it and parses it * for usage in the boards manager// w w w. j ava2 s . com * * @param url * the url of the file to download and load * @param forceDownload * set true if you want to download the file even if it is * already available locally */ static private void loadPackageIndex(String url, boolean forceDownload) { File packageFile = getLocalFileName(url); if (packageFile == null) { return; } if (!packageFile.exists() || forceDownload) { packageFile.getParentFile().mkdirs(); try { Files.copy(new URL(url.trim()).openStream(), packageFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { Common.log(new Status(IStatus.ERROR, Activator.getId(), "Unable to download " + url, e)); //$NON-NLS-1$ } } if (packageFile.exists()) { try (Reader reader = new FileReader(packageFile)) { PackageIndex index = new Gson().fromJson(reader, PackageIndex.class); index.setOwners(null); packageIndices.add(index); } catch (Exception e) { Common.log(new Status(IStatus.ERROR, Activator.getId(), "Unable to parse " + packageFile.getAbsolutePath(), e)); //$NON-NLS-1$ packageFile.delete();// Delete the file so it stops damaging } } }
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;//from www. j a v a 2 s. com } // 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); } }
From source file:org.virtualAsylum.spriggan.data.Addon.java
public State doInstall() { log("Installing %s (%s)", getDisplayName(), getID()); State result = State.IDLE; State error = State.ERROR; setState(State.INSTALLING);// w w w .ja v a 2s .c o m setStateProgress(-1); boolean didError = false; try { //<editor-fold desc="Dependencies"> Collection<String> dependencyIDs = getDependencies(); ArrayList<Addon> dependencies = new ArrayList(); if (dependencyIDs.size() > 0) { setState(State.INSTALLING_DEPENDENCIES); for (String dependencyIDString : dependencyIDs) { Addon dependency = Database.find_ID(dependencyIDString); if (dependency == null) { throw new Exception(String.format("Dependency %s was missing for %s(%s)", dependencyIDString, getDisplayName(), getID())); } if (!dependency.getInstalled()) { dependencies.add(dependency); } } if (dependencies.size() > 0) { SimpleObjectProperty<Boolean> popupResult = new SimpleObjectProperty(null); runLater(() -> { DependencyPopup popup = new DependencyPopup(this, dependencies, popupResult); Stage stage = popup.popup(StageStyle.UTILITY, Modality.WINDOW_MODAL, MainInterface.current.getWindow(), getDisplayName()); stage.setOnCloseRequest(e -> popupResult.set(false)); stage.show(); }); while (popupResult.get() == null) { sleep(500); } if (!popupResult.get()) { error = State.IDLE; throw new Exception(String.format("Did not install dependencies for %s (%s)", getDisplayName(), getID())); } double perDep = 1.0 / dependencies.size(); setStateProgress(0.0); for (Addon dependency : dependencies) { boolean downloaded = Database.getCurrent().getRepository().contains(dependency); State depResult = State.IDLE; if (!downloaded) { depResult = dependency.doDownloadAndInstall(); } else if (!dependency.getInstalled()) { depResult = dependency.doInstall(); } if (depResult != State.IDLE) { throw new Exception( String.format("Dependency %s (%s) failed to download and/or install", dependency.getDisplayName(), dependency.getID())); } incrementStateProgress(perDep); } setState(State.INSTALLING); } } //</editor-fold> error = State.ERROR; final File repositoryDirectory = getRepositoryDirectory(this); final File installDirectory = getInstallDirectory(this); ArrayList<File> files = getRepositoryFiles(); double perFile = 1.0 / files.size(); setStateProgress(0.0); for (File inputFile : files) { File outputFile = new File(installDirectory, repositoryDirectory.toPath().relativize(inputFile.toPath()).toString()); outputFile.getParentFile().mkdirs(); Files.copy(inputFile.toPath(), outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); incrementStateProgress(perFile); } } catch (Exception ex) { if (error == State.ERROR) { handleException(ex); } result = error; didError = true; } if (!didError) { setInstalled(true); } log("Installing %s (%s): %s", getDisplayName(), getID(), result); setStateProgress(0); setState(result); return result; }
From source file:org.apache.lens.regression.util.Util.java
public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception { Path p = Paths.get(remotePath); String fileName = p.getFileName().toString(); backupFile = localFilePath + "backup-" + fileName; localFile = localFilePath + fileName; log.info("Copying " + remotePath + " to " + localFile); remoteFile("get", remotePath, localFile); Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(new FileInputStream(localFile)); doc.normalize();/*from w ww . j av a 2 s . c o m*/ NodeList rootNodes = doc.getElementsByTagName("configuration"); Node root = rootNodes.item(0); Element rootElement = (Element) root; NodeList property = rootElement.getElementsByTagName("property"); for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document Node prop = property.item(i); Element propElement = (Element) prop; Node propChild = propElement.getElementsByTagName("name").item(0); Element nameElement = (Element) propChild; if (map.containsKey(nameElement.getTextContent())) { rootElement.removeChild(prop); i--; } } Iterator<Entry<String, String>> ab = map.entrySet().iterator(); while (ab.hasNext()) { Entry<String, String> entry = ab.next(); String propertyName = entry.getKey(); String propertyValue = entry.getValue(); System.out.println(propertyName + " " + propertyValue + "\n"); Node newNode = doc.createElement("property"); rootElement.appendChild(newNode); Node newName = doc.createElement("name"); Element newNodeElement = (Element) newNode; newName.setTextContent(propertyName); newNodeElement.appendChild(newName); Node newValue = doc.createElement("value"); newValue.setTextContent(propertyValue); newNodeElement.appendChild(newValue); } prettyPrint(doc); remoteFile("put", remotePath, localFile); }
From source file:org.jboss.as.test.clustering.modcluster.WorkerFailoverTestCase.java
private void workerSetup(String cliAddress, int port) throws Exception { try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(null, TestSuiteEnvironment.getServerAddress(cliAddress), port)) { /* Configuration backup */ ModelNode op = createOpNode("path=jboss.server.config.dir", "read-attribute"); op.get("name").set("path"); ModelNode response = client.execute(op); Assert.assertEquals("Workers's configuration file not found!\n" + response.toString(), SUCCESS, response.get("outcome").asString()); String workerConfigFile = response.get("result").asString() + File.separator + System.getProperty("jboss.server.config.file.standalone-ha", "/standalone-ha.xml"); Files.copy(Paths.get(workerConfigFile), Paths.get(workerConfigFile + ".WorkerFailoverTestCase.backup"), REPLACE_EXISTING);/* www .j a va 2s. c o m*/ if (port == 10090) worker1ConfigFile = workerConfigFile; else worker2ConfigFile = workerConfigFile; /* Server configuration */ op = createOpNode("subsystem=modcluster/mod-cluster-config=configuration/", "write-attribute"); op.get("name").set("advertise"); op.get("value").set("false"); response = client.execute(op); Assert.assertEquals("Worker's configuration failed!\n" + response.toString(), SUCCESS, response.get("outcome").asString()); op = createOpNode( "socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=proxy1", "add"); op.get("host").set(TestSuiteEnvironment.getServerAddress("node0")); op.get("port").set("8080"); response = client.execute(op); Assert.assertEquals("Worker's configuration failed!\n" + response.toString(), SUCCESS, response.get("outcome").asString()); op = createOpNode("subsystem=modcluster/mod-cluster-config=configuration", "list-add"); op.get("name").set("proxies"); op.get("value").set("proxy1"); response = client.execute(op); Assert.assertEquals("Worker's configuration failed!\n" + response.toString(), SUCCESS, response.get("outcome").asString()); op = createOpNode("subsystem=modcluster/mod-cluster-config=configuration", "write-attribute"); op.get("name").set("status-interval"); op.get("value").set("1"); response = client.execute(op); Assert.assertEquals("Worker's configuration failed!\n" + response.toString(), SUCCESS, response.get("outcome").asString()); ServerReload.executeReloadAndWaitForCompletion(client, ServerReload.TIMEOUT, false, TestSuiteEnvironment.getServerAddress(cliAddress), port); } }
From source file:com.bc.fiduceo.TestUtil.java
public static File copyFileDir(File sourceFile, File targetDirectory) throws IOException { assertTrue(sourceFile.isFile());/*from w ww . ja v a2 s .co m*/ final String name = sourceFile.getName(); final File targetFile = new File(targetDirectory, name); targetFile.createNewFile(); Files.copy(sourceFile.toPath(), targetFile.toPath(), REPLACE_EXISTING); assertTrue(targetFile.isFile()); return targetFile; }
From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java
public Path copyBundle(final Path extractedGitBundle, final Map<String, String> metadata) throws IOException { final Path bundleDestination = buildBundleDestination(metadata); LOGGER.debug("Copying received bundle from temporary location " + extractedGitBundle + " to " + bundleDestination);//from w w w . j a v a2 s . c om if (Files.exists(bundleDestination)) { Files.copy(extractedGitBundle, bundleDestination, StandardCopyOption.REPLACE_EXISTING); } else { Files.createDirectories(bundleDestination.getParent()); Files.copy(extractedGitBundle, bundleDestination); } registerCreatedFile(extractedGitBundle.toFile()); registerCreatedFile(bundleDestination.toFile()); return bundleDestination; }