/** * Construct a frequency table from an InputStream. This will create a temporary file to copy the * InputStream in. * * @param source the Input Stream * @return an InputStream which is a copy of the source Stream, provided to re-Read the same Bytes * for the actual compression process. */ public InputStream constructTable(InputStream source, boolean copy) { freq = new int[TABLESIZE]; try { File file = null; FileOutputStream fos = null; if (copy == true) { file = File.createTempFile("huf", "tmp"); file.deleteOnExit(); fos = new FileOutputStream(file); } while (source.available() != 0) { int c = source.read(); freq[c]++; if (copy) fos.write(c); } source.close(); if (copy) { fos.close(); return new FileInputStream(file); } return null; } catch (Exception ex) { ExHandler.handle(ex); return null; } }
public Graph(WeightedBVGraph graph, String[] names) { org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("it.unimi.dsi.webgraph.ImmutableGraph"); logger.setLevel(org.apache.log4j.Level.FATAL); if (names.length != graph.numNodes()) throw new Error("Problem with the list of names for the nodes in the graph."); try { File auxFile = File.createTempFile("graph-maps-" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); RecordManager recMan = RecordManagerFactory.createRecordManager(auxFile.getAbsolutePath()); nodes = recMan.hashMap("nodes"); nodesReverse = recMan.hashMap("nodesReverse"); } catch (IOException ex) { throw new Error(ex); } nodes.clear(); nodesReverse.clear(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); this.graph = graph; WeightedArcSet list = new WeightedArcSet(); ArcLabelledNodeIterator it = graph.nodeIterator(); while (it.hasNext()) { if (commit++ % COMMIT_SIZE == 0) { commit(); list.commit(); } Integer aux1 = it.nextInt(); Integer aux2 = null; ArcLabelledNodeIterator.LabelledArcIterator suc = it.successors(); while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { WeightedArc arc = (WeightedArc) cons[0].newInstance(aux2, aux1, suc.label().getFloat()); list.add(arc); this.nodes.put(aux1, names[aux1]); this.nodes.put(aux2, names[aux2]); this.nodesReverse.put(names[aux1], aux1); this.nodesReverse.put(names[aux2], aux2); } catch (Exception ex) { throw new Error(ex); } } reverse = new WeightedBVGraph(list.toArray(new WeightedArc[0])); numArcs = list.size(); iterator = nodeIterator(); try { File auxFile = File.createTempFile("graph" + System.currentTimeMillis(), "aux"); auxFile.deleteOnExit(); String basename = auxFile.getAbsolutePath(); store(basename); } catch (IOException ex) { throw new Error(ex); } commit(); }
public static void init() throws Exception { Properties props = new Properties(); int pid = OSProcess.getId(); String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath(); /** * Return file as string and then modify the string accordingly ** */ String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml")); file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid); String modified_file_str = modifyFile(file_as_str); FileOutputStream fos = new FileOutputStream(path); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos)); wr.write(modified_file_str); wr.flush(); wr.close(); props.setProperty("cache-xml-file", path); // String tableName = ""; // props.setProperty("mcast-port", "10339"); try { // ds = DistributedSystem.connect(props); ds = (new ExceptionsDUnitTest("temp")).getSystem(props); cache = CacheFactory.create(ds); } catch (Exception e) { e.printStackTrace(System.err); throw new Exception("" + e); } }
public static File getSparseBinarySVDLIBCFile() throws Exception { File f = File.createTempFile("unit-test", ".dat"); DataOutputStream pw = new DataOutputStream(new FileOutputStream(f)); pw.writeInt(3); pw.writeInt(3); pw.writeInt(6); pw.writeInt(2); pw.writeInt(0); pw.writeFloat(2.3f); pw.writeInt(2); pw.writeFloat(3.8f); pw.writeInt(1); pw.writeInt(1); pw.writeFloat(1.3f); pw.writeInt(3); pw.writeInt(0); pw.writeFloat(4.2f); pw.writeInt(1); pw.writeFloat(2.2f); pw.writeInt(2); pw.writeFloat(0.5f); pw.close(); return f; }
public void saveCache( JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter) throws IOException { long start = System.currentTimeMillis(); String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname; logger.debug("saving" + msgSuffix); int count = 0; File tmpFile = File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile()); FileOutputStream fout = new FileOutputStream(tmpFile); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout)); FileDescriptor fd = fout.getFD(); for (K key : cache.getKeySet()) { byte[] bytes = converter.apply(key); out.writeInt(bytes.length); out.write(bytes); ++count; } out.flush(); fd.sync(); out.close(); if (!tmpFile.renameTo(savedCachePath)) throw new IOException("Unable to rename cache to " + savedCachePath); if (logger.isDebugEnabled()) logger.debug( "saved " + count + " keys in " + (System.currentTimeMillis() - start) + " ms from" + msgSuffix); }
private static File patchConfFile(File conf, String library) throws IOException { File tmpConf = File.createTempFile("idea-", "-mvn.conf"); tmpConf.deleteOnExit(); patchConfFile(conf, tmpConf, library); return tmpConf; }
/** * Returns the system temporary folder, e.g. /tmp */ public static File tmp() { try { return File.createTempFile("h2o", null).getParentFile(); } catch( IOException e ) { throw new RuntimeException(e); } }
/** * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file. * * @param f The jar file to extract from. * @return a temporary file to which the plugin.xml file has been copied. */ public static File unpackPluginXML(File f) { InputStream in = null; OutputStream out = null; try { JarFile jar = new JarFile(f); ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE); if (entry == null) { return null; } File dest = File.createTempFile("jabref_plugin", ".xml"); dest.deleteOnExit(); in = new BufferedInputStream(jar.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[2048]; for (; ; ) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); return dest; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
@Test public void canFollowLogfile() throws IOException { File tempFile = File.createTempFile("commons-io", "", new File(System.getProperty("java.io.tmpdir"))); tempFile.deleteOnExit(); System.out.println("Temp file = " + tempFile.getAbsolutePath()); PrintStream log = new PrintStream(tempFile); LogfileFollower follower = new LogfileFollower(tempFile); List<String> lines; // Empty file: lines = follower.newLines(); assertEquals(0, lines.size()); // Write two lines: log.println("Line 1"); log.println("Line 2"); lines = follower.newLines(); assertEquals(2, lines.size()); assertEquals("Line 2", lines.get(1)); // Write one more line: log.println("Line 3"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 3", lines.get(0)); // Write one and a half line and finish later: log.println("Line 4"); log.print("Line 5 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); // End last line and start a new one: log.println(" end"); log.print("Line 6 begin"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 5 begin end", lines.get(0)); // End last line: log.println(" end"); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 6 begin end", lines.get(0)); // A line only missing a newline: log.print("Line 7"); lines = follower.newLines(); assertEquals(0, lines.size()); log.println(); lines = follower.newLines(); assertEquals(1, lines.size()); assertEquals("Line 7", lines.get(0)); // Delete: log.close(); lines = follower.newLines(); assertEquals(0, lines.size()); }
public static void createAd(@Valid Ad ad, File photo) throws IOException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // get current date time with Date() Date date = new Date(); ad.createDate = dateFormat.format(date); ad.student = Student.findById(1l); // ad.category=Category.findById(ad.category.id); File d = new File(Play.applicationPath.getAbsolutePath() + "/public/img/ads"); // if(d.exists()){ String suffix = FilenameUtils.getExtension(photo.getName()); File o = File.createTempFile("ad-", "." + suffix, d); InputStream input = new FileInputStream(photo); OutputStream output = new FileOutputStream(o); ad.image = o.getName(); ad.save(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } Ads.index(1, ad.category.id.toString()); }
public static File writeFile(String content) { try { return writeFile(File.createTempFile("h2o", null), content); } catch( IOException e ) { throw Log.errRTExcept(e); } }
public static File createTmpFile() { try { return File.createTempFile("Utility_temp_file-" + String.valueOf(Utility.tic()), ".tmp"); } catch (IOException ex) { mylogger.log(Level.SEVERE, "Error: Can not create temp file ", ex); return null; } }
public static File createTmpFile(String prx, String sfx) { try { return File.createTempFile(prx, sfx); } catch (IOException ex) { mylogger.log(Level.SEVERE, "Error: Can not create temp file ", ex); return null; } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String filePickerResult = ""; if (data != null && resultCode == RESULT_OK) { try { ContentResolver cr = getContentResolver(); Uri uri = data.getData(); Cursor cursor = GeckoApp.mAppContext .getContentResolver() .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); String name = null; if (cursor != null) { try { if (cursor.moveToNext()) { name = cursor.getString(0); } } finally { cursor.close(); } } String fileName = "tmp_"; String fileExt = null; int period; if (name == null || (period = name.lastIndexOf('.')) == -1) { String mimeType = cr.getType(uri); fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType); } else { fileExt = name.substring(period); fileName = name.substring(0, period); } File file = File.createTempFile(fileName, fileExt, sGREDir); FileOutputStream fos = new FileOutputStream(file); InputStream is = cr.openInputStream(uri); byte[] buf = new byte[4096]; int len = is.read(buf); while (len != -1) { fos.write(buf, 0, len); len = is.read(buf); } fos.close(); filePickerResult = file.getAbsolutePath(); } catch (Exception e) { Log.e(LOG_FILE_NAME, "showing file picker", e); } } try { mFilePickerResult.put(filePickerResult); } catch (InterruptedException e) { Log.i(LOG_FILE_NAME, "error returning file picker result", e); } }
@Override public Object apply(List<Object> args, Context context) throws ParseException { File outFile = null; String editor = getEditor(); try { outFile = File.createTempFile("stellar_shell", "out"); if (args.size() > 0) { String arg = (String) args.get(0); try (PrintWriter pw = new PrintWriter(outFile)) { IOUtils.write(arg, pw); } } } catch (IOException e) { String message = "Unable to create temp file: " + e.getMessage(); LOG.error(message, e); throw new IllegalStateException(message, e); } Optional<Object> console = context.getCapability(CONSOLE, false); try { PausableInput.INSTANCE.pause(); // shut down the IO for the console ProcessBuilder processBuilder = new ProcessBuilder(editor, outFile.getAbsolutePath()); processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); try { Process p = processBuilder.start(); // wait for termination. p.waitFor(); try (BufferedReader br = new BufferedReader(new FileReader(outFile))) { String ret = IOUtils.toString(br).trim(); return ret; } } catch (Exception e) { String message = "Unable to read output: " + e.getMessage(); LOG.error(message, e); return null; } } finally { try { PausableInput.INSTANCE.unpause(); if (console.isPresent()) { ((Console) console.get()).pushToInputStream("\b\n"); } } catch (IOException e) { LOG.error("Unable to unpause: " + e.getMessage(), e); } if (outFile.exists()) { outFile.delete(); } } }
private String createTemporaryPreinstallFile() { try { File tempFile = File.createTempFile("preinstall", null); tempFile.deleteOnExit(); InstallUtil.copyResourceToFile("/gnu/io/installer/resources/macosx/preinstall", tempFile); String absPath = tempFile.getAbsolutePath(); Process p = Runtime.getRuntime().exec(new String[] {"chmod", "a+x", absPath}); p.waitFor(); return absPath; } catch (Throwable t) { } return null; }
/** * Creates a file on the local FS. Pass size as {@link LocalDirAllocator.SIZE_UNKNOWN} if not * known apriori. We round-robin over the set of disks (via the configured dirs) and return a * file on the first path which has enough space. The file is guaranteed to go away when the JVM * exits. */ public File createTmpFileForWrite(String pathStr, long size, Configuration conf) throws IOException { // find an appropriate directory Path path = getLocalPathForWrite(pathStr, size, conf, true); File dir = new File(path.getParent().toUri().getPath()); String prefix = path.getName(); // create a temp file on this directory File result = File.createTempFile(prefix, null, dir); result.deleteOnExit(); return result; }
/** * Creates a list of TIFF image files from an image file. It basically converts images of other * formats to TIFF format, or a multi-page TIFF image to multiple TIFF image files. * * @param imageFile input image file * @param index an index of the page; -1 means all pages, as in a multi-page TIFF image * @return a list of TIFF image files * @throws Exception */ public static List<File> createTiffFiles(File imageFile, int index) throws IOException { List<File> tiffFiles = new ArrayList<File>(); String imageFileName = imageFile.getName(); String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat); ImageReader reader = readers.next(); if (reader == null) { throw new RuntimeException( "Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net"); } ImageInputStream iis = ImageIO.createImageInputStream(imageFile); reader.setInput(iis); // Read the stream metadata // IIOMetadata streamMetadata = reader.getStreamMetadata(); // Set up the writeParam TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US); tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED); // Get tif writer and set output to file Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(TIFF_FORMAT); ImageWriter writer = writers.next(); // Read the stream metadata IIOMetadata streamMetadata = writer.getDefaultStreamMetadata(tiffWriteParam); int imageTotal = reader.getNumImages(true); for (int i = 0; i < imageTotal; i++) { // all if index == -1; otherwise, only index-th if (index == -1 || i == index) { // BufferedImage bi = reader.read(i); // IIOImage oimage = new IIOImage(bi, null, reader.getImageMetadata(i)); IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam()); File tiffFile = File.createTempFile(OUTPUT_FILE_NAME, TIFF_EXT); ImageOutputStream ios = ImageIO.createImageOutputStream(tiffFile); writer.setOutput(ios); writer.write(streamMetadata, oimage, tiffWriteParam); ios.close(); tiffFiles.add(tiffFile); } } writer.dispose(); reader.dispose(); return tiffFiles; }
private void createTempDir() { if (tmpDir == null) { try { File tmpFile = File.createTempFile("tmp", "tmp"); tmpFile.delete(); tmpDir = new File(tmpFile.getParentFile(), UUID.randomUUID().toString()); DeleteOnExitHook.add(tmpDir); } catch (IOException e) { throw new SmooksException("Unable to crete temp directory for archive.", e); } } }
public VSphereOutputStream( VsphereConnHandler connHandler, ManagedObjectReference fileManager, ManagedObjectReference vm, NamePasswordAuthentication credentials, String fileName) throws FileNotFoundException, IOException { this( connHandler, fileManager, vm, credentials, File.createTempFile("tmpVixCopy", ".tmp"), fileName); }
public boolean ok(String out, String reference) { try { File fo = File.createTempFile("homeworkeval", ".out"); File fr = File.createTempFile("homeworkeval", ".ref"); log.fine("Running custom validator."); save(out, fo); save(reference, fr); ArrayList<String> c = new ArrayList<String>(); c.add(command); c.add(fo.getPath()); c.add(fr.getPath()); ProcessBuilder pb = new ProcessBuilder(c); Process p = pb.start(); int rc = p.waitFor(); fo.delete(); fr.delete(); log.fine("Custom validator " + command + " says " + rc); return rc == 0; } catch (Exception e) { // Assume NOK. Don't propagate info to the client. log.finer("exc: " + UtilSrv.describe(e)); return false; } }
public boolean buildManifest(ExtFile appDir, Map<String, Object> usesFramework) throws BrutException { try { if (!new File(appDir, "AndroidManifest.xml").exists()) { return false; } if (!apkOptions.forceBuildAll) { LOGGER.info("Checking whether resources has changed..."); } File apkDir = new File(appDir, APK_DIRNAME); if (apkOptions.debugMode) { mAndRes.remove_application_debug(new File(apkDir, "AndroidManifest.xml").getAbsolutePath()); } if (apkOptions.forceBuildAll || isModified( newFiles(APK_MANIFEST_FILENAMES, appDir), newFiles(APK_MANIFEST_FILENAMES, apkDir))) { LOGGER.info("Building AndroidManifest.xml..."); File apkFile = File.createTempFile("APKTOOL", null); apkFile.delete(); File ninePatch = new File(appDir, "9patch"); if (!ninePatch.exists()) { ninePatch = null; } mAndRes.aaptPackage( apkFile, new File(appDir, "AndroidManifest.xml"), null, ninePatch, null, parseUsesFramework(usesFramework)); Directory tmpDir = new ExtFile(apkFile).getDirectory(); tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES); } return true; } catch (IOException | DirectoryException ex) { throw new AndrolibException(ex); } catch (AndrolibException ex) { LOGGER.warning("Parse AndroidManifest.xml failed, treat it as raw file."); return buildManifestRaw(appDir); } }
private static boolean canWrite(File installDir) { if (!installDir.canWrite()) return false; if (!installDir.isDirectory()) return false; File fileTest = null; try { fileTest = File.createTempFile("writtableArea", null, installDir); // $NON-NLS-1$ } catch (IOException e) { // If an exception occured while trying to create the file, it means that it is not writtable return false; } finally { if (fileTest != null) fileTest.delete(); } return true; }
// fix for 4720897 // if the jar file resides in a war file, download it to a temp dir // so it can be used to generate jardiff private String getRealPath(String path) throws IOException { URL fileURL = _servletContext.getResource(path); File tempDir = (File) _servletContext.getAttribute("javax.servlet.context.tempdir"); // download file into temp dir if (fileURL != null) { File newFile = File.createTempFile("temp", ".jar", tempDir); if (download(fileURL, newFile)) { String filePath = newFile.getPath(); return filePath; } } return null; }
protected File createTempFile(JarEntry je) throws IOException { byte[] jeBytes = getJarEntryBytes(outerFile, je); String tempName = je.getName().replace('/', '_') + "."; File tempDir = new File("execwartmp"); if (tempDir.mkdir()) tempDir.deleteOnExit(); File file = File.createTempFile("moqui_temp", tempName, tempDir); file.deleteOnExit(); BufferedOutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); os.write(jeBytes); } finally { if (os != null) os.close(); } return file; }
public boolean buildResourcesFull(File appDir, Map<String, Object> usesFramework) throws AndrolibException { try { if (!new File(appDir, "res").exists()) { return false; } if (!apkOptions.forceBuildAll) { LOGGER.info("Checking whether resources has changed..."); } File apkDir = new File(appDir, APK_DIRNAME); if (apkOptions.forceBuildAll || isModified( newFiles(APP_RESOURCES_FILENAMES, appDir), newFiles(APK_RESOURCES_FILENAMES, apkDir))) { LOGGER.info("Building resources..."); File apkFile = File.createTempFile("APKTOOL", null); apkFile.delete(); File ninePatch = new File(appDir, "9patch"); if (!ninePatch.exists()) { ninePatch = null; } mAndRes.aaptPackage( apkFile, new File(appDir, "AndroidManifest.xml"), new File(appDir, "res"), ninePatch, null, parseUsesFramework(usesFramework)); Directory tmpDir = new ExtFile(apkFile).getDirectory(); tmpDir.copyToDir( apkDir, tmpDir.containsDir("res") ? APK_RESOURCES_FILENAMES : APK_RESOURCES_WITHOUT_RES_FILENAMES); // delete tmpDir apkFile.delete(); } return true; } catch (IOException | BrutException ex) { throw new AndrolibException(ex); } }
/** * Check that the user has properly selected a target node for this tool * * <p> * * @return The phase progress message or <CODE>null</CODE> to abort early. * @throws PipelineException If unable to validate the given user input. */ public synchronized String collectPhaseInput() throws PipelineException { if ((pPrimary == null) || (pSelected.size() != 1)) throw new PipelineException("Please selected one node only."); // folder = nPath.getParent(); // assetName = nPath.getName(); Path nPath = new Path(pPrimary); nPath = nPath.getParentPath().getParentPath(); if (!nPath.toString().matches(assetPattern)) throw new PipelineException( "This tool only works on assets." + nPath.toString() + " " + nPath.toOsString()); // if(!pPrimary.matches(matPattern)) // throw new PipelineException("This tool will only work on a lgt node!"); File errFile; try { errFile = File.createTempFile("MaterialsCheckOut", ".err", PackageInfo.sTempPath.toFile()); err = new PrintWriter(errFile); FileCleaner.add(errFile); } catch (IOException e) { e.printStackTrace(); } NodeStatus status = pSelected.get(pPrimary); NodeID nodeID = status.getNodeID(); pUser = nodeID.getAuthor(); pView = nodeID.getView(); OverallNodeState state = status.getHeavyDetails().getOverallNodeState(); JToolDialog tool = new JToolDialog("MaterialsCheckOut", new JPanel(), "Continue"); if (!state.equals(OverallNodeState.Identical)) { JConfirmDialog dialog = new JConfirmDialog( tool, "This node is different from the checked in node. Do you want to continue with this check out?"); dialog.setVisible(true); if (!dialog.wasConfirmed()) { return null; } // end if } // end if return "...Sing Hallelujah!"; }
public static void main(String[] args) throws IOException { // open file but do not close it. Its existance will be checked by // the calling script. Paths.get(args[0]).newByteChannel(READ, WRITE, DELETE_ON_CLOSE); // check temporary file has been deleted after closing it Path file = File.createTempFile("blah", "tmp").toPath(); file.newByteChannel(READ, WRITE, DELETE_ON_CLOSE).close(); if (file.exists()) throw new RuntimeException("Temporary file was not deleted"); Path dir = TestUtil.createTemporaryDirectory(); try { // check that DELETE_ON_CLOSE fails when file is a sym link if (TestUtil.supportsLinks(dir)) { file = dir.resolve("foo").createFile(); Path link = dir.resolve("link").createSymbolicLink(file); try { link.newByteChannel(READ, WRITE, DELETE_ON_CLOSE); throw new RuntimeException("IOException expected"); } catch (IOException ignore) { } } // check that DELETE_ON_CLOSE works with files created via open // directories DirectoryStream stream = dir.newDirectoryStream(); try { if (stream instanceof SecureDirectoryStream) { SecureDirectoryStream secure = (SecureDirectoryStream) stream; file = Paths.get("foo"); Set<OpenOption> opts = new HashSet<OpenOption>(); opts.add(WRITE); opts.add(DELETE_ON_CLOSE); secure.newByteChannel(file, opts).close(); if (dir.resolve(file).exists()) throw new RuntimeException("File not deleted"); } } finally { stream.close(); } } finally { TestUtil.removeAll(dir); } }
/** * Helper method creates a temp file from the multipart form data and persists the upload file * metadata to the database * * @param filePart data from the form submission * @return an instance of UploadFile that has been persisted to the db */ private static UserUpload uploadFile(Http.MultipartFormData.FilePart filePart) { File src = (File) filePart.getFile(); File file = null; try { file = File.createTempFile(filePart.getFilename() + "-", ".csv"); FileUtils.copyFile(src, file); } catch (IOException e) { throw new RuntimeException("Could not create temp file for upload", e); } UserUpload uploadFile = new UserUpload(); uploadFile.absolutePath = file.getAbsolutePath(); uploadFile.fileName = filePart.getFilename(); uploadFile.user = Application.getCurrentUser(); uploadFile.save(); return uploadFile; }
private Map<String, String> analyzeAndStore( String fileName, InputStream translationFileInputStream) { File tempFile = null; BufferedWriter bw = null; Scanner scanner = null; try { tempFile = File.createTempFile("trans", ".tmp"); bw = new BufferedWriter(new FileWriter(tempFile)); scanner = new Scanner(translationFileInputStream); Map<String, String> properties = new HashMap<String, String>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); addProperty(properties, line); bw.write(line); bw.newLine(); } Closeables.closeQuietly(bw); String keyHash = getKeyHash(properties); File keyHashFolder = new File(propertyService.getProperty(PropertyKey.TRANSLATION_FILE_STORE), keyHash); keyHashFolder.mkdirs(); File translationFile = new File(keyHashFolder, fileName); boolean created = translationFile.createNewFile(); if (created) { Files.copy(tempFile, translationFile); } else { // TODO handle this case } return properties; } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("The hashkey of the given file couldn't be computed.", e); } catch (IOException e) { throw new IllegalStateException("An error occured with the given InputStream.", e); } finally { scanner.close(); Closeables.closeQuietly(bw); tempFile.delete(); } }