List of usage examples for org.apache.commons.io FileUtils copyFile
public static void copyFile(File srcFile, File destFile) throws IOException
From source file:io.dockstore.client.cli.MockedIT.java
@Before public void clearDB() throws Exception { clearState();/*from w ww . jav a 2 s.c o m*/ Client client = mock(Client.class); ToolClient toolClient = spy(new ToolClient(client)); final UsersApi userApiMock = mock(UsersApi.class); when(client.getConfigFile()).thenReturn(TestUtility.getConfigFileLocation(true)); when(userApiMock.getUser()).thenReturn(new User()); whenNew(UsersApi.class).withAnyArguments().thenReturn(userApiMock); whenNew(ToolClient.class).withAnyArguments().thenReturn(toolClient); // mock return of a simple CWL file File sourceFile = new File(ResourceHelpers.resourceFilePath("dockstore-tool-linux-sort.cwl")); final String sourceFileContents = FileUtils.readFileToString(sourceFile); SourceFile file = mock(SourceFile.class); when(file.getContent()).thenReturn(sourceFileContents); doReturn(file).when(toolClient).getDescriptorFromServer("quay.io/collaboratory/dockstore-tool-linux-sort", "cwl"); doNothing().when(toolClient).downloadDescriptors(anyString(), anyString(), anyObject()); // mock return of a more complicated CWL file File sourceFileArrays = new File(ResourceHelpers.resourceFilePath("arrays.cwl")); final String sourceFileArraysContents = FileUtils.readFileToString(sourceFileArrays); SourceFile file2 = mock(SourceFile.class); when(file2.getContent()).thenReturn(sourceFileArraysContents); doReturn(file2).when(toolClient).getDescriptorFromServer("quay.io/collaboratory/arrays", "cwl"); FileUtils.deleteQuietly(new File("/tmp/wc1.out")); FileUtils.deleteQuietly(new File("/tmp/wc2.out")); FileUtils.deleteQuietly(new File("/tmp/example.bedGraph")); try { FileUtils.copyFile(new File(ResourceHelpers.resourceFilePath("example.bedGraph")), new File("./datastore/example.bedGraph")); } catch (IOException e) { e.printStackTrace(); } }
From source file:es.uvigo.ei.sing.adops.datatypes.BatchProject.java
public BatchProject(Configuration configuration, File folder, File[] fastaFiles, boolean absoluteFasta) throws IOException, IllegalArgumentException { this.fastaFiles = new File[fastaFiles.length]; this.folder = folder; this.deleted = false; this.running = false; if (this.folder.exists()) { if (this.folder.listFiles().length > 0) throw new IllegalArgumentException( "Batch project folder already exists and it is not empty (" + this.folder + ")"); if (!this.folder.canRead()) throw new IllegalArgumentException("Batch project folder is not readable (" + this.folder + ")"); if (!this.folder.canWrite()) throw new IllegalArgumentException("Batch project folder is not writeable (" + this.folder + ")"); } else if (!this.folder.mkdirs()) { throw new IllegalArgumentException( "Batch project folder (" + folder.getAbsolutePath() + ") could not be created"); }//from w w w .j a v a 2s.c o m this.propertiesFile = new File(this.folder, BatchProject.CONFIGURATION_FILE); this.configuration = new Configuration(configuration); Utils.storeAllProperties(this.configuration.toProperties(true), this.propertiesFile, LOG); if (absoluteFasta) { System.arraycopy(fastaFiles, 0, this.fastaFiles, 0, fastaFiles.length); this.configuration.setFastaFile(filesToFilenames(this.fastaFiles)); Arrays.sort(this.fastaFiles); } else { for (int i = 0; i < fastaFiles.length; i++) { this.fastaFiles[i] = batchFastaFile(this.folder, fastaFiles[i]); FileUtils.copyFile(fastaFiles[i], this.fastaFiles[i]); } Arrays.sort(this.fastaFiles); this.createFastasFile(); } }
From source file:com.gitblit.tests.HtpasswdAuthenticationTest.java
private void copyInFiles() throws IOException { File dir = new File(RESOURCE_DIR); FilenameFilter filter = new FilenameFilter() { @Override/* w w w . ja v a 2s . c om*/ public boolean accept(File dir, String file) { return file.endsWith(".in"); } }; for (File inf : dir.listFiles(filter)) { File dest = new File(inf.getParent(), inf.getName().substring(0, inf.getName().length() - 3)); FileUtils.copyFile(inf, dest); } }
From source file:net.mindengine.dashserver.compiler.WidgetCompiler.java
private String copyWidgetFile(String widgetName, File widgetItem) throws IOException { String destName = widgetName + "." + widgetItem.getName(); File dest = new File(compiledWidgetsFolder.getAbsolutePath() + File.separator + destName); dest.createNewFile();/*from www. ja va2s. c o m*/ FileUtils.copyFile(widgetItem, dest); return destName; }
From source file:net.sibcolombia.sibsp.service.portal.implementation.SourceManagerImplementation.java
private FileSource addOneFile(Resource resource, File file, @Nullable String sourceName) throws ImportException { FileSource src = new FileSource(); if (sourceName == null) { sourceName = file.getName();// w ww .j a va2 s . co m } src.setName(sourceName); src.setResource(resource); log.debug("ADDING SOURCE " + sourceName + " FROM " + file.getAbsolutePath()); try { // copy file File ddFile = dataDir.sourceFile(resource, src); try { FileUtils.copyFile(file, ddFile); } catch (IOException e1) { throw new ImportException(e1); } src.setFile(ddFile); src.setLastModified(new Date()); // add to resource, allow overwriting existing ones // if the file is uploaded not for the first time resource.addSource(src, true); } catch (AlreadyExistingException e) { throw new ImportException(e); } // analyze file // analyze(src); return src; }
From source file:com.starit.diamond.server.service.DiskService.java
public void saveToDisk(ConfigInfo configInfo) throws IOException { if (configInfo == null) throw new IllegalArgumentException("configInfo?"); if (!StringUtils.hasLength(configInfo.getDataId()) || StringUtils.containsWhitespace(configInfo.getDataId())) throw new IllegalArgumentException("dataId"); if (!StringUtils.hasLength(configInfo.getGroup()) || StringUtils.containsWhitespace(configInfo.getGroup())) throw new IllegalArgumentException("group"); if (!StringUtils.hasLength(configInfo.getContent())) throw new IllegalArgumentException("content"); final String basePath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR); createDirIfNessary(basePath);/*from w w w. j av a2 s . co m*/ final String groupPath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR + "/" + configInfo.getGroup()); createDirIfNessary(groupPath); String group = configInfo.getGroup(); String dataId = configInfo.getDataId(); dataId = SystemConfig.encodeDataIdForFNIfUnderWin(dataId); final String dataPath = WebUtils.getRealPath(servletContext, Constants.BASE_DIR + "/" + group + "/" + dataId); File targetFile = createFileIfNessary(dataPath); File tempFile = File.createTempFile(group + "-" + dataId, ".tmp"); FileOutputStream out = null; PrintWriter writer = null; try { out = new FileOutputStream(tempFile); BufferedOutputStream stream = new BufferedOutputStream(out); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, Constants.ENCODE))); configInfo.dump(writer); writer.flush(); } catch (Exception e) { log.error("??, tempFile:" + tempFile + ",targetFile:" + targetFile, e); } finally { if (writer != null) writer.close(); } String cacheKey = generateCacheKey(configInfo.getGroup(), configInfo.getDataId()); // if (this.modifyMarkCache.putIfAbsent(cacheKey, true) == null) { try { // ??? if (!FileUtils.contentEquals(tempFile, targetFile)) { try { // TODO ?, ??? , ?? FileUtils.copyFile(tempFile, targetFile); } catch (Throwable t) { log.error("??, tempFile:" + tempFile + ", targetFile:" + targetFile, t); SystemConfig.system_pause(); throw new RuntimeException(); } } tempFile.delete(); } finally { // this.modifyMarkCache.remove(cacheKey); } } else throw new ConfigServiceException("??"); }
From source file:com.turn.griffin.GriffinLibCacheUtil.java
public Optional<FileInfo> addFileToLocalLibCache(String blobName, long version, String dest, String filepath) { FileInfo fileInfo = FileInfo.newBuilder().setFilename(blobName).setVersion(version) .setHash(computeMD5(filepath).get()).setDest(dest).setCompression(FILE_COMPRESSION.name()) .setBlockSize(FILE_BLOCK_SIZE).build(); try {//from w ww . ja va 2 s .c o m FileUtils.forceMkdir(new File(getTempCacheDirectory(fileInfo))); String tempCacheFilePath = getTempCacheFilePath(fileInfo); FileUtils.copyFile(new File(filepath), new File(tempCacheFilePath)); /* The compression type is decided only once at the time a file is pushed. This design will ensure that any change to default file compression would not affect any previously pushed file as long as the new code supports the old compression. */ compressFile(tempCacheFilePath, FILE_COMPRESSION); writeTempCacheMetaDataFile(fileInfo); /* Now move everything to local libcache */ moveFromTempCacheToLibCache(fileInfo); } catch (IOException ioe) { logger.error(String.format("Unable to create local repository for %s", blobName), ioe); return Optional.absent(); } String libCacheCompressedFilePath = getLibCacheCompressedFilePath(fileInfo); /* NOTE: Number of blocks are for the compressed file and not the original file. */ int blockCount = (int) Math .ceil(FileUtils.sizeOf(new File(libCacheCompressedFilePath)) / (double) FILE_BLOCK_SIZE); FileInfo finalFileInfo = FileInfo.newBuilder().mergeFrom(fileInfo).setBlockCount(blockCount).build(); return Optional.of(finalFileInfo); }
From source file:com.datatorrent.contrib.enrich.FileEnrichmentTest.java
@Test public void testEnrichmentOperatorDelimitedFSLoader() throws IOException, InterruptedException { URL origUrl = this.getClass().getResource("/productmapping-delim.txt"); URL fileUrl = new URL(this.getClass().getResource("/").toString() + "productmapping-delim1.txt"); FileUtils.deleteQuietly(new File(fileUrl.getPath())); FileUtils.copyFile(new File(origUrl.getPath()), new File(fileUrl.getPath())); MapEnricher oper = new MapEnricher(); DelimitedFSLoader store = new DelimitedFSLoader(); // store.setFieldDescription("productCategory:INTEGER,productId:INTEGER"); store.setFileName(fileUrl.toString()); store.setSchema(//from ww w . j a v a2 s . c om "{\"separator\":\",\",\"fields\": [{\"name\": \"productCategory\",\"type\": \"Integer\"},{\"name\": \"productId\",\"type\": \"Integer\"},{\"name\": \"mfgDate\",\"type\": \"Date\",\"constraints\": {\"format\": \"dd/MM/yyyy\"}}]}"); oper.setLookupFields(Arrays.asList("productId")); oper.setIncludeFields(Arrays.asList("productCategory", "mfgDate")); oper.setStore(store); oper.setup(null); CollectorTestSink<Map<String, Object>> sink = new CollectorTestSink<>(); @SuppressWarnings({ "unchecked", "rawtypes" }) CollectorTestSink<Object> tmp = (CollectorTestSink) sink; oper.output.setSink(tmp); oper.activate(null); oper.beginWindow(0); Map<String, Object> tuple = Maps.newHashMap(); tuple.put("productId", 3); tuple.put("channelId", 4); tuple.put("amount", 10.0); Kryo kryo = new Kryo(); oper.input.process(kryo.copy(tuple)); oper.endWindow(); oper.deactivate(); /* Number of tuple, emitted */ Assert.assertEquals("Number of tuple emitted ", 1, sink.collectedTuples.size()); Map<String, Object> emitted = sink.collectedTuples.iterator().next(); /* The fields present in original event is kept as it is */ Assert.assertEquals("Number of fields in emitted tuple", 5, emitted.size()); Assert.assertEquals("value of productId is 3", tuple.get("productId"), emitted.get("productId")); Assert.assertEquals("value of channelId is 4", tuple.get("channelId"), emitted.get("channelId")); Assert.assertEquals("value of amount is 10.0", tuple.get("amount"), emitted.get("amount")); /* Check if productCategory is added to the event */ Assert.assertEquals("productCategory is part of tuple", true, emitted.containsKey("productCategory")); Assert.assertEquals("value of product category is 1", 5, emitted.get("productCategory")); Assert.assertTrue(emitted.get("productCategory") instanceof Integer); /* Check if mfgDate is added to the event */ Assert.assertEquals("mfgDate is part of tuple", true, emitted.containsKey("productCategory")); Date mfgDate = (Date) emitted.get("mfgDate"); Assert.assertEquals("value of day", 1, mfgDate.getDate()); Assert.assertEquals("value of month", 0, mfgDate.getMonth()); Assert.assertEquals("value of year", 2016, mfgDate.getYear() + 1900); Assert.assertTrue(emitted.get("mfgDate") instanceof Date); }
From source file:com.fluidops.iwb.api.solution.CopyFolderStructureHandler.java
public static int copyFolder(File source, File destination, FileFilter filter) throws IOException { if (!source.isDirectory()) throw new RuntimeException("Source must be a directory: " + source); GenUtil.mkdirs(destination);/*from w w w . j ava 2 s . c o m*/ int copiedFiles = 0; for (File srcFile : source.listFiles(filter)) { File newFile = new File(destination, srcFile.getName()); if (srcFile.isDirectory()) copiedFiles += copyFolder(srcFile, newFile, filter); else { FileUtils.copyFile(srcFile, newFile); copiedFiles++; } } return copiedFiles; }
From source file:de.metalcon.musicStorageServer.MusicStorageServerTest.java
@SuppressWarnings("unchecked") @BeforeClass//from w w w . j a v a 2 s .c o m public static void beforeClass() throws IOException { final MSSConfig config = new MSSConfig(CONFIG_PATH); TEST_FILE_DIRECTORY = new File(config.getMusicDirectory()).getParentFile(); VALID_READ_META_DATA_JSON = new JSONObject(); VALID_READ_META_DATA_JSON.put("title", "My Great Song"); VALID_READ_META_DATA_JSON.put("album", "Testy Forever"); VALID_READ_META_DATA_JSON.put("artist", "Testy"); VALID_READ_META_DATA = VALID_READ_META_DATA_JSON.toJSONString(); VALID_CREATE_META_DATA_JSON = new JSONObject(); VALID_CREATE_META_DATA_JSON.putAll(VALID_READ_META_DATA_JSON); VALID_CREATE_META_DATA_JSON.put("license", "General Less AllYouCanEat License"); VALID_CREATE_META_DATA_JSON.put("date", "1991-11-11"); VALID_CREATE_META_DATA_JSON.put("comment", "All your cookies belong to me!"); VALID_CREATE_META_DATA = VALID_CREATE_META_DATA_JSON.toJSONString(); // convert files for reading tests once final MusicStorageServer server = new MusicStorageServer(CONFIG_PATH); server.clear(); BACKUP_FILE_ORIGINAL = new File(TEST_FILE_DIRECTORY, "original.mp3"); BACKUP_FILE_BASIS = new File(TEST_FILE_DIRECTORY, "basis.ogg"); BACKUP_FILE_STREAMING = new File(TEST_FILE_DIRECTORY, "streaming.ogg"); final String hash = "108053"; final Calendar calendar = Calendar.getInstance(); final String day = FORMATTER.format(calendar.getTime()); final String year = String.valueOf(calendar.get(Calendar.YEAR)); DESTINATION_FILE_ORIGINAL = new File( config.getMusicDirectory() + "originals/" + year + "/" + day + "/1/10/", hash); DESTINATION_FILE_BASIS = new File(config.getMusicDirectory() + "1/10/108/basis/", hash + ".ogg"); DESTINATION_FILE_STREAMING = new File(config.getMusicDirectory() + "1/10/108/streaming/", hash + ".ogg"); // convert and copy files if not existing if (!(BACKUP_FILE_ORIGINAL.exists() && BACKUP_FILE_BASIS.exists() && BACKUP_FILE_STREAMING.exists())) { try { assertTrue(server.createMusicItem(VALID_READ_IDENTIFIER, new FileInputStream(new File(TEST_FILE_DIRECTORY, "mp3.mp3")), VALID_READ_META_DATA, new CreateResponse())); FileUtils.copyFile(DESTINATION_FILE_ORIGINAL, BACKUP_FILE_ORIGINAL); FileUtils.copyFile(DESTINATION_FILE_BASIS, BACKUP_FILE_BASIS); FileUtils.copyFile(DESTINATION_FILE_STREAMING, BACKUP_FILE_STREAMING); } catch (final FileNotFoundException e) { fail("audio file for test is not avialable!\n" + e.getMessage()); } } }