Java Code Examples for org.apache.commons.io.FileUtils#copyFileToDirectory()

The following examples show how to use org.apache.commons.io.FileUtils#copyFileToDirectory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestAddFieldRealTimeGet.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Before
private void initManagedSchemaCore() throws Exception {
  final String tmpSolrHomePath = createTempDir().toFile().getAbsolutePath();
  tmpSolrHome = new File(tmpSolrHomePath).getAbsoluteFile();
  tmpConfDir = new File(tmpSolrHome, confDir);
  File testHomeConfDir = new File(TEST_HOME(), confDir);
  final String configFileName = "solrconfig-managed-schema.xml";
  final String schemaFileName = "schema-id-and-version-fields-only.xml";
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, configFileName), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, schemaFileName), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);

  // initCore will trigger an upgrade to managed schema, since the solrconfig has
  // <schemaFactory class="ManagedIndexSchemaFactory" ... />
  System.setProperty("managed.schema.mutable", "true");
  System.setProperty("enable.update.log", "true");
  initCore(configFileName, schemaFileName, tmpSolrHome.getPath());
}
 
Example 2
Source File: FileInstallerActivity.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
private void installPackage(Uri localApkUri, Uri canonicalUri, Apk apk) {
    Utils.debugLog(TAG, "Installing: " + localApkUri.getPath());
    File path = apk.getMediaInstallPath(activity.getApplicationContext());
    path.mkdirs();
    try {
        FileUtils.copyFileToDirectory(new File(localApkUri.getPath()), path);
    } catch (IOException e) {
        Utils.debugLog(TAG, "Failed to copy: " + e.getMessage());
        installer.sendBroadcastInstall(canonicalUri, Installer.ACTION_INSTALL_INTERRUPTED);
    }
    if (apk.isMediaInstalled(activity.getApplicationContext())) { // Copying worked
        Utils.debugLog(TAG, "Copying worked: " + localApkUri.getPath());
        Toast.makeText(this, String.format(this.getString(R.string.app_installed_media), path.toString()),
                Toast.LENGTH_LONG).show();
        installer.sendBroadcastInstall(canonicalUri, Installer.ACTION_INSTALL_COMPLETE);
    } else {
        installer.sendBroadcastInstall(canonicalUri, Installer.ACTION_INSTALL_INTERRUPTED);
    }
    finish();
}
 
Example 3
Source File: TestManagedSchema.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Before
private void initManagedSchemaCore() throws Exception {
  tmpSolrHome = createTempDir().toFile();
  tmpConfDir = new File(tmpSolrHome, confDir);
  File testHomeConfDir = new File(TEST_HOME(), confDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-managed-schema.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-basic.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig-managed-schema-test.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "solrconfig.snippet.randomindexconfig.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-one-field-no-dynamic-field.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-one-field-no-dynamic-field-unique-key.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-minimal.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema_codec.xml"), tmpConfDir);
  FileUtils.copyFileToDirectory(new File(testHomeConfDir, "schema-bm25.xml"), tmpConfDir);

  // initCore will trigger an upgrade to managed schema, since the solrconfig has
  // <schemaFactory class="ManagedIndexSchemaFactory" ... />
  System.setProperty("managed.schema.mutable", "false");
  System.setProperty("enable.update.log", "false");
  initCore("solrconfig-managed-schema.xml", "schema-minimal.xml", tmpSolrHome.getPath());
}
 
Example 4
Source File: ArtifactHandlerBase.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
private void doCopyResourceToStageDirectory(final FTPResource resource) {
    File file  = new File(resource.getSourcePath());
    if (!file.exists()) {
        task.getLogger().quiet(resource.getSourcePath() + " configured in deployment.resources does not exist.");
        return;
    }
    File destination = new File(Paths.get(getDeploymentStagingDirectoryPath(), resource.getTargetPath()).toString());
    try {
        if (file.isFile()) {
            FileUtils.copyFileToDirectory(file, destination);
        } else if (file.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(file, destination);
        }
    } catch (IOException e) {
        task.getLogger().quiet("exception when copy resource: " + e.getLocalizedMessage());
    }
}
 
Example 5
Source File: GuildelinesExporter.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Copy Project guidelines from the file system of this project to the export folder
 */
@Override
public void exportData(ProjectExportRequest aRequest, ProjectExportTaskMonitor aMonitor,
        ExportedProject aExProject, File aStage)
    throws Exception
{
    File guidelineDir = new File(aStage + GUIDELINES_FOLDER);
    FileUtils.forceMkdir(guidelineDir);
    File annotationGuidlines = projectService.getGuidelinesFolder(aRequest.getProject());
    
    if (annotationGuidlines.exists()) {
        for (File annotationGuideline : annotationGuidlines.listFiles()) {
            FileUtils.copyFileToDirectory(annotationGuideline, guidelineDir);
        }
    }
}
 
Example 6
Source File: Update.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 新增文件的升级操作
 * @param conf
 */
private void updateOfFileAdd(Map<String,Object> conf, String updateDir) throws IOException {
    if(conf != null){
        Set<String> keys = conf.keySet();//key是更新服务器上的文件
        for (String key : keys) {
            String targetDir = String.valueOf(conf.get(key));//value是需要被添加的目录
            if(!StringUtils.isEmpty(targetDir)){
                File updateFile = new File(updateDir + File.separator + key);
                File destDir = new File(agentHome + File.separator + targetDir);
                boolean update = true;
                if(!updateFile.exists()){
                    log.error("{}update file '{}' is not exist",log4UpdateStart,updateFile.getAbsolutePath());
                    update = false;
                }
                if(!destDir.exists()){
                    log.error("{}update dir '{}' is not exist",log4UpdateStart,destDir.getAbsolutePath());
                    update = false;
                }
                if(update){
                    FileUtils.copyFileToDirectory(updateFile,destDir);
                    log.info("{}add file '{}' to dir '{}' <SUCCESS>",log4UpdateStart,updateFile.toPath().getFileName(),destDir.getAbsolutePath());
                }
            }
        }
    }
}
 
Example 7
Source File: Persister4CollectorAPITest.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() {
	configurator.initProperties(PersisterConfigurator.configLoadFileName,PersisterConfigurationProperty.values());
	persister4CollectorAPI = new Persister4CollectorAPI();
	//Creating a sample persister directory
	File folderLocation = new File(configurator.getProperty(PersisterConfigurationProperty.DEFAULT_PERSISTER_FILE_PATH) + existedCollectionCode);
	if(!folderLocation.exists()){
		assertTrue("Unable to create sample directory",folderLocation.mkdirs());
	}
	File sampleFile = new File(System.getProperty("PROJECT_HOME") + "/src/test/resources/qa/qcri/aidr/persister/api/test_collection_code_vol-1.json");
	try {
		FileUtils.copyFileToDirectory(sampleFile, folderLocation, false);
	} catch (IOException e) {
		logger.info("Unable to copy a sample file in unit test in Persister4CollectorAPITest");
		e.printStackTrace();
	}

}
 
Example 8
Source File: VertxMojoTestBase.java    From vertx-maven-plugin with Apache License 2.0 6 votes vote down vote up
static void installPluginToLocalRepository(String local) {
    File repo = new File(local, "io/reactiverse/vertx-maven-plugin/" + VertxMojoTestBase.VERSION);
    if (!repo.isDirectory()) {
        boolean mkdirs = repo.mkdirs();
        Logger.getLogger(VertxMojoTestBase.class.getName())
            .log(Level.FINE, repo.getAbsolutePath() + " created? " + mkdirs);
    }

    File plugin = new File("target", "vertx-maven-plugin-" + VertxMojoTestBase.VERSION + ".jar");

    try {
        FileUtils.copyFileToDirectory(plugin, repo);
        String installedPomName = "vertx-maven-plugin-" + VertxMojoTestBase.VERSION + ".pom";
        FileUtils.copyFile(new File("pom.xml"), new File(repo, installedPomName));
    } catch (IOException e) {
        throw new RuntimeException("Cannot copy the plugin jar, or the pom file, to the local repository", e);
    }
}
 
Example 9
Source File: ResourceCopy.java    From wisdom with Apache License 2.0 5 votes vote down vote up
/**
 * Copies the file <tt>file</tt> to the directory <tt>dir</tt>, keeping the structure relative to <tt>rel</tt>.
 *
 * @param file                 the file to copy
 * @param rel                  the base 'relative'
 * @param dir                  the directory
 * @param mojo                 the mojo
 * @param filtering            the filtering component
 * @param additionalProperties additional properties
 * @throws IOException if the file cannot be copied.
 */
public static void copyFileToDir(File file, File rel, File dir, AbstractWisdomMojo mojo, MavenResourcesFiltering
        filtering, Properties additionalProperties) throws
        IOException {
    if (filtering == null) {
        File out = computeRelativeFile(file, rel, dir);
        if (out.getParentFile() != null) {
            mojo.getLog().debug("Creating " + out.getParentFile() + " : " + out.getParentFile().mkdirs());
            FileUtils.copyFileToDirectory(file, out.getParentFile());
        } else {
            throw new IOException("Cannot copy file - parent directory not accessible for "
                    + file.getAbsolutePath());
        }
    } else {
        Resource resource = new Resource();
        resource.setDirectory(rel.getAbsolutePath());
        resource.setFiltering(true);
        resource.setTargetPath(dir.getAbsolutePath());
        resource.setIncludes(ImmutableList.of("**/" + file.getName()));

        List<String> excludedExtensions = new ArrayList<>();
        excludedExtensions.addAll(filtering.getDefaultNonFilteredFileExtensions());
        excludedExtensions.addAll(NON_FILTERED_EXTENSIONS);

        MavenResourcesExecution exec = new MavenResourcesExecution(ImmutableList.of(resource), dir, mojo.project,
                "UTF-8", Collections.<String>emptyList(), excludedExtensions, mojo.session);

        if (additionalProperties != null) {
            exec.setAdditionalProperties(additionalProperties);
        }
        exec.setEscapeString("\\");

        try {
            filtering.filterResources(exec);
        } catch (MavenFilteringException e) {
            throw new IOException("Error while copying resources", e);
        }
    }
}
 
Example 10
Source File: ServerStartupListener.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void copyFileToDirectory(String filePath, String directoryPath, String parentDir)
        throws IOException {
    try {
        if (new File(parentDir).exists()) {
            FileUtils.copyFileToDirectory(new File(filePath), new File(directoryPath));
        }
    } catch (IOException ex) {
        log.error("An error occurred while copying file to directory", ex);
        throw new IOException("An error occurred while copying file to directory", ex);
    }
}
 
Example 11
Source File: ResourceAllocationsTest.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void createTable() throws Exception {
  updateTestCluster(10, config);

  tblPath = new File(getDfsTestTmpSchemaLocation(), "yelp");
  FileUtils.deleteQuietly(tblPath);
  FileUtils.copyFileToDirectory(new File(TEST_PATH + "/yelp_business.json"), tblPath);
  FileUtils.moveFile(new File(tblPath + "/yelp_business.json"), new File(tblPath + "/1.json"));
  FileUtils.copyFile(new File(tblPath + "/1.json"), new File(tblPath + "/2.json"));
}
 
Example 12
Source File: LocalFileManage.java    From bbs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**  
   * 复制文件
   *  
   * @param resFilePath 源文件路径  
   * @param distFolder  目标文件夹  
   * @IOException 当操作发生异常时抛出  
   */   
  public void copyFile(String resFilePath, String distFolder) throws IOException {   
  	
      File resFile = new File(PathUtil.path()+File.separator+resFilePath);   
      File distFile = new File(PathUtil.path()+File.separator+distFolder+File.separator); 
if (resFile.isFile()) {   
	FileUtils.copyFileToDirectory(resFile,distFile,true);   
      }

  }
 
Example 13
Source File: EI1222JSONSecuredServiceWithXMLCharacterTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private void copyXMLInputFactoryPropertiesFile() throws Exception {
    String carbonHome = System.getProperty(ServerConstants.CARBON_HOME);
    String propertiesSrcLocation =
            getResourceLocation() + File.separator + "resources" + File.separator + INPUT_FACTORY_PROPERTIES_FILE;
    try {
        FileUtils.copyFileToDirectory(new File(propertiesSrcLocation), new File(carbonHome));
        log.info(INPUT_FACTORY_PROPERTIES_FILE + " is copied to $CARBON_HOME.");
    } catch (IOException exception) {
        throw new Exception("Exception occurred while copying the " + INPUT_FACTORY_PROPERTIES_FILE, exception);
    }
}
 
Example 14
Source File: PFileIO.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@PhonkMethod(description = "Copy a file or directory", example = "")
@PhonkMethodParam(params = {"name", "destination"})
public void copy(String name, String to) {
    File file = new File(getAppRunner().getProject().getFullPathForFile(name));
    File dir = new File(getAppRunner().getProject().getFullPathForFile(to));
    dir.mkdirs();

    try {
        FileUtils.copyFileToDirectory(file, dir);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 15
Source File: DiagnosticMode.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
private void copyMigrationLog(final Optional<File> diagnosticsFolder) {

        //copy migration log if available
        final File migrationLog = new File(systemInformation.getLogFolder(), FILE_NAME_MIGRATION_LOG);

        if (migrationLog.exists()) {
            try {
                FileUtils.copyFileToDirectory(migrationLog, diagnosticsFolder.get());
            } catch (final IOException e) {
                log.error("Not able to copy migration log to diagnostics folder", e);
            }
        }
    }
 
Example 16
Source File: ProductTypeDocTool.java    From oodt with Apache License 2.0 5 votes vote down vote up
public void doProductTypeDoc(String productTypeXmlFilePath,
        String elementXmlFilePath) throws IOException, TransformerException {
    // copy element xml to current path
    FileUtils.copyFileToDirectory(new File(elementXmlFilePath), new File(
            "."));
    // copy product type xsl to current path
    FileUtils.copyFileToDirectory(new File(xslFilePath), new File("."));

    String xslLocalFilePath = new File(".").getAbsolutePath();
    if (!xslLocalFilePath.endsWith("/")) {
        xslLocalFilePath += "/";
    }
    xslLocalFilePath += new File(xslFilePath).getName();

    String elementLocalFilePath = new File(".").getAbsolutePath();
    if (!elementLocalFilePath.endsWith("/")) {
        elementLocalFilePath += "/";
    }

    elementLocalFilePath += new File(elementXmlFilePath).getName();

    Transformer xformer = TransformerFactory.newInstance().newTransformer(
            new StreamSource(new File(xslLocalFilePath)));

    xformer.setOutputProperty(OutputKeys.INDENT, "yes");
    String productTypeFileName = new File(productTypeXmlFilePath).getName();
    String outputProductTypeDocFileName = productTypeFileName.replaceAll(
            "xml", "html");

    Result result = new StreamResult(new File(outputDirPath
            + outputProductTypeDocFileName));

    xformer.transform(new StreamSource(new File(productTypeXmlFilePath)),
            result);

    // now cleanup
    new File(xslLocalFilePath).delete();
    new File(elementLocalFilePath).delete();
}
 
Example 17
Source File: InjectScript.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private Boolean injectScript() {
    if (javaListModel.isEmpty()) {
        console.append("\n");
        console.append("Please Load some files and then inject");
    } else {
        Boolean flag = true;
        for (Object object : javaListModel.toArray()) {
            console.append("\n");
            if (injectScript(object.toString()) == 0) {
                console.append(object + " - compiled successfully");
                try {
                    FileUtils.copyFileToDirectory(new File(object.toString()
                            .replace(".java", ".class")),
                            new File("userdefined"));
                } catch (IOException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            } else {
                console.append(object + " - compiled with errors");
                flag = false;
            }
            console.append("\n");
        }
        return flag;
    }
    return false;
}
 
Example 18
Source File: PackageMojo.java    From opoopress with Apache License 2.0 4 votes vote down vote up
private File createArchive() throws MojoExecutionException {
        File outputFile = getOutputFile(buildDirectory, finalName, getClassifier());

        File classesDirectory = getClassesDirectory();
        File classesJarFile = getClassesJarFile(buildDirectory, finalName, getClassesClassifier());

        //must copy all dependencies to 'target/plugins' directory
        File targetPluginsDir = new File(buildDirectory, "plugins");

        try {
            zipArchiver.setDestFile(outputFile);
            zipArchiver.setForced(forceCreation);

            zipArchiver.addDirectory(basedir, getIncludes(), getExcludes());
//            zipArchiver.addDirectory(basedir, buildIncludes(basedir), null);

            //classes jar
            if (classesDirectory.exists() && classesJarFile.exists()) {
                targetPluginsDir.mkdirs();
                FileUtils.copyFileToDirectory(classesJarFile, targetPluginsDir);
            } else {
                getLog().warn("No theme classes add to theme package.");
            }

            //archive classes jar file and all dependencies
            if (targetPluginsDir.exists() && targetPluginsDir.list().length > 0) {
                zipArchiver.addDirectory(buildDirectory, new String[]{"plugins/**"}, null);
            }

            zipArchiver.createArchive();

        } catch (Exception e) {
            throw new MojoExecutionException("Error assembling OpooPress theme package", e);
        }

        /*
        MavenArchiver archiver = new MavenArchiver();

        archiver.setArchiver(jarArchiver);

        archiver.setOutputFile(outputFile);

        archive.setForced(forceCreation);
        archive.setAddMavenDescriptor(false);
//        archive.setManifest(null);

        try {
            archiver.getArchiver().addDirectory(basedir, getIncludes(), getExcludes());

            //classes jar
            if (classesDirectory.exists() && classesJarFile.exists()) {
                targetPluginsDir.mkdirs();
                FileUtils.copyFileToDirectory(classesJarFile, targetPluginsDir);
            } else {
                getLog().warn("No theme classes add to theme package.");
            }

            //archive classes jar file and all dependencies
            if (targetPluginsDir.exists() && targetPluginsDir.list().length > 0) {
                archiver.getArchiver().addDirectory(buildDirectory, new String[]{"plugins/**"}, null);
            }

            archiver.createArchive(project, archive);
        } catch (Exception e) {
            throw new MojoExecutionException("Error assembling OpooPress theme package", e);
        }*/

        return outputFile;
    }
 
Example 19
Source File: Workspace.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public void copy(String from, String to, boolean force) throws IOException {
    Path fromPath = this.getPath(from);
    Path toPath = this.getPath(to);

    boolean fromFileExists = new File(fromPath.toString()).exists();
    boolean toFileExists = new File(toPath.toString()).exists();
    boolean fromFileIsDir = new File(fromPath.toString()).isDirectory();
    boolean toFileIsDir = new File(toPath.toString()).isDirectory();


    if (fromFileExists) {
        if (fromFileIsDir // copy 目录, 且目标目录已存在
                && toFileExists
                && toFileIsDir
                && !force) {
            throw new WorkspaceIOException(to + " is a directory, and is already exist!");
        }

        if (!fromFileIsDir // copy 文件到目录, 且目标文件已存在
                && toFileExists
                && toFileIsDir
                && !force) {

            File destFile = new File(toPath.toFile(), fromPath.toFile().getName());

            if (destFile.exists()) {
                throw new WorkspaceIOException(to + " file already exist");
            }
        }

        if (!toFileIsDir // copy 文件, 且目标已经存在
                && !toFileIsDir
                && toFileExists
                && !force) {
            throw new WorkspaceIOException(to + " file already exist!");
        }

        try {
            if (fromFileIsDir) {
                FileUtils.copyDirectory(fromPath.toFile(), toPath.toFile());
            } else {
                if (toFileIsDir) {
                    FileUtils.copyFileToDirectory(fromPath.toFile(), toPath.toFile());
                } else {
                    FileUtils.copyFile(fromPath.toFile(), toPath.toFile());
                }
            }
        } catch (Exception e) {
            throw new WorkspaceIOException(e);
        }
    } else {
        throw new WorkspaceIOException(from + " no such file found!");
    }

}
 
Example 20
Source File: ZkGrep.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * parse zk-transaction-logs between start and end, if not already parsed
 * @param zkLogDir
 * @param start
 * @param end
 * @return list of parsed zklogs between start and end, in order of last modified timestamp
 */
static List<File> parseZkLogs(String zkLogDir, long start, long end) {
  File zkParsedDir = new File(String.format("%s/zklog-parsed", System.getProperty("user.home")));
  File[] zkLogs = getSortedFiles(zkLogDir, log);
  // printFiles(zkDataFiles);
  List<File> parsedZkLogs = new ArrayList<File>();

  boolean stop = false;
  for (File zkLog : zkLogs) {
    if (stop) {
      break;
    }

    if (zkLog.lastModified() < start) {
      continue;
    }

    if (zkLog.lastModified() > end) {
      stop = true;
    }

    try {
      File parsedZkLog = new File(zkParsedDir, stripGzSuffix(zkLog.getName()) + ".parsed");
      if (!parsedZkLog.exists() || parsedZkLog.lastModified() <= zkLog.lastModified()) {

        if (zkLog.getName().endsWith(gzSuffix)) {
          // copy and gunzip it
          FileUtils.copyFileToDirectory(zkLog, zkParsedDir);
          File zkLogGz = new File(zkParsedDir, zkLog.getName());
          File tmpZkLog = gunzip(zkLogGz);

          // parse gunzip file
          ZKLogFormatter
              .main(new String[] { log, tmpZkLog.getAbsolutePath(), parsedZkLog.getAbsolutePath()
              });

          // delete it
          zkLogGz.delete();
          tmpZkLog.delete();
        } else {
          // parse it directly
          ZKLogFormatter.main(new String[] {
              log, zkLog.getAbsolutePath(), parsedZkLog.getAbsolutePath()
          });
        }
      }
      parsedZkLogs.add(parsedZkLog);
    } catch (Exception e) {
      LOG.error("fail to parse zkLog: " + zkLog, e);
    }
  }

  return parsedZkLogs;
}