List of usage examples for org.apache.commons.io FileUtils forceDeleteOnExit
public static void forceDeleteOnExit(File file) throws IOException
From source file:com.joyent.manta.client.MantaClientPutIT.java
@Test public final void testPutWithPlainTextFileUTF8NonRomanCharacters() throws IOException { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; File temp = File.createTempFile("upload", ".txt"); FileUtils.forceDeleteOnExit(temp); final String content = "????"; Files.write(temp.toPath(), content.getBytes(StandardCharsets.UTF_8)); MantaObject response = mantaClient.put(path, temp); String contentType = response.getContentType(); Assert.assertEquals(contentType, "text/plain", "Content type wasn't detected correctly"); String actual = mantaClient.getAsString(path); Assert.assertEquals(actual, content, "Uploaded file didn't match expectation"); }
From source file:com.joyent.manta.client.MantaClientPutIT.java
@Test public final void testPutWithPlainTextFileWithErrorProneName() throws IOException { final String name = UUID.randomUUID().toString() + "- -~!@#$%^&*().txt"; final String path = testPathPrefix + name; File temp = File.createTempFile("upload", ".txt"); FileUtils.forceDeleteOnExit(temp); Files.write(temp.toPath(), TEST_DATA.getBytes(StandardCharsets.UTF_8)); MantaObject response = mantaClient.put(path, temp); String contentType = response.getContentType(); Assert.assertEquals(contentType, "text/plain", "Content type wasn't detected correctly"); String actual = mantaClient.getAsString(path); Assert.assertEquals(actual, TEST_DATA, "Uploaded file didn't match expectation"); Assert.assertEquals(response.getPath(), path, "path returned as written"); }
From source file:atg.tools.dynunit.nucleus.NucleusUtils.java
/** * This method is used to extract a configdir from a jar archive. * Given a URL this method will extract the jar contents to a temp dir and return that path. * It also adds a shutdown hook to cleanup the tmp dir on normal jvm completion. * If the given URL does not appear to be a path into a jar archive, this method returns * a new File object initialized with <code>dataURL.getFile()</code>. * * @return A temporary directory to be used as a configdir *///from w w w . j a v a 2 s . co m private static File extractJarDataURL(URL dataURL) { // TODO: Extract to a temp location // atg.core.util.JarUtils.extractEntry(arg0, arg1, arg2) int endIndex = dataURL.getFile().lastIndexOf('!'); if (endIndex == -1) { // Not a jar file url return new File(dataURL.getFile()); } logger.info(EXTRACT_TEMP_JAR_FILE_FOR_PATH + dataURL.getFile()); File configDir = null; try { final File tempFile = FileUtil.newTempFile(); final File tmpDir = new File(tempFile.getParentFile(), DYNUNIT_CONFIG + System.currentTimeMillis()); String jarPath = dataURL.getFile().substring(0, endIndex); // Strip leading file: int fileColonIndex = jarPath.indexOf(FILE) + FILE.length(); jarPath = jarPath.substring(fileColonIndex, jarPath.length()); JarUtils.unJar(new File(jarPath), tmpDir, false); // Now get the configpath dir relative to this temp dir String relativePath = dataURL.getFile().substring(endIndex + 1, dataURL.getFile().length()); FileUtils.forceDeleteOnExit(tmpDir); configDir = new File(tmpDir, relativePath); } catch (IOException e) { logger.catching(e); } return configDir; }
From source file:com.joyent.manta.client.MantaClientPutIT.java
@Test public final void testPutWithJPGFile() throws IOException { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; File temp = File.createTempFile("upload", ".jpg"); FileUtils.forceDeleteOnExit(temp); final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream testDataInputStream = classLoader.getResourceAsStream(TEST_FILENAME); OutputStream out = new FileOutputStream(temp)) { IOUtils.copy(testDataInputStream, out); MantaObject response = mantaClient.put(path, temp); String contentType = response.getContentType(); Assert.assertEquals(contentType, "image/jpeg", "Content type wasn't detected correctly"); try (InputStream in = mantaClient.getAsInputStream(path)) { byte[] actual = IOUtils.toByteArray(in); byte[] expected = FileUtils.readFileToByteArray(temp); Assert.assertTrue(Arrays.equals(actual, expected), "Uploaded file isn't the same as actual file"); }// ww w. java 2s .c om } }
From source file:com.joyent.manta.client.MantaClientPutIT.java
@Test public final void testPutWithFileInputStreamAndNoContentLength() throws IOException { final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; File temp = Files.createTempFile("name", ".data").toFile(); FileUtils.forceDeleteOnExit(temp); FileUtils.writeStringToFile(temp, TEST_DATA, StandardCharsets.UTF_8); // Test putting with an unknown content length try (FileInputStream in = new FileInputStream(temp)) { mantaClient.put(path, in);//from ww w. ja va 2 s .c o m } try (final MantaObjectInputStream gotObject = mantaClient.getAsInputStream(path)) { Assert.assertNotNull(gotObject); Assert.assertNotNull(gotObject.getContentType()); Assert.assertNotNull(gotObject.getContentLength()); Assert.assertNotNull(gotObject.getEtag()); Assert.assertNotNull(gotObject.getMtime()); Assert.assertNotNull(gotObject.getPath()); final String data = IOUtils.toString(gotObject, Charset.defaultCharset()); Assert.assertEquals(data, TEST_DATA); } mantaClient.delete(path); MantaAssert.assertResponseFailureStatusCode(404, RESOURCE_NOT_FOUND_ERROR, (MantaFunction<Object>) () -> mantaClient.get(testPathPrefix + name)); }
From source file:com.alibaba.otter.shared.common.utils.NioUtils.java
/** * ??jvm//from www . j a v a 2 s .co m * * @param dest * @param retryTimes */ public static boolean delete(File dest, final int retryTimes) { if (dest == null) { return false; } if (false == dest.exists()) { return true; } int totalRetry = retryTimes; if (retryTimes < 1) { totalRetry = 1; } int retry = 0; while (retry++ < totalRetry) { try { FileUtils.forceDelete(dest); return true; } catch (FileNotFoundException ex) { return true; } catch (Exception ex) { // int wait = (int) Math.pow(retry, retry) * timeWait; wait = (wait < timeWait) ? timeWait : wait; if (retry == totalRetry) { try { FileUtils.forceDeleteOnExit(dest); return false; } catch (Exception e) { // ignore } } else { // logger.warn(String.format("[%s] delete() - retry %s failed : wait [%s] ms , caused by %s", dest.getAbsolutePath(), retry, wait, ex.getMessage())); try { Thread.sleep(wait); } catch (InterruptedException e) { // ignore } } } } return false; }
From source file:com.siblinks.ws.service.impl.PlaylistServiceImpl.java
/** * {@inheritDoc}//from www . j a v a 2 s. c om */ @Override @RequestMapping(value = "/updatePlaylist", method = RequestMethod.POST) public ResponseEntity<Response> updatePlaylist(@RequestParam(required = false) final MultipartFile image, @RequestParam final String oldImage, @RequestParam final String title, @RequestParam final String description, @RequestParam final long subjectId, @RequestParam final long createBy, @RequestParam final long plid) { String entityName = null; boolean updateObject; SimpleResponse reponse = null; if (subjectId <= 0) { reponse = new SimpleResponse(SibConstants.FAILURE, "playlist", "updatePlaylist", "Subject is not valid"); } else { try { List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter(); String strDescription = CommonUtil.filterWord(description, allWordFilter); String strTitle = CommonUtil.filterWord(title, allWordFilter); String newImage = null; Object[] queryParams = null; entityName = SibConstants.SqlMapperBROT44.SQL_UPDATE_PLAYLIST; if (image != null) { newImage = uploadPlaylistThumbnail(image); } if (newImage != null) { queryParams = new Object[] { strTitle, strDescription, newImage, subjectId, plid, createBy }; } else { queryParams = new Object[] { strTitle, strDescription, oldImage, subjectId, plid, createBy }; } updateObject = dao.insertUpdateObject(entityName, queryParams); if (updateObject) { Map<String, Object> map = new HashMap<String, Object>(); map.put("status", "success"); if (newImage != null && newImage.length() > 0) { map.put("newImage", newImage); } else { map.put("newImage", oldImage); } map.put("title", strTitle); map.put("description", strDescription); activiLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_PLAYLIST, "U", "You have updated playlist", String.valueOf(createBy), String.valueOf(plid))); reponse = new SimpleResponse(SibConstants.SUCCESS, "playlist", "updatePlaylist", map); if (newImage != null && !"".equals(newImage) && oldImage != null && !"".equals(oldImage)) { String fileName = oldImage.substring(oldImage.lastIndexOf("/"), oldImage.length()); File fileOld = new File(environment.getProperty("directoryPlaylistImage") + fileName); if (fileOld.exists()) { FileUtils.forceDeleteOnExit(fileOld); } } } else { reponse = new SimpleResponse(SibConstants.SUCCESS, "playlist", "updatePlaylist", "failed"); } } catch (Exception e) { e.printStackTrace(); reponse = new SimpleResponse(SibConstants.FAILURE, "playlist", "updatePlaylist", e.getMessage()); } } return new ResponseEntity<Response>(reponse, HttpStatus.OK); }
From source file:com.joyent.manta.client.multipart.EncryptedServerSideMultipartManagerIT.java
public final void properlyClosesStreamsAfterUpload() throws IOException { final URL testResource = Thread.currentThread().getContextClassLoader().getResource(TEST_FILENAME); Assert.assertNotNull(testResource, "Test file missing"); final File uploadFile = File.createTempFile("upload", ".jpg"); FileUtils.forceDeleteOnExit(uploadFile); FileUtils.copyURLToFile(testResource, uploadFile); Assert.assertTrue(0 < uploadFile.length(), "Error preparing upload file"); final String path = testPathPrefix + UUID.randomUUID().toString(); EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(path); // we are not exercising the FileInputStream code-path due to issues with // spies failing the check for inputStream.getClass().equals(FileInputStream.class) InputStream contentStream = new FileInputStream(uploadFile); InputStream fileInputStreamSpy = Mockito.spy(contentStream); MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, fileInputStreamSpy); // verify the stream we passed was closed Mockito.verify(fileInputStreamSpy, Mockito.times(1)).close(); MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1 }; Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts); multipart.complete(upload, partsStream); }
From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java
protected EncryptedFile encryptedFile(SecretKey key, SupportedCipherDetails cipherDetails, long plaintextSize) throws IOException { File temp = File.createTempFile("encrypted", ".data"); FileUtils.forceDeleteOnExit(temp); try (InputStream in = testURL.openStream()) { return encryptedFile(key, cipherDetails, plaintextSize, in); }/*from w w w. ja va2s. c o m*/ }
From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java
protected EncryptedFile encryptedFile(SecretKey key, SupportedCipherDetails cipherDetails, long plaintextSize, InputStream in) throws IOException { File temp = File.createTempFile("encrypted", ".data"); FileUtils.forceDeleteOnExit(temp); try (FileOutputStream out = new FileOutputStream(temp)) { MantaInputStreamEntity entity = new MantaInputStreamEntity(in, plaintextSize); EncryptingEntity encryptingEntity = new EncryptingEntity(key, cipherDetails, entity); encryptingEntity.writeTo(out);/*from w ww. j a v a2 s. c o m*/ Assert.assertEquals(temp.length(), encryptingEntity.getContentLength(), "Ciphertext doesn't equal calculated size"); return new EncryptedFile(encryptingEntity.getCipher(), temp); } }