Close() public method

public Close ( ) : void
return void
Example #1
0
		// end encodeObject
		/// <summary>
		/// Serializes an object and returns the Base64-encoded
		/// version of that serialized object.
		/// </summary>
		/// <remarks>
		/// Serializes an object and returns the Base64-encoded
		/// version of that serialized object.
		/// <p>As of v 2.3, if the object
		/// cannot be serialized or there is another error,
		/// the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
		/// In earlier versions, it just returned a null value, but
		/// in retrospect that's a pretty poor way to handle it.</p>
		/// The object is not GZip-compressed before being encoded.
		/// <p>
		/// Example options:<pre>
		/// GZIP: gzip-compresses object before encoding it.
		/// DO_BREAK_LINES: break lines at 76 characters
		/// </pre>
		/// <p>
		/// Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
		/// <p>
		/// Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
		/// </remarks>
		/// <param name="serializableObject">The object to encode</param>
		/// <param name="options">Specified options</param>
		/// <returns>The Base64-encoded object</returns>
		/// <seealso cref="Gzip">Gzip</seealso>
		/// <seealso cref="DoBreakLines">DoBreakLines</seealso>
		/// <exception cref="System.IO.IOException">if there is an error</exception>
		/// <since>2.0</since>
		public static string EncodeObject(Serializable serializableObject, int options)
		{
			if (serializableObject == null)
			{
				throw new ArgumentNullException("Cannot serialize a null object.");
			}
			// end if: null
			// Streams
			ByteArrayOutputStream baos = null;
			OutputStream b64os = null;
			GZIPOutputStream gzos = null;
			ObjectOutputStream oos = null;
			try
			{
				// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
				baos = new ByteArrayOutputStream();
				b64os = new Base64.OutputStream(baos, Encode | options);
				if ((options & Gzip) != 0)
				{
					// Gzip
					gzos = new GZIPOutputStream(b64os);
					oos = new ObjectOutputStream(gzos);
				}
				else
				{
					// Not gzipped
					oos = new ObjectOutputStream(b64os);
				}
				oos.WriteObject(serializableObject);
			}
			catch (IOException e)
			{
				// end try
				// Catch it and then throw it immediately so that
				// the finally{} block is called for cleanup.
				throw;
			}
			finally
			{
				// end catch
				try
				{
					oos.Close();
				}
				catch (Exception)
				{
				}
				try
				{
					gzos.Close();
				}
				catch (Exception)
				{
				}
				try
				{
					b64os.Close();
				}
				catch (Exception)
				{
				}
				try
				{
					baos.Close();
				}
				catch (Exception)
				{
				}
			}
			// end finally
			// Return value according to relevant encoding.
			try
			{
				return Sharpen.Runtime.GetStringForBytes(baos.ToByteArray(), PreferredEncoding);
			}
			catch (UnsupportedEncodingException)
			{
				// end try
				// Fall back to some Java default
				return Sharpen.Runtime.GetStringForBytes(baos.ToByteArray());
			}
		}
Example #2
0
		/// <summary>
		/// Similar to
		/// <see cref="EncodeBytes(byte[], int, int, int)">EncodeBytes(byte[], int, int, int)
		/// 	</see>
		/// but returns
		/// a byte array instead of instantiating a String. This is more efficient
		/// if you're working with I/O streams and have large data sets to encode.
		/// </summary>
		/// <param name="source">The data to convert</param>
		/// <param name="off">Offset in array where conversion should begin</param>
		/// <param name="len">Length of data to convert</param>
		/// <param name="options">Specified options</param>
		/// <returns>The Base64-encoded data as a String</returns>
		/// <seealso cref="Gzip">Gzip</seealso>
		/// <seealso cref="DoBreakLines">DoBreakLines</seealso>
		/// <exception cref="System.IO.IOException">if there is an error</exception>
		/// <exception cref="System.ArgumentNullException">if source array is null</exception>
		/// <exception cref="System.ArgumentException">if source array, offset, or length are invalid
		/// 	</exception>
		/// <since>2.3.1</since>
		public static byte[] EncodeBytesToBytes(byte[] source, int off, int len, int options
			)
		{
			if (source == null)
			{
				throw new ArgumentNullException("Cannot serialize a null array.");
			}
			// end if: null
			if (off < 0)
			{
				throw new ArgumentException("Cannot have negative offset: " + off);
			}
			// end if: off < 0
			if (len < 0)
			{
				throw new ArgumentException("Cannot have length offset: " + len);
			}
			// end if: len < 0
			if (off + len > source.Length)
			{
				throw new ArgumentException(string.Format("Cannot have offset of %d and length of %d with array of length %d"
					, off, len, source.Length));
			}
			// end if: off < 0
			// Compress?
			if ((options & Gzip) != 0)
			{
				ByteArrayOutputStream baos = null;
				GZIPOutputStream gzos = null;
				Base64.OutputStream b64os = null;
				try
				{
					// GZip -> Base64 -> ByteArray
					baos = new ByteArrayOutputStream();
					b64os = new Base64.OutputStream(baos, Encode | options);
					gzos = new GZIPOutputStream(b64os);
					gzos.Write(source, off, len);
					gzos.Close();
				}
				catch (IOException e)
				{
					// end try
					// Catch it and then throw it immediately so that
					// the finally{} block is called for cleanup.
					throw;
				}
				finally
				{
					// end catch
					try
					{
						gzos.Close();
					}
					catch (Exception)
					{
					}
					try
					{
						b64os.Close();
					}
					catch (Exception)
					{
					}
					try
					{
						baos.Close();
					}
					catch (Exception)
					{
					}
				}
				// end finally
				return baos.ToByteArray();
			}
			else
			{
				// end if: compress
				// Else, don't compress. Better not to use streams at all then.
				bool breakLines = (options & DoBreakLines) != 0;
				//int    len43   = len * 4 / 3;
				//byte[] outBuff = new byte[   ( len43 )                      // Main 4:3
				//                           + ( (len % 3) > 0 ? 4 : 0 )      // Account for padding
				//                           + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
				// Try to determine more precisely how big the array needs to be.
				// If we get it right, we don't have to do an array copy, and
				// we save a bunch of memory.
				int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);
				// Bytes needed for actual encoding
				if (breakLines)
				{
					encLen += encLen / MaxLineLength;
				}
				// Plus extra newline characters
				byte[] outBuff = new byte[encLen];
				int d = 0;
				int e = 0;
				int len2 = len - 2;
				int lineLength = 0;
				for (; d < len2; d += 3, e += 4)
				{
					Encode3to4(source, d + off, 3, outBuff, e, options);
					lineLength += 4;
					if (breakLines && lineLength >= MaxLineLength)
					{
						outBuff[e + 4] = NewLine;
						e++;
						lineLength = 0;
					}
				}
				// end if: end of line
				// en dfor: each piece of array
				if (d < len)
				{
					Encode3to4(source, d + off, len - d, outBuff, e, options);
					e += 4;
				}
				// end if: some padding needed
				// Only resize array if we didn't guess it right.
				if (e <= outBuff.Length - 1)
				{
					// If breaking lines and the last byte falls right at
					// the line length (76 bytes per line), there will be
					// one extra byte, and the array will need to be resized.
					// Not too bad of an estimate on array size, I'd say.
					byte[] finalOut = new byte[e];
					System.Array.Copy(outBuff, 0, finalOut, 0, e);
					//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
					return finalOut;
				}
				else
				{
					//System.err.println("No need to resize array.");
					return outBuff;
				}
			}
		}
Example #3
0
		/// <summary>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </summary>
		/// <remarks>
		/// Decodes data from Base64 notation, automatically
		/// detecting gzip-compressed data and decompressing it.
		/// </remarks>
		/// <param name="s">the string to decode</param>
		/// <param name="options">encode options such as URL_SAFE</param>
		/// <returns>the decoded data</returns>
		/// <exception cref="System.IO.IOException">if there is an error</exception>
		/// <exception cref="System.ArgumentNullException">if <tt>s</tt> is null</exception>
		/// <since>1.4</since>
		public static byte[] Decode(string s, int options)
		{
			if (s == null)
			{
				throw new ArgumentNullException("Input string was null.");
			}
			// end if
			byte[] bytes;
			try
			{
				bytes = Sharpen.Runtime.GetBytesForString(s, PreferredEncoding);
			}
			catch (UnsupportedEncodingException)
			{
				// end try
				bytes = Sharpen.Runtime.GetBytesForString(s);
			}
			// end catch
			//</change>
			// Decode
			bytes = Decode(bytes, 0, bytes.Length, options);
			// Check to see if it's gzip-compressed
			// GZIP Magic Two-Byte Number: 0x8b1f (35615)
			bool dontGunzip = (options & DontGunzip) != 0;
			if ((bytes != null) && (bytes.Length >= 4) && (!dontGunzip))
			{
				int head = ((int)bytes[0] & unchecked((int)(0xff))) | ((bytes[1] << 8) & unchecked(
					(int)(0xff00)));
				if (GZIPInputStream.GzipMagic == head)
				{
					ByteArrayInputStream bais = null;
					GZIPInputStream gzis = null;
					ByteArrayOutputStream baos = null;
					byte[] buffer = new byte[2048];
					int length = 0;
					try
					{
						baos = new ByteArrayOutputStream();
						bais = new ByteArrayInputStream(bytes);
						gzis = new GZIPInputStream(bais);
						while ((length = gzis.Read(buffer)) >= 0)
						{
							baos.Write(buffer, 0, length);
						}
						// end while: reading input
						// No error? Get new bytes.
						bytes = baos.ToByteArray();
					}
					catch (IOException e)
					{
						// end try
						Sharpen.Runtime.PrintStackTrace(e);
					}
					finally
					{
						// Just return originally-decoded bytes
						// end catch
						try
						{
							baos.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							gzis.Close();
						}
						catch (Exception)
						{
						}
						try
						{
							bais.Close();
						}
						catch (Exception)
						{
						}
					}
				}
			}
			// end finally
			// end if: gzipped
			// end if: bytes.length >= 2
			return bytes;
		}
		/// <exception cref="System.IO.IOException"></exception>
		private void AssertNoCrLfHelper(string expect, string input)
		{
			byte[] inbytes = Sharpen.Runtime.GetBytesForString(input);
			byte[] expectBytes = Sharpen.Runtime.GetBytesForString(expect);
			for (int i = 0; i < 5; ++i)
			{
				byte[] buf = new byte[i];
				ByteArrayInputStream bis = new ByteArrayInputStream(inbytes);
				InputStream @in = new AutoCRLFInputStream(bis, true);
				ByteArrayOutputStream @out = new ByteArrayOutputStream();
				if (i > 0)
				{
					int n;
					while ((n = @in.Read(buf)) >= 0)
					{
						@out.Write(buf, 0, n);
					}
				}
				else
				{
					int c;
					while ((c = @in.Read()) != -1)
					{
						@out.Write(c);
					}
				}
				@out.Flush();
				@in.Close();
				@out.Close();
				byte[] actualBytes = @out.ToByteArray();
				NUnit.Framework.Assert.AreEqual(Encode(expectBytes), Encode(actualBytes), "bufsize="
					 + i);
			}
		}
			public override void Run()
			{
				HttpClient httpclient = new DefaultHttpClient();
				HttpResponse response;
				string responseString = null;
				try
				{
					response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
					StatusLine statusLine = response.GetStatusLine();
					NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
					if (statusLine.GetStatusCode() == HttpStatus.ScOk)
					{
						ByteArrayOutputStream @out = new ByteArrayOutputStream();
						response.GetEntity().WriteTo(@out);
						@out.Close();
						responseString = @out.ToString();
						NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
						Log.D(ReplicationTest.Tag, "result: " + responseString);
					}
					else
					{
						response.GetEntity().GetContent().Close();
						throw new IOException(statusLine.GetReasonPhrase());
					}
				}
				catch (ClientProtocolException e)
				{
					NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
						(), e);
				}
				catch (IOException e)
				{
					NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
				}
				httpRequestDoneSignal.CountDown();
			}
Example #6
0
		public virtual void TestRandomWrites()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			TestRng rng = new TestRng(Sharpen.Extensions.GetTestName());
			int max = TemporaryBuffer.DEFAULT_IN_CORE_LIMIT * 2;
			byte[] expect = new byte[max];
			try
			{
				int written = 0;
				bool onebyte = true;
				while (written < max)
				{
					if (onebyte)
					{
						byte v = unchecked((byte)rng.NextInt());
						b.Write(v);
						expect[written++] = v;
					}
					else
					{
						int len = Math.Min(rng.NextInt() & 127, max - written);
						byte[] tmp = rng.NextBytes(len);
						b.Write(tmp, 0, len);
						System.Array.Copy(tmp, 0, expect, written, len);
						written += len;
					}
					onebyte = !onebyte;
				}
				NUnit.Framework.Assert.AreEqual(expect.Length, written);
				b.Close();
				NUnit.Framework.Assert.AreEqual(expect.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(expect.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(expect, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(expect.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(expect, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #7
0
		public virtual void TestOneByte()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte test = unchecked((byte)new TestRng(Sharpen.Extensions.GetTestName()).NextInt
				());
			try
			{
				b.Write(test);
				b.Close();
				NUnit.Framework.Assert.AreEqual(1, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(1, r.Length);
					NUnit.Framework.Assert.AreEqual(test, r[0]);
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(1, r.Length);
					NUnit.Framework.Assert.AreEqual(test, r[0]);
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #8
0
		public virtual void TestInCoreLimit_SwitchOnCopy()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer
				.DEFAULT_IN_CORE_LIMIT * 2);
			try
			{
				ByteArrayInputStream @in = new ByteArrayInputStream(test, TemporaryBuffer.DEFAULT_IN_CORE_LIMIT
					, test.Length - TemporaryBuffer.DEFAULT_IN_CORE_LIMIT);
				b.Write(test, 0, TemporaryBuffer.DEFAULT_IN_CORE_LIMIT);
				b.Copy(@in);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #9
0
		public virtual void TestOneBlockAndHalf_Copy()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer.Block
				.SZ * 3 / 2);
			try
			{
				ByteArrayInputStream @in = new ByteArrayInputStream(test);
				b.Write(@in.Read());
				b.Copy(@in);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #10
0
		public virtual void TestOneBlock_BulkWrite()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer.Block
				.SZ);
			try
			{
				b.Write(test, 0, 2);
				b.Write(test, 2, 4);
				b.Write(test, 6, test.Length - 6 - 2);
				b.Write(test, test.Length - 2, 2);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					NUnit.Framework.Assert.IsTrue(Arrays.Equals(test, r));
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #11
0
		public virtual void TestInCoreLimit_SwitchBeforeAppendByte()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer
				.DEFAULT_IN_CORE_LIMIT * 3);
			try
			{
				b.Write(test, 0, test.Length - 1);
				b.Write(test[test.Length - 1]);
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					for (int i = 0; i < test.Length; i ++)
						Assert.AreEqual (test[i], r[i]);
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					for (int i = 0; i < test.Length; i ++)
						Assert.AreEqual (test[i], r[i]);
				}
			}
			finally
			{
				b.Destroy();
			}
		}
Example #12
0
		public virtual void TestOneBlockAndHalf_SingleWrite()
		{
			TemporaryBuffer b = new TemporaryBuffer.LocalFile();
			byte[] test = new TestRng(Sharpen.Extensions.GetTestName()).NextBytes(TemporaryBuffer.Block
				.SZ * 3 / 2);
			try
			{
				for (int i = 0; i < test.Length; i++)
				{
					b.Write(test[i]);
				}
				b.Close();
				NUnit.Framework.Assert.AreEqual(test.Length, b.Length());
				{
					byte[] r = b.ToByteArray();
					NUnit.Framework.Assert.IsNotNull(r);
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					for (int i = 0; i < test.Length; i ++)
						Assert.AreEqual (test[i], r[i]);
				}
				{
					ByteArrayOutputStream o = new ByteArrayOutputStream();
					b.WriteTo(o, null);
					o.Close();
					byte[] r = o.ToByteArray();
					NUnit.Framework.Assert.AreEqual(test.Length, r.Length);
					for (int i = 0; i < test.Length; i ++)
						Assert.AreEqual (test[i], r[i]);
				}
			}
			finally
			{
				b.Destroy();
			}
		}