public virtual void SetUp() { actDeltaBuf = new ByteArrayOutputStream(); expDeltaBuf = new ByteArrayOutputStream(); expDeltaEnc = new DeltaEncoder(expDeltaBuf, 0, 0); dstBuf = new ByteArrayOutputStream(); }
/// <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; }
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)); }
/// <summary>Serializes an <code>XMPMeta</code>-object as RDF into a string.</summary> /// <remarks> /// Serializes an <code>XMPMeta</code>-object as RDF into a string. /// <em>Note:</em> Encoding is forced to UTF-16 when serializing to a /// string to ensure the correctness of "exact packet size". /// </remarks> /// <param name="xmp">a metadata implementation object</param> /// <param name="options"> /// Options to control the serialization (see /// <see cref="Com.Adobe.Xmp.Options.SerializeOptions"/> /// ). /// </param> /// <returns>Returns a string containing the serialized RDF.</returns> /// <exception cref="Com.Adobe.Xmp.XMPException">on serializsation errors.</exception> public static string SerializeToString(XMPMetaImpl xmp, SerializeOptions options) { // forces the encoding to be UTF-16 to get the correct string length options = options != null ? options : new SerializeOptions(); options.SetEncodeUTF16BE(true); ByteArrayOutputStream @out = new ByteArrayOutputStream(2048); Serialize(xmp, @out, options); try { return @out.ToString(options.GetEncoding()); } catch (UnsupportedEncodingException) { // cannot happen as UTF-8/16LE/BE is required to be implemented in // Java return @out.ToString(); } }
public virtual void TestParse_explicit_bad_encoded() { ByteArrayOutputStream b = new ByteArrayOutputStream(); b.Write(Sharpen.Runtime.GetBytesForString("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("author F\u00f6r fattare <*****@*****.**> 1218123387 +0700\n" , "ISO-8859-1")); b.Write(Sharpen.Runtime.GetBytesForString("committer C O. Miter <*****@*****.**> 1218123390 -0500\n" , "UTF-8")); b.Write(Sharpen.Runtime.GetBytesForString("encoding EUC-JP\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")); RevCommit c; c = new RevCommit(Id("9473095c4cb2f12aefe1db8a355fe3fafba42f67")); // bogus id c.ParseCanonical(new RevWalk(db), b.ToByteArray()); NUnit.Framework.Assert.AreEqual("Japanese (EUC)", c.Encoding.EncodingName); NUnit.Framework.Assert.AreEqual("F\u00f6r fattare", c.GetAuthorIdent().GetName()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044", c.GetShortMessage()); NUnit.Framework.Assert.AreEqual("\u304d\u308c\u3044\n\nHi\n", c.GetFullMessage()); }
public virtual void TestDiffModified() { Write(new FilePath(db.WorkTree, "test.txt"), "test"); FilePath folder = new FilePath(db.WorkTree, "folder"); folder.Mkdir(); Write(new FilePath(folder, "folder.txt"), "folder"); Git git = new Git(db); git.Add().AddFilepattern(".").Call(); git.Commit().SetMessage("Initial commit").Call(); Write(new FilePath(folder, "folder.txt"), "folder change"); OutputStream @out = new ByteArrayOutputStream(); IList<DiffEntry> entries = git.Diff().SetOutputStream(@out).Call(); NUnit.Framework.Assert.AreEqual(1, entries.Count); NUnit.Framework.Assert.AreEqual(DiffEntry.ChangeType.MODIFY, entries[0].GetChangeType ()); NUnit.Framework.Assert.AreEqual("folder/folder.txt", entries[0].GetOldPath()); NUnit.Framework.Assert.AreEqual("folder/folder.txt", entries[0].GetNewPath()); string actual = @out.ToString(); string expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n" + "index 0119635..95c4c65 100644\n" + "--- a/folder/folder.txt\n" + "+++ b/folder/folder.txt\n" + "@@ -1 +1 @@\n" + "-folder\n" + "\\ No newline at end of file\n" + "+folder change\n" + "\\ No newline at end of file\n"; NUnit.Framework.Assert.AreEqual(expected.ToString(), actual); }
public virtual void SetUp() { @out = new ByteArrayOutputStream(); fmt = new DiffFormatter(@out); }
/// <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(); } } }
/// <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); } }
public virtual void SetUp() { rawOut = new ByteArrayOutputStream(); }
public virtual void SetUp() { rawOut = new ByteArrayOutputStream(); @out = new PacketLineOut(rawOut); }
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()); }
/// <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(); }
/// <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); } }
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(); }
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" ); }
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" ); }
/// <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; } } }
/// <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(); }
/// <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 static byte[] ToByteArray(ObjectId id) { ByteArrayOutputStream buf = new ByteArrayOutputStream(Constants.OBJECT_ID_LENGTH); id.CopyRawTo(buf); return buf.ToByteArray(); }
// 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()); } }
// 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; }); }
/// <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(); }
public virtual void TestDiff() { Write(new FilePath(db.Directory.GetParent(), "test.txt"), "test"); FilePath folder = new FilePath(db.Directory.GetParent(), "folder"); folder.Mkdir(); Write(new FilePath(folder, "folder.txt"), "folder"); Git git = new Git(db); git.Add().AddFilepattern(".").Call(); git.Commit().SetMessage("Initial commit").Call(); Write(new FilePath(folder, "folder.txt"), "folder change"); ByteArrayOutputStream os = new ByteArrayOutputStream(); DiffFormatter df = new DiffFormatter(new BufferedOutputStream(os)); df.SetRepository(db); df.SetPathFilter(PathFilter.Create("folder")); DirCacheIterator oldTree = new DirCacheIterator(db.ReadDirCache()); FileTreeIterator newTree = new FileTreeIterator(db); df.Format(oldTree, newTree); df.Flush(); string actual = os.ToString(); string expected = "diff --git a/folder/folder.txt b/folder/folder.txt\n" + "index 0119635..95c4c65 100644\n" + "--- a/folder/folder.txt\n" + "+++ b/folder/folder.txt\n" + "@@ -1 +1 @@\n" + "-folder\n" + "\\ No newline at end of file\n" + "+folder change\n" + "\\ No newline at end of file\n"; NUnit.Framework.Assert.AreEqual(expected.ToString(), actual); }
/// <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(); }
/// <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(); } }
/// <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="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 )); }