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:com.enioka.jqm.tools.BasicTest.java

@Before
public void before() throws Exception {
    jqmlogger.debug("********* TEST INIT");

    em = Helpers.getNewEm();//from   w  w w. ja  v  a  2s . c o  m
    TestHelpers.cleanup(em);
    TestHelpers.createTestData(em);
    Helpers.setSingleParam("disableWsApi", "false", em);
    Helpers.setSingleParam("enableWsApiAuth", "true", em);
    Helpers.setSingleParam("enableWsApiSsl", "false", em);
    File jar = FileUtils.listFiles(new File("../../jqm-ws/target/"), new String[] { "war" }, false).iterator()
            .next();
    FileUtils.copyFile(jar, new File("./webapp/jqm-ws.war"));

    em.getTransaction().begin();
    Node n = em.find(Node.class, TestHelpers.node.getId());
    em.createQuery("UPDATE GlobalParameter gp set gp.value='true' WHERE gp.key = 'logFilePerLaunch'")
            .executeUpdate();
    n.setRepo("./../..");

    TestHelpers.node.setLoadApiAdmin(true);
    TestHelpers.node.setLoadApiClient(true);
    TestHelpers.node.setLoapApiSimple(true);
    em.getTransaction().commit();

    engine1 = new JqmEngine();
    engine1.start("localhost");

    // Test user
    RRole r = em.createQuery("SELECT rr from RRole rr WHERE rr.name = :r", RRole.class)
            .setParameter("r", "client power user").getSingleResult();
    CreationTools.createUser(em, "test", "test", r);

    Properties p = new Properties();
    em.refresh(n);
    System.out.println(n.getPort());
    p.put("com.enioka.jqm.ws.url", "http://" + n.getDns() + ":" + n.getPort() + "/ws/client");
    p.put("com.enioka.jqm.ws.login", "test");
    p.put("com.enioka.jqm.ws.password", "test");
    JqmClientFactory.setProperties(p);
}

From source file:com.ibm.bi.dml.test.integration.functions.misc.SetWorkingDirTest.java

/**
 * /*from   w w w.j a  v  a2s .  c om*/
 * @param testName
 * @param exceptionExpected
 * @param scriptType
 */
private void runTest(String testName, boolean exceptionExpected, ScriptType scriptType) {

    //construct source filenames of dml scripts 
    String dir = SCRIPT_DIR + TEST_DIR;
    String nameCall = testName + "." + scriptType.lowerCase();
    String nameLib = TEST_NAME0 + "." + scriptType.lowerCase();

    try {
        //copy dml/pydml scripts to current dir
        FileUtils.copyFile(new File(dir + nameCall), new File(nameCall));
        if (!exceptionExpected)
            FileUtils.copyFile(new File(dir + nameLib), new File(nameLib));

        //setup test configuration
        TestConfiguration config = getTestConfiguration(testName);
        fullDMLScriptName = nameCall;
        if (scriptType == ScriptType.PYDML) {
            programArgs = new String[] { "-python" };
        } else {
            programArgs = new String[] {};
        }
        loadTestConfiguration(config);

        //run tests
        runTest(true, exceptionExpected, DMLException.class, -1);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        //delete dml/pydml scripts from current dir (see above)
        LocalFileUtils.deleteFileIfExists(nameCall);
        if (!exceptionExpected)
            LocalFileUtils.deleteFileIfExists(nameLib);
    }
}

From source file:com.frederikam.gensokyobot.command.admin.UpdateCommand.java

private void update(TextChannel channel) throws IOException {
    File homeJar = new File(System.getProperty("user.home") + "/FredBoat-1.0.jar");
    File targetJar = new File("./update/target/FredBoat-1.0.jar");

    targetJar.getParentFile().mkdirs();/*ww w .j a v a2  s .  c  om*/
    targetJar.delete();
    FileUtils.copyFile(homeJar, targetJar);

    //Shutdown for update
    channel.sendMessage("Now restarting...").queue();
    FredBoat.shutdown(ExitCodes.EXIT_CODE_UPDATE);
}

From source file:com.github.brandtg.switchboard.TestMysqlReplicationApplier.java

@Test
public void testRestoreFromBinlog() throws Exception {
    MysqlReplicationApplier applier = null;
    try (Connection conn = DriverManager.getConnection(jdbc, "root", "")) {
        // Write some rows, so we have binlog entries
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO simple VALUES(?, ?)");
        for (int i = 0; i < 10; i++) {
            pstmt.setInt(1, i);// w  w  w  . j a  v  a 2s.co  m
            pstmt.setInt(2, i);
            pstmt.execute();
        }

        // Copy the binlog somewhere
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("SHOW BINARY LOGS");
        rset.next();
        String binlogName = rset.getString("Log_name");
        rset = stmt.executeQuery("SELECT @@datadir");
        rset.next();
        String dataDir = rset.getString("@@datadir");
        File copyFile = new File(System.getProperty("java.io.tmpdir"),
                TestMysqlReplicationApplier.class.getName());
        FileUtils.copyFile(new File(dataDir + binlogName), copyFile);

        // Clear everything in MySQL
        resetMysql();

        // Get input stream, skipping and checking binlog magic number
        InputStream inputStream = new FileInputStream(copyFile);
        byte[] magic = new byte[MySQLConstants.BINLOG_MAGIC.length];
        int bytesRead = inputStream.read(magic);
        Assert.assertEquals(bytesRead, MySQLConstants.BINLOG_MAGIC.length);
        Assert.assertTrue(CodecUtils.equals(magic, MySQLConstants.BINLOG_MAGIC));

        // Restore from binlog
        PoolingDataSource<PoolableConnection> dataSource = getDataSource();
        applier = new MysqlReplicationApplier(inputStream, dataSource);
        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        executorService.submit(applier);

        // Poll until we have restored
        long startTime = System.currentTimeMillis();
        long currentTime = startTime;
        do {
            stmt = conn.createStatement();
            rset = stmt.executeQuery("SELECT COUNT(*) FROM test.simple");
            rset.next();
            long count = rset.getLong(1);
            if (count == 10) {
                return;
            }
            Thread.sleep(1000);
            currentTime = System.currentTimeMillis();
        } while (currentTime - startTime < 10000);
    } finally {
        if (applier != null) {
            applier.shutdown();
        }
    }

    Assert.fail("Timed out when polling");
}

From source file:ch.admin.suis.msghandler.common.CompleteMultiReceiver2Test.java

@Override
void initialize() throws IOException {
    List<File> files = getAllFilesFromDir(new File(BASE_PATH_SETUP + "/case2"));
    for (File f : files) {
        FileUtils.copyFile(f, new File(BASE_PATH_SDX + "/inbox", f.getName()));
    }//from   w ww  .  j a  v  a 2s. co m
}

From source file:eu.cognitum.readandwrite.SimulateReadAndWrite.java

/**
 * Class to simulate both read and write for a generic repository.
 *
 * @param repExt RDF repository to use/* w ww. j  av  a  2  s. c o  m*/
 * @param Nelements Number of elements to be generated by the simulation.
 * @param readStep Number of element to load in the repository before each
 * read.
 * @param commitBufferSize Number of element to load before commiting the
 * changes to the Repository.
 */
public SimulateReadAndWrite(Repository repExt, String outputNameExt, int Nelements, int readStep,
        int commitBufferSize, String graphDbUsedExt, String keyspaceExt, String currentNameSpace,
        RdfGenerator rdfGen) throws RepositoryException, FileNotFoundException, IOException {

    outputName = outputNameExt;

    fileName = outputNameExt + ".rdf";
    String fileGenerated = rdfGen.getFileName();
    FileUtils.copyFile(new File(fileGenerated), new File(fileName));
    rep = repExt;
    _commitBufferSize = commitBufferSize;
    _NelementsFinal = Nelements;
    _step = readStep;
    graphDbUsed = graphDbUsedExt;
    keyspace = keyspaceExt;

    _rdfGenerator = rdfGen;
    _rdfReadHandler = new RdfReadHandler(this, _rdfGenerator, this.currentNamespace);
}

From source file:name.vysoky.epub.Part.java

public void tidy() {
    File temp = null;//w w  w  .j  a  va  2  s.com
    InputStream is = null;
    try {
        temp = new File(file.getAbsolutePath() + ".tmp");
        FileUtils.copyFile(file, temp);
        is = new BufferedInputStream(new FileInputStream(temp));
        this.document = book.getTidy().parseDOM(is, null); // null = do not save
        removeUnsupportedAttributes(document.getDocumentElement());
        save(); // save explicitly
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            FileUtils.forceDelete(temp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.processors.onfile.RunnableProcessorOnFileTest.java

@Before
public void setUp() throws OAuthException, IOException, ValidationException, ReportException,
        ReportDownloadResponseException {

    ModifiedCsvToBean<ReportAccount> csvToBean = new ModifiedCsvToBean<ReportAccount>();
    MappingStrategy<ReportAccount> mappingStrategy = new AnnotationBasedMappingStrategy<ReportAccount>(
            ReportAccount.class);

    FileUtils.copyFile(file, newFile);

    runnableProcessorOnFile = new RunnableProcessorOnFile<ReportAccount>(file, csvToBean, mappingStrategy,
            ReportDefinitionDateRangeType.CUSTOM_DATE, "20140101", "20140131", "123", mockedEntitiesPersister,
            5);//from   w  ww  .  j av a  2 s.  co m

    MockitoAnnotations.initMocks(this);

    runnableProcessorOnFile.setPersister(mockedEntitiesPersister);
}

From source file:com.ibm.dbwkl.request.internal.SetupHandler.java

/**
 * @param configFile//  www. ja v a2s  .com
 * @return returns the result after removing the setup lines
 */
private STAFResult RemoveAutoSetup(File configFile) {

    StringBuilder fileContent = new StringBuilder();

    try {
        // make a backup copy
        File backupConfigFile = new File(configFile.getAbsolutePath() + ".backup");
        FileUtils.copyFile(configFile, backupConfigFile);

        // read the file
        FileReader reader = new FileReader(configFile);
        BufferedReader br = new BufferedReader(reader);

        String line = null;
        boolean inDB2WKLSection = false;
        while ((line = br.readLine()) != null) {
            // on the way, remove all db2wkl lines
            if (line.trim().startsWith("# [DB2WKL SETUP]") && inDB2WKLSection == false)
                inDB2WKLSection = true;

            if (!inDB2WKLSection) {
                fileContent.append(line + "\n");

                if (line.trim().startsWith("# [DB2WKL SETUP]") && inDB2WKLSection == true)
                    inDB2WKLSection = false;
            }

        }
        br.close();
        reader.close();

        // write back the whole file
        FileWriter writer = new FileWriter(configFile);
        BufferedWriter bw = new BufferedWriter(writer);

        bw.write(fileContent.toString());

        bw.close();
        writer.close();

        return new STAFResult(STAFResult.Ok);

    } catch (IOException e) {
        Logger.log(
                "Could not remove existing entries in the config file. If the config file is empty/wrong now replace it with the backup STAF.cfg.backup: "
                        + e.getMessage(),
                LogLevel.Error);
        return new STAFResult(STAFResult.FileWriteError);
    }

}

From source file:com.thoughtworks.go.config.GoConfigMigration.java

private void backup(File configFile, File backupFile) throws IOException {
    FileUtils.copyFile(configFile, backupFile);
    LOG.info("Config file is backed up, location: {}", backupFile.getAbsolutePath());
}