List of usage examples for java.io FileOutputStream getFD
public final FileDescriptor getFD() throws IOException
From source file:org.eclipse.kura.net.admin.visitor.linux.WpaSupplicantConfigWriter.java
private void copyFile(String data, File destination) throws KuraException { FileOutputStream fos = null; PrintWriter pw = null;//w ww . ja v a 2s .co m try { fos = new FileOutputStream(destination); pw = new PrintWriter(fos); pw.write(data); pw.flush(); fos.getFD().sync(); setPermissions(destination.toString()); } catch (IOException e) { throw KuraException.internalError(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ex) { s_logger.error("I/O Exception while closing FileOutputStream!"); } } if (pw != null) { pw.close(); } } }
From source file:org.eclipse.kura.core.deployment.install.InstallImpl.java
private void updateInstallPersistance(String fileName, DeploymentPackageOptions options) { this.m_installPersistance = new Properties(); this.m_installPersistance.setProperty(DeploymentPackageOptions.METRIC_DP_CLIENT_ID, options.getClientId()); this.m_installPersistance.setProperty(DeploymentPackageOptions.METRIC_JOB_ID, Long.toString(options.getJobId())); this.m_installPersistance.setProperty(DeploymentPackageOptions.METRIC_DP_NAME, fileName); this.m_installPersistance.setProperty(DeploymentPackageOptions.METRIC_DP_VERSION, options.getDpVersion()); this.m_installPersistance.setProperty(CloudDeploymentHandlerV2.METRIC_REQUESTER_CLIENT_ID, options.getRequestClientId()); this.m_installPersistance.setProperty(PERSISTANCE_FILE_NAME, fileName); if (this.m_installPersistanceDir == null) { s_logger.warn(MESSAGE_CONFIGURATION_FILE_NOT_SPECIFIED); return;// w w w. java2 s .co m } FileOutputStream fos = null; try { StringBuilder pathSB = new StringBuilder(); pathSB.append(this.m_installPersistanceDir); pathSB.append(File.separator); pathSB.append(fileName); pathSB.append(PERSISTANCE_SUFFIX); String persistanceFile = pathSB.toString(); fos = new FileOutputStream(persistanceFile); this.m_installPersistance.store(fos, null); fos.flush(); fos.getFD().sync(); } catch (IOException e) { s_logger.error("Error writing remote install configuration file", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { s_logger.error("Exception while closing the stream!", e); } } } }
From source file:com.example.download.DownloadThread.java
/** * Sync the destination file to storage. *///from w ww . ja v a 2 s .c o m private void syncDestination(State state) { FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(state.mFilename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { Utils.W("file " + state.mFilename + " not found: " + ex); } catch (SyncFailedException ex) { Utils.W("file " + state.mFilename + " sync failed: " + ex); } catch (IOException ex) { Utils.W("IOException trying to sync " + state.mFilename + ": " + ex); } catch (RuntimeException ex) { Utils.W("exception while syncing file: ", ex); } finally { if (downloadedFileStream != null) { try { downloadedFileStream.close(); } catch (IOException ex) { Utils.W("IOException while closing synced file: ", ex); } catch (RuntimeException ex) { Utils.W("exception while closing file: ", ex); } } } }
From source file:com.lan.nicehair.common.download.DownloadThread.java
/** * Sync the destination file to storage. *//*from w w w.ja va 2 s. com*/ private void syncDestination(State state) { FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(state.mFilename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { AppLog.e(TAG, "file " + state.mFilename + " not found: " + ex); } catch (SyncFailedException ex) { AppLog.e(TAG, "file " + state.mFilename + " sync failed: " + ex); } catch (IOException ex) { AppLog.e(TAG, "IOException trying to sync " + state.mFilename + ": " + ex); } catch (RuntimeException ex) { AppLog.e(TAG, "exception while syncing file: " + ex.getMessage()); } finally { if (downloadedFileStream != null) { try { downloadedFileStream.close(); } catch (IOException ex) { AppLog.e(TAG, "IOException while closing synced file: " + ex.getMessage()); } catch (RuntimeException ex) { AppLog.e(TAG, "exception while closing file: " + ex.getMessage()); } } } }
From source file:cn.dacas.providers.downloads.DownloadThread.java
/** * Sync the destination file to storage. *//*w ww. j a v a 2s . c o m*/ private void syncDestination(State state) { FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(state.mFilename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex); } catch (SyncFailedException ex) { Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex); } catch (IOException ex) { Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex); } catch (RuntimeException ex) { Log.w(Constants.TAG, "exception while syncing file: ", ex); } finally { if (downloadedFileStream != null) { try { downloadedFileStream.close(); } catch (IOException ex) { Log.w(Constants.TAG, "IOException while closing synced file: ", ex); } catch (RuntimeException ex) { Log.w(Constants.TAG, "exception while closing file: ", ex); } } } }
From source file:com.kong.zxreader.down.downloads.DownloadThread.java
/** * Sync the destination file to storage. *//*from w w w. ja v a 2 s. c o m*/ private void syncDestination(State state) { FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(state.mFilename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { Log.w(DownConstants.TAG, "file " + state.mFilename + " not found: " + ex); } catch (SyncFailedException ex) { Log.w(DownConstants.TAG, "file " + state.mFilename + " sync failed: " + ex); } catch (IOException ex) { Log.w(DownConstants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex); } catch (RuntimeException ex) { Log.w(DownConstants.TAG, "exception while syncing file: ", ex); } finally { if (downloadedFileStream != null) { try { downloadedFileStream.close(); } catch (IOException ex) { Log.w(DownConstants.TAG, "IOException while closing synced file: ", ex); } catch (RuntimeException ex) { Log.w(DownConstants.TAG, "exception while closing file: ", ex); } } } }
From source file:com.android.strictmodetest.StrictModeActivity.java
/** Called when the activity is first created. */ @Override/*from www . j ava2 s . co m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); cr = getContentResolver(); final SQLiteDatabase db = openOrCreateDatabase("foo.db", MODE_PRIVATE, null); final Button readButton = (Button) findViewById(R.id.read_button); readButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Cursor c = null; try { c = db.rawQuery("SELECT * FROM foo", null); } finally { if (c != null) c.close(); } } }); final Button writeButton = (Button) findViewById(R.id.write_button); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)"); } }); final Button writeLoopButton = (Button) findViewById(R.id.write_loop_button); writeLoopButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { long startTime = SystemClock.uptimeMillis(); int iters = 1000; BlockGuard.Policy policy = BlockGuard.getThreadPolicy(); for (int i = 0; i < iters; ++i) { policy.onWriteToDisk(); } long endTime = SystemClock.uptimeMillis(); Log.d(TAG, "Time for " + iters + ": " + (endTime - startTime) + ", avg=" + (endTime - startTime) / (double) iters); } }); final Button dnsButton = (Button) findViewById(R.id.dns_button); dnsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Doing DNS lookup for www.l.google.com... " + "(may be cached by InetAddress)"); try { InetAddress[] addrs = InetAddress.getAllByName("www.l.google.com"); for (int i = 0; i < addrs.length; ++i) { Log.d(TAG, "got: " + addrs[i]); } } catch (java.net.UnknownHostException e) { Log.d(TAG, "DNS error: " + e); } } }); final Button httpButton = (Button) findViewById(R.id.http_button); httpButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { // Note: not using AndroidHttpClient, as that comes with its // own pre-StrictMode network-on-Looper thread check. The // intent of this test is that we test the network stack's // instrumentation for StrictMode instead. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse res = httpClient.execute(new HttpGet("http://www.android.com/favicon.ico")); Log.d(TAG, "Fetched http response: " + res); } catch (IOException e) { Log.d(TAG, "HTTP fetch error: " + e); } } }); final Button http2Button = (Button) findViewById(R.id.http2_button); http2Button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { // Usually this ends up tripping in DNS resolution, // so see http3Button below, which connects directly to an IP InputStream is = new URL("http://www.android.com/").openConnection().getInputStream(); Log.d(TAG, "Got input stream: " + is); } catch (IOException e) { Log.d(TAG, "HTTP fetch error: " + e); } } }); final Button http3Button = (Button) findViewById(R.id.http3_button); http3Button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { // One of Google's web IPs, as of 2010-06-16.... InputStream is = new URL("http://74.125.19.14/").openConnection().getInputStream(); Log.d(TAG, "Got input stream: " + is); } catch (IOException e) { Log.d(TAG, "HTTP fetch error: " + e); } } }); final Button binderLocalButton = (Button) findViewById(R.id.binder_local_button); binderLocalButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { boolean value = mLocalServiceConn.stub.doDiskWrite(123 /* dummy */); Log.d(TAG, "local writeToDisk returned: " + value); } catch (RemoteException e) { Log.d(TAG, "local binderButton error: " + e); } } }); final Button binderRemoteButton = (Button) findViewById(R.id.binder_remote_button); binderRemoteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { boolean value = mRemoteServiceConn.stub.doDiskWrite(1); Log.d(TAG, "remote writeToDisk #1 returned: " + value); value = mRemoteServiceConn.stub.doDiskWrite(2); Log.d(TAG, "remote writeToDisk #2 returned: " + value); } catch (RemoteException e) { Log.d(TAG, "remote binderButton error: " + e); } } }); final Button binderOneWayButton = (Button) findViewById(R.id.binder_oneway_button); binderOneWayButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { Log.d(TAG, "doing oneway disk write over Binder."); mRemoteServiceConn.stub.doDiskOneWay(); } catch (RemoteException e) { Log.d(TAG, "remote binderButton error: " + e); } } }); final Button binderCheckButton = (Button) findViewById(R.id.binder_check_button); binderCheckButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int policy; try { policy = mLocalServiceConn.stub.getThreadPolicy(); Log.d(TAG, "local service policy: " + policy); policy = mRemoteServiceConn.stub.getThreadPolicy(); Log.d(TAG, "remote service policy: " + policy); } catch (RemoteException e) { Log.d(TAG, "binderCheckButton error: " + e); } } }); final Button serviceDumpButton = (Button) findViewById(R.id.service_dump); serviceDumpButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "About to do a service dump..."); File file = new File("/sdcard/strictmode-service-dump.txt"); FileOutputStream output = null; final StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); try { StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX); output = new FileOutputStream(file); StrictMode.setThreadPolicy(oldPolicy); boolean dumped = Debug.dumpService("cpuinfo", output.getFD(), new String[0]); Log.d(TAG, "Dumped = " + dumped); } catch (IOException e) { Log.e(TAG, "Can't dump service", e); } finally { StrictMode.setThreadPolicy(oldPolicy); } Log.d(TAG, "Did service dump."); } }); final Button lingerCloseButton = (Button) findViewById(R.id.linger_close_button); lingerCloseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeWithLinger(true); } }); final Button nonlingerCloseButton = (Button) findViewById(R.id.nonlinger_close_button); nonlingerCloseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { closeWithLinger(false); } }); final Button leakCursorButton = (Button) findViewById(R.id.leak_cursor_button); leakCursorButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy(); try { StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() .penaltyLog().penaltyDropBox().build()); db.execSQL("CREATE TABLE IF NOT EXISTS FOO (a INT)"); Cursor c = db.rawQuery("SELECT * FROM foo", null); c = null; // never close it Runtime.getRuntime().gc(); } finally { StrictMode.setVmPolicy(oldPolicy); } } }); final CheckBox checkNoWrite = (CheckBox) findViewById(R.id.policy_no_write); final CheckBox checkNoRead = (CheckBox) findViewById(R.id.policy_no_reads); final CheckBox checkNoNetwork = (CheckBox) findViewById(R.id.policy_no_network); final CheckBox checkPenaltyLog = (CheckBox) findViewById(R.id.policy_penalty_log); final CheckBox checkPenaltyDialog = (CheckBox) findViewById(R.id.policy_penalty_dialog); final CheckBox checkPenaltyDeath = (CheckBox) findViewById(R.id.policy_penalty_death); final CheckBox checkPenaltyDropBox = (CheckBox) findViewById(R.id.policy_penalty_dropbox); View.OnClickListener changePolicy = new View.OnClickListener() { public void onClick(View v) { StrictMode.ThreadPolicy.Builder newPolicy = new StrictMode.ThreadPolicy.Builder(); if (checkNoWrite.isChecked()) newPolicy.detectDiskWrites(); if (checkNoRead.isChecked()) newPolicy.detectDiskReads(); if (checkNoNetwork.isChecked()) newPolicy.detectNetwork(); if (checkPenaltyLog.isChecked()) newPolicy.penaltyLog(); if (checkPenaltyDialog.isChecked()) newPolicy.penaltyDialog(); if (checkPenaltyDeath.isChecked()) newPolicy.penaltyDeath(); if (checkPenaltyDropBox.isChecked()) newPolicy.penaltyDropBox(); StrictMode.ThreadPolicy policy = newPolicy.build(); Log.v(TAG, "Changing policy to: " + policy); StrictMode.setThreadPolicy(policy); } }; checkNoWrite.setOnClickListener(changePolicy); checkNoRead.setOnClickListener(changePolicy); checkNoNetwork.setOnClickListener(changePolicy); checkPenaltyLog.setOnClickListener(changePolicy); checkPenaltyDialog.setOnClickListener(changePolicy); checkPenaltyDeath.setOnClickListener(changePolicy); checkPenaltyDropBox.setOnClickListener(changePolicy); }
From source file:de.gfz_potsdam.datasync.Datasync.java
private void downloadItemFiles(String basedir, ItemMemberRef ref, Container parent) throws Exception { Item item = (Item) srv.getResourceById(ref.getObjid()); for (MetadataRecord mdr : item.getMetadataRecords()) { if (mdr.getName().equals("escidoc")) continue; log.log(Level.WARNING, "FIXME - download of Metadata not yet done"); }/*www . j a v a 2s . c o m*/ File syncdir = new File(directory + File.separator + basedir); for (Component component : item.getComponents()) { String filename = component.getProperties().getFileName(); File syncfile = new File(directory + File.separator + basedir + File.separator + filename); StringBuilder suffix = new StringBuilder(); if (syncfile.exists()) { if (App.db.localIsNewer(basedir + File.separator + filename, item.getObjid(), syncfile.lastModified())) { //local and remote file have changed suffix.append("-"); suffix.append(item.getObjid()); suffix.append(":"); suffix.append(item.getProperties().getVersion().getNumber()); suffix.append("-"); DateTime mdate = new DateTime(item.getLastModificationDate()); suffix.append(mdate.toString("YYYYMMdd-HHmmss")); syncfile = new File( directory + File.separator + basedir + File.separator + filename + suffix.toString()); } else if (!App.db.remoteIsNewer(basedir + File.separator + filename, item.getObjid(), item.getLastModificationDate())) { // do not download we downloaded before continue; } } else { //file was downloaded and locally deleted if (App.db.entryExists(basedir + File.separator + filename, item.getObjid())) continue; } //Download component HttpClient client = new HttpClient(); String url = auth.getServiceAddress() + component.getContent().getXLinkHref().replaceAll("^/", ""); GetMethod method = new GetMethod(url); method.setRequestHeader("Cookie", "escidocCookie=" + auth.getHandle()); try { log.log(Level.INFO, "downloading : {0}", new Object[] { syncfile.getAbsolutePath() }); client.executeMethod(method); InputStream is = method.getResponseBodyAsStream(); FileOutputStream file = new FileOutputStream(syncfile); byte[] buffer = new byte[4096]; int len; while ((len = is.read(buffer, 0, buffer.length)) != -1) { file.write(buffer, 0, len); } file.flush(); file.getFD().sync(); file.close(); } finally { method.releaseConnection(); } //update DB for non-conflicting files if (suffix.length() == 0) { App.db.storeMapping(basedir + File.separator + syncfile.getName(), item.getObjid(), syncfile.lastModified(), item.getLastModificationDate(), SyncDB.FILE); App.db.storeMapping(basedir, parent.getObjid(), syncdir.lastModified(), parent.getLastModificationDate(), SyncDB.DIRECTORY); } } }
From source file:org.eclipse.kura.net.admin.visitor.linux.IfcfgConfigWriter.java
private void writeDebianConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { StringBuffer sb = new StringBuffer(); File kuraFile = new File(DEBIAN_NET_CONFIGURATION_FILE); String iName = netInterfaceConfig.getName(); boolean appendConfig = true; if (kuraFile.exists()) { // found our match so load the properties Scanner scanner = null;// ww w .ja v a2 s. c o m try { scanner = new Scanner(new FileInputStream(kuraFile)); // need to loop through the existing file and replace only the desired interface while (scanner.hasNextLine()) { String noTrimLine = scanner.nextLine(); String line = noTrimLine.trim(); // ignore comments and blank lines if (!line.isEmpty()) { if (line.startsWith("#!kura!")) { line = line.substring("#!kura!".length()); } if (!line.startsWith("#")) { String[] args = line.split("\\s+"); // must be a line stating that interface starts on boot if (args.length > 1) { if (args[1].equals(iName)) { s_logger.debug("Found entry in interface file..."); appendConfig = false; sb.append(debianWriteUtility(netInterfaceConfig, iName)); // remove old config lines from the scanner while (scanner.hasNextLine() && !(line = scanner.nextLine()).isEmpty()) { } sb.append("\n"); } else { sb.append(noTrimLine + "\n"); } } } else { sb.append(noTrimLine + "\n"); } } else { sb.append(noTrimLine + "\n"); } } } catch (FileNotFoundException e1) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e1); } finally { scanner.close(); scanner = null; } // If config not present in file, append to end if (appendConfig) { s_logger.debug("Appending entry to interface file..."); // append an empty line if not there String s = sb.toString(); if (!"\\n".equals(s.substring(s.length() - 1))) { sb.append("\n"); } sb.append(debianWriteUtility(netInterfaceConfig, iName)); sb.append("\n"); } FileOutputStream fos = null; PrintWriter pw = null; try { fos = new FileOutputStream(DEBIAN_TMP_NET_CONFIGURATION_FILE); pw = new PrintWriter(fos); pw.write(sb.toString()); pw.flush(); fos.getFD().sync(); } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ex) { s_logger.error("I/O Exception while closing BufferedReader!"); } } if (pw != null) { pw.close(); } } // move the file if we made it this far File tmpFile = new File(DEBIAN_TMP_NET_CONFIGURATION_FILE); File file = new File(DEBIAN_NET_CONFIGURATION_FILE); try { if (!FileUtils.contentEquals(tmpFile, file)) { if (tmpFile.renameTo(file)) { s_logger.trace("Successfully wrote network interfaces file"); } else { s_logger.error("Failed to write network interfaces file"); throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, "error while building up new configuration file for network interfaces"); } } else { s_logger.info("Not rewriting network interfaces file because it is the same"); } } catch (IOException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } }
From source file:cn.keyshare.download.core.DownloadThread.java
/** * Sync the destination file to storage. *//*from ww w .j a v a 2 s . c o m*/ private void syncDestination(State state) { FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(state.mFilename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { Log.w(Constants.TAG, "file " + state.mFilename + " not found: " + ex); } catch (SyncFailedException ex) { Log.w(Constants.TAG, "file " + state.mFilename + " sync failed: " + ex); } catch (IOException ex) { Log.w(Constants.TAG, "IOException trying to sync " + state.mFilename + ": " + ex); } catch (RuntimeException ex) { Log.w(Constants.TAG, "exception while syncing file: ", ex); } finally { if (downloadedFileStream != null) { try { downloadedFileStream.close(); } catch (IOException ex) { Log.w(Constants.TAG, "IOException while closing synced file: ", ex); } catch (RuntimeException ex) { Log.w(Constants.TAG, "exception while closing file: ", ex); } } } }