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.IfcfgConfigWriter.java
private void writeRedhatConfig(NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig) throws KuraException { String interfaceName = netInterfaceConfig.getName(); String outputFileName = new StringBuffer().append(REDHAT_NET_CONFIGURATION_DIRECTORY).append("ifcfg-") .append(interfaceName).toString(); String tmpOutputFileName = new StringBuffer().append(REDHAT_NET_CONFIGURATION_DIRECTORY).append("ifcfg-") .append(interfaceName).append(".tmp").toString(); s_logger.debug("Writing config for {}", interfaceName); NetInterfaceType type = netInterfaceConfig.getType(); if (type == NetInterfaceType.ETHERNET || type == NetInterfaceType.WIFI || type == NetInterfaceType.LOOPBACK) { StringBuffer sb = new StringBuffer(); sb.append("# Networking Interface\n"); // DEVICE sb.append("DEVICE=").append(netInterfaceConfig.getName()).append("\n"); // NAME/*w w w .j a va 2s . com*/ sb.append("NAME=").append(netInterfaceConfig.getName()).append("\n"); // TYPE sb.append("TYPE=").append(netInterfaceConfig.getType()).append("\n"); List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); s_logger.debug("There are " + netInterfaceAddressConfigs.size() + " NetInterfaceConfigs in this configuration"); boolean allowWrite = false; for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { // ONBOOT sb.append("ONBOOT="); if (((NetConfigIP4) netConfig).isAutoConnect()) { sb.append("yes"); } else { sb.append("no"); } sb.append("\n"); if (((NetConfigIP4) netConfig).isDhcp()) { // BOOTPROTO sb.append("BOOTPROTO="); s_logger.debug("new config is DHCP"); sb.append("dhcp"); sb.append("\n"); } else { // BOOTPROTO sb.append("BOOTPROTO="); s_logger.debug("new config is STATIC"); sb.append("static"); sb.append("\n"); // IPADDR sb.append("IPADDR=") .append(((NetConfigIP4) netConfig).getAddress().getHostAddress()) .append("\n"); // PREFIX sb.append("PREFIX=").append(((NetConfigIP4) netConfig).getNetworkPrefixLength()) .append("\n"); // Gateway if (((NetConfigIP4) netConfig).getGateway() != null) { sb.append("GATEWAY=") .append(((NetConfigIP4) netConfig).getGateway().getHostAddress()) .append("\n"); } } // DEFROUTE if (((NetConfigIP4) netConfig) .getStatus() == NetInterfaceStatus.netIPv4StatusEnabledWAN) { sb.append("DEFROUTE=yes\n"); } else { sb.append("DEFROUTE=no\n"); } // DNS List<? extends IPAddress> dnsAddresses = ((NetConfigIP4) netConfig).getDnsServers(); if (dnsAddresses != null && dnsAddresses.size() > 0) { for (int i = 0; i < dnsAddresses.size(); i++) { IPAddress ipAddr = dnsAddresses.get(i); if (!(ipAddr.isLoopbackAddress() || ipAddr.isLinkLocalAddress() || ipAddr.isMulticastAddress())) { sb.append("DNS").append(i + 1).append("=").append(ipAddr.getHostAddress()) .append("\n"); } } } else { s_logger.debug("no DNS entries"); } allowWrite = true; } } } else { s_logger.debug("netConfigs is null"); } // WIFI if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfig) { s_logger.debug("new config is a WifiInterfaceAddressConfig"); sb.append("\n#Wireless configuration\n"); // MODE String mode = null; WifiMode wifiMode = ((WifiInterfaceAddressConfig) netInterfaceAddressConfig).getMode(); if (wifiMode == WifiMode.INFRA) { mode = "Managed"; } else if (wifiMode == WifiMode.MASTER) { mode = "Master"; } else if (wifiMode == WifiMode.ADHOC) { mode = "Ad-Hoc"; } else if (wifiMode == null) { s_logger.error("WifiMode is null"); mode = "null"; } else { mode = wifiMode.toString(); } sb.append("MODE=").append(mode).append("\n"); } } if (allowWrite) { FileOutputStream fos = null; PrintWriter pw = null; try { fos = new FileOutputStream(tmpOutputFileName); 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(tmpOutputFileName); File outputFile = new File(outputFileName); try { if (!FileUtils.contentEquals(tmpFile, outputFile)) { if (tmpFile.renameTo(outputFile)) { s_logger.trace("Successfully wrote network interface file for {}", interfaceName); } else { s_logger.error("Failed to write network interface file"); throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, "error while building up new configuration file for network interface " + interfaceName); } } else { s_logger.info("Not rewriting network interfaces file for " + interfaceName + " because it is the same"); } } catch (IOException e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, e); } } else { s_logger.warn("writeNewConfig :: operation is not allowed"); } } }
From source file:org.apache.james.queue.file.FileMailQueue.java
@Override public void enQueue(Mail mail, long delay, TimeUnit unit) throws MailQueueException { final String key = mail.getName() + "-" + COUNTER.incrementAndGet(); FileOutputStream out = null;//www . ja v a2 s . c om FileOutputStream foout = null; ObjectOutputStream oout = null; try { int i = (int) (Math.random() * SPLITCOUNT + 1); String name = queueDirName + "/" + i + "/" + key; final FileItem item = new FileItem(name + OBJECT_EXTENSION, name + MSG_EXTENSION); if (delay > 0) { mail.setAttribute(NEXT_DELIVERY, System.currentTimeMillis() + unit.toMillis(delay)); } foout = new FileOutputStream(item.getObjectFile()); oout = new ObjectOutputStream(foout); oout.writeObject(mail); oout.flush(); if (sync) foout.getFD().sync(); out = new FileOutputStream(item.getMessageFile()); mail.getMessage().writeTo(out); out.flush(); if (sync) out.getFD().sync(); keyMappings.put(key, item); if (delay > 0) { // The message should get delayed so schedule it for later scheduler.schedule(new Runnable() { @Override public void run() { try { inmemoryQueue.put(key); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Unable to init", e); } } }, delay, unit); } else { inmemoryQueue.put(key); } //TODO: Think about exception handling in detail } catch (FileNotFoundException e) { throw new MailQueueException("Unable to enqueue mail", e); } catch (IOException e) { throw new MailQueueException("Unable to enqueue mail", e); } catch (MessagingException e) { throw new MailQueueException("Unable to enqueue mail", e); } catch (InterruptedException e) { throw new MailQueueException("Unable to enqueue mail", e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore on close } } if (oout != null) { try { oout.close(); } catch (IOException e) { // ignore on close } } if (foout != null) { try { foout.close(); } catch (IOException e) { // ignore on close } } } }
From source file:net.impjq.providers.downloads.DownloadThread.java
/** * Executes the download in a separate thread *//*from ww w .j a v a2 s. co m*/ public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR; boolean countRetry = false; int retryAfter = 0; int redirectCount = mInfo.mRedirectCount; String newUri = null; boolean gotData = false; String filename = null; String mimeType = sanitizeMimeType(mInfo.mMimeType); FileOutputStream stream = null; AndroidHttpClient client = null; PowerManager.WakeLock wakeLock = null; Uri contentUri = Uri.parse(Downloads.Impl.CONTENT_URI + "/" + mInfo.mId); try { boolean continuingDownload = false; String headerAcceptRanges = null; String headerContentDisposition = null; String headerContentLength = null; String headerContentLocation = null; String headerETag = null; String headerTransferEncoding = null; byte data[] = new byte[Constants.BUFFER_SIZE]; int bytesSoFar = 0; PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG); wakeLock.acquire(); filename = mInfo.mFileName; if (filename != null) { if (!Helpers.isFilenameValid(filename)) { finalStatus = Downloads.Impl.STATUS_FILE_ERROR; notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType); return; } // We're resuming a download that got interrupted File f = new File(filename); if (f.exists()) { long fileLength = f.length(); if (fileLength == 0) { // The download hadn't actually started, we can restart from scratch f.delete(); filename = null; } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) { // Tough luck, that's not a resumable download if (Config.LOGD) { Log.d(Constants.TAG, "can't resume interrupted non-resumable download"); } f.delete(); finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED; notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType); return; } else { // All right, we'll be able to resume this download stream = new FileOutputStream(filename, true); bytesSoFar = (int) fileLength; if (mInfo.mTotalBytes != -1) { headerContentLength = Integer.toString(mInfo.mTotalBytes); } headerETag = mInfo.mETag; continuingDownload = true; } } } int bytesNotified = bytesSoFar; // starting with MIN_VALUE means that the first write will commit // progress to the database long timeLastNotification = 0; client = AndroidHttpClient.newInstance(userAgent(), mContext); if (stream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) { try { stream.close(); stream = null; } catch (IOException ex) { if (Constants.LOGV) { Log.v(Constants.TAG, "exception when closing the file before download : " + ex); } // nothing can really be done if the file can't be closed } } /* * This loop is run once for every individual HTTP request that gets sent. * The very first HTTP request is a "virgin" request, while every subsequent * request is done with the original ETag and a byte-range. */ http_request_loop: while (true) { // Set or unset proxy, which may have changed since last GET request. // setDefaultProxy() supports null as proxy parameter. //Comment it,pjq,20110220,start //ConnRouteParams.setDefaultProxy(client.getParams(), // Proxy.getPreferredHttpHost(mContext, mInfo.mUri)); // Prepares the request and fires it. HttpGet request = new HttpGet(mInfo.mUri); if (Constants.LOGV) { Log.v(Constants.TAG, "initiating download for " + mInfo.mUri); } if (mInfo.mCookies != null) { request.addHeader("Cookie", mInfo.mCookies); } if (mInfo.mReferer != null) { request.addHeader("Referer", mInfo.mReferer); } if (continuingDownload) { if (headerETag != null) { request.addHeader("If-Match", headerETag); } request.addHeader("Range", "bytes=" + bytesSoFar + "-"); } HttpResponse response; try { response = client.execute(request); } catch (IllegalArgumentException ex) { if (Constants.LOGV) { Log.d(Constants.TAG, "Arg exception trying to execute request for " + mInfo.mUri + " : " + ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "Arg exception trying to execute request for " + mInfo.mId + " : " + ex); } finalStatus = Downloads.Impl.STATUS_BAD_REQUEST; request.abort(); break http_request_loop; } catch (IOException ex) { ex.printStackTrace(); if (Constants.LOGX) { if (Helpers.isNetworkAvailable(mContext)) { Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Up"); } else { Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Down"); } } if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; countRetry = true; } else { if (Constants.LOGV) { Log.d(Constants.TAG, "IOException trying to execute request for " + mInfo.mUri + " : " + ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "IOException trying to execute request for " + mInfo.mId + " : " + ex); } finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) { if (Constants.LOGVV) { Log.v(Constants.TAG, "got HTTP response code 503"); } finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; countRetry = true; Header header = response.getFirstHeader("Retry-After"); if (header != null) { try { if (Constants.LOGVV) { Log.v(Constants.TAG, "Retry-After :" + header.getValue()); } retryAfter = Integer.parseInt(header.getValue()); if (retryAfter < 0) { retryAfter = 0; } else { if (retryAfter < Constants.MIN_RETRY_AFTER) { retryAfter = Constants.MIN_RETRY_AFTER; } else if (retryAfter > Constants.MAX_RETRY_AFTER) { retryAfter = Constants.MAX_RETRY_AFTER; } retryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1); retryAfter *= 1000; } } catch (NumberFormatException ex) { // ignored - retryAfter stays 0 in this case. } } request.abort(); break http_request_loop; } if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) { if (Constants.LOGVV) { Log.v(Constants.TAG, "got HTTP redirect " + statusCode); } if (redirectCount >= Constants.MAX_REDIRECTS) { if (Constants.LOGV) { Log.d(Constants.TAG, "too many redirects for download " + mInfo.mId + " at " + mInfo.mUri); } else if (Config.LOGD) { Log.d(Constants.TAG, "too many redirects for download " + mInfo.mId); } finalStatus = Downloads.Impl.STATUS_TOO_MANY_REDIRECTS; request.abort(); break http_request_loop; } Header header = response.getFirstHeader("Location"); if (header != null) { if (Constants.LOGVV) { Log.v(Constants.TAG, "Location :" + header.getValue()); } try { newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString(); } catch (URISyntaxException ex) { if (Constants.LOGV) { Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue() + " for " + mInfo.mUri); } else if (Config.LOGD) { Log.d(Constants.TAG, "Couldn't resolve redirect URI for download " + mInfo.mId); } finalStatus = Downloads.Impl.STATUS_BAD_REQUEST; request.abort(); break http_request_loop; } ++redirectCount; finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; request.abort(); break http_request_loop; } } if ((!continuingDownload && statusCode != Downloads.Impl.STATUS_SUCCESS) || (continuingDownload && statusCode != 206)) { if (Constants.LOGV) { Log.d(Constants.TAG, "http error " + statusCode + " for " + mInfo.mUri); } else if (Config.LOGD) { Log.d(Constants.TAG, "http error " + statusCode + " for download " + mInfo.mId); } if (Downloads.Impl.isStatusError(statusCode)) { finalStatus = statusCode; } else if (statusCode >= 300 && statusCode < 400) { finalStatus = Downloads.Impl.STATUS_UNHANDLED_REDIRECT; } else if (continuingDownload && statusCode == Downloads.Impl.STATUS_SUCCESS) { finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED; } else { finalStatus = Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE; } request.abort(); break http_request_loop; } else { // Handles the response, saves the file if (Constants.LOGV) { Log.v(Constants.TAG, "received response for " + mInfo.mUri); } if (!continuingDownload) { Header header = response.getFirstHeader("Accept-Ranges"); if (header != null) { headerAcceptRanges = header.getValue(); } header = response.getFirstHeader("Content-Disposition"); if (header != null) { headerContentDisposition = header.getValue(); } header = response.getFirstHeader("Content-Location"); if (header != null) { headerContentLocation = header.getValue(); } if (mimeType == null) { header = response.getFirstHeader("Content-Type"); if (header != null) { mimeType = sanitizeMimeType(header.getValue()); } } header = response.getFirstHeader("ETag"); if (header != null) { headerETag = header.getValue(); } header = response.getFirstHeader("Transfer-Encoding"); if (header != null) { headerTransferEncoding = header.getValue(); } if (headerTransferEncoding == null) { header = response.getFirstHeader("Content-Length"); if (header != null) { headerContentLength = header.getValue(); } } else { // Ignore content-length with transfer-encoding - 2616 4.4 3 if (Constants.LOGVV) { Log.v(Constants.TAG, "ignoring content-length because of xfer-encoding"); } } if (Constants.LOGVV) { Log.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges); Log.v(Constants.TAG, "Content-Disposition: " + headerContentDisposition); Log.v(Constants.TAG, "Content-Length: " + headerContentLength); Log.v(Constants.TAG, "Content-Location: " + headerContentLocation); Log.v(Constants.TAG, "Content-Type: " + mimeType); Log.v(Constants.TAG, "ETag: " + headerETag); Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding); } if (!mInfo.mNoIntegrity && headerContentLength == null && (headerTransferEncoding == null || !headerTransferEncoding.equalsIgnoreCase("chunked"))) { if (Config.LOGD) { Log.d(Constants.TAG, "can't know size of download, giving up"); } finalStatus = Downloads.Impl.STATUS_LENGTH_REQUIRED; request.abort(); break http_request_loop; } DownloadFileInfo fileInfo = Helpers.generateSaveFile(mContext, mInfo.mUri, mInfo.mHint, headerContentDisposition, headerContentLocation, mimeType, mInfo.mDestination, (headerContentLength != null) ? Integer.parseInt(headerContentLength) : 0); if (fileInfo.mFileName == null) { finalStatus = fileInfo.mStatus; request.abort(); break http_request_loop; } filename = fileInfo.mFileName; stream = fileInfo.mStream; if (Constants.LOGV) { Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + filename); } ContentValues values = new ContentValues(); values.put(Downloads.Impl._DATA, filename); if (headerETag != null) { values.put(Constants.ETAG, headerETag); } if (mimeType != null) { values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimeType); } int contentLength = -1; if (headerContentLength != null) { contentLength = Integer.parseInt(headerContentLength); } values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength); mContext.getContentResolver().update(contentUri, values, null, null); } InputStream entityStream; try { entityStream = response.getEntity().getContent(); } catch (IOException ex) { if (Constants.LOGX) { if (Helpers.isNetworkAvailable(mContext)) { Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Up"); } else { Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Down"); } } if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; countRetry = true; } else { if (Constants.LOGV) { Log.d(Constants.TAG, "IOException getting entity for " + mInfo.mUri + " : " + ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "IOException getting entity for download " + mInfo.mId + " : " + ex); } finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } for (;;) { int bytesRead; try { bytesRead = entityStream.read(data); } catch (IOException ex) { if (Constants.LOGX) { if (Helpers.isNetworkAvailable(mContext)) { Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Up"); } else { Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Down"); } } ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar); mContext.getContentResolver().update(contentUri, values, null, null); if (!mInfo.mNoIntegrity && headerETag == null) { if (Constants.LOGV) { Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "download IOException for download " + mInfo.mId + " : " + ex); } if (Config.LOGD) { Log.d(Constants.TAG, "can't resume interrupted download with no ETag"); } finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED; } else if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; countRetry = true; } else { if (Constants.LOGV) { Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "download IOException for download " + mInfo.mId + " : " + ex); } finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR; } request.abort(); break http_request_loop; } if (bytesRead == -1) { // success ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar); if (headerContentLength == null) { values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, bytesSoFar); } mContext.getContentResolver().update(contentUri, values, null, null); if ((headerContentLength != null) && (bytesSoFar != Integer.parseInt(headerContentLength))) { if (!mInfo.mNoIntegrity && headerETag == null) { if (Constants.LOGV) { Log.d(Constants.TAG, "mismatched content length " + mInfo.mUri); } else if (Config.LOGD) { Log.d(Constants.TAG, "mismatched content length for " + mInfo.mId); } finalStatus = Downloads.Impl.STATUS_LENGTH_REQUIRED; } else if (!Helpers.isNetworkAvailable(mContext)) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) { finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; countRetry = true; } else { if (Constants.LOGV) { Log.v(Constants.TAG, "closed socket for " + mInfo.mUri); } else if (Config.LOGD) { Log.d(Constants.TAG, "closed socket for download " + mInfo.mId); } finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR; } break http_request_loop; } break; } gotData = true; for (;;) { try { if (stream == null) { stream = new FileOutputStream(filename, true); } stream.write(data, 0, bytesRead); if (mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) { try { stream.close(); stream = null; } catch (IOException ex) { if (Constants.LOGV) { Log.v(Constants.TAG, "exception when closing the file " + "during download : " + ex); } // nothing can really be done if the file can't be closed } } break; } catch (IOException ex) { if (!Helpers.discardPurgeableFiles(mContext, Constants.BUFFER_SIZE)) { finalStatus = Downloads.Impl.STATUS_FILE_ERROR; break http_request_loop; } } } bytesSoFar += bytesRead; long now = System.currentTimeMillis(); if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP && now - timeLastNotification > Constants.MIN_PROGRESS_TIME) { ContentValues values = new ContentValues(); values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar); mContext.getContentResolver().update(contentUri, values, null, null); bytesNotified = bytesSoFar; timeLastNotification = now; } if (Constants.LOGVV) { Log.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.mUri); } synchronized (mInfo) { if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) { if (Constants.LOGV) { Log.v(Constants.TAG, "paused " + mInfo.mUri); } finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED; request.abort(); break http_request_loop; } } if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) { if (Constants.LOGV) { Log.d(Constants.TAG, "canceled " + mInfo.mUri); } else if (Config.LOGD) { // Log.d(Constants.TAG, "canceled id " + mInfo.mId); } finalStatus = Downloads.Impl.STATUS_CANCELED; break http_request_loop; } } if (Constants.LOGV) { Log.v(Constants.TAG, "download completed for " + mInfo.mUri); } finalStatus = Downloads.Impl.STATUS_SUCCESS; } break; } } catch (FileNotFoundException ex) { if (Config.LOGD) { Log.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex); } finalStatus = Downloads.Impl.STATUS_FILE_ERROR; // falls through to the code that reports an error } catch (RuntimeException ex) { //sometimes the socket code throws unchecked exceptions if (Constants.LOGV) { Log.d(Constants.TAG, "Exception for " + mInfo.mUri, ex); } else if (Config.LOGD) { Log.d(Constants.TAG, "Exception for id " + mInfo.mId, ex); } finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR; // falls through to the code that reports an error } finally { mInfo.mHasActiveThread = false; if (wakeLock != null) { wakeLock.release(); wakeLock = null; } if (client != null) { client.close(); client = null; } try { // close the file if (stream != null) { stream.close(); } } catch (IOException ex) { if (Constants.LOGV) { Log.v(Constants.TAG, "exception when closing the file after download : " + ex); } // nothing can really be done if the file can't be closed } if (filename != null) { // if the download wasn't successful, delete the file if (Downloads.Impl.isStatusError(finalStatus)) { new File(filename).delete(); filename = null; } else if (Downloads.Impl.isStatusSuccess(finalStatus)) { //Comment it,pjq,20110220,start // transfer the file to the DRM content provider // File file = new File(filename); // Intent item = // DrmStore.addDrmFile(mContext.getContentResolver(), file, // null); // if (item == null) { // Log.w(Constants.TAG, "unable to add file " + filename + // " to DrmProvider"); // finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR; // } else { // filename = item.getDataString(); // mimeType = item.getType(); // } // // file.delete(); } else if (Downloads.Impl.isStatusSuccess(finalStatus)) { // make sure the file is readable //Comment it,pjq,20110220,start //FileUtils.setPermissions(filename, 0644, -1, -1); // Sync to storage after completion FileOutputStream downloadedFileStream = null; try { downloadedFileStream = new FileOutputStream(filename, true); downloadedFileStream.getFD().sync(); } catch (FileNotFoundException ex) { Log.w(Constants.TAG, "file " + filename + " not found: " + ex); } catch (SyncFailedException ex) { Log.w(Constants.TAG, "file " + filename + " sync failed: " + ex); } catch (IOException ex) { Log.w(Constants.TAG, "IOException trying to sync " + filename + ": " + 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); } } } } } notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, gotData, filename, newUri, mimeType); } }
From source file:org.dcm4chee.proxy.dimse.CStore.java
private Attributes processInputStream(ProxyAEExtension proxyAEE, Association as, PresentationContext pc, Attributes rq, PDVInputStream data, File file) throws FileNotFoundException, IOException { LOG.debug("{}: write {}", as, file); // stream to write spool file FileOutputStream fout = new FileOutputStream(file); BufferedOutputStream bout = new BufferedOutputStream(fout); DicomOutputStream out = new DicomOutputStream(bout, UID.ExplicitVRLittleEndian); String cuid = rq.getString(Tag.AffectedSOPClassUID); String iuid = rq.getString(Tag.AffectedSOPInstanceUID); String tsuid = pc.getTransferSyntax(); Attributes fmi = as.createFileMetaInformation(iuid, cuid, tsuid); // fix//from www .j a v a 2 s . c o m // spool first try { if (data instanceof PDVInputStream) { ((PDVInputStream) data).copyTo(out); } else if (data != null) { StreamUtils.copy(data, out); } } finally { fout.flush(); fout.getFD().sync(); SafeClose.close(out); SafeClose.close(bout); SafeClose.close(fout); } // coerce second DicomInputStream din = new DicomInputStream(file); Attributes attrs = null; try { // include only an uri in the read dataset din.setIncludeBulkData(IncludeBulkData.URI); attrs = din.readDataset(-1, -1); } finally { SafeClose.close(din); } File tempFile = new File(file.getPath() + ".tmpBulkData"); fout = new FileOutputStream(tempFile); bout = new BufferedOutputStream(fout); out = new DicomOutputStream(bout, UID.ExplicitVRLittleEndian); attrs = AttributeCoercionUtils.coerceDataset(proxyAEE, as, Role.SCU, Dimse.C_STORE_RQ, attrs, rq); try { out.writeDataset(fmi, attrs); fout.flush(); fout.getFD().sync(); } finally { SafeClose.close(out); SafeClose.close(bout); SafeClose.close(fout); } try { FileUtils.deleteQuietly(file); FileUtils.moveFile(tempFile, file); } catch (IOException e) { LOG.error("Exception moving temp file with coerced set to spool", e); } Properties prop = new Properties(); prop.setProperty("hostname", as.getConnection().getHostname()); String patID = attrs.getString(Tag.PatientID); prop.setProperty("patient-id", (patID == null || patID.length() == 0) ? "<UNKNOWN>" : patID); prop.setProperty("study-iuid", attrs.getString(Tag.StudyInstanceUID)); prop.setProperty("sop-instance-uid", attrs.getString(Tag.SOPInstanceUID)); prop.setProperty("sop-class-uid", attrs.getString(Tag.SOPClassUID)); prop.setProperty("transfer-syntax-uid", fmi.getString(Tag.TransferSyntaxUID)); prop.setProperty("source-aet", as.getCallingAET()); String path = file.getPath(); File info = new File(path.substring(0, path.length() - 5) + ".info"); FileOutputStream infoOut = new FileOutputStream(info); try { prop.store(infoOut, null); infoOut.flush(); infoOut.getFD().sync(); } finally { infoOut.close(); } attrs = null; return fmi; }
From source file:org.tinymediamanager.core.movie.tasks.MovieExtraImageFetcher.java
private void downloadExtraThumbs() { List<String> thumbs = movie.getExtraThumbs(); // do not create extrathumbs folder, if no extrathumbs are selected if (thumbs.size() == 0) { return;// www . j av a 2s.c om } try { Path folder = movie.getPathNIO().resolve("extrathumbs"); if (Files.isDirectory(folder)) { Utils.deleteDirectoryRecursive(folder); movie.removeAllMediaFiles(MediaFileType.EXTRATHUMB); } Files.createDirectory(folder); // fetch and store images for (int i = 0; i < thumbs.size(); i++) { String url = thumbs.get(i); String providedFiletype = FilenameUtils.getExtension(url); FileOutputStream outputStream = null; InputStream is = null; Path file = null; if (MovieModuleManager.MOVIE_SETTINGS.isImageExtraThumbsResize() && MovieModuleManager.MOVIE_SETTINGS.getImageExtraThumbsSize() > 0) { file = folder.resolve("thumb" + (i + 1) + ".jpg"); outputStream = new FileOutputStream(file.toFile()); try { is = ImageCache.scaleImage(url, MovieModuleManager.MOVIE_SETTINGS.getImageExtraThumbsSize()); } catch (Exception e) { LOGGER.warn("problem with rescaling: " + e.getMessage()); continue; } } else { file = folder.resolve("thumb" + (i + 1) + "." + providedFiletype); outputStream = new FileOutputStream(file.toFile()); Url url1 = new Url(url); is = url1.getInputStream(); } IOUtils.copy(is, outputStream); outputStream.flush(); try { outputStream.getFD().sync(); } catch (Exception e) { // empty here -> just not let the thread crash } outputStream.close(); is.close(); MediaFile mf = new MediaFile(file, MediaFileType.EXTRATHUMB); mf.gatherMediaInformation(); movie.addToMediaFiles(mf); } } catch (IOException e) { LOGGER.warn("download extrathumbs", e); } catch (Exception e) { LOGGER.error(e.getMessage()); } }
From source file:org.signserver.server.log.SystemLoggingTest.java
@Test public void test01ReadEntries() throws Exception { LOG.info(">test01ReadEntries"); final File testFile = File.createTempFile("testreadentries", "tmp"); testFile.deleteOnExit();// w ww.ja v a 2 s .c o m final String line0 = "2012-10-19 10:51:43,240 INFO [ISystemLogger] EVENT: GLOBAL_CONFIG_RELOAD; MODULE: GLOBAL_CONFIG; CUSTOM_ID: ; REPLY_TIME:1350636703240\n"; final String line1 = "2012-10-19 10:51:43,277 INFO [ISystemLogger] EVENT: SET_WORKER_CONFIG; MODULE: WORKER_CONFIG; CUSTOM_ID: 100; REPLY_TIME:1350636703277\n"; final String line2 = "2012-10-19 10:51:44,048 INFO [ISystemLogger] EVENT: CERTINSTALLED; MODULE: WORKER_CONFIG; CUSTOM_ID: 100; CERTIFICATE: Subject: CN=Anyone\n" + "Issuer: CN=Anyone\n" + "-----BEGIN CERTIFICATE-----\n" + "MIIBnTCCAQagAwIBAgIIFxjq8olIqcYwDQYJKoZIhvcNAQEFBQAwETEPMA0GA1UE\n" + "AwwGQW55b25lMB4XDTEyMTAxOTA4NTE0M1oXDTEzMTAxOTA4NTE0M1owETEPMA0G\n" + "A1UEAwwGQW55b25lMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjkj6skp1w\n" + "NduK3lBUG9Gx72nH/vhR5p+zX8eCbOYIPQGT4GtHMZHaPzqMg/xmFxRFePovlN1l\n" + "l6a+1GOHv30wXDk+lu+Y1MUh24wbONj3g+j7pLz/sn4APxrZGrCwS/To6c3PhIwb\n" + "FsqWdXv+puFaWtipFBtVh7j4vQ2M6NJENQIDAQABMA0GCSqGSIb3DQEBBQUAA4GB\n" + "AFRT8DeFuAzWImZhjPpXN3L+0GSYoDtiL8k1ekpH/r17FEuzlYyCeUv5nh+jMgOU\n" + "vEMwq6WMvMRmMxSyh2125F00tdQgShvsuaZ3PG2OYdlYk9YhBHUtJm+Z7n2d0Aho\n" + "j6aIoPC6sBAsyrSumCWxVjZvgQNoefuN6I1/KpC7QVYP\n" + "-----END CERTIFICATE-----\n" + "; SCOPE: GLOB.; REPLY_TIME:1350636704048\n"; final String line3 = "2012-10-19 10:51:44,130 INFO [ISystemLogger] EVENT: SET_WORKER_CONFIG; MODULE: WORKER_CONFIG; CUSTOM_ID: 100; REPLY_TIME:1350636704130\n"; PrintWriter writer = null; try { FileOutputStream fout = new FileOutputStream(testFile); writer = new PrintWriter(fout); // Adding 4 entries writer.print(line0); writer.print(line1); writer.print(line2); writer.print(line3); writer.flush(); fout.getFD().sync(); writer.close(); } finally { if (writer != null) { writer.close(); } } assertEquals("count entries", 4, readEntriesCount(testFile)); List<String> lines = readEntries(testFile, 0, 1); assertEquals("read line0.count", 1, lines.size()); assertEquals("read line0", line0, lines.get(0)); lines = readEntries(testFile, 1, 1); assertEquals("read line1.count", 1, lines.size()); assertEquals("read line1", line1, lines.get(0)); lines = readEntries(testFile, 2, 1); assertEquals("read line2.count", 1, lines.size()); assertEquals("read line2", line2, lines.get(0)); lines = readEntries(testFile, 3, 1); assertEquals("read line3.count", 1, lines.size()); assertEquals("read line3", line3, lines.get(0)); lines = readEntries(testFile, 2, 2); assertEquals("read last2.count", 2, lines.size()); assertEquals("read last2.1", line2, lines.get(0)); assertEquals("read last2.2", line3, lines.get(1)); }
From source file:org.eclipse.kura.net.admin.visitor.linux.DhcpConfigWriter.java
private void writeConfigFile(String configFileName, String ifaceName, DhcpServerConfig4 dhcpServerConfig) throws KuraException { FileOutputStream fos = null; PrintWriter pw = null;// ww w . ja va2 s .c o m try { fos = new FileOutputStream(configFileName); pw = new PrintWriter(fos); s_logger.trace("writing to {} with: {}", configFileName, dhcpServerConfig.toString()); DhcpServerTool dhcpServerTool = DhcpServerManager.getTool(); if (dhcpServerTool == DhcpServerTool.DHCPD) { pw.print(dhcpServerConfig.toString()); } else if (dhcpServerTool == DhcpServerTool.UDHCPD) { pw.println("start " + dhcpServerConfig.getRangeStart().getHostAddress()); pw.println("end " + dhcpServerConfig.getRangeEnd().getHostAddress()); pw.println("interface " + ifaceName); pw.println("pidfile " + DhcpServerManager.getPidFilename(ifaceName)); pw.println("max_leases " + (ip2int(dhcpServerConfig.getRangeEnd()) - ip2int(dhcpServerConfig.getRangeStart()))); pw.println("auto_time 0"); pw.println("decline_time " + dhcpServerConfig.getDefaultLeaseTime()); pw.println("conflict_time " + dhcpServerConfig.getDefaultLeaseTime()); pw.println("offer_time " + dhcpServerConfig.getDefaultLeaseTime()); pw.println("min_lease " + dhcpServerConfig.getDefaultLeaseTime()); pw.println("opt subnet " + dhcpServerConfig.getSubnetMask().getHostAddress()); pw.println("opt router " + dhcpServerConfig.getRouterAddress().getHostAddress()); pw.println("opt lease " + dhcpServerConfig.getDefaultLeaseTime()); } pw.flush(); fos.getFD().sync(); } catch (Exception e) { throw new KuraException(KuraErrorCode.CONFIGURATION_ERROR, "error while building up new configuration files for dhcp servers", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ex) { s_logger.warn("Error while closing FileOutputStream"); } } if (pw != null) { pw.close(); } } }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.environment.UnixFileEnvironmentRepository.java
public void save(final String backupFileName, ConfigResponse config, Environment environment) throws PluginException { BufferedReader envFileReader = null; FileOutputStream newSetEnv = null; try {// w w w. j a va 2s .c om try { envFileReader = new BufferedReader(new FileReader(backupFileName)); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save setenv. Error parsing existing file. Cause: " + e.getMessage()); } try { newSetEnv = new FileOutputStream(Metric.decode(config.getValue("installpath")) + "/bin/setenv.sh"); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save setenv. Error writing to existing file. Cause: " + e.getMessage()); } // write backup file to setenv, replacing existing JVM_OPTS line String line; try { line = envFileReader.readLine(); boolean processedJavaHome = false; for (; line != null; line = envFileReader.readLine()) { if (line.trim().startsWith("JVM_OPTS")) { while (line != null && !line.trim().endsWith("\"")) { line = envFileReader.readLine(); } writeJvmOpts(environment, newSetEnv); continue; } else if (line.trim().startsWith("JAVA_HOME") || line.trim().startsWith("#JAVA_HOME")) { processedJavaHome = true; writeJavaHome(environment, newSetEnv); } else { newSetEnv.write(line.getBytes()); newSetEnv.write("\n".getBytes()); } } if (!processedJavaHome) { // append JAVA_HOME even if it is not already in the file writeJavaHome(environment, newSetEnv); } newSetEnv.flush(); newSetEnv.getFD().sync(); } catch (IOException e) { throw new PluginException("Error writing JVM options to setenv. Cause: " + e.getMessage()); } } finally { try { if (envFileReader != null) { envFileReader.close(); } } catch (IOException e) { logger.warn("Error closing reader to backup setenv file. Cause: " + e.getMessage()); } try { if (newSetEnv != null) { newSetEnv.close(); } } catch (IOException e) { logger.warn("Error closing output stream to setenv file. Cause: " + e.getMessage()); } } }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.environment.WindowsFileEnvironmentRepository.java
public void save(String backupFileName, ConfigResponse config, Environment environment) throws PluginException { BufferedReader wrapperconfFileReader = null; FileOutputStream newWrapperconf = null; try {//from w ww . j a v a 2s .c om try { wrapperconfFileReader = new BufferedReader(new FileReader(backupFileName)); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save wrapper.conf. Error parsing existing file. Cause: " + e.getMessage()); } try { newWrapperconf = new FileOutputStream( Metric.decode(config.getValue("installpath")) + "/conf/wrapper.conf"); } catch (FileNotFoundException e) { throw new PluginException( "Unable to save wrapper.conf. Error writing to existing file. Cause: " + e.getMessage()); } // write backup file to wrapper.conf, replacing existing JVM_OPTS and JAVA_HOME String line; try { line = wrapperconfFileReader.readLine(); boolean processedJvmOpts = false; boolean processingJvmOpts = false; boolean processedJavaHome = false; List<String> exsistingJvmOpts = new ArrayList<String>(); for (; line != null; line = wrapperconfFileReader.readLine()) { /** * The two following "if" statements represents an embedded state machine here where it flip flops * between parsing JVM options and having completed that phase. * * -- Testing for wrapper.java.additional enters a special state tagged "processingJvmOpts". -- When * the last wrapper.java.additional is passed, it exits the state "processingJvmOpts". * * The if-then checks for this MUST come before any other checks. Otherwise, the state machine gets * mixed up with other line checks, and can cause lines to be dropped. */ if (line.trim().startsWith("wrapper.java.additional")) { if (!processingJvmOpts) { processingJvmOpts = true; } // add jvm opt to exsistingJvmOpts int pos = line.indexOf("="); if (pos != -1) { exsistingJvmOpts.add(windowsOptsUtil.stripQuotes(line.substring(pos + 1))); } } else if (processingJvmOpts) { writeJvmOpts(environment.getJvmOptions(), newWrapperconf, exsistingJvmOpts); processingJvmOpts = false; processedJvmOpts = true; } /** * The rest of these else-if's represent simple line checks for parsing and involves no special * state machine. */ else if (line.trim().equals("")) { newWrapperconf.write(line.getBytes()); newWrapperconf.write("\n".getBytes()); } else if (line.trim().startsWith("set.JAVA_HOME") || line.trim().startsWith("#set.JAVA_HOME")) { if (!processedJavaHome) { writeJavaHome(environment.getJavaHome(), newWrapperconf); processedJavaHome = true; } } else { newWrapperconf.write(line.getBytes()); newWrapperconf.write("\n".getBytes()); } } if (!processedJvmOpts) { writeJvmOpts(environment.getJvmOptions(), newWrapperconf, null); } if (!processedJavaHome) { writeJavaHome(environment.getJavaHome(), newWrapperconf); } newWrapperconf.flush(); newWrapperconf.getFD().sync(); } catch (IOException e) { throw new PluginException("Error writing JVM options to wrapper.conf. Cause: " + e.getMessage()); } } finally { try { if (wrapperconfFileReader != null) { wrapperconfFileReader.close(); } } catch (IOException e) { logger.warn("Error closing input stream to backup wrapper.conf file. Cause: " + e.getMessage()); } try { if (newWrapperconf != null) { newWrapperconf.close(); } } catch (IOException e) { logger.warn("Error closing output stream to wrapper.conf file. Cause: " + e.getMessage()); } } }
From source file:com.google.bitcoin.core.Wallet.java
/** Saves the wallet first to the given temp file, then renames to the dest file. */ public void saveToFile(File temp, File destFile) throws IOException { FileOutputStream stream = null; lock.lock();/* ww w. j ava2 s . c o m*/ try { stream = new FileOutputStream(temp); saveToFileStream(stream); // Attempt to force the bits to hit the disk. In reality the OS or hard disk itself may still decide // to not write through to physical media for at least a few seconds, but this is the best we can do. stream.flush(); stream.getFD().sync(); stream.close(); stream = null; if (Utils.isWindows()) { // Work around an issue on Windows whereby you can't rename over existing files. File canonical = destFile.getCanonicalFile(); canonical.delete(); if (temp.renameTo(canonical)) return; // else fall through. throw new IOException("Failed to rename " + temp + " to " + canonical); } else if (!temp.renameTo(destFile)) { throw new IOException("Failed to rename " + temp + " to " + destFile); } } catch (RuntimeException e) { log.error("Failed whilst saving wallet", e); throw e; } finally { lock.unlock(); if (stream != null) { stream.close(); } } }