List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:siddur.solidtrust.newprice2.Newprice2Controller.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException { //upload//from w ww .j a va 2 s.com log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } FileStatus fs = new FileStatus(); fs.setFile(temp); log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; String[] fields; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); fields = StringUtils.split(firstLine, ";"); ; orders = new int[fields.length]; for (int i = 0; i < orders.length; i++) { orders[i] = ArrayUtils.indexOf(FIELDS, fields[i].trim()); } //count while (br.readLine() != null) { fs.next(); } } finally { if (br != null) { br.close(); } } fs.flip(); log4j.info("Total rows: " + fs.getTotalRow()); //persist carService.saveCars(fs, orders, carService); return "redirect:/v2/upload.html"; }
From source file:heigit.ors.routing.RoutingProfilesUpdater.java
private void downloadFile(String url, File destination) { try {//from ww w.j av a 2 s.c o m URL website = new URL(url); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream(destination); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.onebusaway.webapp.actions.admin.bundles.SyncBundleAction.java
public String syncBundle() { String syncStatus = "Syncing in progress"; String apiHost = "http://admin.staging.obast.org:9999/api/bundle/latest"; JsonObject latestBundle = null;/*from w w w . ja v a2 s. c o m*/ try { latestBundle = getJsonData(apiHost).getAsJsonObject(); } catch (Exception e) { _log.error("Failed to retrieve name of the latest deployed bundle"); } String datasetName = latestBundle.get("dataset").getAsString(); String buildName = latestBundle.get("name").getAsString(); String bundleId = latestBundle.get("id").getAsString(); String bundleFileName = buildName + ".tar.gz"; String tmpDir = new NYCFileUtils().createTmpDirectory(); String bundleDir = "/var/lib/oba/bundles"; String deployDir = "/var/lib/oba/bundles/active"; String bundleBuildDir = "/var/lib/oba/bundles/builder"; try { String bundleSourceString = "http://admin.staging.obast.org:9999/api/bundle/archive/get-by-name/" + datasetName + "/" + buildName + "/" + bundleFileName; URL bundleSource = new URL(bundleSourceString); ReadableByteChannel rbc = Channels.newChannel(bundleSource.openStream()); FileOutputStream fos = new FileOutputStream(tmpDir + File.separator + bundleFileName); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { unzipBundle(tmpDir, bundleFileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy to extracted files /var/lib/oba/bundles/active try { //FileUtils.copyDirectory(new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName), new File(deployDir)); FileUtils.copyDirectory(new File(tmpDir + File.separator + "untarredBundle"), new File(deployDir)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy downloaded .tar.gz bundle to bundle builds dir String buildDest = bundleBuildDir + File.separator + datasetName + File.separator + "builds" + File.separator + buildName + File.separator + bundleFileName; try { FileUtils.copyFile(new File(tmpDir + File.separator + bundleFileName), new File(buildDest)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy inputs and outputs dirs File srcInputDir = new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName + File.separator + "inputs"); File srcOutputDir = new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName + File.separator + "outputs"); String destBuildsDir = bundleBuildDir + File.separator + datasetName + File.separator + "builds" + File.separator + buildName; try { FileUtils.copyDirectory(srcInputDir, new File(destBuildsDir + File.separator + "inputs")); FileUtils.copyDirectory(srcOutputDir, new File(destBuildsDir + File.separator + "outputs")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy gtfs and aux files to aux_latest and gtfs_latest String gtfsFileDest = bundleBuildDir + File.separator + datasetName + File.separator + "gtfs_latest"; String auxFileDest = bundleBuildDir + File.separator + datasetName + File.separator + "aux_latest"; File[] inputFiles = srcInputDir.listFiles(); for (File inputFile : inputFiles) { try { String fileName = inputFile.getName(); int idx = fileName.indexOf("_"); if (idx > 0) { // Skip over config dir String agencyNum = fileName.substring(0, idx); String zipFileName = fileName.substring(idx + 1); if (agencyNum.equals("29")) { // For CT aux files String fileDest = auxFileDest + File.separator + agencyNum + File.separator + zipFileName; FileUtils.copyFile(inputFile, new File(fileDest)); } else { String fileDest = gtfsFileDest + File.separator + agencyNum + File.separator + zipFileName; FileUtils.copyFile(inputFile, new File(fileDest)); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } syncStatus = "Complete"; return "syncStatus"; }
From source file:model.settings.ReadSettings.java
/** * Update the entire program.//from ww w . j a v a2s . c o m */ public static void update(final View _view, final boolean _showNoUpdateMSG) { new Thread() { public void run() { final boolean newReleaseAccepted = checkForUpdate(_view, _showNoUpdateMSG); if (newReleaseAccepted) { _view.dispose(); /* * dispose current version of paint that is currently running. */ InformationWindow iw = new InformationWindow("Update current version of Paint"); iw.setText("\t\t\tPaint update\n" + "This window will give information on the\n" + "update process of the paint - program.\n\n" + "The Program is directly pulled from the github\n" + "update page which can be found at\n" + "https://github.com/juliusHuelsmann/paint.git.\n" + "\nThe update-performance depends on your\n" + " internet connection.\n\n"); /* * Property name for getting operating system identifier. */ final String os_propertyName = "os.name"; /* * Different property content values for deciding which * operating system is used. */ final String propertyLinux = "Linux"; final String propertyOSX = "Mac OS X"; final String propertyWindows = "Windows"; /* * The identifier for the currently used operating system. */ final String propertyContent = System.getProperties().getProperty(os_propertyName); /* * Compute TEMP directory path depending on the currently * used operating system. */ iw.appendNewOperation("Checking operating system:"); iw.startWaiting(true); final String temp; if (propertyContent.equals(propertyLinux)) { temp = System.getenv().get("TMPDIR"); iw.appendNewResult("Linux"); } else if (propertyContent.equals(propertyWindows)) { temp = System.getenv().get("TMPDIR"); iw.appendNewResult("Windows"); } else if (propertyContent.equals(propertyOSX)) { temp = System.getenv().get("TMPDIR"); iw.appendNewResult("OS X"); } else { temp = System.getenv().get("TMPDIR"); iw.appendNewResult("Not found, System not implemented " + "yet. \nThis may cause errors."); throw new UnsupportedOperationException("not impl. yet."); } /* * Create sub-TEMP directory */ final String tempDirPaint = temp + "paint/"; final String ret0_a, command0 = "mkdir " + tempDirPaint; iw.appendNewOperation("Check whether sub-temp dir exists"); if (new File(tempDirPaint).exists()) { ret0_a = "The file already exists: "; // + tempDirPaint + "." ; iw.appendNewResult(ret0_a); // remove file iw.appendNewOperation("Remove old temp file."); final String ret0_b, command0_b = "rm -r -f " + tempDirPaint; ret0_b = Util.executeCommandLinux(command0_b); iw.appendNewResult(ret0_b); } iw.appendNewOperation("Create sub-TEMP directory"); final String ret0 = Util.executeCommandLinux(command0); iw.appendNewResult(ret0); /* * Check whether git is installted at the machine. */ iw.appendNewOperation("Clone Project into TEMP directory."); iw.appendNewOperation("Check whether git is installed."); final String command1 = "git version"; String ret1 = Util.executeCommandLinux(command1); boolean installed = ret1.contains(Util.EXECUTION_SUCCESS); if (installed) { iw.appendNewResult("Git installed."); /* * Clone project into TEMP directory */ iw.appendNewOperation("Clone Project into TEMP directory."); final String command1a = "git clone " + "https://github.com/juliusHuelsmann/paint.git " + tempDirPaint; String ret1a = Util.executeCommandLinux(command1a); iw.appendNewResult(ret1a); /* * Start jar file which copies itself into the program directory. */ iw.appendNewOperation("Launching new project file"); final String command2a = "java -jar " + tempDirPaint + "PaintNotes/paint.jar"; String ret2a = Util.executeCommandLinux(command2a); iw.appendNewResult(ret2a); } else { iw.appendNewOperation("\t Git not installed. Manual download."); /* * Download Program from repository URL */ final String repoURL = "https://github.com/juliusHuelsmann/paint/archive/master.zip"; final String zipPath = tempDirPaint + "master.zip"; try { iw.appendNewResult("Download zip"); URL website = new URL(repoURL); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos; fos = new FileOutputStream(zipPath); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); iw.appendNewResult("Failed download. exit."); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.exit(1); } catch (IOException e) { e.printStackTrace(); iw.appendNewResult("Failed download. exit."); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.exit(1); } /* * Unzip the program */ iw.appendNewOperation("unzip"); /** * The command which is executed for unzipping the program. */ final String commandUnzip = "unzip " + zipPath + " -d " + tempDirPaint; /** * The result of the command's execution in terminal. * If the response tells that the command has been executed * successfully, there is nothing to do. Otherwise * perform rotation done by program and print a warning. */ final String resultUnzip = Util.executeCommandLinux(commandUnzip); iw.appendNewResult(resultUnzip); if (resultUnzip.startsWith(Util.EXECUTION_SUCCESS)) { //print success information model.settings.State.getLogger().info("Download and execution successfull"); } else if (resultUnzip.startsWith(Util.EXECUTION_FAILED)) { // model.settings.State.getLogger().severe("Download and execution failed" + resultUnzip); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.exit(1); } // /** * Command for removing zip download file. */ iw.appendNewOperation("Remove zip file"); final String commandMv = "rm " + zipPath; final String resultClear = Util.executeCommandLinux(commandMv); iw.appendNewResult(resultClear); /* * Start jar file which copies itself into the program directory. */ iw.appendNewOperation("Launching new project file"); final String command2a = "java -jar " + tempDirPaint + "paint-master/PaintNotes/paint.jar"; String ret2a = Util.executeCommandLinux(command2a); iw.appendNewResult(ret2a); } iw.stopWaiting(); try { Thread.sleep(2000); } catch (InterruptedException e1) { e1.printStackTrace(); } System.exit(1); // // // /* // * Check for version number // */ // final String command1 = "git clone " // + "https://github.com/juliusHuelsmann/paint.git " // + tempDirPaint; // String ret2 = Util.executeCommandLinux(command1); // model.settings.State.getLogger().severe("Executed" // + "\nC1:\t" + command0 + "\n\t" + ret0_a // + "\nC2:\t" + command1 + "\n\t" + ret1 // + "\nC3:\t" + command2 + "\n\t" + ret2); } } }.start(); }
From source file:org.apache.hadoop.hdfs.tools.offlineEditsViewer.TestOfflineEditsViewer.java
@Test public void testRecoveryMode() throws IOException { // edits generated by nnHelper (MiniDFSCluster), should have all op codes // binary, XML, reparsed binary String edits = nnHelper.generateEdits(); FileOutputStream os = new FileOutputStream(edits, true); // Corrupt the file by truncating the end FileChannel editsFile = os.getChannel(); editsFile.truncate(editsFile.size() - 5); String editsParsedXml = folder.newFile("editsRecoveredParsed.xml").getAbsolutePath(); String editsReparsed = folder.newFile("editsRecoveredReparsed").getAbsolutePath(); String editsParsedXml2 = folder.newFile("editsRecoveredParsed2.xml").getAbsolutePath(); // Can't read the corrupted file without recovery mode assertEquals(-1, runOev(edits, editsParsedXml, "xml", false)); // parse to XML then back to binary assertEquals(0, runOev(edits, editsParsedXml, "xml", true)); assertEquals(0, runOev(editsParsedXml, editsReparsed, "binary", false)); assertEquals(0, runOev(editsReparsed, editsParsedXml2, "xml", false)); // judgment time assertTrue("Test round trip", FileUtils.contentEqualsIgnoreEOL(new File(editsParsedXml), new File(editsParsedXml2), "UTF-8")); os.close();/*from w w w.j a v a 2s .co m*/ }
From source file:com.titankingdoms.nodinchan.mobjockeys.MobJockeys.java
/** * Checks for update of the library/* w w w . j av a 2 s. c o m*/ */ private void updateLib() { PluginManager pm = getServer().getPluginManager(); NCBL libPlugin = (NCBL) pm.getPlugin("NC-BukkitLib"); File destination = new File(getDataFolder().getParentFile().getParentFile(), "lib"); destination.mkdirs(); File lib = new File(destination, "NC-BukkitLib.jar"); File pluginLib = new File(getDataFolder().getParentFile(), "NC-BukkitLib.jar"); boolean inPlugins = false; boolean download = false; try { URL url = new URL("http://bukget.org/api/plugin/nc-bukkitlib"); JSONObject jsonPlugin = (JSONObject) new JSONParser().parse(new InputStreamReader(url.openStream())); JSONArray versions = (JSONArray) jsonPlugin.get("versions"); if (libPlugin == null) { getLogger().log(Level.INFO, "Missing NC-Bukkit lib"); inPlugins = true; download = true; } else { double currentVer = Double.parseDouble(libPlugin.getDescription().getVersion()); double newVer = currentVer; for (int ver = 0; ver < versions.size(); ver++) { JSONObject version = (JSONObject) versions.get(ver); if (version.get("type").equals("Release")) { newVer = Double .parseDouble(((String) version.get("name")).split(" ")[1].trim().substring(1)); break; } } if (newVer > currentVer) { getLogger().log(Level.INFO, "NC-Bukkit lib outdated"); download = true; } } if (download) { System.out.println("Downloading NC-Bukkit lib..."); String dl_link = ""; for (int ver = 0; ver < versions.size(); ver++) { JSONObject version = (JSONObject) versions.get(ver); if (version.get("type").equals("Release")) { dl_link = (String) version.get("dl_link"); break; } } if (dl_link == null) throw new Exception(); URL link = new URL(dl_link); ReadableByteChannel rbc = Channels.newChannel(link.openStream()); if (inPlugins) { FileOutputStream output = new FileOutputStream(pluginLib); output.getChannel().transferFrom(rbc, 0, 1 << 24); pm.loadPlugin(pluginLib); } else { FileOutputStream output = new FileOutputStream(lib); output.getChannel().transferFrom(rbc, 0, 1 << 24); } getLogger().log(Level.INFO, "Downloaded NC-Bukkit lib"); } } catch (Exception e) { System.out.println("Failed to check for library update"); } }
From source file:gridool.util.xfer.RecievedFileWriter.java
public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket) throws IOException { final StopWatch sw = new StopWatch(); if (!inChannel.isBlocking()) { inChannel.configureBlocking(true); }/*from ww w.ja v a 2 s . c o m*/ InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); String fname = IOUtils.readString(dis); String dirPath = IOUtils.readString(dis); long len = dis.readLong(); boolean append = dis.readBoolean(); boolean ackRequired = dis.readBoolean(); boolean hasAdditionalHeader = dis.readBoolean(); if (hasAdditionalHeader) { readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired); } final File file; if (dirPath == null) { file = new File(baseDir, fname); } else { File dir = FileUtils.resolvePath(baseDir, dirPath); file = new File(dir, fname); } preFileAppend(file, append); final FileOutputStream dst = new FileOutputStream(file, append); final String fp = file.getAbsolutePath(); final ReadWriteLock filelock = accquireLock(fp, locks); final FileChannel fileCh = dst.getChannel(); final long startPos = file.length(); try { NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation? } finally { IOUtils.closeQuietly(fileCh, dst); releaseLock(fp, filelock, locks); postFileAppend(file, startPos, len); } if (ackRequired) { OutputStream out = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeLong(len); postAck(file, startPos, len); } if (LOG.isDebugEnabled()) { SocketAddress remoteAddr = socket.getRemoteSocketAddress(); LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of " + len + " bytes from " + remoteAddr + " in " + sw.toString()); } }
From source file:siddur.solidtrust.classic.ClassicController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws Exception { //upload/*from www . j a v a2 s. c o m*/ log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize()); File temp = File.createTempFile("data", ".csv"); log4j.info("Will save to " + temp.getAbsolutePath()); InputStream in = null; FileOutputStream fout = null; try { fout = new FileOutputStream(temp); FileChannel fcout = fout.getChannel(); in = file.getInputStream(); ReadableByteChannel cin = Channels.newChannel(in); ByteBuffer buf = ByteBuffer.allocate(1024 * 8); while (true) { buf.clear(); int r = cin.read(buf); if (r == -1) { break; } buf.flip(); fcout.write(buf); } } finally { if (in != null) { in.close(); } if (fout != null) { fout.close(); } } log4j.info("Uploading complete"); //fields BufferedReader br = null; int[] orders; try { in = new FileInputStream(temp); br = new BufferedReader(new InputStreamReader(in)); //first line for fields String firstLine = br.readLine(); orders = persister.validateTitle(firstLine); //persist persister.parseAndSave(br, orders, persister); } finally { if (br != null) { br.close(); } } return "redirect:upload.html"; }
From source file:xbird.util.xfer.RecievedFileWriter.java
public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket) throws IOException { final StopWatch sw = new StopWatch(); if (!inChannel.isBlocking()) { inChannel.configureBlocking(true); }//from w ww . j av a 2 s .c om InputStream in = socket.getInputStream(); DataInputStream dis = new DataInputStream(in); String fname = IOUtils.readString(dis); String dirPath = IOUtils.readString(dis); long len = dis.readLong(); boolean append = dis.readBoolean(); boolean ackRequired = dis.readBoolean(); boolean hasAdditionalHeader = dis.readBoolean(); if (hasAdditionalHeader) { readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired); } final File file; if (dirPath == null) { file = new File(baseDir, fname); } else { File dir = FileUtils.resolvePath(baseDir, dirPath); file = new File(dir, fname); } preFileAppend(file, append); final FileOutputStream dst = new FileOutputStream(file, append); final String fp = file.getAbsolutePath(); final ReadWriteLock filelock = accquireLock(fp, locks); final FileChannel fileCh = dst.getChannel(); final long startPos = file.length(); try { NIOUtils.transferFullyFrom(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation? } finally { IOUtils.closeQuietly(fileCh, dst); releaseLock(fp, filelock, locks); postFileAppend(file, startPos, len); } if (ackRequired) { OutputStream out = socket.getOutputStream(); DataOutputStream dos = new DataOutputStream(out); dos.writeLong(len); postAck(file, startPos, len); } if (LOG.isDebugEnabled()) { SocketAddress remoteAddr = socket.getRemoteSocketAddress(); LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of " + len + " bytes from " + remoteAddr + " in " + sw.toString()); } }
From source file:com.wet.wired.jsr.recorder.JRecorder.java
private void saveVideo(File targetWithOwl) { File capFile = new File( targetWithOwl.getAbsolutePath().substring(0, targetWithOwl.getAbsolutePath().lastIndexOf(".")) + ".owl.cap"); logger.info("start save cap"); try {/*from w w w . ja v a 2 s. c om*/ FileOutputStream fos = new FileOutputStream(capFile); recorder.writeFrameIndex(fos.getChannel()); recorder.writeVideo(fos.getChannel()); fos.close(); } catch (FileNotFoundException e) { logger.error("cannot save cap file", e); exceptionWindow.show(e, "cannot save cap file"); } catch (IOException e) { logger.error("cannot close outputstream", e); exceptionWindow.show(e, "cannot close outputstream"); } processRecordingWindow.setProgressValue(1); logger.info("stop save cap"); }