List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:org.kuali.rice.testtools.selenium.JenkinsJsonJobResultsBase.java
protected void fetchArchive(String job, String jobNumber) throws InterruptedException, IOException { String archiveUrl = jenkinsBase; // Views will need to be updated/improved to work with ci.kuali.org if (job.contains("rice-2.4")) { archiveUrl += "/view/rice-2.4"; }// w w w . java 2 s.co m archiveUrl += "/job/" + job + "/" + jobNumber + "/artifact/*zip*/archive.zip"; driver.get(archiveUrl); Thread.sleep(10000); //zip needs time to download FileUtils.moveFile(new File(downloadDir + File.separator + "archive.zip"), new File(downloadDir + File.separator + job + "-" + jobNumber + ".zip")); }
From source file:org.lamport.tla.toolbox.tool.tlc.model.Model.java
public Model snapshot() throws CoreException { // Create a copy of the underlying launch configuration. final Model snapshot = copy(getName() + SNAP_SHOT + System.currentTimeMillis()); // Snapshot the model's markers as well (e.g. the information about errors, see hasErrors()). final IMarker[] markers = getMarkers(); for (IMarker iMarker : markers) { snapshot.setMarker(iMarker.getAttributes(), iMarker.getType()); }/*from w w w . j a va2 s . c o m*/ // Set the snapshot to be locked? Do we want the user to be able to run it again? // snapshot.setLocked(true); /* * Snapshot (copy) the model folder which include the TLC output as well as the version * of the spec and module overwrites with which TLC ran. */ final IPath snapshotPath = getSpec().getProject().getFolder(snapshot.getName()).getLocation(); final IPath modelFolder = getSpec().getProject().getFolder(this.getName()).getLocation(); // Use non-Eclipse API instead of modelFolder.copy(snapshotFolder, false, // monitor which supports a non-recursive copy. A recursive copy includes the // states/ directory leftover from TLC which waste quite some space and might // take some time to copy. try { FileUtils.copyDirectory(modelFolder.toFile(), snapshotPath.toFile(), new NotFileFilter(DirectoryFileFilter.DIRECTORY)); // Rename .dot file name because hasStateGraphDump checks if a .dot file exists // that matches the name of the model. if (hasStateGraphDump()) { final IPath oldDotFile = getSpec().getProject() .getFolder(snapshot.getName() + File.separator + this.getName() + ".dot").getLocation(); final IPath newDotFile = getSpec().getProject() .getFolder(snapshot.getName() + File.separator + snapshot.getName() + ".dot").getLocation(); FileUtils.moveFile(oldDotFile.toFile(), newDotFile.toFile()); } // Now that we've had a successful save, prune any snapshots, starting with the oldest, in order to assure the // cardinality no greater than snapshotKeepCount. pruneOldestSnapshots(); // Refresh the snapshot folder after having copied files without using the // Eclipse resource API. Otherwise, the resource API does not see the files // which e.g. results in an incomplete model deletion or hasStateGraphDump // incorrectly returning false. snapshot.getFolder().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor()); } catch (IOException e) { throw new CoreException(new Status(Status.ERROR, TLCActivator.PLUGIN_ID, e.getMessage(), e)); } return snapshot; }
From source file:org.messic.server.api.APIAlbum.java
public long createOrUpdateAlbum(User user, Album album) throws IOException, ExistingMessicException { Long sidResult = 0l;// w w w .j a v a2 s.co m MDOGenre mdoGenre = null; MDOAlbum mdoAlbum = null; MDOAuthor mdoAuthor = null; MDOUser mdouser = daoUser.getUserByLogin(user.getLogin()); char replacementChar = daoSettings.getSettings().getIllegalCharacterReplacement(); MDOMessicSettings settings = daoSettings.getSettings(); // 1st getting genre ############################################################################### if (album.getGenre() != null && album.getGenre().getSid() != null) { mdoGenre = daoGenre.get(album.getGenre().getSid()); } if (mdoGenre == null) { if (album.getGenre() != null && album.getGenre().getName() != null && album.getGenre().getName().trim().length() > 0) { mdoGenre = daoGenre.getByName(user.getLogin(), album.getGenre().getName()); } } if (mdoGenre == null && album.getGenre() != null && album.getGenre().getName() != null && album.getGenre().getName().trim().length() > 0) { mdoGenre = new MDOGenre(album.getGenre().getName(), mdouser); } // 2nd getting the album if exist // ############################################################################### if (album.getSid() > 0) { mdoAlbum = daoAlbum.get(album.getSid()); } // 3rd getting the author ############################################################################### if (album.getAuthor().getSid() > 0) { // trying by sid mdoAuthor = daoAuthor.get(user.getLogin(), album.getAuthor().getSid()); } if (mdoAuthor == null) { // trying by name mdoAuthor = daoAuthor.getByName(album.getAuthor().getName(), user.getLogin()); } if (mdoAuthor != null) { // an existing album from this autor?? if (mdoAlbum == null) { mdoAlbum = daoAlbum.getByName(mdoAuthor.getName(), album.getName(), user.getLogin()); } } // let's create a new author if (mdoAuthor == null) { mdoAuthor = new MDOAuthor(); mdoAuthor.setName(album.getAuthor().getName().trim()); mdoAuthor.setOwner(mdouser); mdoAuthor.setLocation( Util.replaceIllegalFilenameCharacters(album.getAuthor().getName(), replacementChar)); } // 4th new album if none ############################################################################### if (mdoAlbum == null) { mdoAlbum = new MDOAlbum(); } boolean flagExistingAuthor = (mdoAuthor.getSid() != null && mdoAuthor.getSid() > 0); boolean flagAuthorNameChanged = false; boolean flagExistingAlbum = (mdoAlbum.getSid() != null && mdoAlbum.getSid() > 0); // checking if the user is trying to create a new album with the same name and author of another existing one. // the reason to forbide this is because of the filesystem. Both albums will have the same filesystem path, and // will merge their content!! panic!! List<MDOAlbum> albumsSameName = daoAlbum.findAlbum(album.getName(), user.getLogin()); if (albumsSameName.size() > 0) { for (MDOAlbum mdoAlbumSameName : albumsSameName) { if (mdoAlbumSameName.getSid() != mdoAlbum.getSid()) { String authorName = mdoAlbumSameName.getAuthor().getName(); if (authorName.toUpperCase().equals(album.getAuthor().getName().toUpperCase())) { throw new ExistingMessicException(); } } } } // old album path if the album was an existing one String oldAlbumPath = null; if (flagExistingAlbum) { oldAlbumPath = mdoAlbum.calculateAbsolutePath(settings); } // 5th updating / creating the album // ############################################################################### // if its an existing author and the name of the author has changed...wow!! we must do more things if (flagExistingAuthor && !album.getAuthor().getName().trim().toUpperCase() .equals(mdoAuthor.getName().trim().toUpperCase())) { // the name of the author has changed!!! flagAuthorNameChanged = true; mdoAuthor.setName(album.getAuthor().getName()); mdoAuthor.setLocation( Util.replaceIllegalFilenameCharacters(album.getAuthor().getName(), replacementChar)); } mdoAlbum.setName(album.getName()); mdoAlbum.setLocation(Util.replaceIllegalFilenameCharacters(album.getName(), replacementChar)); mdoAlbum.setAuthor(mdoAuthor); mdoAlbum.setComments(album.getComments()); mdoAlbum.setGenre(mdoGenre); mdoAlbum.setOwner(mdouser); mdoAlbum.setYear(album.getYear()); // 6th saving author, genre and album // ############################################################################### daoAuthor.save(mdoAuthor); if (mdoGenre != null) { daoGenre.save(mdoGenre); } daoAlbum.save(mdoAlbum); sidResult = mdoAlbum.getSid(); if (sidResult <= 0) { mdoAlbum = daoAlbum.merge(mdoAlbum); sidResult = mdoAlbum.getSid(); } // 7th moving album resources to definitive location // ############################################################################### String currentAlbumPath = mdoAlbum.calculateAbsolutePath(settings); File currentAlbumPathFile = new File(currentAlbumPath); String userTmpPath = mdouser.calculateTmpPath(settings, album.getCode()); // creating album path currentAlbumPathFile.mkdirs(); // 7.1 - Songs resources if (album.getSongs() != null && album.getSongs().size() > 0) { List<Song> songs = album.getSongs(); for (Song song : songs) { MDOSong mdoSong = new MDOSong(); File fnew = null; if (song.getSid() <= 0) { MDOSongStatistics ss = new MDOSongStatistics(); ss.setTimesplayed(0); ss.setTimesstopped(0); daoSongStatistics.save(ss); // new song mdoSong.setStatistics(ss); mdoSong.setTrack(song.getTrack()); mdoSong.setName(song.getName()); String secureExtension = song.calculateSecureExtension(replacementChar); String theoricalFileName = mdoSong.calculateSongTheoricalFileName(secureExtension, replacementChar); mdoSong.setLocation(theoricalFileName); mdoSong.setOwner(mdouser); mdoSong.setAlbum(mdoAlbum); daoSong.save(mdoSong); // moving resource to the new location File tmpRes = new File( userTmpPath + File.separatorChar + song.calculateSecureFileName(replacementChar)); fnew = new File(mdoSong.calculateAbsolutePath(settings)); if (fnew.exists()) { fnew.delete(); } FileUtils.moveFile(tmpRes, fnew); } else { // existing song... mdoSong = daoSong.get(user.getLogin(), song.getSid()); if (mdoSong != null) { mdoSong.setTrack(song.getTrack()); mdoSong.setName(song.getName()); String oldLocation = mdoSong.calculateAbsolutePath(settings); String theoricalFileName = mdoSong.calculateSongTheoricalFileName(mdoSong.getExtension(), replacementChar); mdoSong.setLocation(theoricalFileName); daoSong.save(mdoSong); File fold = new File(oldLocation); fnew = new File(mdoSong.calculateAbsolutePath(settings)); if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) { FileUtils.moveFile(fold, fnew); } } } AudioTaggerTAGWizardPlugin atp = new AudioTaggerTAGWizardPlugin(); org.messic.server.api.tagwizard.service.Album salbum = new org.messic.server.api.tagwizard.service.Album(); salbum.author = mdoAlbum.getAuthor().getName(); salbum.name = mdoAlbum.getName(); if (mdoAlbum.getComments() != null) salbum.comments = mdoAlbum.getComments(); if (mdoAlbum.getGenre() != null) salbum.genre = mdoAlbum.getGenre().getName(); salbum.year = mdoAlbum.getYear(); org.messic.server.api.tagwizard.service.Song ssong = new org.messic.server.api.tagwizard.service.Song(); ssong.track = mdoSong.getTrack(); ssong.name = mdoSong.getName(); try { atp.saveTags(salbum, ssong, fnew); } catch (CannotReadException e) { log.error(e); // throw new IOException( e.getMessage(), e.getCause() ); } catch (TagException e) { log.error(e); // throw new IOException( e.getMessage(), e.getCause() ); } catch (ReadOnlyFileException e) { log.error(e); // throw new IOException( e.getMessage(), e.getCause() ); } catch (InvalidAudioFrameException e) { log.error(e); // throw new IOException( e.getMessage(), e.getCause() ); } catch (CannotWriteException e) { log.error(e); // throw new IOException( e.getMessage(), e.getCause() ); } } } // 7.2 - Artwork resources if (album.getArtworks() != null && album.getArtworks().size() > 0) { List<org.messic.server.api.datamodel.File> files = album.getArtworks(); for (org.messic.server.api.datamodel.File file : files) { if (file.getSid() <= 0) { MDOArtwork mdopr = new MDOArtwork(); mdopr.setLocation(file.calculateSecureFileName(replacementChar)); mdopr.setOwner(mdouser); mdopr.setAlbum(mdoAlbum); org.messic.server.api.datamodel.File fcover = album.getCover(); if (fcover != null && file.getFileName().equals(album.getCover().getFileName())) { mdopr.setCover(true); } daoPhysicalResource.save(mdopr); mdoAlbum.getArtworks().add(mdopr); // moving resource to the new location File tmpRes = new File( userTmpPath + File.separatorChar + file.calculateSecureFileName(replacementChar)); File newFile = new File( currentAlbumPath + File.separatorChar + file.calculateSecureFileName(replacementChar)); if (newFile.exists()) { newFile.delete(); } FileUtils.moveFileToDirectory(tmpRes, currentAlbumPathFile, false); } else { // existing artwork... MDOAlbumResource resource = daoAlbumResource.get(user.getLogin(), file.getSid()); if (resource != null) { String oldLocation = resource.calculateAbsolutePath(settings); resource.setLocation(file.calculateSecureFileName(replacementChar)); daoAlbumResource.save(resource); File fold = new File(oldLocation); File fnew = new File(resource.calculateAbsolutePath(settings)); if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) { FileUtils.moveFile(fold, fnew); } } } } daoAlbum.save(mdoAlbum); } // 7.3 - Other resources if (album.getOthers() != null && album.getOthers().size() > 0) { List<org.messic.server.api.datamodel.File> files = album.getOthers(); for (org.messic.server.api.datamodel.File file : files) { if (file.getSid() <= 0) { MDOOtherResource mdopr = new MDOOtherResource(); mdopr.setLocation(file.calculateSecureFileName(replacementChar)); mdopr.setOwner(mdouser); mdopr.setAlbum(mdoAlbum); daoPhysicalResource.save(mdopr); mdoAlbum.getOthers().add(mdopr); // moving resource to the new location File tmpRes = new File( userTmpPath + File.separatorChar + file.calculateSecureFileName(replacementChar)); File newFile = new File(mdopr.calculateAbsolutePath(settings)); if (newFile.exists()) { newFile.delete(); } FileUtils.moveFileToDirectory(tmpRes, currentAlbumPathFile, false); } else { // existing artwork... MDOAlbumResource resource = daoAlbumResource.get(user.getLogin(), file.getSid()); if (resource != null) { String oldLocation = resource.calculateAbsolutePath(settings); resource.setLocation(file.calculateSecureFileName(replacementChar)); daoAlbumResource.save(resource); File fold = new File(oldLocation); File fnew = new File(resource.calculateAbsolutePath(settings)); if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) { FileUtils.moveFile(fold, fnew); } } } } daoAlbum.save(mdoAlbum); } // let's see if the album was an existing one... then it should moved to the new location if (oldAlbumPath != null && !oldAlbumPath.equals(currentAlbumPath)) { List<MDOAlbumResource> resources = mdoAlbum.getAllResources(); for (int i = 0; i < resources.size(); i++) { MDOAlbumResource resource = resources.get(i); String resourceNewPath = resource.calculateAbsolutePath(settings); String resourceCurrentPath = oldAlbumPath + File.separatorChar + resource.getLocation(); File fnewPath = new File(resourceNewPath); File foldPath = new File(resourceCurrentPath); if (foldPath.exists()) { FileUtils.moveFile(foldPath, fnewPath); } } File fAlbumOldPath = new File(oldAlbumPath); FileUtils.deleteDirectory(fAlbumOldPath); // if the author have changed the name, we have only moved those resources from this album, but the author // could have other albums, we need to move also. if (flagAuthorNameChanged) { File newAuthorLocation = new File(mdoAuthor.calculateAbsolutePath(settings)); // we must move all the authors albums to the new one folder File oldAuthorFolder = fAlbumOldPath.getParentFile(); File[] oldfiles = oldAuthorFolder.listFiles(); for (File file2 : oldfiles) { if (file2.isDirectory()) { FileUtils.moveDirectoryToDirectory(file2, newAuthorLocation, true); } } // finally we remove the old location FileUtils.deleteDirectory(oldAuthorFolder); } } return sidResult; }
From source file:org.messic.server.api.APISong.java
@Transactional public void updateSong(User user, Song song) throws SidNotFoundMessicException, IOException { MDOSong mdosong = daoSong.get(user.getLogin(), song.getSid()); if (mdosong != null) { String oldLocation = mdosong.calculateAbsolutePath(daoSettings.getSettings()); boolean nameChanged = !song.getName().equals(mdosong.getName()); try {// ww w.j a v a2 s .c om if (nameChanged) { mdosong.setName(song.getName()); } mdosong.setRate(song.getRate()); mdosong.setTrack(song.getTrack()); daoSong.save(mdosong); } finally { if (nameChanged) { String newLocation = mdosong.calculateAbsolutePath(daoSettings.getSettings()); File fOld = new File(oldLocation); if (fOld.exists()) { FileUtils.moveFile(fOld, new File(newLocation)); } else { throw new IOException("The song file doesn't exist!!"); } } } } else { throw new SidNotFoundMessicException(); } }
From source file:org.metaeffekt.dcc.commons.execution.ExecutionStateHandler.java
/** * Called by the command executor after successful command execution to update the local * execution state (cache)./*from w ww . java 2 s .com*/ * * @param executionPropertiesFile */ public void persistStateAfterSuccessfulExecution(Id<? extends Type> id, Commands command, File executionPropertiesFile) { File targetFolder = configurationDirectory; if (id.getType().isAssignableFrom(UnitId.class)) { handleStateOfDependendCommands(id.getValue(), command); } // handle file if exists (some commands do not produce a properties file) if (executionPropertiesFile != null && executionPropertiesFile.exists()) { // some commands should not persist a state at all if (command.persistentState()) { try { File targetFile = DccUtils.propertyFileForGenericId(targetFolder, id, command); // NOTE we do not delete/move any file if the source is the target. This // is for example the case for the agent watchdog, which operates on the start.properties. if (!executionPropertiesFile.getCanonicalPath().equals(targetFile.getCanonicalPath())) { FileUtils.deleteQuietly(targetFile); FileUtils.moveFile(executionPropertiesFile, targetFile); if (!targetFile.exists()) { throw new IllegalStateException(String.format( "Error while updating execution status: Moved execution properties are not in %s", targetFile)); } } } catch (IOException up) { LOG.error(String.format( "Error while updating execution status: Unable to move execution properties %s to %s", executionPropertiesFile.getAbsolutePath(), configurationDirectory.getAbsolutePath()), up); throw new RuntimeException(up); } } } }
From source file:org.metaeffekt.dita.maven.mojo.GenerateDocumentationMojo.java
/** * Iterates of the {@link org.metaeffekt.dita.maven.generation.DocumentItem} objects defined * in the plugin configuration. For each of the items to the following: * <ul>/*w ww . ja v a 2 s . c o m*/ * <li>Validate the configuration of the item.</li> * <li>Setup the DITA OT Ant-based launcher.</li> * <li>Generate the documentation in the specified output format.</li> * <li>Do postprocessing depending on the type of documentation created (e.g. create ZIP-archive).</li> * <li>Attach the generated artifact to the current Maven module.</li> * </ul> * * @throws MojoExecutionException * @throws MojoFailureException */ @Override public void execute() throws MojoExecutionException, MojoFailureException { super.execute(); if (skipProject()) { if (isPomPackagingProject()) { getLog().info("Skipping execution project of packaging type POM."); } return; } // iterate over the document items defined in the POM in the plugin configuration for (DocumentItem documentItem : documentItems) { // validate the configuration given and locate the DITA Map documentItem.validate(); File ditaMap = new File(ditaBuildDir, documentItem.getDitaMap()); if (!ditaMap.exists()) { throw new MojoExecutionException("DITA Map '" + ditaMap.getAbsolutePath() + "' does not exist!"); } else { getLog().info("Found DITA Map: " + ditaMap.getAbsolutePath()); } String documentName = documentItem.getTargetFileName(getCurrentProject().getVersion()); getLog().info("Document name: " + documentName); // Common Bootstrapping // setup the Ant task for launching the DITA OT ExternalAntDitaLauncher dita = new ExternalAntDitaLauncher(); dita.setInputMap(ditaMap.getAbsolutePath()); dita.setBaseDir(ditaGenerationDir.getAbsolutePath()); dita.setDitaDir(getDitaHome()); dita.setTranstype(documentItem.getDitaTranstype().toString()); dita.setCleanDitaTemp(ditaCleanTemp); dita.setLog(getLog()); dita.setGenerateToc(generateToc); dita.setDraft(ditaIsDraft); dita.setGrammarCacheEnabled(enableGrammarCache); if (ditaCustomizationDir != null) { dita.setCustomizationDir(ditaCustomizationDir.getAbsolutePath()); } dita.setCustomCss(documentItem.getCustomCss()); addDitavalFile(dita, ditaMap); dita.setTempDir(getTempDirectory()); ArtifactHandler handler = artifactHandlerManager .getArtifactHandler(getTransTypeFileExtension(documentItem.getDitaTranstype())); // the handler is not directly used, so the jar handler is also fine, if there is // no handler available for PDF documents if (handler == null) { handler = artifactHandlerManager.getArtifactHandler("jar"); } if (MULTI_FILE_FORMATS.contains(documentItem.getDitaTranstype())) { dita.setOutputDir(ditaTargetDir.getAbsolutePath() + File.separator + documentItem.getArtifactId() + ((documentItem.getArtifactClassifier().equals("")) ? "" : "-" + documentItem.getArtifactClassifier())); // generate documentation dita.execute(); // copy additional resources, if any if (documentItem.getAdditionalResources() != null && documentItem.getAdditionalResources().isDirectory()) { try { FileUtils.copyDirectory(documentItem.getAdditionalResources(), new File(dita.getOutputDir())); } catch (IOException e) { getLog().error("Could not copy additional resources.", e); } } // create zip of generated HTML-type documentation getLog().info("Create ZIP of generated documentation."); Zip zip = new Zip(); zip.setProject(new Project()); zip.setBasedir(new File(dita.getOutputDir())); zip.setDestFile(new File(ditaTargetDir, documentItem.getArtifactId() + ((documentItem.getArtifactClassifier() == null || documentItem.getArtifactClassifier().equals("")) ? "" : "-" + documentItem.getArtifactClassifier()) + ".zip")); zip.execute(); AttachedZipArtifact artifact = new AttachedZipArtifact(getCurrentProject().getArtifact(), // artifact handler, // handler new File(ditaTargetDir, documentItem.getArtifactId() + ((documentItem.getArtifactClassifier() == null || documentItem.getArtifactClassifier().equals("")) ? "" : "-" + documentItem.getArtifactClassifier()) + ".zip"), // fileToAttach documentItem.getArtifactId(), // artifactId documentItem.getArtifactClassifier(), // classifier getCurrentProject().getVersion() // version ); getLog().info("Attaching artifact: " + artifact.toString()); getCurrentProject().addAttachedArtifact(artifact); } else if (PDF_FORMATS.contains(documentItem.getDitaTranstype())) { dita.setOutputDir(ditaTargetDir.getAbsolutePath()); // generate documentation dita.execute(); getLog().info("Renaming generated PDF file."); File fromPdf = getGeneratedPdfFile(dita, documentItem); File toPdf = getMavenizedPdfFile(dita, documentItem); try { if (!fromPdf.getCanonicalPath().equals(toPdf.getCanonicalPath())) { FileUtils.moveFile(getGeneratedPdfFile(dita, documentItem), toPdf); } else { getLog().warn( "No need to rename the PDF file, since the generated PDF has already the expected name."); } } catch (IOException e) { getLog().error("From File: " + fromPdf.getAbsolutePath()); getLog().error("To File: " + toPdf.getAbsolutePath()); throw new MojoExecutionException("Could not rename PDF file."); } AttachedPdfArtifact artifact = new AttachedPdfArtifact(getCurrentProject().getArtifact(), // artifact handler, // handler toPdf, // fileToAttach documentItem.getArtifactId(), // artifactId documentItem.getArtifactClassifier(), // classifier getCurrentProject().getVersion() // version ); getLog().info("Attaching artifact: " + artifact.toString()); getCurrentProject().addAttachedArtifact(artifact); } else { throw new MojoFailureException("The given TransType is not yet implemented."); } } }
From source file:org.mnsoft.pdfocr.Wrapper.java
/** * Run the Wrapper.// w w w.ja va 2s .c o m * * @throws IOException * @throws InterruptedException * @throws DocumentException */ @SuppressWarnings("rawtypes") public void run() throws IOException, InterruptedException, DocumentException { RecursiveFileListIterator it = new RecursiveFileListIterator(new File(wd), new FileFilter(".pdf")); while (it.hasNext()) { final File originalFile = it.next(); final String originalFilePath = originalFile.getAbsolutePath(); /* * Open the reader on the original File */ PdfReader readerOnOriginalFile; try { readerOnOriginalFile = new PdfReader(originalFilePath); } catch (Exception e) { log.error("! ERROR: " + e.getMessage() + " File: " + originalFilePath); continue; } /* * Get the document information */ Map info = readerOnOriginalFile.getInfo(); /* * Get the document creator. If the document * has already been worked on, continue with * the next document. */ String doc_creator = (String) info.get("Creator"); if (this.OCR_CREATOR.equals(doc_creator)) { log.debug( "+ INFO: File " + originalFilePath + " had already been run trough OCR engine. Skipping."); continue; } /* * Get the document time stamp so that we can set it later. */ final Date doc_timestamp = new Date(originalFile.lastModified()); /* * Get the number of pages in the original file */ int nOri = readerOnOriginalFile.getNumberOfPages(); log.debug("+ Working on: " + originalFilePath + " (" + nOri + " pages)."); final StringBuffer sb = new StringBuffer(); sb.append(originalFilePath + " ... "); /* * Get the remaining meta data */ String doc_title = ((String) info.get("Title") == null) ? "" : (String) info.get("Title"); String doc_subject = ((String) info.get("Subject") == null) ? "" : (String) info.get("Subject"); String doc_keywords = ((String) info.get("Keywords") == null) ? "" : (String) info.get("Keywords"); String doc_author = ((String) info.get("Author") == null) ? "" : (String) info.get("Author"); readerOnOriginalFile.close(); /* * Set the creator to our marker */ doc_creator = this.OCR_CREATOR; /* * Run the OCR Engine */ File outputFileFromOCR = null; try { outputFileFromOCR = ocr(originalFile); } catch (Exception e) { log.error("! ERROR: " + e.getMessage()); continue; } /* * Check for the result of the OCR Engine */ if ((outputFileFromOCR == null) || !outputFileFromOCR.exists()) { continue; } log.debug("+ " + outputFileFromOCR.getAbsolutePath() + " has come out of the OCR engine."); /* * Create final output */ /* * Create a temporary file and copy the source * file to it, to avoid UTF-8 encoding problems * on the filename confusing the OCR engine */ final File temp = File.createTempFile("ocr", ".pdf", new File(this.TMP_DIR)); temp.deleteOnExit(); mergePDFs(originalFile, outputFileFromOCR, temp, doc_title, doc_subject, doc_keywords, doc_author, doc_creator); FileUtils.deleteQuietly(originalFile); FileUtils.moveFile(temp, new File(originalFilePath)); /* * Set the file access time */ if ("true".equals(getAttribute("KEEPTS"))) { if (originalFile.exists()) { originalFile.setLastModified(doc_timestamp.getTime() + 1000); } } /* * Finally, remove the temporary document */ FileUtils.deleteQuietly(temp); FileUtils.deleteQuietly(outputFileFromOCR); } }
From source file:org.mnsoft.pdfocr.Wrapper.java
/** * Run the OCR command// w w w . j a va 2 s . c om * * @param originalFile The file to run the command on * @return The file that was created * @throws IOException * @throws InterruptedException */ private File ocr(File originalFile) throws IOException, InterruptedException { /* * Create a temporary file and copy the source * file to it, to avoid UTF-8 encoding problems * on the filename confusing the OCR engine */ log.debug("> Creating Temporary Source File"); final File sourceFileForOCR = File.createTempFile("ocr", ".pdf", new File(this.TMP_DIR)); sourceFileForOCR.deleteOnExit(); log.debug("< Created Temporary Source File: " + sourceFileForOCR.getAbsolutePath()); FileUtils.copyFile(originalFile, sourceFileForOCR, true); log.debug("+ Copied " + originalFile.getAbsolutePath() + " to " + sourceFileForOCR.getAbsolutePath()); /* * Create the command line */ String[] cmd = StringUtility.split(getAttribute("cmd"), " "); for (int i = 0; i < cmd.length; i++) { if ("###IF###".equals(cmd[i])) { cmd[i] = sourceFileForOCR.getAbsolutePath(); } else if ("###OF###".equals(cmd[i])) { cmd[i] = sourceFileForOCR.getAbsolutePath() + this.TMP_EXTENSION; } else if ("###CREATOR###".equals(cmd[i])) { cmd[i] = getAttribute("creator"); } } final StringBuffer sb = new StringBuffer(); for (int i = 0; i < cmd.length; i++) { sb.append(cmd[i]); sb.append(" "); } log.debug("> Calling OCR Engine: " + sb); callOCREngine(cmd); /* * Copy temporary output file to output file */ final File targetFile = new File(this.TMP_DIR + "/" + originalFile.getName() + this.TMP_EXTENSION); FileUtils.deleteQuietly(targetFile); FileUtils.moveFile(new File(sourceFileForOCR.getAbsolutePath() + this.TMP_EXTENSION), targetFile); /* * Delete temporary file */ FileUtils.deleteQuietly(new File(sourceFileForOCR.getAbsolutePath() + this.TMP_EXTENSION)); log.debug("< Calling OCR Engine. Output file is: " + targetFile.getAbsolutePath()); return targetFile; }
From source file:org.mobicents.servlet.restcomm.cache.DiskCache.java
private URI cache(final Object message) throws IOException, URISyntaxException { final DiskCacheRequest request = (DiskCacheRequest) message; if (request.hash() == null) { if (request.uri().getScheme().equalsIgnoreCase("file")) { File origFile = new File(request.uri()); File destFile = new File(location + origFile.getName()); if (!destFile.exists()) FileUtils.moveFile(origFile, destFile); return URI.create(this.uri + destFile.getName()); } else {/*from ww w. j a va2 s. co m*/ //Handle all the rest // This is a request to cache a URI String hash = null; URI uri = null; if (request.uri().toString().contains("hash")) { String fragment = request.uri().getFragment(); hash = fragment.replace("hash=", ""); String uriStr = ((request.uri().toString()).replace(fragment, "")).replace("#", ""); uri = URI.create(uriStr); } else { uri = request.uri(); hash = new Sha256Hash(uri.toString()).toHex(); } final String extension = extension(uri).toLowerCase(); final File path = new File(location + hash + "." + extension); if (!path.exists()) { final File tmp = new File(path + "." + "tmp"); InputStream input = null; OutputStream output = null; HttpClient client = null; HttpResponse httpResponse = null; try { if (request.uri().getScheme().equalsIgnoreCase("https")) { //Handle the HTTPS URIs client = CustomHttpClientBuilder.build(RestcommConfiguration.getInstance().getMain()); URI result = new URIBuilder().setScheme(uri.getScheme()).setHost(uri.getHost()) .setPort(uri.getPort()).setPath(uri.getPath()).build(); HttpGet httpRequest = new HttpGet(result); httpResponse = client.execute((HttpUriRequest) httpRequest); int code = httpResponse.getStatusLine().getStatusCode(); if (code >= 400) { String requestUrl = httpRequest.getRequestLine().getUri(); String errorReason = httpResponse.getStatusLine().getReasonPhrase(); String httpErrorMessage = String.format( "Error while fetching http resource: %s \n Http error code: %d \n Http error message: %s", requestUrl, code, errorReason); logger.warning(httpErrorMessage); } input = httpResponse.getEntity().getContent(); } else { input = uri.toURL().openStream(); } output = new FileOutputStream(tmp); final byte[] buffer = new byte[4096]; int read = 0; do { read = input.read(buffer, 0, 4096); if (read > 0) { output.write(buffer, 0, read); } } while (read != -1); tmp.renameTo(path); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (httpResponse != null) { ((CloseableHttpResponse) httpResponse).close(); httpResponse = null; } if (client != null) { HttpClientUtils.closeQuietly(client); client = null; } } } URI result = URI.create(this.uri + hash + "." + extension); return result; } } else { // This is a check cache request final String extension = "wav"; final String hash = request.hash(); final String filename = hash + "." + extension; Path p = Paths.get(location + filename); if (Files.exists(p)) { // return URI.create(matchedFile.getAbsolutePath()); return URI.create(this.uri + filename); } else { throw new FileNotFoundException(filename); } } }
From source file:org.movsim.MovsimCoreMainWithExperiments.java
/** * The main method.//w w w .j a va2 s . com * * @param args * the command line arguments * @throws SAXException * @throws JAXBException * @throws ParserConfigurationException */ public static void main(String[] args) throws JAXBException, SAXException { int numExperiment = 0; Arrays.sort(DO_EXPERIMENT); for (String experimentName : NAME_EXPERIMENT) { numExperiment++; if (Arrays.binarySearch(DO_EXPERIMENT, experimentName) < 0) { for (int i = 1; i <= NUM_REPETITIONS; i++) { String[] argsExp = new String[] { "-f", PATH_EXPERIMENT + "\\" + experimentName }; Locale.setDefault(Locale.US); // final ProjectMetaData projectMetaData = ProjectMetaData.getInstance(); // parse the command line, putting the results into projectMetaData Logger.initializeLogger(); MovsimCommandLine.parse(argsExp); if (!ProjectMetaData.getInstance().hasProjectName()) { System.err.println("no xml simulation configuration file provided."); System.exit(-1); } LogFileAppender.initialize(ProjectMetaData.getInstance()); final Simulator simulator = new Simulator(); simulator.initialize(); simulator.runToCompletion(); String prefixFile = null; Collection<File> lstFile = FileUtils.listFiles(new File("./"), new String[] { "csv" }, false); File fRoute; File fRouteDir = new File(PATH_EXPERIMENT + "\\" + numExperiment + "\\" + i); boolean isFirstFile = false; for (File file : lstFile) { if (file.getName().startsWith(FilenameUtils.getBaseName(experimentName) + ".tt.route") || file.getName().startsWith( FilenameUtils.getBaseName(experimentName) + ".consumption.route")) { if (file.getName() .startsWith(FilenameUtils.getBaseName(experimentName) + ".tt.route")) { prefixFile = ".tt.route"; } else { prefixFile = ".consumption.route"; } fRoute = new File(PATH_EXPERIMENT + "\\" + numExperiment + "\\" + i + "\\" + FilenameUtils.getBaseName(experimentName) + prefixFile + ".csv"); if (!fRoute.exists()) { try { isFirstFile = true; FileUtils.forceMkdir(fRouteDir); fRoute.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { appendFiles(file, fRoute, isFirstFile); isFirstFile = false; } catch (IOException e) { e.printStackTrace(); } try { FileUtils.moveFile(file, new File(PATH_EXPERIMENT + "\\" + numExperiment + "\\" + i + "\\src\\" + file.getName())); } catch (IOException e) { e.printStackTrace(); } } } } } } }