ToByteArray() public method

public ToByteArray ( ) : byte[]
return byte[]
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static Couchbase.Lite.Document CreateTask(Database database, string title, 
     Bitmap image, string listId)
 {
     SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
         );
     Calendar calendar = GregorianCalendar.GetInstance();
     string currentTimeString = dateFormatter.Format(calendar.GetTime());
     IDictionary<string, object> properties = new Dictionary<string, object>();
     properties.Put("type", DocType);
     properties.Put("title", title);
     properties.Put("checked", false);
     properties.Put("created_at", currentTimeString);
     properties.Put("list_id", listId);
     Couchbase.Lite.Document document = database.CreateDocument();
     UnsavedRevision revision = document.CreateRevision();
     revision.SetUserProperties(properties);
     if (image != null)
     {
         ByteArrayOutputStream @out = new ByteArrayOutputStream();
         image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
         ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
         revision.SetAttachment("image", "image/jpg", @in);
     }
     revision.Save();
     return document;
 }
Example #2
0
		public virtual void TestWriteLine1()
		{
			RawText a = new RawText(Constants.EncodeASCII("foo-a\nfoo-b\n"));
			ByteArrayOutputStream o = new ByteArrayOutputStream();
			a.WriteLine(o, 0);
			byte[] r = o.ToByteArray();
			NUnit.Framework.Assert.AreEqual("foo-a", RawParseUtils.Decode(r));
		}
			/// <exception cref="System.IO.IOException"></exception>
			internal byte[] ToArray()
			{
				try
				{
					if (length >= 0)
					{
						byte[] r = new byte[(int)length];
						IOUtil.ReadFully(@in, r, 0, r.Length);
						return r;
					}
					ByteArrayOutputStream r_1 = new ByteArrayOutputStream();
					byte[] buf = new byte[2048];
					int n;
					while ((n = @in.Read(buf)) >= 0)
					{
						r_1.Write(buf, 0, n);
					}
					return r_1.ToByteArray();
				}
				finally
				{
					@in.Close();
				}
			}
		/// <summary>Overwrite (or create) a loose ref in the remote repository.</summary>
		/// <remarks>
		/// Overwrite (or create) a loose ref in the remote repository.
		/// <p>
		/// This method creates any missing parent directories, if necessary.
		/// </remarks>
		/// <param name="name">
		/// name of the ref within the ref space, for example
		/// <code>refs/heads/pu</code>.
		/// </param>
		/// <param name="value">new value to store in this ref. Must not be null.</param>
		/// <exception cref="System.IO.IOException">
		/// writing is not supported, or attempting to write the file
		/// failed, possibly due to permissions or remote disk full, etc.
		/// </exception>
		internal virtual void WriteRef(string name, ObjectId value)
		{
			ByteArrayOutputStream b;
			b = new ByteArrayOutputStream(Constants.OBJECT_ID_STRING_LENGTH + 1);
			value.CopyTo(b);
			b.Write('\n');
			WriteFile(ROOT_DIR + name, b.ToByteArray());
		}
 // COPY: Copied from libcore.net.UriCodec
 /// <param name="convertPlus">true to convert '+' to ' '.</param>
 public static string Decode(string s, bool convertPlus, Encoding charset)
 {
     if (s.IndexOf('%') == -1 && (!convertPlus || s.IndexOf('+') == -1))
     {
         return s;
     }
     StringBuilder result = new StringBuilder(s.Length);
     ByteArrayOutputStream @out = new ByteArrayOutputStream();
     for (int i = 0; i < s.Length; )
     {
         char c = s[i];
         if (c == '%')
         {
             do
             {
                 if (i + 2 >= s.Length)
                 {
                     throw new ArgumentException("Incomplete % sequence at: " + i);
                 }
                 int d1 = HexToInt(s[i + 1]);
                 int d2 = HexToInt(s[i + 2]);
                 if (d1 == -1 || d2 == -1)
                 {
                     throw new ArgumentException("Invalid % sequence " + Sharpen.Runtime.Substring(s, 
                         i, i + 3) + " at " + i);
                 }
                 @out.Write(unchecked((byte)((d1 << 4) + d2)));
                 i += 3;
             }
             while (i < s.Length && s[i] == '%');
             result.Append(charset.GetString(@out.ToByteArray()));
             @out.Reset();
         }
         else
         {
             if (convertPlus && c == '+')
             {
                 c = ' ';
             }
             result.Append(c);
             i++;
         }
     }
     return result.ToString();
 }
 /// <summary>
 /// Determines the total length of the multipart content (content length of
 /// individual parts plus that of extra elements required to delimit the parts
 /// from one another).
 /// </summary>
 /// <remarks>
 /// Determines the total length of the multipart content (content length of
 /// individual parts plus that of extra elements required to delimit the parts
 /// from one another). If any of the @{link BodyPart}s contained in this object
 /// is of a streaming entity of unknown length the total length is also unknown.
 /// <p/>
 /// This method buffers only a small amount of data in order to determine the
 /// total length of the entire entity. The content of individual parts is not
 /// buffered.
 /// </remarks>
 /// <returns>
 /// total length of the multipart entity if known, <code>-1</code>
 /// otherwise.
 /// </returns>
 public virtual long GetTotalLength()
 {
     long contentLen = 0;
     foreach (FormBodyPart part in this.parts)
     {
         ContentBody body = part.GetBody();
         long len = body.GetContentLength();
         if (len >= 0)
         {
             contentLen += len;
         }
         else
         {
             return -1;
         }
     }
     ByteArrayOutputStream @out = new ByteArrayOutputStream();
     try
     {
         DoWriteTo(this.mode, @out, false);
         byte[] extra = @out.ToByteArray();
         return contentLen + extra.Length;
     }
     catch (IOException)
     {
         // Should never happen
         return -1;
     }
 }
Example #7
0
		/// <exception cref="System.IO.IOException"></exception>
		private IOException Error(string action, string key, HttpURLConnection c)
		{
			IOException err = new IOException(MessageFormat.Format(JGitText.Get().amazonS3ActionFailed
				, action, key, HttpSupport.Response(c), c.GetResponseMessage()));
			ByteArrayOutputStream b = new ByteArrayOutputStream();
			byte[] buf = new byte[2048];
			for (; ; )
			{
				int n = c.GetErrorStream().Read(buf);
				if (n < 0)
				{
					break;
				}
				if (n > 0)
				{
					b.Write(buf, 0, n);
				}
			}
			buf = b.ToByteArray();
			if (buf.Length > 0)
			{
				Sharpen.Extensions.InitCause(err, new IOException("\n" + Sharpen.Extensions.CreateString
					(buf)));
			}
			return err;
		}
		/// <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];
				InputStream @in = new ByteArrayInputStream(inbytes);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				OutputStream @out = new AutoCRLFOutputStream(bos);
				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 = bos.ToByteArray();
				NUnit.Framework.Assert.AreEqual(Encode(expectBytes), Encode(actualBytes), "bufsize="
					 + i);
			}
		}
		public virtual void TestReadWriteV3()
		{
			FilePath file = PathOf("gitgit.index.v3");
			DirCache dc = new DirCache(file, FS.DETECTED);
			dc.Read();
			NUnit.Framework.Assert.AreEqual(10, dc.GetEntryCount());
			AssertV3TreeEntry(0, "dir1/file1.txt", false, false, dc);
			AssertV3TreeEntry(1, "dir2/file2.txt", true, false, dc);
			AssertV3TreeEntry(2, "dir3/file3.txt", false, false, dc);
			AssertV3TreeEntry(3, "dir3/file3a.txt", true, false, dc);
			AssertV3TreeEntry(4, "dir4/file4.txt", true, false, dc);
			AssertV3TreeEntry(5, "dir4/file4a.txt", false, false, dc);
			AssertV3TreeEntry(6, "file.txt", true, false, dc);
			AssertV3TreeEntry(7, "newdir1/newfile1.txt", false, true, dc);
			AssertV3TreeEntry(8, "newdir1/newfile2.txt", false, true, dc);
			AssertV3TreeEntry(9, "newfile.txt", false, true, dc);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			dc.WriteTo(bos);
			byte[] indexBytes = bos.ToByteArray();
			byte[] expectedBytes = IOUtil.ReadFully(file);
			CollectionAssert.AreEquivalent(expectedBytes, indexBytes);
		}
Example #10
0
        // Replaces the "follows" key with the real attachment data in all attachments to 'doc'.
        internal bool InlineFollowingAttachmentsIn(RevisionInternal rev)
        {
            return rev.MutateAttachments((s, attachment)=>
            {
                if (!attachment.ContainsKey("follows"))
                {
                    return attachment;
                }

                var fileURL = FileForAttachmentDict(attachment);
                byte[] fileData = null;
                try
                {
                    var inputStream = fileURL.OpenConnection().GetInputStream();
                    var os = new ByteArrayOutputStream();
                    inputStream.CopyTo(os);
                    fileData = os.ToByteArray();
                }
                catch (IOException e)
                {
                    Log.E(TAG, "could not retrieve attachment data: {0}".Fmt(fileURL.ToString()), e);
                    return null;
                }

                var editedAttachment = new Dictionary<string, object>(attachment);
                editedAttachment.Remove("follows");
                editedAttachment.Put("data", Convert.ToBase64String(fileData));

                return editedAttachment;
            });
        }
Example #11
0
		/// <summary>Save the configuration as a Git text style configuration file.</summary>
		/// <remarks>
		/// Save the configuration as a Git text style configuration file.
		/// <p>
		/// <b>Warning:</b> Although this method uses the traditional Git file
		/// locking approach to protect against concurrent writes of the
		/// configuration file, it does not ensure that the file has not been
		/// modified since the last read, which means updates performed by other
		/// objects accessing the same backing file may be lost.
		/// </remarks>
		/// <exception cref="System.IO.IOException">the file could not be written.</exception>
		public override void Save()
		{
			byte[] @out;
			string text = ToText();
			if (utf8Bom)
			{
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bos.Write(unchecked((int)(0xEF)));
				bos.Write(unchecked((int)(0xBB)));
				bos.Write(unchecked((int)(0xBF)));
				bos.Write(Sharpen.Runtime.GetBytesForString(text, RawParseUtils.UTF8_CHARSET.Name
					()));
				@out = bos.ToByteArray();
			}
			else
			{
				@out = Constants.Encode(text);
			}
			LockFile lf = new LockFile(GetFile(), fs);
			if (!lf.Lock())
			{
				throw new LockFailedException(GetFile());
			}
			try
			{
				lf.SetNeedSnapshot(true);
				lf.Write(@out);
				if (!lf.Commit())
				{
					throw new IOException(MessageFormat.Format(JGitText.Get().cannotCommitWriteTo, GetFile
						()));
				}
			}
			finally
			{
				lf.Unlock();
			}
			snapshot = lf.GetCommitSnapshot();
			hash = Hash(@out);
			// notify the listeners
			FireConfigChangedEvent();
		}
Example #12
0
		public virtual void TestLargeObjectLoader()
		{
			byte[] act = GetRng().NextBytes(512);
			ObjectLoader ldr = new _ObjectLoader_122(act);
			NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, ldr.GetType());
			NUnit.Framework.Assert.AreEqual(act.Length, ldr.GetSize());
			NUnit.Framework.Assert.IsTrue(ldr.IsLarge(), "is large");
			try
			{
				ldr.GetCachedBytes();
				NUnit.Framework.Assert.Fail("did not throw on getCachedBytes()");
			}
			catch (LargeObjectException)
			{
			}
			// expected
			try
			{
				ldr.GetBytes();
				NUnit.Framework.Assert.Fail("did not throw on getBytes()");
			}
			catch (LargeObjectException)
			{
			}
			// expected
			try
			{
				ldr.GetCachedBytes(64);
				NUnit.Framework.Assert.Fail("did not throw on getCachedBytes(64)");
			}
			catch (LargeObjectException)
			{
			}
			// expected
			byte[] copy = ldr.GetCachedBytes(1024);
			NUnit.Framework.Assert.AreNotSame(act, copy);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			ObjectStream @in = ldr.OpenStream();
			NUnit.Framework.Assert.IsNotNull(@in, "has stream");
			NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, @in.GetType());
			NUnit.Framework.Assert.AreEqual(act.Length, @in.GetSize());
			NUnit.Framework.Assert.AreEqual(act.Length, @in.Available());
			NUnit.Framework.Assert.IsTrue(@in.MarkSupported(), "mark supported");
			copy = new byte[act.Length];
			NUnit.Framework.Assert.AreEqual(act.Length, @in.Read(copy));
			NUnit.Framework.Assert.AreEqual(0, @in.Available());
			NUnit.Framework.Assert.AreEqual(-1, @in.Read());
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			ByteArrayOutputStream tmp = new ByteArrayOutputStream();
			ldr.CopyTo(tmp);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, tmp.ToByteArray()), "same content"
				);
		}
		/// <exception cref="System.IO.IOException"></exception>
		private void AddDocWithId(string docId, string attachmentName)
		{
			string docJson;
			if (attachmentName != null)
			{
				// add attachment to document
				InputStream attachmentStream = GetAsset(attachmentName);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				IOUtils.Copy(attachmentStream, baos);
				string attachmentBase64 = Base64.EncodeBytes(baos.ToByteArray());
				docJson = string.Format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"i_use_couchdb.png\": { \"content_type\": \"image/png\", \"data\": \"%s\" } } }"
					, attachmentBase64);
			}
			else
			{
				docJson = "{\"foo\":1,\"bar\":false}";
			}
			// push a document to server
			Uri replicationUrlTrailingDoc1 = new Uri(string.Format("%s/%s", GetReplicationURL
				().ToExternalForm(), docId));
			Uri pathToDoc1 = new Uri(replicationUrlTrailingDoc1, docId);
			Log.D(Tag, "Send http request to " + pathToDoc1);
			CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
			BackgroundTask getDocTask = new _BackgroundTask_376(pathToDoc1, docJson, httpRequestDoneSignal
				);
			getDocTask.Execute();
			Log.D(Tag, "Waiting for http request to finish");
			try
			{
				httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
				Log.D(Tag, "http request finished");
			}
			catch (Exception e)
			{
				Sharpen.Runtime.PrintStackTrace(e);
			}
		}
Example #14
0
        /// <exception cref="System.IO.IOException"></exception>
        internal DirCacheEntry(byte[] sharedInfo, MutableInteger infoAt, InputStream @in, 
			MessageDigest md)
        {
            // private static final int P_CTIME_NSEC = 4;
            // private static final int P_MTIME_NSEC = 12;
            // private static final int P_DEV = 16;
            // private static final int P_INO = 20;
            // private static final int P_UID = 28;
            // private static final int P_GID = 32;
            info = sharedInfo;
            infoOffset = infoAt.value;
            IOUtil.ReadFully(@in, info, infoOffset, INFO_LEN);
            int len;
            if (IsExtended)
            {
                len = INFO_LEN_EXTENDED;
                IOUtil.ReadFully(@in, info, infoOffset + INFO_LEN, INFO_LEN_EXTENDED - INFO_LEN);
                if ((GetExtendedFlags() & ~EXTENDED_FLAGS) != 0)
                {
                    throw new IOException(MessageFormat.Format(JGitText.Get().DIRCUnrecognizedExtendedFlags
                        , GetExtendedFlags().ToString()));
                }
            }
            else
            {
                len = INFO_LEN;
            }
            infoAt.value += len;
            md.Update(info, infoOffset, len);
            int pathLen = NB.DecodeUInt16(info, infoOffset + P_FLAGS) & NAME_MASK;
            int skipped = 0;
            if (pathLen < NAME_MASK)
            {
                path = new byte[pathLen];
                IOUtil.ReadFully(@in, path, 0, pathLen);
                md.Update(path, 0, pathLen);
            }
            else
            {
                ByteArrayOutputStream tmp = new ByteArrayOutputStream();
                {
                    byte[] buf = new byte[NAME_MASK];
                    IOUtil.ReadFully(@in, buf, 0, NAME_MASK);
                    tmp.Write(buf);
                }
                for (; ; )
                {
                    int c = @in.Read();
                    if (c < 0)
                    {
                        throw new EOFException(JGitText.Get().shortReadOfBlock);
                    }
                    if (c == 0)
                    {
                        break;
                    }
                    tmp.Write(c);
                }
                path = tmp.ToByteArray();
                pathLen = path.Length;
                skipped = 1;
                // we already skipped 1 '\0' above to break the loop.
                md.Update(path, 0, pathLen);
                md.Update(unchecked((byte)0));
            }
            // Index records are padded out to the next 8 byte alignment
            // for historical reasons related to how C Git read the files.
            //
            int actLen = len + pathLen;
            int expLen = (actLen + 8) & ~7;
            int padLen = expLen - actLen - skipped;
            if (padLen > 0)
            {
                IOUtil.SkipFully(@in, padLen);
                md.Update(nullpad, 0, padLen);
            }
        }
 /// <exception cref="System.IO.IOException"></exception>
 private void AssertFileContentsEqual(FilePath actFile, string @string)
 {
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     FileInputStream fis = null;
     byte[] buffer = new byte[100];
     try
     {
         fis = new FileInputStream(actFile);
         int read = fis.Read(buffer);
         while (read > 0)
         {
             bos.Write(buffer, 0, read);
             read = fis.Read(buffer);
         }
         string content = Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(), "UTF-8");
         NUnit.Framework.Assert.AreEqual(@string, content);
     }
     finally
     {
         if (fis != null)
         {
             fis.Close();
         }
     }
 }
Example #16
0
 public virtual void TestWriteLine3()
 {
     RawText a = new RawText(Constants.EncodeASCII("a\n\nb\n"));
     ByteArrayOutputStream o = new ByteArrayOutputStream();
     a.WriteLine(o, 1);
     byte[] r = o.ToByteArray();
     NUnit.Framework.Assert.AreEqual(string.Empty, RawParseUtils.Decode(r));
 }
Example #17
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 #18
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 #19
0
		public virtual void TestParse_explicit_bad_encoded2()
		{
			ByteArrayOutputStream b = new ByteArrayOutputStream();
			b.Write(Sharpen.Runtime.GetBytesForString("object 9788669ad918b6fcce64af8882fc9a81cb6aba67\n"
				, "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("type tree\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("tag v1.2.3.4.5\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("tagger F\u00f6r fattare <*****@*****.**> 1218123387 +0700\n"
				, "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("encoding ISO-8859-1\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("\u304d\u308c\u3044\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("\n", "UTF-8"));
			b.Write(Sharpen.Runtime.GetBytesForString("Hi\n", "UTF-8"));
			RevTag c;
			c = new RevTag(Id("9473095c4cb2f12aefe1db8a355fe3fafba42f67"));
			c.ParseCanonical(new RevWalk(db), b.ToByteArray());
			NUnit.Framework.Assert.AreEqual("F\u00f6r fattare", c.GetTaggerIdent().GetName());
			NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044", c.GetShortMessage());
			NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044\n\nHi\n", c.GetFullMessage());
		}
Example #20
0
		/// <summary>Format this builder's state as an annotated tag object.</summary>
		/// <remarks>Format this builder's state as an annotated tag object.</remarks>
		/// <returns>
		/// this object in the canonical annotated tag format, suitable for
		/// storage in a repository.
		/// </returns>
		public virtual byte[] Build()
		{
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			OutputStreamWriter w = new OutputStreamWriter(os, Constants.CHARSET);
			try
			{
				w.Write("object ");
				GetObjectId().CopyTo(w);
				w.Write('\n');
				w.Write("type ");
				w.Write(Constants.TypeString(GetObjectType()));
				w.Write("\n");
				w.Write("tag ");
				w.Write(GetTag());
				w.Write("\n");
				if (GetTagger() != null)
				{
					w.Write("tagger ");
					w.Write(GetTagger().ToExternalString());
					w.Write('\n');
				}
				w.Write('\n');
				if (GetMessage() != null)
				{
					w.Write(GetMessage());
				}
				w.Close();
			}
			catch (IOException err)
			{
				// This should never occur, the only way to get it above is
				// for the ByteArrayOutputStream to throw, but it doesn't.
				//
				throw new RuntimeException(err);
			}
			return os.ToByteArray();
		}
Example #21
0
		/// <exception cref="System.IO.IOException"></exception>
		private static byte[] ToByteArray(ObjectId id)
		{
			ByteArrayOutputStream buf = new ByteArrayOutputStream(Constants.OBJECT_ID_LENGTH);
			id.CopyRawTo(buf);
			return buf.ToByteArray();
		}
Example #22
0
		public virtual void TestSmallObjectLoader()
		{
			byte[] act = GetRng().NextBytes(512);
			ObjectLoader ldr = new ObjectLoader.SmallObject(Constants.OBJ_BLOB, act);
			NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, ldr.GetType());
			NUnit.Framework.Assert.AreEqual(act.Length, ldr.GetSize());
			NUnit.Framework.Assert.IsFalse(ldr.IsLarge(), "not is large");
			NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes());
			NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes(1));
			NUnit.Framework.Assert.AreSame(act, ldr.GetCachedBytes(int.MaxValue));
			byte[] copy = ldr.GetBytes();
			NUnit.Framework.Assert.AreNotSame(act, copy);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			copy = ldr.GetBytes(1);
			NUnit.Framework.Assert.AreNotSame(act, copy);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			copy = ldr.GetBytes(int.MaxValue);
			NUnit.Framework.Assert.AreNotSame(act, copy);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			ObjectStream @in = ldr.OpenStream();
			NUnit.Framework.Assert.IsNotNull(@in, "has stream");
			NUnit.Framework.Assert.IsTrue(@in is ObjectStream.SmallStream, "is small stream");
			NUnit.Framework.Assert.AreEqual(Constants.OBJ_BLOB, @in.GetType());
			NUnit.Framework.Assert.AreEqual(act.Length, @in.GetSize());
			NUnit.Framework.Assert.AreEqual(act.Length, @in.Available());
			NUnit.Framework.Assert.IsTrue(@in.MarkSupported(), "mark supported");
			copy = new byte[act.Length];
			NUnit.Framework.Assert.AreEqual(act.Length, @in.Read(copy));
			NUnit.Framework.Assert.AreEqual(0, @in.Available());
			NUnit.Framework.Assert.AreEqual(-1, @in.Read());
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, copy), "same content");
			ByteArrayOutputStream tmp = new ByteArrayOutputStream();
			ldr.CopyTo(tmp);
			NUnit.Framework.Assert.IsTrue(Arrays.Equals(act, tmp.ToByteArray()), "same content"
				);
		}
Example #23
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;
		}
Example #24
0
 /// <exception cref="System.IO.IOException"></exception>
 private byte[] Delta(byte[] @base, byte[] dest)
 {
     ByteArrayOutputStream tmp = new ByteArrayOutputStream();
     DeltaEncoder de = new DeltaEncoder(tmp, @base.Length, dest.Length);
     de.Insert(dest, 0, 1);
     de.Copy(1, @base.Length - 1);
     return tmp.ToByteArray();
 }
		/// <exception cref="System.Exception"></exception>
		private static byte[] Entry(FileMode mode, string name, ObjectId id)
		{
			ByteArrayOutputStream @out = new ByteArrayOutputStream();
			mode.CopyTo(@out);
			@out.Write(' ');
			@out.Write(Constants.Encode(name));
			@out.Write(0);
			id.CopyRawTo(@out);
			return @out.ToByteArray();
		}
		/// <exception cref="System.Exception"></exception>
		private static byte[] Mktree(params byte[][] data)
		{
			ByteArrayOutputStream @out = new ByteArrayOutputStream();
			foreach (byte[] e in data)
			{
				@out.Write(e);
			}
			return @out.ToByteArray();
		}
Example #27
0
 /// <exception cref="System.IO.IOException"></exception>
 private byte[] ReadFile(string patchFile)
 {
     InputStream @in = typeof(DiffFormatterReflowTest).GetResourceAsStream(patchFile);
     if (@in == null)
     {
         NUnit.Framework.Assert.Fail("No " + patchFile + " test vector");
         return null;
     }
     // Never happens
     try
     {
         byte[] buf = new byte[1024];
         ByteArrayOutputStream temp = new ByteArrayOutputStream();
         int n;
         while ((n = @in.Read(buf)) > 0)
         {
             temp.Write(buf, 0, n);
         }
         return temp.ToByteArray();
     }
     finally
     {
         @in.Close();
     }
 }
Example #28
0
 /// <exception cref="System.IO.IOException"></exception>
 private string Merge(string commonBase, string ours, string theirs)
 {
     MergeResult<RawText> r = new MergeAlgorithm().Merge(RawTextComparator.DEFAULT, RT(commonBase
         ), RT(ours), RT(theirs));
     ByteArrayOutputStream bo = new ByteArrayOutputStream(50);
     fmt.FormatMerge(bo, r, "B", "O", "T", Constants.CHARACTER_ENCODING);
     return Sharpen.Extensions.CreateString(bo.ToByteArray(), Constants.CHARACTER_ENCODING
         );
 }
 /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
 public static void AttachImage(Couchbase.Lite.Document task, Bitmap image)
 {
     if (task == null || image == null)
     {
         return;
     }
     UnsavedRevision revision = task.CreateRevision();
     ByteArrayOutputStream @out = new ByteArrayOutputStream();
     image.Compress(Bitmap.CompressFormat.Jpeg, 50, @out);
     ByteArrayInputStream @in = new ByteArrayInputStream(@out.ToByteArray());
     revision.SetAttachment("image", "image/jpg", @in);
     revision.Save();
 }
Example #30
-1
		/// <exception cref="System.IO.IOException"></exception>
		protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData
			, SignerInformation si, SignatureParameters parameters, Document originalData)
		{
			si = base.ExtendCMSSignature(signedData, si, parameters, originalData);
			DerObjectIdentifier attributeId = null;
			ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();
			switch (GetExtendedValidationType())
			{
				case 1:
				{
					attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp;
					toTimestamp.Write(si.GetSignature());
					// We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5,
					// NOTE 2)
					toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]
						.AttrType.GetDerEncoded());
					toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]
						.AttrValues.GetDerEncoded());
					break;
				}

				case 2:
				{
					attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp;
					break;
				}

				default:
				{
					throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)"
						);
				}
			}
			toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs]
				.AttrType.GetDerEncoded());
			toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs]
				.AttrValues.GetDerEncoded());
			toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs]
				.AttrType.GetDerEncoded());
			toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs]
				.AttrValues.GetDerEncoded());
			//IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
			BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa(
				), digestAlgorithm, toTimestamp.ToByteArray());
			//unsignedAttrHash.Put(attributeId, extendedTimeStamp);
            unsignedAttrHash.Add(attributeId, extendedTimeStamp);
			return SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash
				));
		}