/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public virtual void AppendData(byte[] data) { try { outStream.Write(data); } catch (IOException e) { throw new RuntimeException("Unable to write to stream.", e); } length += data.Length; sha1Digest.Update(data); md5Digest.Update(data); }
private static string getData() { StringBuffer response = null; URL obj = new URL("http://192.168.1.17/easyserver/WebService.php"); switch (mFunction) { case "setUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8") + "&name=" + URLEncoder.Encode(mName, "UTF-8") + "&age=" + URLEncoder.Encode(mAge, "UTF-8"); break; case "getUser": data = "function=" + URLEncoder.Encode(mFunction, "UTF-8"); break; } //creación del objeto de conexión HttpURLConnection con = (HttpURLConnection)obj.OpenConnection(); //Agregando la cabecera //Enviamos la petición por post con.RequestMethod = "POST"; con.DoOutput = true; con.DoInput = true; con.SetRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //Envio de datos //obtener el tamaño de los datos con.SetFixedLengthStreamingMode(data.Length); /* * OutputStream clase abstracta que es la superclase de todas las clases que * representan la salida de un flujo de bytes. Un flujo de salida acepta bytes de salida. * BufferOutputStream es la clase que implementa un flujo de salida con buffer */ OutputStream ouT = new BufferedOutputStream(con.OutputStream); byte[] array = Encoding.ASCII.GetBytes(data); ouT.Write(array); ouT.Flush(); ouT.Close(); /* * Obteniendo datos * BufferedRead Lee texto de una corriente de caracteres de entrada, * Un InputStreamReader es un puente de flujos de streams de caracteres: se lee los * bytes y los decodifica en caracteres */ BufferedReader iN = new BufferedReader(new InputStreamReader(con.InputStream)); string inputLine; response = new StringBuffer(); while ((inputLine = iN.ReadLine()) != null) { response.Append(inputLine); } iN.Close(); return(response.ToString()); }
/// <exception cref="System.IO.IOException"></exception> protected virtual void Copy(Socket4Adapter sock, IOutputStream rawout, int length , bool update) { var @out = new BufferedOutputStream(rawout); var buffer = new byte[BlobImpl.CopybufferLength]; var totalread = 0; while (totalread < length) { var stilltoread = length - totalread; var readsize = (stilltoread < buffer.Length ? stilltoread : buffer.Length); var curread = sock.Read(buffer, 0, readsize); if (curread < 0) { throw new IOException(); } @out.Write(buffer, 0, curread); totalread += curread; if (update) { _currentByte += curread; } } @out.Flush(); @out.Close(); }
public static void saveDecFile(byte[] encodedBytes, String path, string fileName) { try { System.IO.File.Copy(path, "/storage/emulated/0/movies/" + fileName); Java.IO.File file = new Java.IO.File(path); System.IO.FileStream fs = new System.IO.FileStream("/storage/emulated/0/movies/" + fileName, FileMode.Open); BufferedOutputStream bos = new BufferedOutputStream(fs); bos.Write(encodedBytes); bos.Flush(); bos.Close(); } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } catch (Exception e) { // e.PrintStackTrace(); } }
/// <summary> /// 解压文件 /// </summary> /// <param name="inputZip"></param> /// <param name="destinationDirectory"></param> public static void UnzipFile(string inputZip, string destinationDirectory) { int buffer = 2048; List <string> zipFiles = new List <string>(); File sourceZipFile = new File(inputZip); File unzipDirectory = new File(destinationDirectory); CreateDir(unzipDirectory.AbsolutePath); ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OpenRead); IEnumeration zipFileEntries = zipFile.Entries(); while (zipFileEntries.HasMoreElements) { ZipEntry entry = (ZipEntry)zipFileEntries.NextElement(); string currentEntry = entry.Name; File destFile = new File(unzipDirectory, currentEntry); if (currentEntry.EndsWith(Constant.SUFFIX_ZIP)) { zipFiles.Add(destFile.AbsolutePath); } File destinationParent = destFile.ParentFile; CreateDir(destinationParent.AbsolutePath); if (!entry.IsDirectory) { if (destFile != null && destFile.Exists()) { continue; } BufferedInputStream inputStream = new BufferedInputStream(zipFile.GetInputStream(entry)); int currentByte; // buffer for writing file byte[] data = new byte[buffer]; var fos = new System.IO.FileStream(destFile.AbsolutePath, System.IO.FileMode.OpenOrCreate); BufferedOutputStream dest = new BufferedOutputStream(fos, buffer); while ((currentByte = inputStream.Read(data, 0, buffer)) != -1) { dest.Write(data, 0, currentByte); } dest.Flush(); dest.Close(); inputStream.Close(); } } zipFile.Close(); foreach (var zipName in zipFiles) { UnzipFile(zipName, destinationDirectory + File.SeparatorChar + zipName.Substring(0, zipName.LastIndexOf(Constant.SUFFIX_ZIP))); } }
/// <summary>Appends data to the blob.</summary> /// <remarks>Appends data to the blob. Call this when new data is available.</remarks> public void AppendData(IEnumerable <Byte> data) { var dataVector = data.ToArray(); try { outStream.Write(dataVector); } catch (IOException e) { throw new RuntimeException("Unable to write to stream.", e); } length += dataVector.Length; sha1Digest.Update(dataVector); md5Digest.Update(dataVector); }
private Object Post(string parameters) { try { conn = (HttpURLConnection)url.OpenConnection(); conn.RequestMethod = "POST"; conn.DoOutput = true; conn.DoInput = true; conn.Connect(); Android.Util.Log.Debug("SendToServer", "parametros " + parameters); byte[] bytes = Encoding.ASCII.GetBytes(parameters); OutputStream outputStream = new BufferedOutputStream(conn.OutputStream); outputStream.Write(bytes); outputStream.Flush(); outputStream.Close(); InputStream inputStream = new BufferedInputStream(conn.InputStream); return(ReadString(inputStream)); } catch (IOException e) { Android.Util.Log.Debug("SendToServer", "Problems to send data to server!! " + e.Message); return(false); } finally { conn.Disconnect(); } }
/** * Writes the chunks to a file as a contiguous stream. Useful for debugging. */ public void saveToFile(string path) { System.IO.FileStream fos = null; BufferedOutputStream bos = null; try { fos = new System.IO.FileStream(path, System.IO.FileMode.Create); bos = new BufferedOutputStream(fos); fos = null; // closing bos will also close fos int numChunks = NumChunks; for (int i = 0; i < numChunks; i++) { byte[] chunk = _chunks[i]; bos.Write(chunk); } } catch (System.IO.IOException) { //throw new RuntimeException(ioe); } finally { try { if (bos != null) { bos.Close(); } if (fos != null) { fos.Close(); } } catch (System.IO.IOException) { //throw new RuntimeException(ioe); } } }
/// <summary>Write output to files.</summary> /// <exception cref="System.IO.IOException"/> /// <exception cref="System.Exception"/> protected override void Cleanup(Reducer.Context context) { Configuration conf = context.GetConfiguration(); Path dir = new Path(conf.Get(WorkingDirProperty)); FileSystem fs = dir.GetFileSystem(conf); { // write hex output Path hexfile = new Path(conf.Get(HexFileProperty)); OutputStream @out = new BufferedOutputStream(fs.Create(hexfile)); try { foreach (byte b in hex) { @out.Write(b); } } finally { @out.Close(); } } // If the starting digit is 1, // the hex value can be converted to decimal value. if (conf.GetInt(DigitStartProperty, 1) == 1) { Path outfile = new Path(dir, "pi.txt"); Log.Info("Writing text output to " + outfile); OutputStream outputstream = fs.Create(outfile); try { PrintWriter @out = new PrintWriter(new OutputStreamWriter(outputstream, Charsets. Utf8), true); // write hex text Print(@out, hex.GetEnumerator(), "Pi = 0x3.", "%02X", 5, 5); @out.WriteLine("Total number of hexadecimal digits is " + 2 * hex.Count + "."); // write decimal text BaileyBorweinPlouffe.Fraction dec = new BaileyBorweinPlouffe.Fraction(hex); int decDigits = 2 * hex.Count; // TODO: this is conservative. Print(@out, new _IEnumerator_168(decDigits, dec), "Pi = 3.", "%d", 10, 5); @out.WriteLine("Total number of decimal digits is " + decDigits + "."); } finally { outputstream.Close(); } } }
/** * 解压文件 * * @param filePath 压缩文件路径 */ public static void unzip(string filePath) { //isSuccess = false; File source = new File(filePath); if (source.Exists()) { ZipInputStream zis = null; BufferedOutputStream bos = null; try { zis = new ZipInputStream(new System.IO.FileStream(source.Path, System.IO.FileMode.Append)); ZipEntry entry = null; while ((entry = zis.NextEntry) != null && !entry.IsDirectory) { File target = new File(source.Parent, entry.Name); if (!target.ParentFile.Exists()) { // 创建文件父目录 target.ParentFile.Mkdirs(); } // 写入文件 bos = new BufferedOutputStream(new System.IO.FileStream(target.Path, System.IO.FileMode.Append)); int read = 0; byte[] buffer = new byte[1024 * 10]; while ((read = zis.Read(buffer, 0, buffer.Length)) != -1) { bos.Write(buffer, 0, read); } bos.Flush(); } zis.CloseEntry(); } catch (IOException e) { throw new RuntimeException(e); } finally { zis.Close(); bos.Close(); // isSuccess = true; } } }
/// <summary> /// Save file from URI to destination path /// </summary> /// <param name="context">Current context</param> /// <param name="uri">File URI</param> /// <param name="destinationPath">Destination path</param> /// <returns>Task for await</returns> private static void SaveFileFromUri(Context context, global::Android.Net.Uri uri, string destinationPath) { Stream stream = context.ContentResolver.OpenInputStream(uri); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(System.IO.File.OpenWrite(destinationPath)); int bufferSize = 1024 * 4; byte[] buffer = new byte[bufferSize]; while (true) { int len = stream.Read(buffer, 0, bufferSize); if (len == 0) { break; } bos.Write(buffer, 0, len); } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } finally { try { if (stream != null) { stream.Close(); } if (bos != null) { bos.Close(); } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); } } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public static java.io.File unzip(Class testClass, String resource, java.io.File targetDirectory) throws java.io.IOException //JAVA TO C# CONVERTER NOTE: Members cannot have the same name as their enclosing type: public static File UnzipConflict(Type testClass, string resource, File targetDirectory) { Stream source = testClass.getResourceAsStream(resource); if (source == null) { throw new FileNotFoundException("Could not find resource '" + resource + "' to unzip"); } try { using (ZipInputStream zipStream = new ZipInputStream(source)) { ZipEntry entry; sbyte[] scratch = new sbyte[8096]; while ((entry = zipStream.NextEntry) != null) { if (entry.Directory) { (new File(targetDirectory, entry.Name)).mkdirs(); } else { using (Stream file = new BufferedOutputStream(new FileStream(targetDirectory, entry.Name, FileMode.Create, FileAccess.Write))) { long toCopy = entry.Size; while (toCopy > 0) { int read = zipStream.read(scratch); file.Write(scratch, 0, read); toCopy -= read; } } } zipStream.closeEntry(); } } } finally { source.Close(); } return(targetDirectory); }
private static void DeserializeGroupState(SessionState messageGroupState, XmlReader reader) { int num; byte[] numArray = SessionState.ReadBytes(reader, 9); long num1 = BitConverter.ToInt64(numArray, 1); if (num1 == (long)0) { return; } InternalBufferManager bufferManager = ThrottledBufferManager.GetBufferManager(); using (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(1024, 2147483647, bufferManager)) { byte[] numArray1 = bufferManager.TakeBuffer(1024); long num2 = (long)0; try { while (true) { int num3 = reader.ReadContentAsBase64(numArray1, 0, (int)numArray1.Length); if (num3 == 0) { break; } num2 = num2 + (long)num3; bufferedOutputStream.Write(numArray1, 0, num3); } } finally { bufferManager.ReturnBuffer(numArray1); } byte[] array = bufferedOutputStream.ToArray(out num); messageGroupState.Stream = new BufferedInputStream(array, num, bufferManager); if (num1 > (long)0 && num2 != num1) { throw Fx.Exception.AsError(new InvalidOperationException(SRClient.FailedToDeSerializeEntireSessionStateStream), null); } } }
public static void saveFile(byte[] encodedBytes, String path) { try { Java.IO.File file = new Java.IO.File(path); System.IO.FileStream fs = new System.IO.FileStream(path, FileMode.Open); BufferedOutputStream bos = new BufferedOutputStream(fs); bos.Write(encodedBytes); bos.Flush(); bos.Close(); } catch (Java.IO.FileNotFoundException e) { e.PrintStackTrace(); } catch (Java.IO.IOException e) { e.PrintStackTrace(); } catch (Exception e) { // e.PrintStackTrace(); } }
/// <exception cref="System.IO.IOException"/> public virtual void TestContainerLogPageAccess() { // SecureIOUtils require Native IO to be enabled. This test will run // only if it is enabled. Assume.AssumeTrue(NativeIO.IsAvailable()); string user = "******" + Runtime.CurrentTimeMillis(); FilePath absLogDir = null; FilePath appDir = null; FilePath containerDir = null; FilePath syslog = null; try { // target log directory absLogDir = new FilePath("target", typeof(TestContainerLogsPage).Name + "LogDir") .GetAbsoluteFile(); absLogDir.Mkdir(); Configuration conf = new Configuration(); conf.Set(YarnConfiguration.NmLogDirs, absLogDir.ToURI().ToString()); conf.Set(CommonConfigurationKeysPublic.HadoopSecurityAuthentication, "kerberos"); UserGroupInformation.SetConfiguration(conf); NodeHealthCheckerService healthChecker = new NodeHealthCheckerService(); healthChecker.Init(conf); LocalDirsHandlerService dirsHandler = healthChecker.GetDiskHandler(); // Add an application and the corresponding containers RecordFactory recordFactory = RecordFactoryProvider.GetRecordFactory(conf); long clusterTimeStamp = 1234; ApplicationId appId = BuilderUtils.NewApplicationId(recordFactory, clusterTimeStamp , 1); Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application app = Org.Mockito.Mockito.Mock <Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application >(); Org.Mockito.Mockito.When(app.GetAppId()).ThenReturn(appId); // Making sure that application returns a random user. This is required // for SecureIOUtils' file owner check. Org.Mockito.Mockito.When(app.GetUser()).ThenReturn(user); ApplicationAttemptId appAttemptId = BuilderUtils.NewApplicationAttemptId(appId, 1 ); ContainerId container1 = BuilderUtils.NewContainerId(recordFactory, appId, appAttemptId , 0); // Testing secure read access for log files // Creating application and container directory and syslog file. appDir = new FilePath(absLogDir, appId.ToString()); appDir.Mkdir(); containerDir = new FilePath(appDir, container1.ToString()); containerDir.Mkdir(); syslog = new FilePath(containerDir, "syslog"); syslog.CreateNewFile(); BufferedOutputStream @out = new BufferedOutputStream(new FileOutputStream(syslog) ); @out.Write(Sharpen.Runtime.GetBytesForString("Log file Content")); @out.Close(); Context context = Org.Mockito.Mockito.Mock <Context>(); ConcurrentMap <ApplicationId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application > appMap = new ConcurrentHashMap <ApplicationId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application >(); appMap[appId] = app; Org.Mockito.Mockito.When(context.GetApplications()).ThenReturn(appMap); ConcurrentHashMap <ContainerId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container > containers = new ConcurrentHashMap <ContainerId, Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Container.Container >(); Org.Mockito.Mockito.When(context.GetContainers()).ThenReturn(containers); Org.Mockito.Mockito.When(context.GetLocalDirsHandler()).ThenReturn(dirsHandler); MockContainer container = new MockContainer(appAttemptId, new AsyncDispatcher(), conf, user, appId, 1); container.SetState(ContainerState.Running); context.GetContainers()[container1] = container; ContainerLogsPage.ContainersLogsBlock cLogsBlock = new ContainerLogsPage.ContainersLogsBlock (context); IDictionary <string, string> @params = new Dictionary <string, string>(); @params[YarnWebParams.ContainerId] = container1.ToString(); @params[YarnWebParams.ContainerLogType] = "syslog"; Injector injector = WebAppTests.TestPage <ContainerLogsPage.ContainersLogsBlock>(typeof( ContainerLogsPage), cLogsBlock, @params, (Module[])null); PrintWriter spyPw = WebAppTests.GetPrintWriter(injector); Org.Mockito.Mockito.Verify(spyPw).Write("Exception reading log file. Application submitted by '" + user + "' doesn't own requested log file : syslog"); } finally { if (syslog != null) { syslog.Delete(); } if (containerDir != null) { containerDir.Delete(); } if (appDir != null) { appDir.Delete(); } if (absLogDir != null) { absLogDir.Delete(); } } }
/** * Send Notification button click handler. This method parses the * DefaultFullSharedAccess connection string and generates a SaS token. The * token is added to the Authorization header on the POST request to the * notification hub. The text in the editTextNotificationMessage control * is added as the JSON body for the request to add a GCM message to the hub. * * @param v */ public static void SendNotification(string title, string _msg, string type, Dictionary <string, string> intent = null, string tag = null) { String msg = new String(_msg); //EditText notificationText = (EditText)findViewById(R.id.editTextNotificationMessage); //String json = "{\"data\":{\"message\":\"" + notificationText.getText().toString() + "\"}}"; StringBuilder jsonBuilder = new StringBuilder(); jsonBuilder.Append( "{" + "\"data\":" + "{"); if (intent != null) { foreach (var p in intent) { jsonBuilder.Append( $"\"{p.Key}\":\"{p.Value}\","); } } jsonBuilder.Append( $"\"{NotificationManager.Flags.Title}\":\"{title}\"," + $"\"{NotificationManager.Flags.Message}\":\"{msg}\"," + $"\"{NotificationManager.Flags.Type}\":\"{type}\"," + $"\"{NotificationManager.Flags.DeviceId}\":\"{AppData.AppDataConstants.DeviceId}\"," + $"\"{NotificationManager.Flags.UserId}\":\"{AppData.AppData.user.Id}\"" + "}" + "}"); String json = new String(jsonBuilder.ToString()); new Thread(new System.Action(() => { try { // Based on reference documentation... // http://msdn.microsoft.com/library/azure/dn223273.aspx ParseConnectionString(HubFullAccess); URL url = new URL("" + HubEndpoint + HubName + "/messages/?api-version=2015-01"); HttpURLConnection urlConnection = (HttpURLConnection)url.OpenConnection(); try { // POST request urlConnection.DoOutput = true;//.SetDoOutput(true); // Authenticate the POST request with the SaS token urlConnection.SetRequestProperty("Authorization", GenerateSasToken(new String(url.ToString())).ToString()); // Notification format should be GCM urlConnection.SetRequestProperty("ServiceBusNotification-Format", "gcm"); // Include any tags // Example below targets 3 specific tags // Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/ // urlConnection.setRequestProperty("ServiceBusNotification-Tags", // "tag1 || tag2 || tag3"); // Send notification message if (tag != null) { urlConnection.SetRequestProperty("ServiceBusNotification-Tags", tag); } var jsonBytes = json.GetBytes(); urlConnection.SetFixedLengthStreamingMode(jsonBytes.Length); OutputStream bodyStream = new BufferedOutputStream(urlConnection.OutputStream /*.GetOutputStream()*/); bodyStream.Write(jsonBytes); bodyStream.Close(); //MainActivity.CurrentActivity.ToastNotify(urlConnection.ToString()); // Get reponse urlConnection.Connect(); int responseCode = (int)urlConnection.ResponseCode;//.GetResponseCode(); if ((responseCode != 200) && (responseCode != 201)) { BufferedReader br = new BufferedReader(new InputStreamReader((urlConnection.ErrorStream /*.getErrorStream()*/))); String line; StringBuilder builder = new StringBuilder("Send Notification returned " + responseCode + " : "); while ((line = new String(br.ReadLine())) != null) { builder.Append(line.ToString()); } MainActivity.CurrentActivity.ToastNotify(builder.ToString()); } } finally { urlConnection.Disconnect(); } } catch (Exception e) { MainActivity.CurrentActivity.ToastNotify("Exception Sending Notification : " + e.Message.ToString()); //if (isVisible) //{ // ToastNotify("Exception Sending Notification : " + e.getMessage().toString()); //} } })).Start(); }
public virtual void StarredExportPleco() { string stars = sharedPrefs.GetString("stars", ""); if (stars.Length < 2) { Toast.MakeText(this, "Starred list is empty. Nothing to export.", ToastLength.Long).Show(); return; } try { File dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/ChineseReader"); dir.Mkdirs(); System.IO.FileStream os = new System.IO.FileStream(dir.AbsolutePath + "/chinesereader_starred.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); BufferedOutputStream bos = new BufferedOutputStream(os); StringBuilder english = new StringBuilder(); int oldIndex = 0, nIndex; while ((nIndex = stars.IndexOf("\n", oldIndex)) > -1) { english.Length = 0; int entry = Dict.BinarySearch(stars.SubstringSpecial(oldIndex, nIndex), false); oldIndex = nIndex + 1; if (entry == -1) { continue; } english.Append(Dict.GetCh(entry)).Append("\t").Append(Regex.Replace(Dict.GetPinyin(entry), @"(\\d)", "$1 ")).Append("\t"); string[] parts = Regex.Split(Regex.Replace(Dict.GetEnglish(entry), @"/", "; "), @"\\$"); int j = 0; foreach (string str in parts) { if (j++ % 2 == 1) { english.Append(" [ ").Append(Regex.Replace(str, @"(\\d)", "$1 ")).Append("] "); } else { english.Append(str); } } english.Append("\n"); bos.Write(Encoding.UTF8.GetBytes(english.ToString())); } os.Flush(); bos.Flush(); bos.Close(); os.Close(); Toast.MakeText(this, "Successfully exported to " + dir.AbsolutePath + "/chinesereader_starred.txt", ToastLength.Long).Show(); } catch (Exception e) { Toast.MakeText(this, "Could not export: " + e.Message, ToastLength.Long).Show(); } }