Inheritance: InputStream
Beispiel #1
0
		public virtual void Test1()
		{
			FilePath packFile = JGitTestUtil.GetTestResourceFile("pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack"
				);
			InputStream @is = new FileInputStream(packFile);
			try
			{
				ObjectDirectoryPackParser p = (ObjectDirectoryPackParser)Index(@is);
				p.Parse(NullProgressMonitor.INSTANCE);
				PackFile file = p.GetPackFile();
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("82c6b885ff600be425b4ea96dee75dca255b69e7"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("902d5476fa249b7abc9d84c611577a81381f0327"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("aabf2ffaec9b497f0950352b3e582d73035c2035"
					)));
				NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("c59759f143fb1fe21c197981df75a7ee00290799"
					)));
			}
			finally
			{
				@is.Close();
			}
		}
Beispiel #2
0
 public static sbyte[] ReadBytes([NotNull] FilePath file)
 {
     int length = (int)file.Length();
     // should only be zero if loading from a network or similar
     System.Diagnostics.Debug.Assert((length != 0));
     sbyte[] bytes = new sbyte[length];
     int totalBytesRead = 0;
     FileInputStream inputStream = null;
     try
     {
         inputStream = new FileInputStream(file);
         while (totalBytesRead != length)
         {
             int bytesRead = inputStream.Read(bytes, totalBytesRead, length - totalBytesRead);
             if (bytesRead == -1)
             {
                 break;
             }
             totalBytesRead += bytesRead;
         }
     }
     finally
     {
         if (inputStream != null)
         {
             inputStream.Close();
         }
     }
     return bytes;
 }
		/// <exception cref="System.IO.IOException"></exception>
		public static void CopyFile(FilePath sourceFile, FilePath destFile)
		{
			if (!destFile.Exists())
			{
				destFile.CreateNewFile();
			}
			FileChannel source = null;
			FileChannel destination = null;
			try
			{
				source = new FileInputStream(sourceFile).GetChannel();
				destination = new FileOutputStream(destFile).GetChannel();
				destination.TransferFrom(source, 0, source.Size());
			}
			finally
			{
				if (source != null)
				{
					source.Close();
				}
				if (destination != null)
				{
					destination.Close();
				}
			}
		}
Beispiel #4
0
		/// <summary>Read an entire local file into memory as a byte array.</summary>
		/// <remarks>Read an entire local file into memory as a byte array.</remarks>
		/// <param name="path">location of the file to read.</param>
		/// <param name="max">
		/// maximum number of bytes to read, if the file is larger than
		/// this limit an IOException is thrown.
		/// </param>
		/// <returns>complete contents of the requested local file.</returns>
		/// <exception cref="System.IO.FileNotFoundException">the file does not exist.</exception>
		/// <exception cref="System.IO.IOException">the file exists, but its contents cannot be read.
		/// 	</exception>
		public static byte[] ReadFully(FilePath path, int max)
		{
			FileInputStream @in = new FileInputStream(path);
			try
			{
				long sz = @in.GetChannel().Size();
				if (sz > max)
				{
					throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path));
				}
				byte[] buf = new byte[(int)sz];
				IOUtil.ReadFully(@in, buf, 0, buf.Length);
				return buf;
			}
			finally
			{
				try
				{
					@in.Close();
				}
				catch (IOException)
				{
				}
			}
		}
Beispiel #5
0
		/// <exception cref="System.IO.IOException"></exception>
		protected internal static void CopyFile(FilePath src, FilePath dst)
		{
			FileInputStream fis = new FileInputStream(src);
			try
			{
				FileOutputStream fos = new FileOutputStream(dst);
				try
				{
					byte[] buf = new byte[4096];
					int r;
					while ((r = fis.Read(buf)) > 0)
					{
						fos.Write(buf, 0, r);
					}
				}
				finally
				{
					fos.Close();
				}
			}
			finally
			{
				fis.Close();
			}
		}
Beispiel #6
0
		/// <summary>Read at most limit bytes from the local file into memory as a byte array.
		/// 	</summary>
		/// <remarks>Read at most limit bytes from the local file into memory as a byte array.
		/// 	</remarks>
		/// <param name="path">location of the file to read.</param>
		/// <param name="limit">
		/// maximum number of bytes to read, if the file is larger than
		/// only the first limit number of bytes are returned
		/// </param>
		/// <returns>
		/// complete contents of the requested local file. If the contents
		/// exceeds the limit, then only the limit is returned.
		/// </returns>
		/// <exception cref="System.IO.FileNotFoundException">the file does not exist.</exception>
		/// <exception cref="System.IO.IOException">the file exists, but its contents cannot be read.
		/// 	</exception>
		public static byte[] ReadSome(FilePath path, int limit)
		{
			FileInputStream @in = new FileInputStream(path);
			try
			{
				byte[] buf = new byte[limit];
				int cnt = 0;
				for (; ; )
				{
					int n = @in.Read(buf, cnt, buf.Length - cnt);
					if (n <= 0)
					{
						break;
					}
					cnt += n;
				}
				if (cnt == buf.Length)
				{
					return buf;
				}
				byte[] res = new byte[cnt];
				System.Array.Copy(buf, 0, res, 0, cnt);
				return res;
			}
			finally
			{
				try
				{
					@in.Close();
				}
				catch (IOException)
				{
				}
			}
		}
		public static GifHeaderDirectory ProcessBytes(string file)
		{
			Com.Drew.Metadata.Metadata metadata = new Com.Drew.Metadata.Metadata();
			InputStream stream = new FileInputStream(file);
			new GifReader().Extract(new Com.Drew.Lang.StreamReader(stream), metadata);
			stream.Close();
			GifHeaderDirectory directory = metadata.GetDirectory<GifHeaderDirectory>();
			NUnit.Framework.Assert.IsNotNull(directory);
			return directory;
		}
Beispiel #8
0
		/// <exception cref="NSch.JSchException"></exception>
		internal virtual void SetKnownHosts(string foo)
		{
			try
			{
				known_hosts = foo;
				FileInputStream fis = new FileInputStream(foo);
				SetKnownHosts(fis);
			}
			catch (FileNotFoundException)
			{
			}
		}
Beispiel #9
0
 public static Com.Drew.Metadata.Metadata ReadMetadata([NotNull] FilePath file)
 {
     InputStream inputStream = new FileInputStream(file);
     Com.Drew.Metadata.Metadata metadata;
     try
     {
         metadata = ReadMetadata(inputStream);
     }
     finally
     {
         inputStream.Close();
     }
     new FileMetadataReader().Read(file, metadata);
     return metadata;
 }
 private static Com.Drew.Metadata.Metadata ProcessFile([NotNull] string filePath)
 {
     FileInputStream inputStream = null;
     try
     {
         inputStream = new FileInputStream(filePath);
         return PngMetadataReader.ReadMetadata(inputStream);
     }
     finally
     {
         if (inputStream != null)
         {
             inputStream.Close();
         }
     }
 }
		public static Com.Drew.Metadata.Metadata ReadMetadata(FilePath file, Iterable<JpegSegmentMetadataReader> readers)
		{
			InputStream inputStream = null;
			try
			{
				inputStream = new FileInputStream(file);
				return ReadMetadata(inputStream, readers);
			}
			finally
			{
				if (inputStream != null)
				{
					inputStream.Close();
				}
			}
		}
		/// <exception cref="Com.Drew.Imaging.Png.PngProcessingException"/>
		/// <exception cref="System.IO.IOException"/>
		public static IList<PngChunk> ProcessFile(string filePath)
		{
			FileInputStream inputStream = null;
			try
			{
				inputStream = new FileInputStream(filePath);
				return Iterables.ToList(new PngChunkReader().Extract(new Com.Drew.Lang.StreamReader(inputStream), null));
			}
			finally
			{
				if (inputStream != null)
				{
					inputStream.Close();
				}
			}
		}
		public static Com.Drew.Metadata.Metadata ReadMetadata(FilePath file)
		{
			FileInputStream stream = null;
			try
			{
				stream = new FileInputStream(file);
				return ReadMetadata(stream);
			}
			finally
			{
				if (stream != null)
				{
					stream.Close();
				}
			}
		}
Beispiel #14
0
		/// <exception cref="System.IO.IOException"></exception>
		public override void VisitFile(FileTreeEntry f)
		{
			FilePath path = new FilePath(GetCurrentDirectory(), f.GetName());
			FileInputStream @in = new FileInputStream(path);
			try
			{
				long sz = @in.GetChannel().Size();
				f.SetId(inserter.Insert(Constants.OBJ_BLOB, sz, @in));
				inserter.Flush();
			}
			finally
			{
				inserter.Release();
				@in.Close();
			}
		}
		public static JpegSegmentData ReadSegments(FilePath file, Iterable<JpegSegmentType> segmentTypes)
		{
			FileInputStream stream = null;
			try
			{
				stream = new FileInputStream(file);
				return ReadSegments(new Com.Drew.Lang.StreamReader(stream), segmentTypes);
			}
			finally
			{
				if (stream != null)
				{
					stream.Close();
				}
			}
		}
 public static PsdHeaderDirectory ProcessBytes([NotNull] string file)
 {
     Com.Drew.Metadata.Metadata metadata = new Com.Drew.Metadata.Metadata();
     InputStream stream = new FileInputStream(new FilePath(file));
     try
     {
         new PsdReader().Extract(new Com.Drew.Lang.StreamReader(stream), metadata);
     }
     catch (Exception e)
     {
         stream.Close();
         throw;
     }
     PsdHeaderDirectory directory = metadata.GetFirstDirectoryOfType<PsdHeaderDirectory>();
     NUnit.Framework.Assert.IsNotNull(directory);
     return directory;
 }
Beispiel #17
0
 public virtual void Test2()
 {
     FilePath packFile = JGitTestUtil.GetTestResourceFile("pack-df2982f284bbabb6bdb59ee3fcc6eb0983e20371.pack"
         );
     InputStream @is = new FileInputStream(packFile);
     try
     {
         ObjectDirectoryPackParser p = (ObjectDirectoryPackParser)Index(@is);
         p.Parse(NullProgressMonitor.INSTANCE);
         PackFile file = p.GetPackFile();
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("02ba32d3649e510002c21651936b7077aa75ffa9"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("0966a434eb1a025db6b71485ab63a3bfbea520b6"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("09efc7e59a839528ac7bda9fa020dc9101278680"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("0a3d7772488b6b106fb62813c4d6d627918d9181"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1004d0d7ac26fbf63050a234c9b88a46075719d3"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("10da5895682013006950e7da534b705252b03be6"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1203b03dc816ccbb67773f28b3c19318654b0bc8"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("15fae9e651043de0fd1deef588aa3fbf5a7a41c6"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("16f9ec009e5568c435f473ba3a1df732d49ce8c3"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("1fd7d579fb6ae3fe942dc09c2c783443d04cf21e"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("20a8ade77639491ea0bd667bf95de8abf3a434c8"
             )));
         NUnit.Framework.Assert.IsTrue(file.HasObject(ObjectId.FromString("2675188fd86978d5bc4d7211698b2118ae3bf658"
             )));
     }
     finally
     {
         // and lots more...
         @is.Close();
     }
 }
		/// <exception cref="System.IO.FileNotFoundException"></exception>
		/// <exception cref="System.InvalidOperationException"></exception>
		/// <exception cref="System.IO.IOException"></exception>
		private bool ContentMerge(CanonicalTreeParser @base, CanonicalTreeParser ours, CanonicalTreeParser
			 theirs)
		{
			MergeFormatter fmt = new MergeFormatter();
			RawText baseText = @base == null ? RawText.EMPTY_TEXT : GetRawText(@base.EntryObjectId
				, db);
			// do the merge
			MergeResult<RawText> result = mergeAlgorithm.Merge(RawTextComparator.DEFAULT, baseText
				, GetRawText(ours.EntryObjectId, db), GetRawText(theirs.EntryObjectId, db));
			FilePath of = null;
			FileOutputStream fos;
			if (!inCore)
			{
				FilePath workTree = db.WorkTree;
				if (workTree == null)
				{
					// TODO: This should be handled by WorkingTreeIterators which
					// support write operations
					throw new NotSupportedException();
				}
				of = new FilePath(workTree, tw.PathString);
				fos = new FileOutputStream(of);
				try
				{
					fmt.FormatMerge(fos, result, Arrays.AsList(commitNames), Constants.CHARACTER_ENCODING
						);
				}
				finally
				{
					fos.Close();
				}
			}
			else
			{
				if (!result.ContainsConflicts())
				{
					// When working inCore, only trivial merges can be handled,
					// so we generate objects only in conflict free cases
					of = FilePath.CreateTempFile("merge_", "_temp", null);
					fos = new FileOutputStream(of);
					try
					{
						fmt.FormatMerge(fos, result, Arrays.AsList(commitNames), Constants.CHARACTER_ENCODING
							);
					}
					finally
					{
						fos.Close();
					}
				}
			}
			if (result.ContainsConflicts())
			{
				// a conflict occured, the file will contain conflict markers
				// the index will be populated with the three stages and only the
				// workdir (if used) contains the halfways merged content
				Add(tw.RawPath, @base, DirCacheEntry.STAGE_1);
				Add(tw.RawPath, ours, DirCacheEntry.STAGE_2);
				Add(tw.RawPath, theirs, DirCacheEntry.STAGE_3);
				mergeResults.Put(tw.PathString, result.Upcast ());
				return false;
			}
			else
			{
				// no conflict occured, the file will contain fully merged content.
				// the index will be populated with the new merged version
				DirCacheEntry dce = new DirCacheEntry(tw.PathString);
				dce.FileMode = tw.GetFileMode(0);
				dce.LastModified = of.LastModified();
				dce.SetLength((int)of.Length());
				InputStream @is = new FileInputStream(of);
				try
				{
					dce.SetObjectId(oi.Insert(Constants.OBJ_BLOB, of.Length(), @is));
				}
				finally
				{
					@is.Close();
					if (inCore)
					{
						FileUtils.Delete(of);
					}
				}
				builder.Add(dce);
				return true;
			}
		}
Beispiel #19
0
		/// <summary>Resets the index to represent exactly some filesystem content.</summary>
		/// <remarks>
		/// Resets the index to represent exactly some filesystem content. E.g. the
		/// following call will replace the index with the working tree content:
		/// <p>
		/// <code>resetIndex(new FileSystemIterator(db))</code>
		/// <p>
		/// This method can be used by testcases which first prepare a new commit
		/// somewhere in the filesystem (e.g. in the working-tree) and then want to
		/// have an index which matches their prepared content.
		/// </remarks>
		/// <param name="treeItr">
		/// a
		/// <see cref="NGit.Treewalk.FileTreeIterator">NGit.Treewalk.FileTreeIterator</see>
		/// which determines which files should
		/// go into the new index
		/// </param>
		/// <exception cref="System.IO.FileNotFoundException">System.IO.FileNotFoundException
		/// 	</exception>
		/// <exception cref="System.IO.IOException">System.IO.IOException</exception>
		protected internal virtual void ResetIndex(FileTreeIterator treeItr)
		{
			ObjectInserter inserter = db.NewObjectInserter();
			DirCacheBuilder builder = db.LockDirCache().Builder();
			DirCacheEntry dce;
			while (!treeItr.Eof)
			{
				long len = treeItr.GetEntryLength();
				dce = new DirCacheEntry(treeItr.EntryPathString);
				dce.FileMode = treeItr.EntryFileMode;
				dce.LastModified = treeItr.GetEntryLastModified();
				dce.SetLength((int)len);
				FileInputStream @in = new FileInputStream(treeItr.GetEntryFile());
				dce.SetObjectId(inserter.Insert(Constants.OBJ_BLOB, len, @in));
				@in.Close();
				builder.Add(dce);
				treeItr.Next(1);
			}
			builder.Commit();
			inserter.Flush();
			inserter.Release();
		}
Beispiel #20
0
 public virtual void CheckLockedFilesToBeDeleted()
 {
     Git git = Git.Wrap(db);
     WriteTrashFile("a.txt", "orig");
     WriteTrashFile("b.txt", "orig");
     git.Add().AddFilepattern("a.txt").AddFilepattern("b.txt").Call();
     RevCommit first = git.Commit().SetMessage("added a.txt, b.txt").Call();
     // modify and delete files on the master branch
     WriteTrashFile("a.txt", "master");
     git.Rm().AddFilepattern("b.txt").Call();
     RevCommit masterCommit = git.Commit().SetMessage("modified a.txt, deleted b.txt")
         .SetAll(true).Call();
     // switch back to a side branch
     git.Checkout().SetCreateBranch(true).SetStartPoint(first).SetName("side").Call();
     WriteTrashFile("c.txt", "side");
     git.Add().AddFilepattern("c.txt").Call();
     git.Commit().SetMessage("added c.txt").Call();
     // Get a handle to the the file so on windows it can't be deleted.
     FileInputStream fis = new FileInputStream(new FilePath(db.WorkTree, "b.txt"));
     MergeCommandResult mergeRes = git.Merge().Include(masterCommit).Call();
     if (mergeRes.GetMergeStatus().Equals(MergeStatus.FAILED))
     {
         // probably windows
         NUnit.Framework.Assert.AreEqual(1, mergeRes.GetFailingPaths().Count);
         NUnit.Framework.Assert.AreEqual(ResolveMerger.MergeFailureReason.COULD_NOT_DELETE
             , mergeRes.GetFailingPaths().Get("b.txt"));
     }
     NUnit.Framework.Assert.AreEqual("[a.txt, mode:100644, content:master]" + "[c.txt, mode:100644, content:side]"
         , IndexState(CONTENT));
     fis.Close();
 }
 /// <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();
         }
     }
 }
Beispiel #22
0
        /// <exception cref="NGit.Errors.CorruptObjectException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void AssertWorkDir(Dictionary<string, string> i)
        {
            TreeWalk walk = new TreeWalk(db);
            walk.Recursive = true;
            walk.AddTree(new FileTreeIterator(db));
            string expectedValue;
            string path;
            int nrFiles = 0;
            FileTreeIterator ft;
            while (walk.Next())
            {
                ft = walk.GetTree<FileTreeIterator>(0);
                path = ft.EntryPathString;
                expectedValue = i.Get(path);
                NUnit.Framework.Assert.IsNotNull(expectedValue, "found unexpected file for path "
                     + path + " in workdir");
                FilePath file = new FilePath(db.WorkTree, path);
                NUnit.Framework.Assert.IsTrue(file.Exists());
                if (file.IsFile())
                {
                    FileInputStream @is = new FileInputStream(file);
                    byte[] buffer = new byte[(int)file.Length()];
                    int offset = 0;
                    int numRead = 0;
                    while (offset < buffer.Length && (numRead = @is.Read(buffer, offset, buffer.Length
                         - offset)) >= 0)
                    {
                        offset += numRead;
                    }
                    @is.Close();

                    CollectionAssert.AreEqual (buffer, Sharpen.Runtime.GetBytesForString(i.Get(path)),
                        "unexpected content for path " + path + " in workDir. ");
                    nrFiles++;
                }
            }
            NUnit.Framework.Assert.AreEqual(i.Count, nrFiles, "WorkDir has not the right size."
                );
        }
Beispiel #23
0
 /// <summary>Copy the current file content into the temporary file.</summary>
 /// <remarks>
 /// Copy the current file content into the temporary file.
 /// <p>
 /// This method saves the current file content by inserting it into the
 /// temporary file, so that the caller can safely append rather than replace
 /// the primary file.
 /// <p>
 /// This method does nothing if the current file does not exist, or exists
 /// but is empty.
 /// </remarks>
 /// <exception cref="System.IO.IOException">
 /// the temporary file could not be written, or a read error
 /// occurred while reading from the current file. The lock is
 /// released before throwing the underlying IO exception to the
 /// caller.
 /// </exception>
 /// <exception cref="Sharpen.RuntimeException">
 /// the temporary file could not be written. The lock is released
 /// before throwing the underlying exception to the caller.
 /// </exception>
 public virtual void CopyCurrentContent()
 {
     RequireLock();
     try
     {
         FileInputStream fis = new FileInputStream(@ref);
         try
         {
             if (fsync)
             {
                 FileChannel @in = fis.GetChannel();
                 long pos = 0;
                 long cnt = @in.Size();
                 while (0 < cnt)
                 {
                     long r = os.GetChannel().TransferFrom(@in, pos, cnt);
                     pos += r;
                     cnt -= r;
                 }
             }
             else
             {
                 byte[] buf = new byte[2048];
                 int r;
                 while ((r = fis.Read(buf)) >= 0)
                 {
                     os.Write(buf, 0, r);
                 }
             }
         }
         finally
         {
             fis.Close();
         }
     }
     catch (FileNotFoundException)
     {
     }
     catch (IOException ioe)
     {
         // Don't worry about a file that doesn't exist yet, it
         // conceptually has no current content to copy.
         //
         Unlock();
         throw;
     }
     catch (RuntimeException ioe)
     {
         Unlock();
         throw;
     }
     catch (Error ioe)
     {
         Unlock();
         throw;
     }
 }
Beispiel #24
0
		/// <summary>Loads the script at the given URL.</summary>
		/// <remarks>Loads the script at the given URL.</remarks>
		private string LoadSource(string sourceUrl)
		{
			string source = null;
			int hash = sourceUrl.IndexOf('#');
			if (hash >= 0)
			{
				sourceUrl = Sharpen.Runtime.Substring(sourceUrl, 0, hash);
			}
			try
			{
				Stream @is;
				if (sourceUrl.IndexOf(':') < 0)
				{
					// Can be a file name
					try
					{
						if (sourceUrl.StartsWith("~/"))
						{
							string home = SecurityUtilities.GetSystemProperty("user.home");
							if (home != null)
							{
								string pathFromHome = Sharpen.Runtime.Substring(sourceUrl, 2);
								FilePath f = new FilePath(new FilePath(home), pathFromHome);
								if (f.Exists())
								{
									@is = new FileInputStream(f);
									goto openStream_break;
								}
							}
						}
						FilePath f_1 = new FilePath(sourceUrl);
						if (f_1.Exists())
						{
							@is = new FileInputStream(f_1);
							goto openStream_break;
						}
					}
					catch (SecurityException)
					{
					}
					// No existing file, assume missed http://
					if (sourceUrl.StartsWith("//"))
					{
						sourceUrl = "http:" + sourceUrl;
					}
					else
					{
						if (sourceUrl.StartsWith("/"))
						{
							sourceUrl = "http://127.0.0.1" + sourceUrl;
						}
						else
						{
							sourceUrl = "http://" + sourceUrl;
						}
					}
				}
				@is = (new Uri(sourceUrl)).OpenStream();
openStream_break: ;
				try
				{
					source = Kit.ReadReader(new StreamReader(@is));
				}
				finally
				{
					@is.Close();
				}
			}
			catch (IOException ex)
			{
				System.Console.Error.WriteLine("Failed to load source from " + sourceUrl + ": " + ex);
			}
			return source;
		}
 /// <exception cref="System.IO.IOException"></exception>
 public override void WriteTo(OutputStream @out)
 {
     if (@out == null)
     {
         throw new ArgumentException("Output stream may not be null");
     }
     InputStream @in = new FileInputStream(this.file);
     try
     {
         byte[] tmp = new byte[4096];
         int l;
         while ((l = @in.Read(tmp)) != -1)
         {
             @out.Write(tmp, 0, l);
         }
         @out.Flush();
     }
     finally
     {
         @in.Close();
     }
 }
Beispiel #26
0
        /// <exception cref="System.IO.IOException"></exception>
        private DirCacheEntry AddEntryToBuilder(string path, FilePath file, ObjectInserter
			 newObjectInserter, DirCacheBuilder builder, int stage)
        {
            FileInputStream inputStream = new FileInputStream(file);
            ObjectId id = newObjectInserter.Insert(Constants.OBJ_BLOB, file.Length(), inputStream
                );
            inputStream.Close();
            DirCacheEntry entry = new DirCacheEntry(path, stage);
            entry.SetObjectId(id);
            entry.FileMode = FileMode.REGULAR_FILE;
            entry.LastModified = file.LastModified();
            entry.SetLength((int)file.Length());
            builder.Add(entry);
            return entry;
        }
			/// <exception cref="System.IO.IOException"></exception>
			public override void WriteTo(OutputStream os, ProgressMonitor pm)
			{
				if (onDiskFile == null)
				{
					base.WriteTo(os, pm);
					return;
				}
				if (pm == null)
				{
					pm = NullProgressMonitor.INSTANCE;
				}
				FileInputStream @in = new FileInputStream(onDiskFile);
				try
				{
					int cnt;
					byte[] buf = new byte[TemporaryBuffer.Block.SZ];
					while ((cnt = @in.Read(buf)) >= 0)
					{
						os.Write(buf, 0, cnt);
						pm.Update(cnt / 1024);
					}
				}
				finally
				{
					@in.Close();
				}
			}
			/// <exception cref="System.IO.IOException"></exception>
			public override byte[] ToByteArray()
			{
				if (onDiskFile == null)
				{
					return base.ToByteArray();
				}
				long len = Length();
				if (int.MaxValue < len)
				{
					throw new OutOfMemoryException(JGitText.Get().lengthExceedsMaximumArraySize);
				}
				byte[] @out = new byte[(int)len];
				FileInputStream @in = new FileInputStream(onDiskFile);
				try
				{
					IOUtil.ReadFully(@in, @out, 0, (int)len);
				}
				finally
				{
					@in.Close();
				}
				return @out;
			}
 /// <exception cref="System.IO.IOException"></exception>
 private static byte[] GetBytesFromFile(FilePath file)
 {
     InputStream @is = new FileInputStream(file);
     // Get the size of the file
     long length = file.Length();
     // Create the byte array to hold the data
     byte[] bytes = new byte[(int)length];
     // Read in the bytes
     int offset = 0;
     int numRead = 0;
     while (offset < bytes.Length && (numRead = @is.Read(bytes, offset, bytes.Length -
          offset)) >= 0)
     {
         offset += numRead;
     }
     // Ensure all the bytes have been read in
     if (offset < bytes.Length)
     {
         throw new IOException("Could not completely read file " + file.GetName());
     }
     // Close the input stream and return bytes
     @is.Close();
     return bytes;
 }
 public static BlobKey KeyForBlobFromFile(FileInfo file)
 {
     MessageDigest md;
     try
     {
         md = MessageDigest.GetInstance("SHA-1");
     }
     catch (NoSuchAlgorithmException)
     {
         Log.E(Database.Tag, "Error, SHA-1 digest is unavailable.");
         return null;
     }
     byte[] sha1hash = new byte[40];
     try
     {
         var fis = new FileInputStream(file);
         byte[] buffer = new byte[65536];
         int lenRead = fis.Read(buffer);
         while (lenRead > 0)
         {
             md.Update(buffer, 0, lenRead);
             lenRead = fis.Read(buffer);
         }
         fis.Close();
     }
     catch (IOException)
     {
         Log.E(Database.Tag, "Error readin tmp file to compute key");
     }
     sha1hash = md.Digest();
     BlobKey result = new BlobKey(sha1hash);
     return result;
 }