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

The following are Jave code examples for showing how to use copyFile() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Moenagade   File: Project.java   View Source Code Vote up 6 votes
public void loadImage(File source)
{
    lastOpenedImage=source.getAbsolutePath();
    File dest = new File(getImageDirectory()+source.getName());
    //System.out.println(source);
    //System.out.println(dest);
    try 
    {
        FileUtils.copyFile(source, dest);
    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(frame, "A terrible error occured!\n"+
                ex.getMessage()+"\n","Error", JOptionPane.ERROR_MESSAGE,Moenagade.IMG_ERROR);
    }
}
 
Example 2
Project: atlas   File: BetterZip.java   View Source Code Vote up 6 votes
public static boolean addFile(File zipFile, String path, File file) throws IOException {

        if (file.isDirectory()) {
            return false;
        }

        File rootDir = new File(file.getParentFile(), "_tmp");
        rootDir.delete();

        FileUtils.copyFile(file, new File(rootDir, path));

        //zip -r taobao-android-debug.apk zzzz
        boolean success = CmdExecutor.execute(rootDir.getAbsolutePath(), "zip", "-r", zipFile.getAbsolutePath(), path);

        rootDir.delete();
        if (success) {
            return true;
        }

        File tmpFile = new File(zipFile.getParentFile(), zipFile.getName() + "_tmp");
        ZipUtils.addFileToZipFile(zipFile, tmpFile, file, path, true);
        zipFile.delete();
        tmpFile.renameTo(zipFile);

        return true;
    }
 
Example 3
Project: Moenagade   File: Project.java   View Source Code Vote up 6 votes
public void loadSound(File source)
{
    lastOpenedSound=source.getAbsolutePath();
    File dest = new File(getSoundDirectory()+source.getName());
    //System.out.println(source);
    //System.out.println(dest);
    try 
    {
        FileUtils.copyFile(source, dest);
    } 
    catch (IOException ex) 
    {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(frame, "A terrible error occured!\n"+
                ex.getMessage()+"\n","Error", JOptionPane.ERROR_MESSAGE,Moenagade.IMG_ERROR);
    }
}
 
Example 4
Project: convertigo-engine   File: MobilePlatform.java   View Source Code Vote up 6 votes
private void checkFolder() {
	File folder = getResourceFolder();
	File templateFolder = new File(Engine.TEMPLATES_PATH, "base/DisplayObjects/platforms/" + getClass().getSimpleName());

	try {
		if (!folder.exists()) {
			FileUtils.copyDirectory(templateFolder, folder);
		} else {
			File config = new File(folder, "config.xml");
			if (!config.exists()) {
				FileUtils.copyFile(new File(templateFolder, "config.xml"), config);
			}
			File res = new File(folder, "res");
			if (!res.exists()) {
				FileUtils.copyDirectory(new File(templateFolder, "res"), res);
			}
		}
	} catch (IOException e) {
		Engine.logBeans.warn("(MobilePlatform) The folder '" + folder.getAbsolutePath() + "' doesn't exist and cannot be created", e);
	}
}
 
Example 5
Project: osc-core   File: ImportPluginService.java   View Source Code Vote up 6 votes
@Override
  public BaseResponse exec(ImportFileRequest request, EntityManager em) throws Exception {
      BaseResponse response = new BaseResponse();
      File tmpUploadFolder = new File(request.getUploadPath());

      try {
validate(em, request, tmpUploadFolder);

File pluginTarget = new File(ApiFactoryService.PLUGINS_DIRECTORY, this.deploymentName);

FileUtils.copyFile(this.barFile, pluginTarget);

      } finally {
          cleanTmpFolder(tmpUploadFolder);
      }
      return response;
  }
 
Example 6
Project: zucchini   File: ScreenshotHook.java   View Source Code Vote up 6 votes
public static void createScreenshot(String fileName) {

		if (SeleniumDriver.getInstance() instanceof TakesScreenshot) {

			File fileSrc = ((TakesScreenshot) SeleniumDriver.getInstance()).getScreenshotAs(OutputType.FILE);

			try {
				File destFile = new File(String.format(SCREENSHOTS_FORMAT, fileName));
				FileUtils.copyFile(fileSrc, destFile);
				LOG.info("[Screenshot] " + destFile.getAbsolutePath());
			} catch (IOException e) {
				;
			}
		}

	}
 
Example 7
Project: dcmrs-broker   File: DicomMultipartResponse.java   View Source Code Vote up 5 votes
@Override
protected void send(Path path) throws Exception
{
	Part part = new Part(APPLICATION_DICOM);
	out.addPart(part);
	
	if (acceptableTransferSyntaxes.contains("*")) {
		// Client accepts any transfer syntax so just send the file
		FileUtils.copyFile(path.toFile(), out);
	}
	else {
		String tx = DicomUtil.getTransferSyntax(path);
		if (acceptableTransferSyntaxes.contains(tx)) {
			// Client accepts the transfer syntax of the file, so just send it
			FileUtils.copyFile(path.toFile(), out);
		}
		else {
			// Client does not accept the transfer syntax of the file, so we transcode it to LEE
			try (Transcoder transcoder = new Transcoder(path.toFile())) {
				transcoder.setDestinationTransferSyntax(ExplicitVRLittleEndian);
				transcoder.setIncludeFileMetaInformation(true);
				transcoder.setCloseInputStream(true);
				transcoder.setCloseOutputStream(false);
				transcoder.setIncludeBulkData(DicomInputStream.IncludeBulkData.YES);
				
				transcoder.transcode((Transcoder t, Attributes dataset) -> out);
			}
		}
	}
}
 
Example 8
Project: Reer   File: GFileUtils.java   View Source Code Vote up 5 votes
public static void copyFile(File source, File destination) {
    try {
        FileUtils.copyFile(source, destination);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 9
Project: Cognizant-Intelligent-Test-Scripter   File: ReportUtils.java   View Source Code Vote up 5 votes
public static Boolean takeScreenshot(SeleniumDriver seleniumdriver, String imgSrc) {
    try {
        File scrFile = seleniumdriver.createScreenShot();
        if (scrFile != null) {
            File imgFile = new File(FilePath.getCurrentResultsPath() + imgSrc);
            FileUtils.copyFile(scrFile, imgFile, true);
            scrFile.delete();
            return true;
        }
    } catch (Exception ex) {
        Logger.getLogger(ReportUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example 10
Project: ObjectCache   File: DiskLruCacheTest.java   View Source Code Vote up 5 votes
@Test public void journalFileIsPreferredOverBackupFile() throws Exception {
    DiskLruCacheWithExpiry.Editor creator = cache.edit("k1");
    creator.set(0, "ABC");
    creator.set(1, "DE");
    creator.commit();
    cache.flush();

    FileUtils.copyFile(journalFile, journalBkpFile);

    creator = cache.edit("k2");
    creator.set(0, "F");
    creator.set(1, "GH");
    creator.commit();
    cache.close();

    assertThat(journalFile.exists()).isTrue();
    assertThat(journalBkpFile.exists()).isTrue();

    cache = DiskLruCacheWithExpiry.open(cacheDir, appVersion, 2, Integer.MAX_VALUE);

    DiskLruCacheWithExpiry.Snapshot snapshotA = cache.get("k1");
    assertThat(snapshotA.getString(0)).isEqualTo("ABC");
    assertThat(snapshotA.getLength(0)).isEqualTo(3);
    assertThat(snapshotA.getString(1)).isEqualTo("DE");
    assertThat(snapshotA.getLength(1)).isEqualTo(2);

    DiskLruCacheWithExpiry.Snapshot snapshotB = cache.get("k2");
    assertThat(snapshotB.getString(0)).isEqualTo("F");
    assertThat(snapshotB.getLength(0)).isEqualTo(1);
    assertThat(snapshotB.getString(1)).isEqualTo("GH");
    assertThat(snapshotB.getLength(1)).isEqualTo(2);

    assertThat(journalBkpFile.exists()).isFalse();
    assertThat(journalFile.exists()).isTrue();
}
 
Example 11
Project: jmt   File: JmvaClosedModelTest.java   View Source Code Vote up 5 votes
@Test
public void randomModel_closed_7() throws IOException, URISyntaxException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("randomModel_closed_7", ".xml");
	File expected = new File(getClass().getResource("randomModel_closed_7-expectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("randomModel_closed_7-input.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 12
Project: jmt   File: JmvaClosedModelTest.java   View Source Code Vote up 5 votes
@Test
public void randomModel_closed_12() throws IOException, URISyntaxException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("randomModel_closed_12", ".xml");
	File expected = new File(getClass().getResource("randomModel_closed_12-expectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("randomModel_closed_12-input.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 13
Project: jmt   File: JmvaOpenModelTest.java   View Source Code Vote up 5 votes
@Test
public void randomModel_open_1() throws IOException, URISyntaxException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("randomModel_open_1", ".xml");
	File expected = new File(getClass().getResource("randomModel_open_1-expectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("randomModel_open_1-input.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 14
Project: jmt   File: JmvaMixedModelTest.java   View Source Code Vote up 5 votes
@Test
public void randomModel_mixed_2() throws IOException, URISyntaxException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("randomModel_mixed_2", ".xml");
	File expected = new File(getClass().getResource("randomModel_mixed_2-expectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("randomModel_mixed_2-input.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 15
Project: pdi-git-plugin   File: GitControllerTest.java   View Source Code Vote up 5 votes
@Test
public void testVisualDiff() throws Exception {
  XulMessageBox message = spy( new XulMessageBoxMock( XulDialogCallback.Status.ACCEPT ) );
  when( document.createElement( MESSAGEBOX ) ).thenReturn( message );
  UIFile file = new UIFile( "test.txt", ChangeType.MODIFY, true );
  doReturn( Collections.singletonList( file ) ).when( controller ).getSelectedChangedFiles();
  controller.visualdiff();
  verify( message ).setTitle( BaseMessages.getString( PKG, "Dialog.Error" ) );

  // .ktr
  file = new UIFile( "test.ktr", ChangeType.MODIFY, true );
  doReturn( Collections.singletonList( file ) ).when( controller ).getSelectedChangedFiles();
  doReturn( new FileInputStream( new File( "src/test/resources/r1.ktr" ) ) ).when( uiGit ).open( "test.ktr", Constants.HEAD );
  doReturn( new FileInputStream( new File( "src/test/resources/r2.ktr" ) ) ).when( uiGit ).open( "test.ktr", IVCS.WORKINGTREE );
  controller.visualdiff();
  verify( uiGit ).open( "test.ktr", Constants.HEAD );
  verify( uiGit ).open( "test.ktr", IVCS.WORKINGTREE );
  verify( controller ).loadMainPerspective();

  // conflicted ktr
  file = new UIFile( "test.kjb.ours", ChangeType.ADD, false );
  File dir = File.createTempFile( "git_test_", "_controller" );
  dir.delete();
  dir.mkdir();
  File ours = new File( dir.getPath(), "test.kjb.ours" );
  File theirs = new File( dir.getPath(), "test.kjb.theirs" );
  FileUtils.copyFile( new File( "src/test/resources/r1.kjb" ), ours );
  FileUtils.copyFile( new File( "src/test/resources/r2.kjb" ), theirs );
  doReturn( dir.getPath() ).when( uiGit ).getDirectory();
  doReturn( Collections.singletonList( file ) ).when( controller ).getSelectedChangedFiles();
  doReturn( new FileInputStream( ours ) ).when( uiGit ).open( "test.kjb.ours", IVCS.WORKINGTREE );
  doReturn( new FileInputStream( theirs ) ).when( uiGit ).open( "test.kjb.theirs", IVCS.WORKINGTREE );
  controller.visualdiff();
  FileUtils.deleteDirectory( dir );
  verify( uiGit ).open( "test.kjb.ours", IVCS.WORKINGTREE );
  verify( uiGit ).open( "test.kjb.theirs", IVCS.WORKINGTREE );
  verify( controller, times( 2 ) ).loadMainPerspective();
}
 
Example 16
Project: jmt   File: CommandLineTest.java   View Source Code Vote up 5 votes
@Test
public void stat_mixedJMVAtest() throws URISyntaxException, IOException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("inputStatMixed", ".xml");
	File expected = new File(getClass().getResource("stat_mixedExpectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("stat_mixedInputData.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 17
Project: Actitime-Framework   File: ExtentReport.java   View Source Code Vote up 5 votes
/**
 * This method captures the screenshot and places it in the execution report
 **/
public static void captureAndDisplayScreenShot(WebDriver ldriver,
		ExtentTest eTest) {
	Date dtnow2 = new Date();
	String strStartDate2 = dtnow2.toString().replace(":", "_");
	String strDateStamp2 = strStartDate2.replace(" ", "_");
	File src = ((TakesScreenshot) ldriver).getScreenshotAs(OutputType.FILE);
	try {
		String screenshotPath = dirPath + "_" + strDateStamp2 + ".png";
		FileUtils.copyFile(src, new File(screenshotPath));
		eTest.addScreenCaptureFromPath(screenshotPath);
	} catch (IOException e) {
		System.out.println(e.getMessage());
	}
}
 
Example 18
Project: jmt   File: JmvaMixedModelTest.java   View Source Code Vote up 5 votes
@Test
public void randomModel_mixed_3() throws IOException, URISyntaxException {
	CommandLineSolver solver = new CommandLineSolver();

	File input = File.createTempFile("randomModel_mixed_3", ".xml");
	File expected = new File(getClass().getResource("randomModel_mixed_3-expectedOutput.xml").toURI());
	FileUtils.copyFile(new File(getClass().getResource("randomModel_mixed_3-input.xml").toURI()), input);

	assertTrue("Solver was not able to solve file!", solver.solve(input));
	assertTrue(": Real output differs from expected!\n"
			+ "Expected: \n" + FileUtils.readFileToString(expected)
			+ "\nActual: \n" + FileUtils.readFileToString(input), 
			FileUtils.contentEquals(input, expected));			
}
 
Example 19
Project: lams   File: QuestionParser.java   View Source Code Vote up 4 votes
/**
    * Adapts QTI form field for Tools to use. Some Tools do not accept HTML, so it gets converted to plain text. Also
    * image placeholders get resolved here.
    */
   public static String processHTMLField(String fieldText, boolean forcePlainText, String contentFolderID,
    String resourcesFolderPath) {
String result = forcePlainText ? WebUtil.removeHTMLtags(fieldText) : fieldText;

if (!StringUtils.isBlank(result)) {
    Matcher imageMatcher = QuestionParser.IMAGE_PATTERN.matcher(result);
    StringBuffer resultBuilder = new StringBuffer();

    // find image placeholders
    while (imageMatcher.find()) {
	String fileName = imageMatcher.group(1);
	// if it is plain text or something goes wrong, the placeholder simply gets removed
	String replacement = "";
	if (!forcePlainText) {
	    if (resourcesFolderPath == null) {
		QuestionParser.log
			.warn("Image " + fileName + " declaration found but its location is unknown.");
	    } else {
		File sourceFile = new File(resourcesFolderPath, fileName);
		if (sourceFile.canRead()) {
		    // copy the image from exploded IMS zip to secure dir in lams-www
		    File uploadDir = UploadFileUtil.getUploadDir(contentFolderID, "Image");
		    String destinationFileName = UploadFileUtil.getUploadFileName(uploadDir, fileName);
		    File destinationFile = new File(uploadDir, destinationFileName);
		    String uploadWebPath = UploadFileUtil.getUploadWebPath(contentFolderID, "Image") + '/'
			    + fileName;
		    try {
			FileUtils.copyFile(sourceFile, destinationFile);
			replacement = "<img src=\"" + uploadWebPath + "\" />";
		    } catch (IOException e) {
			QuestionParser.log.error("Could not store image " + fileName);
		    }
		} else {
		    QuestionParser.log.warn("Image " + fileName + " declaration found but it can not be read.");
		}
	    }
	}
	imageMatcher.appendReplacement(resultBuilder, replacement);
    }
    imageMatcher.appendTail(resultBuilder);
    result = resultBuilder.toString();
}

return StringUtils.isBlank(result) ? null : result;
   }
 
Example 20
Project: twitter-stuff   File: StatusUtils.java   View Source Code Vote up 4 votes
public static void takeStatusScreenshot(Status status, MongoDatabase mongoDatabase, WebDriver driver) {
    long id = status.getId();
    User user = status.getUser();
    try {
        // visit the twitter url
        driver.get(TWITTER_BASE_URL + user.getScreenName() + "/status/" + id);

        WebDriverWait webDriverWait = new WebDriverWait(driver, 4);
        webDriverWait.until(
                ExpectedConditions.visibilityOfElementLocated(
                        By.cssSelector(PERMALINK_TWEET_CONTAINER)));

        // Find the tweet container
        WebElement element = driver.findElement(By.cssSelector(PERMALINK_TWEET_CONTAINER));

        // take a full screenshot
        File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // create in memory image data
        BufferedImage screenshotImage = ImageIO.read(screenshotFile);

        // calculate the position of the tweet element
        Point point = element.getLocation();
        int elementWidth = element.getSize().getWidth();
        int elementHeight = element.getSize().getHeight();

        // crop to get only the container of the tweet itself (sometimes this doesn't work on mac)
        BufferedImage elementScreenshotImage =
                screenshotImage.getSubimage(
                        point.getX() + 4,
                        point.getY() + 4,
                        elementWidth - 4,
                        screenshotImage.getHeight() < point.getY() + elementHeight
                                ? screenshotImage.getHeight() - 4
                                : elementHeight - 4);
        ImageIO.write(elementScreenshotImage, "png", screenshotFile);
        FileUtils.copyFile(screenshotFile, new File("screenshot/" + id + ".png"));
    } catch (Exception e) {
        saveFailureStatusProcesssed(mongoDatabase, id, false);
        System.out.println(
                String.format(
                        "Unable to create screenshot for %s with id: %d",
                        user.getScreenName(),
                        id));
        e.printStackTrace();
    }
}