List of usage examples for java.io FileOutputStream getChannel
public FileChannel getChannel()
From source file:net.technicpack.launchercore.mirror.download.Download.java
@Override @SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null; try {/*w ww . j a va 2 s .com*/ HttpURLConnection conn = Utils.openHttpConnection(url); int response = conn.getResponseCode(); int responseFamily = response / 100; if (responseFamily == 3) { String redirUrlText = conn.getHeaderField("Location"); if (redirUrlText != null && !redirUrlText.isEmpty()) { URL redirectUrl = null; try { redirectUrl = new URL(redirUrlText); } catch (MalformedURLException ex) { throw new DownloadException("Invalid Redirect URL: " + url, ex); } conn = Utils.openHttpConnection(redirectUrl); response = conn.getResponseCode(); responseFamily = response / 100; } } if (responseFamily != 2) { throw new DownloadException("The server issued a " + response + " response code."); } InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); synchronized (timeoutLock) { if (isTimedOut) { return; } } if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (ClosedByInterruptException ex) { result = Result.FAILURE; return; } catch (PermissionDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:org.getspout.spout.Spout.java
protected void update() { //test install once File runOnce = new File(getDataFolder(), "runonce"); if (!runOnce.exists()) { try {/*from w w w . j a v a2 s .c o m*/ runOnce.createNewFile(); pingLink("http://bit.ly/spoutserverrunonce"); } catch (Exception e) { } } if (!isUpdateAvailable()) { return; } FileOutputStream fos = null; try { File directory = new File(Bukkit.getServer().getUpdateFolder()); if (!directory.exists()) { try { directory.mkdir(); } catch (SecurityException e1) { } } File tempDirectory = new File(directory, "temp"); if (!tempDirectory.exists()) { try { tempDirectory.mkdir(); } catch (SecurityException e1) { } } File plugin = new File(directory.getPath(), "Spout.jar"); File temp = new File(tempDirectory.getPath(), "Spout.jar"); if (!plugin.exists()) { URL spout = new URL( "http://ci.getspout.org/view/SpoutDev/job/Spout/promotion/latest/Recommended/artifact/target/spout-dev-SNAPSHOT.jar"); HttpURLConnection con = (HttpURLConnection) (spout.openConnection()); System.setProperty("http.agent", ""); //Spoofing the user agent is required to track stats con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30"); ReadableByteChannel rbc = Channels.newChannel(con.getInputStream()); fos = new FileOutputStream(temp); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } if (temp.exists()) { FileUtils.moveFile(temp, plugin); } } catch (Exception e) { } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } }
From source file:JNLPAppletLauncher.java
/** * This method is called by the static initializer to create / initialize * the temp root directory that will hold the temp directories for this * instance of the JVM. This is done as follows: * * 1. Synchronize on a global lock. Note that for this purpose we will * use System.out in the absence of a true global lock facility. * We are careful not to hold this lock too long. * * 2. Check for the existence of the "jnlp.applet.launcher.tmproot" * system property.//from w w w.ja va2s . co m * * a. If set, then some other thread in a different ClassLoader has * already created the tmprootdir, so we just need to * use it. The remaining steps are skipped. * * b. If not set, then we are the first thread in this JVM to run, * and we need to create the the tmprootdir. * * 3. Create the tmprootdir, along with the appropriate locks. * Note that we perform the operations in the following order, * prior to creating tmprootdir itself, to work around the fact that * the file creation and file lock steps are not atomic, and we need * to ensure that a newly-created tmprootdir isn't reaped by a * concurrently running JVM. * * create jlnNNNN.tmp using File.createTempFile() * lock jlnNNNN.tmp * create jlnNNNN.lck while holding the lock on the .tmp file * lock jlnNNNN.lck * * Since the Reaper thread will enumerate the list of *.lck files * before starting, we can guarantee that if there exists a *.lck file * for an active process, then the corresponding *.tmp file is locked * by that active process. This guarantee lets us avoid reaping an * active process' files. * * 4. Set the "jnlp.applet.launcher.tmproot" system property. * * 5. Add a shutdown hook to cleanup jlnNNNN.lck and jlnNNNN.tmp. We * don't actually expect that this shutdown hook will ever be called, * but the act of doing this, ensures that the locks never get * garbage-collected, which is necessary for correct behavior when * the first ClassLoader is later unloaded, while subsequent Applets * are still running. * * 6. Start the Reaper thread to cleanup old installations. */ private static void initTmpRoot() throws IOException { if (VERBOSE) { System.err.println("---------------------------------------------------"); } synchronized (System.out) { // Get the name of the tmpbase directory. String tmpBaseName = System.getProperty("java.io.tmpdir") + File.separator + "jnlp-applet"; tmpBaseDir = new File(tmpBaseName); // Get the value of the tmproot system property final String tmpRootPropName = "jnlp.applet.launcher.tmproot"; tmpRootPropValue = System.getProperty(tmpRootPropName); if (tmpRootPropValue == null) { // Create the tmpbase directory if it doesn't already exist tmpBaseDir.mkdir(); if (!tmpBaseDir.isDirectory()) { throw new IOException("Cannot create directory " + tmpBaseDir); } // Create ${tmpbase}/jlnNNNN.tmp then lock the file File tmpFile = File.createTempFile("jln", ".tmp", tmpBaseDir); if (VERBOSE) { System.err.println("tmpFile = " + tmpFile.getAbsolutePath()); } final FileOutputStream tmpOut = new FileOutputStream(tmpFile); final FileChannel tmpChannel = tmpOut.getChannel(); final FileLock tmpLock = tmpChannel.lock(); // Strip off the ".tmp" to get the name of the tmprootdir String tmpFileName = tmpFile.getAbsolutePath(); String tmpRootName = tmpFileName.substring(0, tmpFileName.lastIndexOf(".tmp")); // create ${tmpbase}/jlnNNNN.lck then lock the file String lckFileName = tmpRootName + ".lck"; File lckFile = new File(lckFileName); if (VERBOSE) { System.err.println("lckFile = " + lckFile.getAbsolutePath()); } lckFile.createNewFile(); final FileOutputStream lckOut = new FileOutputStream(lckFile); final FileChannel lckChannel = lckOut.getChannel(); final FileLock lckLock = lckChannel.lock(); // Create tmprootdir tmpRootDir = new File(tmpRootName); if (DEBUG) { System.err.println("tmpRootDir = " + tmpRootDir.getAbsolutePath()); } if (!tmpRootDir.mkdir()) { throw new IOException("Cannot create " + tmpRootDir); } // Add shutdown hook to cleanup the OutputStream, FileChannel, // and FileLock for the jlnNNNN.lck and jlnNNNN.lck files. // We do this so that the locks never get garbage-collected. Runtime.getRuntime().addShutdownHook(new Thread() { /* @Override */ public void run() { // NOTE: we don't really expect that this code will ever // be called. If it does, we will close the output // stream, which will in turn close the channel. // We will then release the lock. try { tmpOut.close(); tmpLock.release(); lckOut.close(); lckLock.release(); } catch (IOException ex) { // Do nothing } } }); // Set the system property... tmpRootPropValue = tmpRootName.substring(tmpRootName.lastIndexOf(File.separator) + 1); System.setProperty(tmpRootPropName, tmpRootPropValue); if (VERBOSE) { System.err.println("Setting " + tmpRootPropName + "=" + tmpRootPropValue); } // Start a new Reaper thread to do stuff... Thread reaperThread = new Thread() { /* @Override */ public void run() { deleteOldTempDirs(); } }; reaperThread.setName("AppletLauncher-Reaper"); reaperThread.start(); } else { // Make sure that the property is not set to an illegal value if (tmpRootPropValue.indexOf('/') >= 0 || tmpRootPropValue.indexOf(File.separatorChar) >= 0) { throw new IOException("Illegal value of: " + tmpRootPropName); } // Set tmpRootDir = ${tmpbase}/${jnlp.applet.launcher.tmproot} if (VERBOSE) { System.err.println("Using existing value of: " + tmpRootPropName + "=" + tmpRootPropValue); } tmpRootDir = new File(tmpBaseDir, tmpRootPropValue); if (DEBUG) { System.err.println("tmpRootDir = " + tmpRootDir.getAbsolutePath()); } if (!tmpRootDir.isDirectory()) { throw new IOException("Cannot access " + tmpRootDir); } } } }
From source file:com.pari.ic.ICManager.java
private String retriveICPackageFile(ICStorageServerSettings settings, ICPackage pkg, PollJobDetails details) throws Exception { String log = null;/*from w w w. j ava 2 s .c o m*/ InputStream inStream = null; HttpClient httpclient = null; Customer customer = CustomerManager.getInstance().getCustomerById(pkg.getCustomerId()); String customerName = customer.getCustomerName(); if (settings.getConnectivityType() == ConnectivityTypeEnum.CONNECTIVITY) { // DefaultHttpClient httpclient = null; // For Standalone NCCM, send the request via Connectivity String tegHost = settings.getTegHost(); if (tegHost == null) { log = "TEG URL is not configured.... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); return null; } String tegUrl = "http://" + tegHost + "/NccmCollector/ICDownloadServlet?"; log = "URL to TEG : " + tegUrl; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); // Sample URL - // http://172.21.136.202:8090/NccmCollector/ICDownloadServlet?GET_IC_PACK=TRUE&PACK_ID=1234 tegUrl = tegUrl + "GET_IC_PACK=TRUE"; tegUrl = tegUrl + "&"; tegUrl = tegUrl + "PACK_ID" + "=" + pkg.getPackageId(); String request = new URL(getFullUrl(settings.getServerHost()) + "/NetworkManagerWS/getFile/forPackage/" + pkg.getPackageId() + "/" + pkg.getPackageVersion() + "/" + customerName + "/" + pkg.getInstance_name()).toString(); request = request + "&&&"; request = request + settings.getUserId(); request = request + "&&&"; request = request + settings.getPassword(); log = "Request URL package download : " + request; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); try { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); tegUrl = tegUrl.replaceAll(" ", "%20"); log = "Posting request to url: " + tegUrl; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); HttpPost httppost = new HttpPost(tegUrl); httppost.setEntity(new StringEntity(request, null, null)); httppost.setHeader("Content-type", "text/xml"); HttpResponse response = httpclient.execute(httppost); log = "Response from HTTP Client in retriveICPackageFile : " + response.toString(); logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.INFO_INT, null); inStream = response.getEntity().getContent(); } catch (Exception e) { log = "Error while posting request to TEG... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e); } } else { try { httpclient = new DefaultHttpClient(); this.pasHttpRequestHandler.getSecuredHttpClient(httpclient); HttpGet request = new HttpGet(getFullUrl(settings.getServerHost()) + "/NetworkManagerWS/getFile/forPackage/" + pkg.getPackageId() + "/" + pkg.getPackageVersion() + "/" + customerName + "/" + pkg.getInstance_name()); ((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(settings.getUserId(), settings.getPassword())); HttpResponse response = httpclient.execute(request); inStream = response.getEntity().getContent(); } catch (Exception e) { log = "Error while posting request to retrieve package... "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, e); } } try { if (inStream != null) { ReadableByteChannel rbc = Channels.newChannel(inStream); String filePath = ICF_UPLOAD_FOLDER + File.separatorChar + pkg.getPackageId(); File file = new File(filePath); if (!file.getParentFile().exists()) { // ensure parent folder exists file.getParentFile().mkdir(); } if (file.exists()) { file.delete(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); } finally { try { if (fos != null) { fos.close(); } } catch (Exception ignore) { log = "Error while closing FileOutputStream : "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore); } try { inStream.close(); } catch (Exception ignore) { log = "Error while closing inStream : "; logMsg(details, log, JobStageConstants.PollingStages.RUNNING, Priority.ERROR_INT, ignore); } } return filePath; } } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return null; }
From source file:jackpal.androidterm.Term.java
private void copyClipboardToFile(String filename) { if (filename == null) return;//w w w. ja v a 2 s . co m FileOutputStream fos; try { fos = new FileOutputStream(filename); FileChannel fc = fos.getChannel(); try { ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext()); if (clip.hasText()) { ByteBuffer by = ByteBuffer.wrap(clip.getText().toString().getBytes()); fc.write(by); } fc.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.castis.sysComp.PoisConverterSysComp.java
private void writeClientUIFile(List<sceneDTO> list, String platform, File file) throws FileNotFoundException { FileOutputStream fos = null; String dir = filePolling.getValidFileDirectory(resultDir); String fileName = file.getName(); String tempDir = dir + "/temp/"; File targetDirectory = new File(CiFileUtil.getReplaceFullPath(tempDir)); if (!targetDirectory.isDirectory()) { CiFileUtil.createDirectory(tempDir); }/*from w w w .j a v a2s .c o m*/ fos = new FileOutputStream(tempDir + fileName); int byteSize = 2048; ByteBuffer byteBuffer = ByteBuffer.allocateDirect(byteSize); GatheringByteChannel outByteCh = fos.getChannel(); try { for (int i = 0; i < list.size(); i++) { sceneDTO scene = list.get(i); StringBuffer strBuffer = new StringBuffer(); if (i == 0) { strBuffer.append("policy"); strBuffer.append("|"); strBuffer.append(platform); strBuffer.append("|"); strBuffer.append("ClientUI"); strBuffer.append("\r\n"); } strBuffer.append("info"); strBuffer.append("|"); strBuffer.append(platform); strBuffer.append("|"); strBuffer.append(scene.getId()); strBuffer.append("|"); strBuffer.append(scene.getName()); strBuffer.append("|"); strBuffer.append(scene.getTemplateFileName()); strBuffer.append("|"); strBuffer.append(scene.getMenuId()); strBuffer.append("|"); strBuffer.append(scene.getMenuName()); strBuffer.append("|"); strBuffer.append(scene.getSpaceId()); strBuffer.append("|"); strBuffer.append(scene.getSpaceName()); strBuffer.append("|"); strBuffer.append(scene.getResolution()); strBuffer.append("|"); strBuffer.append(scene.getResolutionOnFocus()); strBuffer.append("|"); strBuffer.append(scene.getSizeLimit()); strBuffer.append("|"); strBuffer.append(scene.getClickable()); strBuffer.append("\r\n"); byte[] outByte = null; try { outByte = strBuffer.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } byteBuffer.put(outByte); byteBuffer.flip(); try { outByteCh.write(byteBuffer); } catch (IOException e) { } byteBuffer.clear(); } fos.close(); String targetDir = resultDir; File sourceFile = new File(tempDir + fileName); int index = fileName.indexOf("-"); if (index != -1) { fileName = fileName.substring(index + 1, fileName.length()); } index = fileName.indexOf("_"); if (index != -1) { String directory = fileName.substring(0, index); targetDir += "/" + directory; } index = fileName.indexOf("."); if (index != -1) { fileName = fileName.substring(0, index) + ".csv"; } try { File resultTargetDir = new File(CiFileUtil.getReplaceFullPath(targetDir)); if (!resultTargetDir.isDirectory()) { CiFileUtil.createDirectory(targetDir); } CiFileUtil.renameFile(sourceFile, targetDir, fileName); } catch (Exception e) { log.error(e.getMessage()); } } catch (Exception e) { String errorMsg = e.getMessage(); log.error(errorMsg, e); throw new DataParsingException(errorMsg, e); //throw(e); } }
From source file:JNLPAppletLauncher.java
/** * Called by the Reaper thread to delete old temp directories * Only one of these threads will run per JVM invocation. */// w ww.j a v a 2 s . c om private static void deleteOldTempDirs() { if (VERBOSE) { System.err.println("*** Reaper: deleteOldTempDirs in " + tmpBaseDir.getAbsolutePath()); } // enumerate list of jnl*.lck files, ignore our own jlnNNNN file final String ourLockFile = tmpRootPropValue + ".lck"; FilenameFilter lckFilter = new FilenameFilter() { /* @Override */ public boolean accept(File dir, String name) { return name.endsWith(".lck") && !name.equals(ourLockFile); } }; // For each file <file>.lck in the list we will first try to lock // <file>.tmp if that succeeds then we will try to lock <file>.lck // (which should always succeed unless there is a problem). If we can // get the lock on both files, then it must be an old installation, and // we will delete it. String[] fileNames = tmpBaseDir.list(lckFilter); if (fileNames != null) { for (int i = 0; i < fileNames.length; i++) { String lckFileName = fileNames[i]; String tmpDirName = lckFileName.substring(0, lckFileName.lastIndexOf(".lck")); String tmpFileName = tmpDirName + ".tmp"; File lckFile = new File(tmpBaseDir, lckFileName); File tmpFile = new File(tmpBaseDir, tmpFileName); File tmpDir = new File(tmpBaseDir, tmpDirName); if (lckFile.exists() && tmpFile.exists() && tmpDir.isDirectory()) { FileOutputStream tmpOut = null; FileChannel tmpChannel = null; FileLock tmpLock = null; try { tmpOut = new FileOutputStream(tmpFile); tmpChannel = tmpOut.getChannel(); tmpLock = tmpChannel.tryLock(); } catch (Exception ex) { // Ignore exceptions if (DEBUG) { ex.printStackTrace(); } } if (tmpLock != null) { FileOutputStream lckOut = null; FileChannel lckChannel = null; FileLock lckLock = null; try { lckOut = new FileOutputStream(lckFile); lckChannel = lckOut.getChannel(); lckLock = lckChannel.tryLock(); } catch (Exception ex) { if (DEBUG) { ex.printStackTrace(); } } if (lckLock != null) { // Recursively remove the old tmpDir and all of // its contents removeAll(tmpDir); // Close the streams and delete the .lck and .tmp // files. Note that there is a slight race condition // in that another process could open a stream at // the same time we are trying to delete it, which will // prevent deletion, but we won't worry about it, since // the worst that will happen is we might have an // occasional 0-byte .lck or .tmp file left around try { lckOut.close(); } catch (IOException ex) { } lckFile.delete(); try { tmpOut.close(); } catch (IOException ex) { } tmpFile.delete(); } else { try { // Close the file and channel for the *.lck file if (lckOut != null) { lckOut.close(); } // Close the file/channel and release the lock // on the *.tmp file tmpOut.close(); tmpLock.release(); } catch (IOException ex) { if (DEBUG) { ex.printStackTrace(); } } } } } else { if (VERBOSE) { System.err.println(" Skipping: " + tmpDir.getAbsolutePath()); } } } } }
From source file:in.neoandroid.neoupdate.neoUpdate.java
private boolean downloadFile(NewAsset asset, String toPath, TarArchiveInputStream tin, TarArchiveEntry ae) { if (enableDebug) Log.d(TAG, "Start download: " + asset.path + ":NPK: " + (tin != null)); boolean resume = (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_RESUME); String newPath;/*from w w w. ja v a2 s . com*/ if (toPath != null) newPath = toPath; else newPath = mapPath(asset.path); createSubDirectories(newPath); File newFile = new File(newPath); long fromBytes = 0; if (resume) fromBytes = newFile.length(); try { FileOutputStream os = new FileOutputStream(newFile, resume); db.setMd5(asset.path, asset.md5); if (tin != null && ae != null) { // Via NPK final int BUFF_SIZE = (8 * 1024); // Buffer size of 8KB byte[] buffer = new byte[BUFF_SIZE]; int n = 0; long size = ae.getSize(); if (resume && fromBytes > 0 && fromBytes < size) { tin.skip(fromBytes); size -= fromBytes; } while (size > 0) { n = BUFF_SIZE; if (n > size) n = (int) size; n = tin.read(buffer, 0, n); if (n < 0) break; if (n > 0) os.write(buffer, 0, n); } } else if (nConnections <= 0) { // Via Local File System FileInputStream is = new FileInputStream(baseUrl + asset.path); is.getChannel().transferTo(fromBytes, is.getChannel().size() - fromBytes, os.getChannel()); is.close(); } else { // Via Internet HttpResponse resp = HttpWithPostData(asset.path, fromBytes); resp.getEntity().writeTo(os); } db.setDownloaded(asset.path, true); os.close(); } catch (Exception e) { if (enableDebug) e.printStackTrace(); return false; } return true; }
From source file:be.ppareit.swiftp.server.CmdAbstractStore.java
public void doStorOrAppe(String param, boolean append) { Log.d(TAG, "STOR/APPE executing with append=" + append); File storeFile = inputPathToChrootedFile(sessionThread.getWorkingDir(), param); String errString = null;// w ww .j a va 2 s . c o m //OutputStream out = null; FileOutputStream out = null; // DedicatedWriter dedicatedWriter = null; // int origPriority = Thread.currentThread().getPriority(); // myLog.l(Log.DEBUG, "STOR original priority: " + origPriority); storing: { // Get a normalized absolute path for the desired file if (violatesChroot(storeFile)) { errString = "550 Invalid name or chroot violation\r\n"; break storing; } if (storeFile.isDirectory()) { errString = "451 Can't overwrite a directory\r\n"; break storing; } if ((sessionThread.offset >= 0) && (append)) { errString = "555 Append can not be used after a REST command\r\n"; break storing; } try { if (storeFile.exists()) { if (!append) { if (!FileUtil.deleteFile(storeFile, App.getAppContext())) { errString = "451 Couldn't truncate file\r\n"; break storing; } // Notify other apps that we just deleted a file MediaUpdater.notifyFileDeleted(storeFile.getPath()); } } if (!storeFile.exists()) { FileUtil.mkfile(storeFile, App.getAppContext()); } out = FileUtil.getOutputStream(storeFile, App.getAppContext()); //file if (sessionThread.offset <= 0) { out.getChannel().position(storeFile.length()); //out = new FileOutputStream(storeFile, append); } else if (sessionThread.offset == storeFile.length()) { out.getChannel().position(storeFile.length()); //out = new FileOutputStream(storeFile, true); } else { out.getChannel().position(sessionThread.offset); // final RandomAccessFile raf = new RandomAccessFile(storeFile, "rw"); // raf.seek(sessionThread.offset); // out = new OutputStream() { // @Override // public void write(int oneByte) throws IOException { // raf.write(oneByte); // } // // @Override // public void close() throws IOException { // raf.close(); // } // }; } } catch (FileNotFoundException e) { Log.e(TAG, "error : ", e); try { errString = "451 Couldn't open file \"" + param + "\" aka \"" + storeFile.getCanonicalPath() + "\" for writing\r\n"; } catch (IOException io_e) { errString = "451 Couldn't open file, nested exception\r\n"; } break storing; } catch (IOException e) { errString = "451 Unable to seek in file to append\r\n"; break storing; } if (!sessionThread.openDataSocket()) { errString = "425 Couldn't open data socket\r\n"; break storing; } Log.d(TAG, "Data socket ready"); sessionThread.writeString("150 Data socket ready\r\n"); byte[] buffer = new byte[SessionThread.DATA_CHUNK_SIZE]; // dedicatedWriter = new DedicatedWriter(out); // dedicatedWriter.start(); // start the writer thread executing // myLog.l(Log.DEBUG, "Started DedicatedWriter"); int numRead; // Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // int newPriority = Thread.currentThread().getPriority(); // myLog.l(Log.DEBUG, "New STOR prio: " + newPriority); if (sessionThread.isBinaryMode()) { Log.d(TAG, "Mode is binary"); } else { Log.d(TAG, "Mode is ascii"); } while (true) { /* * if(dedicatedWriter.checkErrorFlag()) { errString = * "451 File IO problem\r\n"; break storing; } */ switch (numRead = sessionThread.receiveFromDataSocket(buffer)) { case -1: Log.d(TAG, "Returned from final read"); // We're finished reading break storing; case 0: errString = "426 Couldn't receive data\r\n"; break storing; case -2: errString = "425 Could not connect data socket\r\n"; break storing; default: try { // Log.d(TAG, "Enqueueing buffer of " + numRead); // dedicatedWriter.enqueueBuffer(buffer, numRead); if (sessionThread.isBinaryMode()) { out.write(buffer, 0, numRead); } else { // ASCII mode, substitute \r\n to \n int startPos = 0, endPos; for (endPos = 0; endPos < numRead; endPos++) { if (buffer[endPos] == '\r') { out.write(buffer, startPos, endPos - startPos); // Our hacky method is to drop all \r startPos = endPos + 1; } } // Write last part of buffer as long as there was something // left after handling the last \r if (startPos < numRead) { out.write(buffer, startPos, endPos - startPos); } } // Attempted bugfix for transfer stalls. Reopen file periodically. // bytesSinceReopen += numRead; // if(bytesSinceReopen >= Defaults.bytes_between_reopen && // Defaults.do_reopen_hack) { // Log.d(TAG, "Closing and reopening file: " + storeFile); // out.close(); // out = new FileOutputStream(storeFile, true/*append*/); // bytesSinceReopen = 0; // } // Attempted bugfix for transfer stalls. Flush file periodically. // bytesSinceFlush += numRead; // if(bytesSinceFlush >= Defaults.bytes_between_flush && // Defaults.do_flush_hack) { // Log.d(TAG, "Flushing: " + storeFile); // out.flush(); // bytesSinceFlush = 0; // } // If this transfer fails, a later APPEND operation might be // received. In that case, we will need to have flushed the // previous writes in order for the append to work. The // filesystem on my G1 doesn't seem to recognized unflushed // data when appending. //out.flush(); } catch (IOException e) { errString = "451 File IO problem. Device might be full.\r\n"; Log.d(TAG, "Exception while storing: " + e); Log.d(TAG, "Message: " + e.getMessage()); Log.d(TAG, "Stack trace: "); StackTraceElement[] traceElems = e.getStackTrace(); for (StackTraceElement elem : traceElems) { Log.d(TAG, elem.toString()); } break storing; } break; } } } // // Clean up the dedicated writer thread // if(dedicatedWriter != null) { // dedicatedWriter.exit(); // set its exit flag // dedicatedWriter.interrupt(); // make sure it wakes up to process the flag // } // Thread.currentThread().setPriority(origPriority); try { // if(dedicatedWriter != null) { // dedicatedWriter.exit(); // } if (out != null) { out.close(); } } catch (IOException e) { } if (errString != null) { Log.i(TAG, "STOR error: " + errString.trim()); sessionThread.writeString(errString); } else { sessionThread.writeString("226 Transmission complete\r\n"); // Notify the music player (and possibly others) that a few file has // been uploaded. MediaUpdater.notifyFileCreated(storeFile.getPath()); } sessionThread.closeDataSocket(); Log.d(TAG, "STOR finished"); }
From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java
/** * Copy Files from One location to Other * @param Source File/*from w ww. j a v a2s . co m*/ * @param target File * @param Boolean Value * @throws FileNotFoundException */ public void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) { //log("Copying files with channels."); //ensureTargetDirectoryExists(aTargetFile.getParentFile()); FileChannel inChannel = null; FileChannel outChannel = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { try { inStream = new FileInputStream(aSourceFile); inChannel = inStream.getChannel(); outStream = new FileOutputStream(aTargetFile, aAppend); outChannel = outStream.getChannel(); long bytesTransferred = 0; //defensive loop - there's usually only a single iteration : while (bytesTransferred < inChannel.size()) { bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { //being defensive about closing all channels and streams if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } } catch (FileNotFoundException ex) { System.out.println("File not found: " + ex); } catch (IOException ex) { System.out.println(ex); } }