List of usage examples for java.nio.file Files createTempFile
public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
From source file:business.services.FileService.java
public File uploadPart(User user, String name, File.AttachmentType type, MultipartFile file, Integer chunk, Integer chunks, String flowIdentifier) { try {//w w w. j av a2 s . com String identifier = user.getId().toString() + "_" + flowIdentifier; String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE; log.info("File content-type: " + file.getContentType()); try { contentType = MediaType.valueOf(file.getContentType()).toString(); log.info("Media type: " + contentType); } catch (InvalidMediaTypeException e) { log.warn("Invalid content type: " + e.getMediaType()); //throw new FileUploadError("Invalid content type: " + e.getMediaType()); } InputStream input = file.getInputStream(); // Create temporary file for chunk Path path = fileSystem.getPath(uploadPath).normalize(); if (!path.toFile().exists()) { Files.createDirectory(path); } name = URLEncoder.encode(name, "utf-8"); String prefix = getBasename(name); String suffix = getExtension(name); Path f = Files.createTempFile(path, prefix, suffix + "." + chunk + ".chunk").normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, f.getParent())) { // Path f is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Copying file to " + f.toString()); // Copy chunk to temporary file Files.copy(input, f, StandardCopyOption.REPLACE_EXISTING); // Save chunk location in chunk map SortedMap<Integer, Path> chunkMap; synchronized (uploadChunks) { // FIXME: perhaps use a better identifier? Not sure if this one // is unique enough... chunkMap = uploadChunks.get(identifier); if (chunkMap == null) { chunkMap = new TreeMap<Integer, Path>(); uploadChunks.put(identifier, chunkMap); } } chunkMap.put(chunk, f); log.info("Chunk " + chunk + " saved to " + f.toString()); // Assemble complete file if all chunks have been received if (chunkMap.size() == chunks.intValue()) { uploadChunks.remove(identifier); Path assembly = Files.createTempFile(path, prefix, suffix).normalize(); // filter path names that point to places outside the upload path. // E.g., to prevent that in cases where clients use '../' in the filename // arbitrary locations are reachable. if (!Files.isSameFile(path, assembly.getParent())) { // Path assembly is not in the upload path. Maybe 'name' contains '..'? throw new FileUploadError("Invalid file name"); } log.info("Assembling file " + assembly.toString() + " from " + chunks + " chunks..."); OutputStream out = Files.newOutputStream(assembly, StandardOpenOption.CREATE, StandardOpenOption.APPEND); // Copy chunks to assembly file, delete chunk files for (int i = 1; i <= chunks; i++) { //log.info("Copying chunk " + i + "..."); Path source = chunkMap.get(new Integer(i)); if (source == null) { log.error("Cannot find chunk " + i); throw new FileUploadError("Cannot find chunk " + i); } Files.copy(source, out); Files.delete(source); } // Save assembled file name to database log.info("Saving attachment to database..."); File attachment = new File(); attachment.setName(URLDecoder.decode(name, "utf-8")); attachment.setType(type); attachment.setMimeType(contentType); attachment.setDate(new Date()); attachment.setUploader(user); attachment.setFilename(assembly.getFileName().toString()); attachment = fileRepository.save(attachment); return attachment; } return null; } catch (IOException e) { log.error(e); throw new FileUploadError(e.getMessage()); } }
From source file:io.druid.server.namespace.cache.NamespaceExtractionCacheManagerExecutorsTest.java
@Before public void setUp() throws IOException { lifecycle = new Lifecycle(); manager = new OnHeapNamespaceExtractionCacheManager(lifecycle, fnCache, new NoopServiceEmitter(), ImmutableMap.<Class<? extends ExtractionNamespace>, ExtractionNamespaceFunctionFactory<?>>of( URIExtractionNamespace.class, new URIExtractionNamespaceFunctionFactory( ImmutableMap.<String, SearchableVersionedDataFinder>of("file", new LocalFileTimestampVersionFinder())))); tmpFile = Files.createTempFile(tmpDir, "druidTestURIExtractionNS", ".dat").toFile(); tmpFile.deleteOnExit();//w w w.java 2 s .c o m final ObjectMapper mapper = new DefaultObjectMapper(); try (OutputStream ostream = new FileOutputStream(tmpFile)) { try (OutputStreamWriter out = new OutputStreamWriter(ostream)) { out.write(mapper.writeValueAsString(ImmutableMap.<String, String>of("foo", "bar"))); } } factory = new URIExtractionNamespaceFunctionFactory(ImmutableMap .<String, SearchableVersionedDataFinder>of("file", new LocalFileTimestampVersionFinder())) { public Callable<String> getCachePopulator(final URIExtractionNamespace extractionNamespace, final String lastVersion, final Map<String, String> cache) { final Callable<String> superCallable = super.getCachePopulator(extractionNamespace, lastVersion, cache); return new Callable<String>() { @Override public String call() throws Exception { superCallable.call(); return String.format("%d", System.currentTimeMillis()); } }; } }; }
From source file:de.unirostock.sems.caroweb.Converter.java
private void run(HttpServletRequest request, HttpServletResponse response, String uploadedName, String[] req, File tmp, File out, Path STORAGE) throws ServletException, IOException { cleanUp();/*w w w. j a v a2 s . co m*/ uploadedName.replaceAll("[^A-Za-z0-9 ]", "_"); if (uploadedName.length() < 3) uploadedName += "container"; CaRoConverter conv = null; if (req[1].equals("caro")) conv = new CaToRo(tmp); else if (req[1].equals("roca")) conv = new RoToCa(tmp); else { error(request, response, "do not know what to do"); return; } conv.convertTo(out); List<CaRoNotification> notifications = conv.getNotifications(); Path result = null; if (out.exists()) { result = Files.createTempFile(STORAGE, uploadedName, "-converted-" + CaRoWebutils.getTimeStamp() + "." + (req[1].equals("caro") ? "ro" : "omex")); try { Files.copy(out.toPath(), result, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { notifications.add(new CaRoNotification(CaRoNotification.SERVERITY_ERROR, "wasn't able to copy converted container to storage")); } } JSONArray errors = new JSONArray(); JSONArray warnings = new JSONArray(); JSONArray notes = new JSONArray(); for (CaRoNotification note : notifications) if (note.getSeverity() == CaRoNotification.SERVERITY_ERROR) errors.add(note.getMessage()); else if (note.getSeverity() == CaRoNotification.SERVERITY_WARN) warnings.add(note.getMessage()); else if (note.getSeverity() == CaRoNotification.SERVERITY_NOTE) notes.add(note.getMessage()); JSONObject json = new JSONObject(); json.put("errors", errors); json.put("warnings", warnings); json.put("notifications", notes); if (result != null && Files.exists(result)) { json.put("checkout", result.getFileName().toString()); if (request.getParameter("redirect") != null && request.getParameter("redirect").equals("checkout")) { response.sendRedirect("/checkout/" + result.getFileName().toString()); } } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter outWriter = response.getWriter(); outWriter.print(json); out.delete(); }
From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java
private File createTempFileWithContent() throws IOException { final File newFile = Files.createTempFile(tempFilePath, "xyz", "txt").toFile(); FileUtils.write(newFile, "Test", UTF_8); return newFile; }
From source file:io.fabric8.docker.client.impl.ImageOperationImpl.java
@Override public Boolean load(InputStream inputStream) { try {// ww w . ja v a2 s. c o m File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile(); try (final FileOutputStream fout = new FileOutputStream(tempFile)) { InputStreamPumper pumper = new InputStreamPumper(inputStream, new Callback<byte[], Void>() { @Override public Void call(byte[] input) { try { fout.write(input); } catch (IOException e) { throw DockerClientException.launderThrowable(e); } return null; } }); pumper.run(); pumper.close(); } return load(tempFile.getAbsolutePath()); } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:org.nuxeo.ecm.core.api.impl.blob.FileBlob.java
/** * Moves this blob's temporary file to a new non-temporary location. * <p>//from www . ja va 2 s. co m * The move is done as atomically as possible. * * @since 7.2 */ public void moveTo(File dest) throws IOException { if (!isTemporary) { throw new IOException("Cannot move non-temporary file: " + file); } Path path = file.toPath(); Path destPath = dest.toPath(); try { Files.move(path, destPath, ATOMIC_MOVE); file = dest; } catch (AtomicMoveNotSupportedException e) { // Do a copy through a tmp file on the same filesystem then atomic rename Path tmp = Files.createTempFile(destPath.getParent(), null, null); try { Files.copy(path, tmp, REPLACE_EXISTING); Files.delete(path); Files.move(tmp, destPath, ATOMIC_MOVE); file = dest; } catch (IOException ioe) { // don't leave tmp file in case of error Files.deleteIfExists(tmp); throw ioe; } } isTemporary = false; }
From source file:org.guvnor.ala.build.maven.executor.MavenDependencyConfigExecutorTest.java
private Path generateSettingsXml() throws IOException { final String localRepositoryUrl = m2Folder.getAbsolutePath(); String settingsXml = "<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/SETTINGS/1.0.0\n" + " http://maven.apache.org/xsd/settings-1.0.0.xsd\">\n" + " <localRepository>" + localRepositoryUrl + "</localRepository>\n" + " <offline>true</offline>\n" + "</settings>\n"; final Path settingsXmlPath = Files.createTempFile(m2Folder.toPath(), "settings", ".xml"); Files.write(settingsXmlPath, settingsXml.getBytes()); return settingsXmlPath; }
From source file:com.haulmont.yarg.formatters.impl.doc.connector.OfficeResourceProvider.java
protected File createTempFile(byte[] bytes) { try {//from w ww .j a va 2 s. com String tempFileName = String.format("document%d", counter.incrementAndGet()); String tempFileExt = ".tmp"; if (StringUtils.isNotBlank(officeIntegration.getTemporaryDirPath())) { Path tempDir = Paths.get(officeIntegration.getTemporaryDirPath()); tempDir.toFile().mkdirs(); temporaryFile = Files.createTempFile(tempDir, tempFileName, tempFileExt).toFile(); } else { temporaryFile = File.createTempFile(tempFileName, tempFileExt); } FileUtils.writeByteArrayToFile(temporaryFile, bytes); return temporaryFile; } catch (java.io.IOException e) { throw new ReportFormattingException("Could not create temporary file for pdf conversion", e); } }
From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java
@Test public final void testUploadSetOfFile() throws IOException { Set<File> files = new HashSet<>(); for (int no = 0; no < 10; no++) { final File newFile = Files.createTempFile(tempFilePath, "xyz" + no, "txt").toFile(); FileUtils.write(newFile, "Test", UTF_8); files.add(newFile);// ww w .j av a2 s . c o m } for (File file : files) { Files.deleteIfExists(file.toPath()); } }
From source file:nl.salp.warcraft4j.config.PropertyWarcraft4jConfigTest.java
@Test public void shouldNotCreateCacheDirectoryIfExisting() throws Exception { Files.createDirectories(cacheDir); assertTrue("Cache directory does not exist after creation.", Files.exists(cacheDir)); Path testFile = Files.createTempFile(cacheDir, "testFile", "tmp"); long creationTime = Files.getLastModifiedTime(cacheDir).toMillis(); PropertyWarcraft4jConfig config = new PropertyWarcraft4jConfig(configuration); assertTrue("Cache directory does not exist.", Files.exists(config.getCacheDirectory())); assertTrue("Cache directory is not a directory.", Files.isDirectory(config.getCacheDirectory())); assertTrue("Cache directory is not readable.", Files.isReadable(config.getCacheDirectory())); assertEquals("Cache directory modification time changed after initialisation", creationTime, Files.getLastModifiedTime(config.getCacheDirectory()).toMillis()); assertTrue("Test file in cache directory does not exist anymore.", Files.exists(testFile)); }