List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:de.uzk.hki.da.convert.DocxConversionStrategy.java
@Override public List<Event> convertFile(WorkArea wa, ConversionInstruction ci) throws FileNotFoundException { if (ci.getConversion_routine() == null) throw new IllegalStateException("conversionRoutine not set"); if (ci.getConversion_routine().getTarget_suffix().isEmpty()) throw new IllegalStateException("target suffix in conversionRoutine not set"); if (ci.getConversion_routine().getParams() == null) throw new IllegalStateException("add params not set"); if (cliConnector == null) throw new IllegalStateException("Cli Connector is not set"); File result = new File(generateTargetFilePath(wa, ci)); List<Event> results = new ArrayList<Event>(); getHttpclient().setUrl(ci.getConversion_routine().getParams()); getHttpclient()/*from w w w .j a va 2 s. c o m*/ .setSourceMimeType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); getHttpclient().postFileAndReadResponse(wa.toFile(ci.getSource_file()), result); if (result.exists()) { DAFile daf = new DAFile(object.getNameOfLatestBRep(), StringUtilities.slashize(ci.getTarget_folder()) + result.getName()); logger.debug("new dafile:" + daf); // TODO Doing PDF/A Conversion with a temp file, due to recieve PDF 1.5 from MS instead of PDF/A . // This should be the same command for "normal" PDFs // read it from Database? File tempFile = new File( "/" + FilenameUtils.getPath(wa.toFile(daf).getAbsolutePath()) + "_" + wa.toFile(daf).getName()); String commandAsArray[] = new String[] { "gs", "-q", "-dPDFA", "-dPDFACompatibilityPolicy=1", "-dBATCH", "-dNOPAUSE", "-dNOOUTERSAVE", "-dUseCIEColor", "-sProcessColorModel=DeviceCMYK", "-sDEVICE=pdfwrite", "-sOutputFile=" + tempFile.getAbsolutePath(), "conf/PDFA_def.ps", wa.toFile(daf).getAbsolutePath() }; if (!cliConnector.execute(commandAsArray)) { throw new RuntimeException("GS command not succeeded"); } try { if (tempFile.exists()) { result.delete(); FileUtils.moveFile(tempFile, wa.toFile(daf)); } else throw new RuntimeException("temp file " + tempFile.getAbsolutePath() + " was not created!"); } catch (IOException e1) { throw new RuntimeException("MV command not succeeded on temp file " + tempFile.getAbsolutePath(), e1); } PdfService.validatePdfA(wa.toFile(daf)); Event e = new Event(); e.setType("CONVERT"); e.setDetail("Webservice DOCX2PDF " + ci.getConversion_routine().getParams() + " AND " + StringUtilities.createString(commandAsArray)); e.setSource_file(daf); e.setTarget_file(daf); e.setDate(new Date()); results.add(e); } else throw new RuntimeException("Target File not found! " + result.getAbsolutePath()); return results; }
From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java
/** * This does the hard work of sorting - called as a shutdown hook. * TODO: consider recursion.//w ww . j ava 2 s. c o m * @param outputName name for the output file. * @param files list of MiniSEED files to multiplex. * @param cleanup flag indicating whether to cleanup after ourselves or not. * @throws IOException */ public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty) throws IOException { ArrayList<File> cleanupFiles = new ArrayList<File>(files); ArrayList<File> moreFiles = new ArrayList<File>(); File outputFile = new File(outputName); File tempOutputFile = new File(outputName + ".tmp"); do { // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...? if (!moreFiles.isEmpty()) { logger.info("more files left to multiplex..."); FileUtils.deleteQuietly(tempOutputFile); FileUtils.moveFile(outputFile, tempOutputFile); cleanupFiles.add(tempOutputFile); moreFiles.add(tempOutputFile); files = moreFiles; moreFiles = new ArrayList<File>(); } logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}", new Object[] { files.size(), outputName }); BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile)); // The hard part, sorting the temp files... TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>( new MiniSeedTimeOnlyComparator()); // Prime the TreeMap logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files); for (File file : files) { logger.log(Level.INFO, "Reading first block from {0}", file.toString()); try { FileInputStream fs = FileUtils.openInputStream(file); MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty); if (ms != null) { blks.put(ms, fs); } else { logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString()); } } catch (IOException ex) { // Catch "Too many open files" i.e. hitting ulimit, throw anything else. if (ex.getMessage().contains("Too many open files")) { logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString()); moreFiles.add(file); } else throw ex; } } while (!blks.isEmpty()) { MiniSeed next = blks.firstKey(); out.write(next.getBuf(), 0, next.getBlockSize()); FileInputStream fs = blks.remove(next); next = getNextValidMiniSeed(fs, allowEmpty); if (next != null) { blks.put(next, fs); } else { fs.close(); } } out.close(); } while (!moreFiles.isEmpty()); if (cleanup) { logger.log(Level.INFO, "Cleaning up..."); for (File file : cleanupFiles) { FileUtils.deleteQuietly(file); } } }
From source file:com.cyberocw.habittodosecretary.file.StorageHelper.java
/** * Creates a fiile to be used as attachment. *///from w w w .jav a 2 s .c o m public static FileVO createAttachmentFromUri(Context mContext, Uri uri, boolean moveSource) { String name = FileHelper.getNameFromUri(mContext, uri); String extension = FileHelper.getFileExtension(name).toLowerCase(Locale.getDefault()); File f; if (moveSource) { f = createNewAttachmentFile(mContext, extension); try { FileUtils.moveFile(new File(uri.getPath()), f); } catch (IOException e) { //Log.e(Constants.TAG, "Can't move file " + uri.getPath()); } } else { //getExternalFilesDir ? ? f = StorageHelper.createExternalStoragePrivateFile(mContext, uri, extension); } FileVO mAttachment = null; if (f != null) { mAttachment = new FileVO(Uri.fromFile(f), StorageHelper.getMimeTypeInternal(mContext, uri)); mAttachment.setName(name); mAttachment.setSize(f.length()); } return mAttachment; }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File hudsonTemplateWar = new File(warTemplateFile); if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) { String message = "The given Hudson template WAR [" + hudsonTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);//from w w w . j a va 2 s.c o m throw new IllegalStateException(message); } String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration); File hudsonDeployFile = new File(deployLocation); if (hudsonDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct HUDSON_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar), hudsonTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat. FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:gsn.http.ac.ParameterSet.java
public DataSource fileUploader(String vsname, String saveDirectory) { DataSource ds = null;//from w ww. j a va2 s . c o m String name = null; String filename = null; String filetype = null; File file = null; try { Enumeration filesEnum = this.multipartreq.getFileNames(); while (filesEnum.hasMoreElements()) { name = (String) filesEnum.nextElement(); filename = this.multipartreq.getFilesystemName(name); filetype = this.multipartreq.getContentType(name); file = this.multipartreq.getFile(name); if (filename != null && filetype != null) { //rename the name of the Virtual Sensor to the unique name //logger.info("filename " + filename); //logger.info("name " + name); //logger.info("abs path " + file.getAbsolutePath()); changeSensorName(file.getAbsolutePath(), vsname); String newFilePath = file.getAbsolutePath().replace(file.getName(), "") + vsname + ".xml"; File newFile = new File(newFilePath); try { FileUtils.moveFile(file, newFile); } catch (IOException e) { logger.error(e.getMessage(), e); } ds = new DataSource(vsname, "4", vsname + ".xml", filetype, saveDirectory); } if (file != null) { logger.info("length: " + file.length()); } } } catch (Exception e) { logger.error("ERROR IN fileUploader Method"); logger.error(e.getMessage(), e); } return ds; }
From source file:com.serotonin.m2m2.Main.java
private static void openZipFiles() throws Exception { ProcessEPoll pep = new ProcessEPoll(); try {//w w w.j a v a2s . c o m new Thread(pep).start(); File[] zipFiles = new File(new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString()) .listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".zip"); } }); if ((zipFiles == null) || (zipFiles.length == 0)) return; for (File file : zipFiles) { if (!file.isFile()) { continue; } ZipFile zip = new ZipFile(file); try { Properties props = getProperties(zip); String moduleName = props.getProperty("name"); if (moduleName == null) { throw new RuntimeException("name not defined in module properties"); } if (!ModuleUtils.validateName(moduleName)) { throw new RuntimeException(new StringBuilder().append("Module name '").append(moduleName) .append("' is invalid").toString()); } File moduleDir = new File( new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString(), moduleName); if (moduleDir.exists()) LOG.info(new StringBuilder().append("Upgrading module ").append(moduleName).toString()); else { LOG.info(new StringBuilder().append("Installing module ").append(moduleName).toString()); } String persistDirs = props.getProperty("persistPaths"); File moduleSaveDir = new File(new StringBuilder().append(moduleDir).append(".save").toString()); if (!org.apache.commons.lang3.StringUtils.isBlank(persistDirs)) { String[] paths = persistDirs.split(","); for (String path : paths) { path = path.trim(); if (!org.apache.commons.lang3.StringUtils.isBlank(path)) { File from = new File(moduleDir, path); File to = new File(moduleSaveDir, path); if (from.exists()) { if (from.isDirectory()) moveDir(from, to); else { FileUtils.moveFile(from, to); } } } } } deleteDir(moduleDir); if (moduleSaveDir.exists()) moveDir(moduleSaveDir, moduleDir); else { moduleDir.mkdirs(); } Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(moduleDir, name); if (entry.isDirectory()) entryFile.mkdirs(); else { writeFile(entryFile, zip.getInputStream(entry)); } } File moduleWorkDir = new File(moduleDir, "work"); if (moduleWorkDir.exists()) { moveDir(moduleWorkDir, new File(Common.MA_HOME, "work")); } if (HostUtils.isLinux()) { String permissions = props.getProperty("permissions"); if (!org.apache.commons.lang3.StringUtils.isBlank(permissions)) { String[] s = permissions.split(","); for (String permission : s) { setPermission(pep, moduleName, moduleDir, permission); } } } zip.close(); } catch (Exception e) { LOG.warn(new StringBuilder().append("Error while opening zip file ").append(file.getName()) .append(". Is this module built for the core version that you are using? Module ignored.") .toString(), e); } finally { zip.close(); } file.delete(); } } finally { pep.waitForAll(); pep.terminate(); } }
From source file:gov.nih.nci.caintegrator.file.FileManagerImpl.java
/** * {@inheritDoc}//from w w w . j av a 2 s . c om */ public File createSamplesFile(StudySubscription studySubscription, SampleWithChromosomalSegmentSet[] samples) throws IOException { File tmpFile = GisticUtils.writeSampleFile(samples); File resultFile = createNewStudySubscriptionFile(studySubscription, tmpFile.getName()); FileUtils.moveFile(tmpFile, resultFile); return resultFile; }
From source file:is.iclt.jcorpald.CorpaldModel.java
private void performRunQuery() throws Exception { String queryFile = null;//from w ww . j av a 2 s . com String outputFile = null; String targetFile = null; if (this.file == null) { queryFile = new File(this.getTempQueryPath()).getPath(); // outputFile = this.getTempOutputPath(); } else { queryFile = this.file.getPath(); // outputFile = queryFile.substring(0,queryFile.length()-2)+".out"; } outputFile = queryFile.substring(0, queryFile.length() - 2) + ".out"; targetFile = outputFile.substring(0, outputFile.length() - 4) + ".txt"; try { // FileUtils.deleteQui(new File(outputFile)); new File(outputFile).delete(); System.out.println("Deleted: " + outputFile); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } // Write the query to a temporary file this.file = new File(queryFile); FileUtils.writeStringToFile(file, this.constructQueryFile(), "utf-8"); String cmd = "java -classpath lib/CS_2.002.75.jar csearch.CorpusSearch \"" + new File(queryFile).getPath() + "\" corpora/" + CorpaldSettings.getInstance().getProperty("corpus.directory") + "/*.psd -out \"" + new File(outputFile).getPath() + "\""; if (!OSValidator.isWindows()) { cmd = cmd.replace("\"", ""); } result = cmd; System.out.println(cmd); /* Runtime run = Runtime.getRuntime(); Process pr = null; pr = run.exec(cmd); pr.waitFor(); */ //hhhhhhhh Process application = Runtime.getRuntime().exec(cmd); StringBuffer inBuffer = new StringBuffer(); InputStream inStream = application.getInputStream(); new InputStreamHandler(inBuffer, inStream); StringBuffer errBuffer = new StringBuffer(); InputStream errStream = application.getErrorStream(); new InputStreamHandler(errBuffer, errStream); application.waitFor(); // TODO deal with somehow // System.out.println(stdout); // System.out.println(stderr); String result = FileUtils.readFileToString(new File(outputFile), "utf-8"); FileUtils.deleteQuietly(new File(targetFile)); FileUtils.moveFile(new File(outputFile), new File(targetFile)); //String line; //boolean error = false; //String stdout = IOUtils.toString(pr.getInputStream()).trim(); // String stderr = "x"; // IOUtils.toString(pr.getErrorStream()).trim(); // if( pr.getErrorStream() // System.out.println(stderr); if (errBuffer.toString().indexOf("ERROR!") > -1) { result = "Unfortunately there is a problem with your query.\nCorpusSearch was unable to " + "come up with results.\n\n" + "Did you misspell a keyword, a logical operator or a reference to the definitions file?\n" + "- those are displayed in orange, blue and green respectively if well-formed\n" + "Did you use the correct number of arguments for all search functions?\n" + "- for example, 'idoms' requires two arguments while 'idomsmod' requires three \n" + "- see CorpusSearch documentation (http://corpussearch.sourceforge.net)\n" + "Do you have unmatched parentheses or brackets?\n"; } this.setModified(false); this.notifyQueryObservsers(); setResult(result); }
From source file:algorithm.BagItPackaging.java
@Override public List<RestoredFile> restore(File data) throws IOException { // BagIt won't override an existing directory, so delete: FileUtils.deleteDirectory(new File(RESTORED_DIRECTORY + data.getName().split("_")[0] + "_BAG")); File restoredData = new File(RESTORED_DIRECTORY + data.getName()); // Move bag to restoration directory: if (!data.getPath().equals(restoredData.getPath())) { FileUtils.copyFile(data, restoredData); }/*from w w w .j a va 2 s. c om*/ List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>(); Loader loader = new Loader(restoredData); Bag bag = loader.load(); // get carrier / digital object files: Map<String, String> carriersContents = bag.payloadManifest(); for (Entry<String, String> entry : carriersContents.entrySet()) { String carrierName = entry.getKey(); File carrierFile = new File(RESTORED_DIRECTORY + bag.bagName() + File.separator + carrierName); RestoredFile restoredCarrier = new RestoredFile(RESTORED_DIRECTORY + carrierFile.getName()); restoredCarrier.delete();// BagIt won't override! FileUtils.moveFile(carrierFile, restoredCarrier); restoredCarrier.algorithm = this; restoredCarrier.wasCarrier = true; restoredFiles.add(restoredCarrier); } // get payload / metadata files: Map<String, String> payloadContents = bag.tagManifest(); payloadContents.remove("bagit.txt"); payloadContents.remove("bag-info.txt"); payloadContents.remove("manifest-md5.txt"); for (Entry<String, String> entry : payloadContents.entrySet()) { String payloadName = entry.getKey(); File payloadFile = new File(RESTORED_DIRECTORY + bag.bagName() + File.separator + payloadName); RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadFile.getName()); restoredPayload.delete();// BagIt won't override existing files! FileUtils.moveFile(payloadFile, restoredPayload); restoredPayload.wasPayload = true; restoredFiles.add(restoredPayload); } for (RestoredFile file : restoredFiles) { file.algorithm = this; file.checksumValid = true; file.restorationNote = "The algorithm doesn't alter these files, so they are brought to its original state. No checksum validation executed."; for (RestoredFile relatedFile : restoredFiles) { if (file != relatedFile) { file.relatedFiles.add(relatedFile); } } } return restoredFiles; }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.RemoveRawFileListener.java
@Override public void handleEvent(Event event) { Vector<File> files = this.selectRawFilesUI.getSelectedRemovedFile(); File cmf = ((ClinicalData) this.dataType).getCMF(); File wmf = ((ClinicalData) this.dataType).getWMF(); boolean confirm = this.selectRawFilesUI.confirm( "The column mapping file and the word mapping file will be updated or removed consequently.\nAre you sure to remove these files?"); for (File file : files) { if (file == null) { return; }/* w w w . j a v a 2s . co m*/ if (((ClinicalData) this.dataType).getRawFiles().size() == files.size()) { if (cmf != null || wmf != null) { if (confirm) { if (cmf != null) { ((ClinicalData) this.dataType).setCMF(null); try { FileUtils.forceDelete(cmf); } catch (IOException e) { // TODO Auto-generated catch block this.selectRawFilesUI.displayMessage("File error: " + e.getLocalizedMessage()); e.printStackTrace(); } } if (wmf != null) { ((ClinicalData) this.dataType).setWMF(null); try { FileUtils.forceDelete(wmf); } catch (IOException e) { // TODO Auto-generated catch block this.selectRawFilesUI.displayMessage("File error: " + e.getLocalizedMessage()); e.printStackTrace(); } } ((ClinicalData) this.dataType).getRawFiles().remove(file); FileUtils.deleteQuietly(file); UsedFilesPart.sendFilesChanged(dataType); } } else { if (confirm) { ((ClinicalData) this.dataType).getRawFiles().remove(file); FileUtils.deleteQuietly(file); UsedFilesPart.sendFilesChanged(dataType); } } } else {//several raw files: update cmf and wmf to remove lines for this raw file if (cmf != null || wmf != null) { if (confirm) { if (cmf != null) { File newCmf = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try { FileWriter fw = new FileWriter(newCmf); BufferedWriter out = new BufferedWriter(fw); try { BufferedReader br = new BufferedReader(new FileReader(cmf)); String line; while ((line = br.readLine()) != null) { if (line.split("\t", -1)[0].compareTo(file.getName()) != 0) { out.write(line + "\n"); } } br.close(); } catch (Exception e) { this.selectRawFilesUI.displayMessage("File error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } out.close(); String fileName = cmf.getName(); FileUtils.deleteQuietly(cmf); try { File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(newCmf, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (Exception ioe) { this.selectRawFilesUI .displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.selectRawFilesUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } } if (wmf != null) { File newWmf = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".words.tmp"); try { FileWriter fw = new FileWriter(newWmf); BufferedWriter out = new BufferedWriter(fw); try { BufferedReader br = new BufferedReader(new FileReader(wmf)); String line; while ((line = br.readLine()) != null) { if (line.split("\t", -1)[0].compareTo(file.getName()) != 0) { out.write(line + "\n"); } } br.close(); } catch (Exception e) { this.selectRawFilesUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } out.close(); String fileName = wmf.getName(); FileUtils.deleteQuietly(wmf); try { File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(newWmf, fileDest); ((ClinicalData) this.dataType).setWMF(fileDest); } catch (Exception ioe) { this.selectRawFilesUI .displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.selectRawFilesUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } } ((ClinicalData) this.dataType).getRawFiles().remove(file); FileUtils.deleteQuietly(file); UsedFilesPart.sendFilesChanged(dataType); } } else { if (confirm) { ((ClinicalData) this.dataType).getRawFiles().remove(file); FileUtils.deleteQuietly(file); UsedFilesPart.sendFilesChanged(dataType); } } } } this.selectRawFilesUI.updateViewer(); WorkPart.updateSteps(); WorkPart.updateFiles(); }