List of usage examples for org.apache.commons.io FileUtils copyDirectory
public static void copyDirectory(File srcDir, File destDir) throws IOException
From source file:mecha.db.SolrManager.java
private synchronized void createCore(String coreName, String corePath, File corePathFile) throws Exception { log.info("createCore(" + coreName + ", " + corePathFile + ")"); corePathFile.mkdirs();//w ww . j av a 2 s. c o m File source = new File("./solr/_p/conf"); FileUtils.copyDirectory(source, corePathFile); String solrConfigStr = TextFile.get(corePath + "/solrconfig.xml.template"); String solrCoreDataDir = Mecha.getConfig().getString("solr-data-dir") + "/core/" + coreName; solrConfigStr = solrConfigStr.replaceAll("<<mecha:data-dir>>", solrCoreDataDir); TextFile.put(corePath + "/solrconfig.xml", solrConfigStr); log.info("solrconfig.xml written"); }
From source file:gr.auth.ee.lcs.evaluators.FileLogger.java
/** * A FileLogger constructor to set the directory in which the metrics are stored for all FileLoggers * and copy a backup of the src directory for debugging purposes * //from ww w.java2 s .c o m * * @author alexandros filotheou * * */ public FileLogger(final AbstractLearningClassifierSystem lcs) { file = null; actualEvaluator = null; final Calendar cal = Calendar.getInstance(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd 'at' kk.mm.ss"); String timestamp = sdf.format(cal.getTime()); // make directory hookedMetrics/{simpleDateFormat} File dir = new File("hookedMetrics/" + timestamp); System.out.println(dir.toString()); if (!dir.exists()) { dir.mkdirs(); } storeDirectory = "hookedMetrics/" + timestamp; dir = new File(storeDirectory + "/evals"); if (!dir.exists()) { dir.mkdirs(); } // set the name of the directory in which the metrics will be stored if (lcs.hookedMetricsFileDirectory == null) lcs.setHookedMetricsFileDirectory(storeDirectory); try { // keep a copy of thedefaultLcs.properties configuration File getConfigurationFile = new File(storeDirectory, "defaultLcs.properties"); if (!getConfigurationFile.exists()) { FileInputStream in = new FileInputStream("defaultLcs.properties"); FileOutputStream out = new FileOutputStream(storeDirectory + "/defaultLcs.properties"); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } catch (Exception e) { e.printStackTrace(); } // copy the /src directory into storeDirectory String sourceDir = "src"; File srcDir = new File(sourceDir); String destinationDir = storeDirectory + "/src"; File destDir = new File(destinationDir); if (!destDir.exists()) destDir.mkdir(); try { FileUtils.copyDirectory(srcDir, destDir); } catch (Exception e) { e.printStackTrace(); } try { // record fitness mode, deletion mode and whether # participate in the correct sets in the file essentialSettings.txt final FileWriter fstream = new FileWriter(storeDirectory + "/essentialSettings.txt", true); final BufferedWriter buffer = new BufferedWriter(fstream); int fitness_mode = (int) SettingsLoader.getNumericSetting("FITNESS_MODE", 0); int deletion_mode = (int) SettingsLoader.getNumericSetting("DELETION_MODE", 0); boolean wildCardsParticipateInCorrectSets = String .valueOf(SettingsLoader.getStringSetting("wildCardsParticipateInCorrectSets", "true")) .equals("true"); boolean initializePopulation = String .valueOf(SettingsLoader.getStringSetting("initializePopulation", "true")).equals("true"); buffer.write("fitness mode: " + fitness_mode + System.getProperty("line.separator") + "deletion mode: " + deletion_mode + System.getProperty("line.separator") + "# in correct sets :" + wildCardsParticipateInCorrectSets + System.getProperty("line.separator") + (wildCardsParticipateInCorrectSets ? "balance correct sets: " + String.valueOf( SettingsLoader.getStringSetting("balanceCorrectSets", "true").equals("true")) + (String.valueOf( SettingsLoader.getStringSetting("balanceCorrectSets", "true").equals("true") ? ", with ratio: " + SettingsLoader .getNumericSetting("wildCardParticipationRatio", 0) : "")) : "" + System.getProperty("line.separator") + (initializePopulation ? "population initialized via clustering: " + initializePopulation : "") + System.getProperty("line.separator"))); buffer.flush(); buffer.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:alluxio.server.ft.BackwardsCompatibilityIntegrationTest.java
@Test public void readOldJournals() throws Exception { Assume.assumeTrue("Journals must be replayed by the same user that generated them, so this " + "test must be run as root", LoginUser.get().getName().equals("root")); // Starts a cluster from each old journal, and checks that all operation checks pass. List<Journal> journals = Arrays .asList(new File(BackwardsCompatibilityJournalGenerator.OLD_JOURNALS_RESOURCE).listFiles()).stream() .map(f -> Journal.parse(f.getAbsolutePath())).filter(Optional::isPresent).map(o -> o.get()) .collect(Collectors.toList()); for (Journal journal : journals) { System.out.printf("Checking journal %s\n", journal.getDir()); LOG.info("Checking journal %s\n", journal.getDir()); Builder builder = MultiProcessCluster.newBuilder(PortCoordination.BACKWARDS_COMPATIBILITY) .setClusterName("BackwardsCompatibility").setNumMasters(1).setNumWorkers(1); if (journal.isBackup()) { builder.addProperty(PropertyKey.MASTER_JOURNAL_INIT_FROM_BACKUP, journal.getDir()); } else {//from w w w . ja v a 2s . c om File journalDir = AlluxioTestDirectory.createTemporaryDirectory("backwardsCompatibility-journal"); FileUtils.copyDirectory(new File(journal.getDir()), new File(journalDir.getAbsolutePath())); builder.setNoFormat(true); builder.addProperty(PropertyKey.MASTER_JOURNAL_FOLDER, journalDir.getAbsolutePath()); } mCluster = builder.build(); try { mCluster.start(); mCluster.waitForAllNodesRegistered(30 * Constants.SECOND_MS); Clients clients = mCluster.getClients(); for (TestOp op : BackwardsCompatibilityJournalGenerator.OPS) { if (op.supportsVersion(journal.getVersion())) { op.check(clients); } } } finally { mCluster.destroy(); } } }
From source file:com.spotify.helios.ZooKeeperStandaloneServerManager.java
public void backup(final Path destination) { try {//w w w . j a v a2 s .co m FileUtils.copyDirectory(dataDir, destination.toFile()); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:azkaban.execapp.FlowRunnerTestUtil.java
public static ExecutableFlow prepareExecDir(final File workingDir, final File execDir, final String flowName, final int execId) throws IOException { FileUtils.copyDirectory(execDir, workingDir); final File jsonFlowFile = new File(workingDir, flowName + ".flow"); final Object flowObj = JSONUtils.parseJSONFromFile(jsonFlowFile); final Project project = new Project(1, "test"); final Flow flow = Flow.flowFromObject(flowObj); final ExecutableFlow execFlow = new ExecutableFlow(project, flow); execFlow.setExecutionId(execId);/*from w w w . j a v a 2 s.c o m*/ execFlow.setExecutionPath(workingDir.getPath()); return execFlow; }
From source file:com.uwsoft.editor.data.manager.SceneDataManager.java
public void buildScenes(String targetPath) { String srcPath = dataManager.getCurrentWorkingPath() + "/" + dataManager.currentProjectVO.projectName + "/scenes"; FileHandle scenesDirectoryHandle = Gdx.files.absolute(srcPath); File fileTarget = new File(targetPath + "/" + scenesDirectoryHandle.name()); try {/*from w ww . ja v a 2 s . c om*/ FileUtils.copyDirectory(scenesDirectoryHandle.file(), fileTarget); } catch (IOException e) { e.printStackTrace(); } //copy project dt try { FileUtils .copyFile( new File(dataManager.getCurrentWorkingPath() + "/" + dataManager.currentProjectVO.projectName + "/project.dt"), new File(targetPath + "/project.dt")); } catch (IOException e) { e.printStackTrace(); } }
From source file:launcher.workflow.update.UpdateWorkflow.java
public static void begin(final Settings launcherCfg, final String license) { WorkflowStep prepare = new WorkflowStep("Preparing to launch the game", new WorkflowAction() { @Override// w ww.j av a2 s. co m public boolean act() { return true; } }); WorkflowStep checkLicense = new WorkflowStep("Checking to see if a license has been entered.", new WorkflowAction() { @Override public boolean act() throws Exception { if (license == null || license.isEmpty()) { LaunchLogger.error(LaunchLogger.Tab + "No valid license found."); return false; } WorkflowWindowManager.setProgressVisible(true); URL licenseCheckUrl = new URL(launcherCfg.licenseCall(license)); String response = IOUtils.toString(licenseCheckUrl.openStream()); WorkflowWindowManager.setProgressVisible(false); if (response.contains("true")) { LaunchLogger.info(LaunchLogger.Tab + "License is valid."); return true; } else { if (License.isCached()) { LaunchLogger .info("Invalid license was found. Deleting the locally cached license."); License.deleteCache(); return false; } } return false; } }); WorkflowStep checkVersion = new WorkflowStep("Checking for updates.", new WorkflowAction() { @Override public boolean act() throws Exception { File versionPath = new File("assets/data/version.dat"); String myVersion = "0.0.0"; if (versionPath.exists()) { myVersion = FileUtils.readFileToString(versionPath); LaunchLogger.info("Detected version: " + myVersion); } WorkflowWindowManager.setProgressVisible(true); URL versionCheckUrl = new URL(launcherCfg.versionCall(myVersion)); String result = IOUtils.toString(versionCheckUrl.openStream()); WorkflowWindowManager.setProgressVisible(false); if (result.contains("true")) { LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is out of date."); return true; } LaunchLogger.info(LaunchLogger.Tab + "Local copy of the game is up to date. No update required."); return false; } }); WorkflowStep downloadUpdate = new WorkflowStep("Preparing the update location", new WorkflowAction() { @Override public boolean act() throws Exception { if (UpdateWorkflowData.UpdateArchive.exists()) { FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive); } int responseTimeoutMs = launcherCfg.responseTimeoutMilliseconds; int downloadTimeoutMs = launcherCfg.downloadTimeoutMilliseconds; LaunchLogger.info("Attempting to download an update using license: [" + license + "]"); WorkflowWindowManager.setProgressVisible(true); String downloadUrl = launcherCfg.downloadCall(license, "update"); LaunchLogger.info("Downloading latest stable edition"); FileUtils.copyURLToFile(new URL(downloadUrl), UpdateWorkflowData.UpdateArchive, responseTimeoutMs, downloadTimeoutMs); WorkflowWindowManager.setProgressVisible(false); LaunchLogger.info(LaunchLogger.Tab + "Update downloaded successfully."); return true; } }); WorkflowStep applyUpdate = new WorkflowStep("Unpacking update archive", new WorkflowAction() { @Override public boolean act() throws IOException { WorkflowWindowManager.setProgressVisible(true); Archive.unzip(UpdateWorkflowData.UpdateArchive, UpdateWorkflowData.UpdateWorkingDirectory); LaunchLogger.info("Replacing old content"); File game = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/game.jar"); File gameTarget = new File("./"); LaunchLogger.info("Attempting to copy: " + game + " to " + gameTarget); FileUtils.copyFileToDirectory(game, gameTarget); File assets = new File(UpdateWorkflowData.UpdateWorkingDirectory + "/assets"); File assetsTarget = new File("./assets"); LaunchLogger.info("Attempting to copy: " + assets + " to " + assetsTarget); FileUtils.copyDirectory(assets, assetsTarget); WorkflowWindowManager.setProgressVisible(false); LaunchLogger.info(LaunchLogger.Tab + "Update applied successfully."); return true; } }); WorkflowStep clean = new WorkflowStep("Cleaning up temporary files", new WorkflowAction() { @Override public boolean act() throws IOException { if (UpdateWorkflowData.UpdateArchive.exists()) { FileUtils.forceDelete(UpdateWorkflowData.UpdateArchive); } if (UpdateWorkflowData.UpdateWorkingDirectory.exists()) { FileUtils.deleteDirectory(UpdateWorkflowData.UpdateWorkingDirectory); } return true; } }); prepare.setOnSuccess(checkLicense); checkLicense.setOnSuccess(checkVersion); checkVersion.setOnSuccess(downloadUpdate); downloadUpdate.setOnSuccess(applyUpdate); applyUpdate.setOnSuccess(clean); prepare.setOnFailure(clean); checkLicense.setOnFailure(clean); checkVersion.setOnFailure(clean); downloadUpdate.setOnFailure(clean); applyUpdate.setOnFailure(clean); prepare.execute(); }
From source file:ezbake.frack.submitter.SubmitterService.java
@Override public SubmitResult submit(ByteBuffer zip, String pipelineId) throws TException { File unzippedPack = null;//from w w w . ja va2s . c o m try { // Unzip the provided pack unzippedPack = UnzipUtil.unzip(new File("/tmp"), zip); // Find the jar path Optional<String> jarPath = UnzipUtil.getJarPath(unzippedPack); if (!jarPath.isPresent()) { return new SubmitResult(false, "Could not find jar file. Make sure to place jar file in zip within bin/ directory"); } final File jarFile = new File(jarPath.get()); // Get the builder class Optional<String> builderClass = ClasspathUtil.findClassInJar(jarFile); if (!builderClass.isPresent()) { log.error("Could not find PipelineBuilder implementation in {}", jarFile.getName()); return new SubmitResult(false, "Could not find PipelineBuilder implementation in jar: " + jarFile.getName()); } log.debug("Building pipeline with builder class {}", builderClass.get()); SubmitterConfiguration config = new SubmitterConfiguration().setIngestSystem("Storm") .setBuilderClass(builderClass.get()).setPipelineId(pipelineId).setProduction(!insecure); Optional<String> confPath = UnzipUtil.getConfDirectory(unzippedPack); List<File> newFiles = Lists.newArrayList(); if (confPath.isPresent()) { config.setUserPropertiesFolder(confPath.get()); File confDir = new File(confPath.get()); File stagingDir = new File(unzippedPack, "staging"); stagingDir.mkdir(); File newPropertiesDir = new File(stagingDir, "frack_properties"); FileUtils.copyDirectory(confDir, newPropertiesDir); newFiles.add(newPropertiesDir); Optional<String> sslPath = UnzipUtil.getSSLPath(confDir); if (sslPath.isPresent()) { File sslDir = new File(sslPath.get()); config.setSslDir(sslDir.getAbsoluteFile().getAbsolutePath()); File newSSLDir = new File(stagingDir, "ssl"); FileUtils.copyDirectory(sslDir, newSSLDir); newFiles.add(newSSLDir); } else { log.warn("No SSL directory found for {}, needed for using Thrift services", jarFile.getName()); } File keyDir = UnzipUtil.findSubDir(unzippedPack, "keys"); if (keyDir != null && keyDir.exists()) { File newKeyDir = new File(stagingDir, "keys"); FileUtils.copyDirectory(keyDir, newKeyDir); newFiles.add(newKeyDir); } else { log.warn("No Keys directory found for {}, needed for broadcasting", jarFile.getName()); } } else { log.warn("No configuration directory found for {}", jarFile.getName()); } // Create the repackaged jar log.info("Repackaging jar with configuration information"); File newJar = JarUtil.addFilesToJar(jarFile, newFiles); config.setPathToJar(newJar.getAbsolutePath()); log.debug("Sending information to PipelineSubmitter"); SubmitResult result = PipelineSubmitter.submit(config); log.info("Submission result: {}", result.getMessage()); return result; } catch (IOException e) { String message = "Could not unzip provided build pack binary"; log.error(message, e); throw new TException(message, e); } catch (InterruptedException e) { String message = "Interrupted exception occurred when submitting pipeline"; log.error(message, e); throw new TException(message, e); } catch (ClassNotFoundException e) { String message = "PipelineBuilder class not found when interrogating jar file"; log.error(message, e); throw new TException(message, e); } finally { if (unzippedPack != null && unzippedPack.exists()) { try { FileUtils.deleteDirectory(unzippedPack); } catch (IOException e) { throw new TException("Could not delete unzipped buildpack directory", e); } } } }
From source file:net.ftb.workers.RetiredPacksLoaderTest.java
@Test public void realSetting() throws Exception { temporaryFolder = tf.newFolder();/*from ww w . java 2 s. com*/ FileUtils.copyDirectory(sourceFolder, temporaryFolder); loader = new RetiredPacksLoader(json.toURL(), temporaryFolder.getAbsolutePath(), temporaryFolder.getAbsolutePath()); //******************************************* // fully mock Settings and ModPack classes with failing default answers //******************************************* //Settings mockedSettings = Mockito.mock(Settings.class, new RuntimeExceptionAnswer()); Settings mockedSettings_real = new Settings(new File(temporaryFolder, "not_exists")); Settings mockedSettings = Mockito.spy(mockedSettings_real); PowerMockito.mockStatic(Settings.class, new RuntimeExceptionAnswer()); //not needed (yet) ModPack mockedModPack = Mockito.mock(ModPack.class, new RuntimeExceptionAnswer()); PowerMockito.mockStatic(ModPack.class, new RuntimeExceptionAnswer()); // mock singleton getter to return mocked instance of the Settings class // doReturn/doNothing/... is required instead of when() because we are re-stubbing methods PowerMockito.doReturn(mockedSettings).when(Settings.class, "getSettings"); // ******************************************* // mock functions which are called from CUT... // // TODO: * Write external classes for default mocking of Settings/Modpack/CommandLineArguments default mocking with sane default values // * Move common stubs in @Setup // * Add tests: e.g. return some pack code for Settings.getSettings().getPrivatePacks() // ******************************************* //Mockito.doReturn(new ArrayList<String>()).when(mockedSettings).getPrivatePacks(); PowerMockito.doNothing().when(ModPack.class, "loadXml", anyString()); //Mockito.doNothing().when(mockedSettings).addPrivatePack(anyString()); Mockito.doNothing().when(mockedSettings).save(); // run the "thread" loader.run(); // check if stubbed methods were called // TODO: check that functions are not called with other arguments PowerMockito.verifyStatic(); ModPack.loadXml("RPGImmersion.xml"); Mockito.verify(mockedSettings).addPrivatePack("RPGImmersion"); Mockito.verify(mockedSettings).save(); }
From source file:com.orange.ocara.model.export.docx.DocxWriterTest.java
@Test public void export_Should_Succeed() throws DocxWriterException, IOException { // Given//w w w.j av a2s .c o m DocxWriter writer = buildDocxWriter(); FileUtils.copyDirectory(new File("src/main/assets/export/docx"), workingDirectory); // When writer.export(); // Then Assertions.assertThat(isZipFile(exportFile)).isTrue(); }