Example usage for org.apache.commons.io FileUtils copyFile

List of usage examples for org.apache.commons.io FileUtils copyFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils copyFile.

Prototype

public static void copyFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Copies a file to a new location preserving the file date.

Usage

From source file:mx.itesm.imb.handlers.RooHandler.java

@SuppressWarnings("unchecked")
public Object execute(final ExecutionEvent event) throws ExecutionException {
    File rooFile;/*from w w w .  j  a  v  a  2 s  .c o m*/
    File ecoreFile;
    IProject project;
    File installRooFile;
    Map<String, File> rooFiles;
    List<File> installRooFiles;
    List<EPackage> ecorePackages;
    MessageConsoleStream consoleStream;

    consoleStream = this.getConsoleStream();
    ecorePackages = (List<EPackage>) Util.getSelectedItems(event);

    // Generate the IMB artifacts for the selected Ecore packages
    this.clearConsole();
    for (EPackage ecorePackage : ecorePackages) {
        try {
            ecoreFile = Util.getEcoreFile(ecorePackage);

            // Roo and Bus scripts
            consoleStream.println("Generating roo scripts for package: " + ecorePackage.getName() + "...");
            rooFiles = Util.executeAtlQueries(this, ecoreFile, consoleStream);

            // Generate a new project for each roo script
            installRooFiles = new ArrayList<File>(rooFiles.size());
            for (String script : rooFiles.keySet()) {
                rooFile = rooFiles.get(script);
                project = Util.createProject(ecoreFile.getName().replace(".ecore", "." + script));
                installRooFile = new File(project.getLocation().toFile(), rooFile.getName());

                installRooFiles.add(installRooFile);
                FileUtils.copyFile(rooFile, installRooFile);
                rooFile.delete();
            }
        } catch (Exception e) {
            consoleStream
                    .println("The Ecore package could not be successfully transformed to a Spring Roo script");
            e.printStackTrace(new PrintStream(consoleStream));
        }
    }

    return null;
}

From source file:net.fabricmc.loom.task.ProcessModsTask.java

@TaskAction
public void mix() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {
    LoomGradleExtension extension = this.getProject().getExtensions().getByType(LoomGradleExtension.class);
    Configuration configuration = getProject().getConfigurations().getByName(Constants.COMPILE_MODS);
    List<File> mods = new ArrayList<>();
    for (ResolvedArtifact artifact : configuration.getResolvedConfiguration().getResolvedArtifacts()) {
        getProject().getLogger().lifecycle(":found mod to mix:" + artifact.getFile().getName());
        mods.add(artifact.getFile());/*  w  w w . j a  v a 2s . com*/
    }
    if (Constants.MINECRAFT_FINAL_JAR.get(extension).exists()) {
        Constants.MINECRAFT_FINAL_JAR.get(extension).delete();
    }
    if (mods.size() == 0) {
        FileUtils.copyFile(Constants.MINECRAFT_MAPPED_JAR.get(extension),
                Constants.MINECRAFT_FINAL_JAR.get(extension));
    } else {
        downloadRequiredDeps(extension);
        new PreBakeMixins().proccess(getProject(), extension, mods);
    }
}

From source file:kaljurand_at_gmail_dot_com.diktofon.MyFileUtils.java

public static File copyFileToRecordingsDir(File file) throws IOException {
    String ext = getExtension(file.getName());
    String newFileName = String.valueOf(System.currentTimeMillis()) + ext;
    String newPath = Dirs.getRecordingsDir().getAbsolutePath() + "/" + newFileName;
    File newFile = new File(newPath);
    if (newFile.exists()) {
        throw new IOException("Not overwriting existing file: " + newFileName);
    }/*from  ww w.j ava 2  s. c  om*/
    FileUtils.copyFile(file, newFile);
    return newFile;
}

From source file:com.mscorp.automation.seleniumCoreUtils.TakeScreenshot.java

public void takeScreenshot() {
    screenshotPath = (getProperty("screenshot-path") != null) ? getProperty("screenshot-path") : screenshotPath;
    DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_a");
    Date date = new Date();
    String date_time = dateFormat.format(date);
    File file = new File(System.getProperty("user.dir") + File.separator + screenshotPath + File.separator
            + this.testname + File.separator + date_time);
    boolean exists = file.exists();
    if (!exists) {
        new File(System.getProperty("user.dir") + File.separator + screenshotPath + File.separator
                + this.testname + File.separator + date_time).mkdir();
    }/*  ww w . j  a v a2 s  . com*/

    File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    try {
        String saveImgFile = System.getProperty("user.dir") + File.separator + screenshotPath + File.separator
                + this.testname + File.separator + date_time + File.separator + "screenshot.png";
        System.out.println("Save Image File Path : " + saveImgFile);
        FileUtils.copyFile(scrFile, new File(saveImgFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:co.cask.hydrator.plugin.RunTest.java

@Test
public void testRunWithJarInput() throws Exception {
    String inputTable = "run-jar-input";
    URL testRunnerUrl = this.getClass().getResource("/SampleRunner.jar");
    FileUtils.copyFile(new File(testRunnerUrl.getFile()), new File(sourceFolder, "/SampleRunner.jar"));

    ETLStage source = new ETLStage("source", MockSource.getPlugin(inputTable, INPUT));

    Map<String, String> runProperties = new ImmutableMap.Builder<String, String>()
            .put("commandToExecute", "java -jar " + sourceFolder.toPath() + "/SampleRunner.jar")
            .put("fieldsToProcess", "input").put("fixedInputs", "CASK").put("outputField", "output")
            .put("outputFieldType", "string").build();

    ETLStage transform = new ETLStage("transform",
            new ETLPlugin("Run", Transform.PLUGIN_TYPE, runProperties, null));

    String sinkTable = "run-jar-output";

    ETLStage sink = new ETLStage("sink", MockSink.getPlugin(sinkTable));
    ETLBatchConfig etlConfig = ETLBatchConfig.builder("* * * * *").addStage(source).addStage(transform)
            .addStage(sink).addConnection(source.getName(), transform.getName())
            .addConnection(transform.getName(), sink.getName()).build();

    AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(ETLBATCH_ARTIFACT, etlConfig);
    ApplicationId appId = NamespaceId.DEFAULT.app("RunJarTest");
    ApplicationManager appManager = deployApplication(appId.toId(), appRequest);

    DataSetManager<Table> inputManager = getDataset(inputTable);
    List<StructuredRecord> input = ImmutableList.of(
            StructuredRecord.builder(INPUT).set("id", 1).set("input", "Brett").build(),
            StructuredRecord.builder(INPUT).set("id", 2).set("input", "Chang").build(),
            StructuredRecord.builder(INPUT).set("id", 3).set("input", "Roy").build(),
            StructuredRecord.builder(INPUT).set("id", 4).set("input", "John").build(),
            StructuredRecord.builder(INPUT).set("id", 5).set("input", "Michael").build());

    MockSource.writeInput(inputManager, input);
    MapReduceManager mrManager = appManager.getMapReduceManager(ETLMapReduce.NAME);
    mrManager.start();/*from w  w w .  ja  v a 2 s.c  o m*/
    mrManager.waitForFinish(5, TimeUnit.MINUTES);

    DataSetManager<Table> outputManager = getDataset(sinkTable);
    List<StructuredRecord> outputRecords = MockSink.readOutput(outputManager);

    Assert.assertEquals("OutputRecords", 5, outputRecords.size());
    for (StructuredRecord record : outputRecords) {
        int value = (record.get("id"));
        if (value == 1) {
            Assert.assertEquals("Brett", record.get("input"));
            Assert.assertEquals("Hello Brett...Welcome to the CASK!!!", record.get("output"));
        } else if (value == 2) {
            Assert.assertEquals("Chang", record.get("input"));
            Assert.assertEquals("Hello Chang...Welcome to the CASK!!!", record.get("output"));
        } else if (value == 3) {
            Assert.assertEquals("Roy", record.get("input"));
            Assert.assertEquals("Hello Roy...Welcome to the CASK!!!", record.get("output"));
        } else if (value == 4) {
            Assert.assertEquals("John", record.get("input"));
            Assert.assertEquals("Hello John...Welcome to the CASK!!!", record.get("output"));
        } else {
            Assert.assertEquals("Michael", record.get("input"));
            Assert.assertEquals("Hello Michael...Welcome to the CASK!!!", record.get("output"));
        }
    }
}

From source file:ZipUtilInPlaceTest.java

public void testRemoveDirs() throws IOException {
    File src = new File(getClass().getResource("demo-dirs.zip").getPath());

    File dest = File.createTempFile("temp", null);
    try {//  w ww.  ja v a  2 s .c om
        FileUtils.copyFile(src, dest);

        ZipUtil.removeEntries(dest, new String[] { "bar.txt", "a/b" });

        assertFalse("Result zip still contains 'bar.txt'", ZipUtil.containsEntry(dest, "bar.txt"));
        assertFalse("Result zip still contains dir 'a/b'", ZipUtil.containsEntry(dest, "a/b"));
        assertTrue("Result doesn't containt 'attic'", ZipUtil.containsEntry(dest, "attic/treasure.txt"));
        assertTrue("Entry whose prefix is dir name is removed too: 'b.txt'",
                ZipUtil.containsEntry(dest, "a/b.txt"));
        assertFalse("Entry in a removed dir is still there: 'a/b/c.txt'",
                ZipUtil.containsEntry(dest, "a/b/c.txt"));
    } finally {
        FileUtils.deleteQuietly(dest);
    }
}

From source file:Cursling.deleteMonitor.java

public String _deleteMonitor(String monitor_name) {
    isdeleted = false;//from ww  w  .j av a2s  .  c om
    try {
        File inFile = new File(input_file_del);

        if (!inFile.isFile()) {
            logger.info("Failed to Delete. Data file not found.");
            return ("failed");
        }
        storeUpdate = new File(input_file_del);
        File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
        BufferedReader br = new BufferedReader(new FileReader(input_file_del));
        PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
        String line = null;

        while ((line = br.readLine()) != null) {
            if (!line.equalsIgnoreCase("")) {
                String tmp_linee = line.replaceAll("\\\\", "");
                if (tmp_linee.startsWith(monitor_name + " = ht")
                        || tmp_linee.startsWith(monitor_name + "=ht")) {
                    isdeleted = true;
                    pw.flush();
                } else if (tmp_linee.startsWith(monitor_name.toLowerCase() + " = ena")
                        || tmp_linee.startsWith(monitor_name.toLowerCase() + " = dis")
                        || tmp_linee.startsWith(monitor_name.toLowerCase() + "=ena")
                        || tmp_linee.startsWith(monitor_name.toLowerCase() + "=dis")) {
                    isdeleted = true;
                    pw.flush();
                } else {
                    pw.println(line);
                    pw.flush();
                }

            } else {
            }
        }

        pw.close();
        br.close();

        //Rename the new file to the filename the original file had.
        if (tempFile.canRead()) {
            Long before = storeUpdate.lastModified();
            FileUtils.copyFile(tempFile, storeUpdate);
            Long after = storeUpdate.lastModified();
            if (before.equals(after)) {
                logger.info("failed to delete Monitor " + monitor_name);
                return ("failed");
            } else if (isdeleted == true && deleteOutput(monitor_name) == true) {
                logger.info("Monitor " + monitor_name + " Deleted.");
                return ("deleted");
            } else if (isdeleted == true && deleteOutput(monitor_name) == false) {
                logger.info("Monitor " + monitor_name + " Deleted. But output will removed in Sometime.");
                return ("deleted");
            } else {
                logger.info("Failed to delete Monitor " + monitor_name + " . Monitor not found.");
                return ("not_found");
            }
        } else {
            logger.info("failed to delete Monitor " + monitor_name);
            return ("failed");
        }
    } catch (FileNotFoundException ex) {
        logger.info("failed to delete Monitor " + monitor_name);
        logger.error("Error1 : " + ex);
        return ("failed");
    } catch (IOException ex) {
        logger.info("failed to delete Monitor " + monitor_name);
        logger.error("Error2 : " + ex);
        return ("failed");
    }
}

From source file:fm.last.moji.local.LocalMojiFile.java

@Override
public void copyToFile(File destination) throws IOException {
    if (!file.exists()) {
        throw new FileNotFoundException(file.getCanonicalPath());
    }//from  ww w  . j  av a  2 s . c  o  m
    FileUtils.copyFile(file, destination);
}

From source file:com.eviware.soapui.plugins.PluginLoader.java

private ReflectionsAndClassLoader makeJarFileScanner(File pluginFile,
        Collection<JarClassLoader> dependencyClassLoaders) throws IOException {
    File tempFile = File.createTempFile("soapuios", ".jar");
    tempFile.deleteOnExit();// w w  w  .  ja va  2  s . c o  m
    FileUtils.copyFile(pluginFile, tempFile);
    JarClassLoader jarClassLoader = new JarClassLoader(tempFile, PluginLoader.class.getClassLoader(),
            dependencyClassLoaders);
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().setUrls(jarClassLoader.getURLs())
            .addClassLoader(jarClassLoader);

    if (jarClassLoader.hasScripts()) {
        configurationBuilder.addClassLoader(jarClassLoader.getScriptClassLoader());
        configurationBuilder.addScanners(new TypeAnnotationsScanner());
        configurationBuilder.setMetadataAdapter(new GroovyAndJavaReflectionAdapter(jarClassLoader));
    }

    return new ReflectionsAndClassLoader(new Reflections(configurationBuilder), jarClassLoader);
}

From source file:com.ec2box.manage.action.UploadAndPushAction.java

@Action(value = "/admin/upload", results = { @Result(name = "input", location = "/admin/upload.jsp"),
        @Result(name = "success", location = "/admin/upload_result.jsp") })
public String upload() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    try {/*  w  w w . j  a va 2 s.c om*/
        File destination = new File(UPLOAD_PATH, uploadFileName);
        FileUtils.copyFile(upload, destination);

        pendingSystemStatus = SystemStatusDB.getNextPendingSystem(userId);

        hostSystemList = SystemStatusDB.getAllSystemStatus(userId);

    } catch (Exception e) {
        e.printStackTrace();
        return INPUT;
    }

    return SUCCESS;
}