/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception> public override void Close() { // FIXME: This is a temporary quickfix for a bug in Android. // Remove after Android has been fixed. try { if (_delegate != null) { _delegate.Seek(0); } } catch (IOException) { } // ignore Platform4.UnlockFile(_path, _delegate); try { if (_delegate != null) { _delegate.Close(); } } catch (IOException e) { throw new Db4oIOException(e); } }
/// <exception cref="System.IO.IOException"></exception> protected internal override PackParser.ObjectTypeAndSize SeekDatabase(PackParser.UnresolvedDelta delta, PackParser.ObjectTypeAndSize info) { @out.Seek(delta.GetOffset()); crc.Reset(); return(ReadObjectHeader(info)); }
/// <exception cref="System.IO.IOException"/> public static FsImageProto.FileSummary LoadSummary(RandomAccessFile file) { int FileLengthFieldSize = 4; long fileLength = file.Length(); file.Seek(fileLength - FileLengthFieldSize); int summaryLength = file.ReadInt(); if (summaryLength <= 0) { throw new IOException("Negative length of the file"); } file.Seek(fileLength - FileLengthFieldSize - summaryLength); byte[] summaryBytes = new byte[summaryLength]; file.ReadFully(summaryBytes); FsImageProto.FileSummary summary = FsImageProto.FileSummary.ParseDelimitedFrom(new ByteArrayInputStream(summaryBytes)); if (summary.GetOndiskVersion() != FileVersion) { throw new IOException("Unsupported file version " + summary.GetOndiskVersion()); } if (!NameNodeLayoutVersion.Supports(LayoutVersion.Feature.ProtobufFormat, summary .GetLayoutVersion())) { throw new IOException("Unsupported layout version " + summary.GetLayoutVersion()); } return(summary); }
/// <exception cref="System.IO.IOException"></exception> internal virtual ByteArrayWindow Read(long pos, int size) { lock (readLock) { if (length < pos + size) { size = (int)(length - pos); } byte[] buf = new byte[size]; fd.Seek(pos); fd.ReadFully(buf, 0, size); return(new ByteArrayWindow(this, pos, buf)); } }
/// <summary> /// Corrupt the byte at the given offset in the given file, /// by subtracting 1 from it. /// </summary> /// <exception cref="System.IO.IOException"/> private void CorruptByteInFile(FilePath file, long offset) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); try { raf.Seek(offset); int origByte = raf.Read(); raf.Seek(offset); raf.WriteByte(origByte - 1); } finally { IOUtils.CloseStream(raf); } }
/// <summary> /// Set the position of this stream. /// </summary> /// <param name="offset">Byte offset relative to origin.</param> /// <param name="origin">Reference point.</param> /// <returns>New position of the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { long target; switch (origin) { case SeekOrigin.Current: target = Position + offset; break; case SeekOrigin.Begin: target = offset; break; case SeekOrigin.End: target = file.Length() + offset; break; default: throw new ArgumentException("Invalid origin"); } if ((target < 0) || (target > file.Length())) { throw new IOException("Seek outside file limits"); } file.Seek(target); return(Position); }
public void SaveAnchor(byte[] anchor) { #if SILVERLIGHT if (this.UseElevatedTrust) { string filePath = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc"; FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); file.Seek(0, SeekOrigin.Begin); file.Write(anchor, 0, anchor.Length); file.Close(); } else { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream phisicalFile = new IsolatedStorageFileStream(siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc", FileMode.OpenOrCreate, FileAccess.ReadWrite, isf); phisicalFile.Seek(0, SeekOrigin.Begin); phisicalFile.Write(anchor, 0, anchor.Length); phisicalFile.Close(); } #elif MONODROID string filePath = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc"; RandomAccessFile file = new RandomAccessFile(filePath, "rw"); file.Seek(0); file.Write(anchor, 0, anchor.Length); file.Close(); #else string filePath = siaqodb.GetDBPath() + System.IO.Path.DirectorySeparatorChar + "anchor_" + CacheController.ControllerBehavior.ScopeName + ".anc"; FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); file.Seek(0, SeekOrigin.Begin); file.Write(anchor, 0, anchor.Length); file.Close(); #endif }
/// <summary> /// Create a FileInputStream that shares delete permission on the /// file opened at a given offset, i.e. /// </summary> /// <remarks> /// Create a FileInputStream that shares delete permission on the /// file opened at a given offset, i.e. other process can delete /// the file the FileInputStream is reading. Only Windows implementation /// uses the native interface. /// </remarks> /// <exception cref="System.IO.IOException"/> public static FileInputStream GetShareDeleteFileInputStream(FilePath f, long seekOffset ) { if (!Shell.Windows) { RandomAccessFile rf = new RandomAccessFile(f, "r"); if (seekOffset > 0) { rf.Seek(seekOffset); } return(new FileInputStream(rf.GetFD())); } else { // Use Windows native interface to create a FileInputStream that // shares delete permission on the file opened, and set it to the // given offset. // FileDescriptor fd = NativeIO.Windows.CreateFile(f.GetAbsolutePath(), NativeIO.Windows .GenericRead, NativeIO.Windows.FileShareRead | NativeIO.Windows.FileShareWrite | NativeIO.Windows.FileShareDelete, NativeIO.Windows.OpenExisting); if (seekOffset > 0) { NativeIO.Windows.SetFilePointer(fd, seekOffset, NativeIO.Windows.FileBegin); } return(new FileInputStream(fd)); } }
public double GetCpuTemp() { if (cpuTempFile == null) { throw new NotSupportedException("CPU Temp not available"); } cpuTempFile.Seek(0); var s = cpuTempFile?.ReadLine(); if (string.IsNullOrWhiteSpace(s)) { throw new NotSupportedException("CPU Temp not available"); } double val; if (!double.TryParse(s, out val)) { throw new NotSupportedException("CPU Temp not available"); } if (val < -30 || val > 300) { val = val / 1000; } return(val); }
/// <summary> /// Calculate the md5sum of an image after zeroing out the transaction ID /// field in the header. /// </summary> /// <remarks> /// Calculate the md5sum of an image after zeroing out the transaction ID /// field in the header. This is useful for tests that want to verify /// that two checkpoints have identical namespaces. /// </remarks> /// <exception cref="System.IO.IOException"/> public static string GetImageFileMD5IgnoringTxId(FilePath imageFile) { FilePath tmpFile = FilePath.CreateTempFile("hadoop_imagefile_tmp", "fsimage"); tmpFile.DeleteOnExit(); try { Files.Copy(imageFile, tmpFile); RandomAccessFile raf = new RandomAccessFile(tmpFile, "rw"); try { raf.Seek(ImageTxidPos); raf.WriteLong(0); } finally { IOUtils.CloseStream(raf); } return(GetFileMD5(tmpFile)); } finally { tmpFile.Delete(); } }
/// <exception cref="Db4objects.Db4o.Ext.Db4oIOException"></exception> protected RandomAccessFileAdapter(string path, bool lockFile, long initialLength, bool readOnly) { bool ok = false; try { _path = new Sharpen.IO.File(path).GetCanonicalPath(); _delegate = RandomAccessFileFactory.NewRandomAccessFile(_path, readOnly, lockFile ); if (initialLength > 0) { _delegate.Seek(initialLength - 1); _delegate.Write(new byte[] { 0 }); } ok = true; } catch (IOException e) { throw new Db4oIOException(e); } finally { if (!ok) { Close(); } } }
/// <exception cref="System.IO.IOException"/> private void CheckFileCorruption(LocalFileSystem fileSys, Path file, Path fileToCorrupt ) { // corrupt the file RandomAccessFile @out = new RandomAccessFile(new FilePath(fileToCorrupt.ToString( )), "rw"); byte[] buf = new byte[(int)fileSys.GetFileStatus(file).GetLen()]; int corruptFileLen = (int)fileSys.GetFileStatus(fileToCorrupt).GetLen(); NUnit.Framework.Assert.IsTrue(buf.Length >= corruptFileLen); rand.NextBytes(buf); @out.Seek(corruptFileLen / 2); @out.Write(buf, 0, corruptFileLen / 4); @out.Close(); bool gotException = false; InputStream @in = fileSys.Open(file); try { IOUtils.ReadFully(@in, buf, 0, buf.Length); } catch (ChecksumException) { gotException = true; } NUnit.Framework.Assert.IsTrue(gotException); @in.Close(); }
/// <summary>Read the header at the beginning of the given block meta file.</summary> /// <remarks> /// Read the header at the beginning of the given block meta file. /// The current file position will be altered by this method. /// If an error occurs, the file is <em>not</em> closed. /// </remarks> /// <exception cref="System.IO.IOException"/> public static Org.Apache.Hadoop.Hdfs.Server.Datanode.BlockMetadataHeader ReadHeader (RandomAccessFile raf) { byte[] buf = new byte[GetHeaderSize()]; raf.Seek(0); raf.ReadFully(buf, 0, buf.Length); return(ReadHeader(new DataInputStream(new ByteArrayInputStream(buf)))); }
/// <exception cref="System.IO.IOException"></exception> internal virtual void Seek(long pos) { if (DTrace.enabled) { DTrace.RegularSeek.Log(pos); } _file.Seek(pos); }
public virtual void TestWriteFully() { int InputBufferLen = 10000; int Halfway = 1 + (InputBufferLen / 2); byte[] input = new byte[InputBufferLen]; for (int i = 0; i < input.Length; i++) { input[i] = unchecked ((byte)(i & unchecked ((int)(0xff)))); } byte[] output = new byte[input.Length]; try { RandomAccessFile raf = new RandomAccessFile(TestFileName, "rw"); FileChannel fc = raf.GetChannel(); ByteBuffer buf = ByteBuffer.Wrap(input); IOUtils.WriteFully(fc, buf); raf.Seek(0); raf.Read(output); for (int i_1 = 0; i_1 < input.Length; i_1++) { Assert.Equal(input[i_1], output[i_1]); } buf.Rewind(); IOUtils.WriteFully(fc, buf, Halfway); for (int i_2 = 0; i_2 < Halfway; i_2++) { Assert.Equal(input[i_2], output[i_2]); } raf.Seek(0); raf.Read(output); for (int i_3 = Halfway; i_3 < input.Length; i_3++) { Assert.Equal(input[i_3 - Halfway], output[i_3]); } } finally { FilePath f = new FilePath(TestFileName); if (f.Exists()) { f.Delete(); } } }
/// <exception cref="System.IO.IOException"/> private void Seek(int index) { if (index == _currentIndex) { return; } _file.Seek(index); _currentIndex = index; }
private static void ReadUsage() { try { var topActivity = TinyIoC.TinyIoCContainer.Current.Resolve <IMvxAndroidCurrentTopActivity> (); RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); string load = reader.ReadLine(); string[] toks = load.Split(' '); long idle1 = long.Parse(toks [5]); long cpu1 = long.Parse(toks [2]) + long.Parse(toks [3]) + long.Parse(toks [4]) + long.Parse(toks [6]) + long.Parse(toks [7]) + long.Parse(toks [8]); try { Thread.Sleep(360); } catch (Exception) { } reader.Seek(0); load = reader.ReadLine(); reader.Close(); toks = load.Split(' '); float idle2 = float.Parse(toks [5]); float cpu2 = float.Parse(toks [2]) + float.Parse(toks [3]) + float.Parse(toks [4]) + float.Parse(toks [6]) + float.Parse(toks [7]) + float.Parse(toks [8]); float cpuValue = ((cpu2 - cpu1) * 100f / ((cpu2 + idle2) - (cpu1 + idle1))); CpuStack [_cpuStackPointer++] = cpuValue; if (_cpuStackPointer == 10) { _cpuStackPointer = 0; } var averageTxt = ((int)CpuStack.Take(10).Average()).ToString().PadLeft(2, '0'); TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1)); // Get VM Heap Size by calling: var heapSize = (Java.Lang.Runtime.GetRuntime().TotalMemory() / 1000).ToString().PadLeft(6, '0'); // Get Allocated VM Memory by calling: var allocated = ((Java.Lang.Runtime.GetRuntime().TotalMemory() - Java.Lang.Runtime.GetRuntime().FreeMemory()) / 1000).ToString().PadLeft(6, '0'); // Get Free Memory var free = (Java.Lang.Runtime.GetRuntime().FreeMemory() / 1000).ToString().PadLeft(6, '0'); // Get VM Heap Size Limit by calling: var heapSizeLimit = (Java.Lang.Runtime.GetRuntime().MaxMemory() / 1000).ToString().PadLeft(6, '0'); var mem = heapSize + " " + allocated + " " + free + " " + heapSizeLimit; System.Console.WriteLine("-|-cpu " + (((long)t.TotalSeconds * 1000L) + (long)DateTime.Now.Millisecond).ToString() + " " + averageTxt + " " + mem + " " + topActivity.Activity.Title); } catch (System.IO.IOException) { } }
public void SeekTest() { string filePath = "RAFSeekTest.arr"; RandomAccessFile target = InitRAF(filePath); int position = 3; target.Seek(position); target.Close(); }
public void WriteTxtToFile(string buffer, bool append) { Log.Info(Tag, "writeTxtToFile strFilePath =" + Path); RandomAccessFile raf = null; FileOutputStream outStream = null; try { File dir = new File(Path); if (!dir.Exists()) { dir.Mkdirs(); } File file = new File(Path + "/" + "Result.txt"); if (!file.Exists()) { file.CreateNewFile(); } if (append) { raf = new RandomAccessFile(file, "rw"); raf.Seek(file.Length()); raf.Write(Encoding.ASCII.GetBytes(buffer)); } else { outStream = new FileOutputStream(file); outStream.Write(Encoding.ASCII.GetBytes(buffer)); outStream.Flush(); } } catch (IOException e) { Log.Error(Tag, e.Message); } finally { try { if (raf != null) { raf.Close(); } if (outStream != null) { outStream.Close(); } } catch (IOException e) { Log.Error(Tag, e.Message); } } }
/// <summary> /// Open a random access file for the given path, more and access. /// </summary> private static RandomAccessFile Open(string path, FileMode mode, FileAccess access) { var file = new Java.Io.File(path); switch (mode) { case FileMode.CreateNew: if (file.Exists()) { throw new IOException("File already exists"); } break; case FileMode.Open: if (!file.Exists()) { throw new FileNotFoundException(path); } break; case FileMode.Append: access = FileAccess.Write; break; } switch (mode) { case FileMode.Create: case FileMode.CreateNew: case FileMode.OpenOrCreate: if (access == FileAccess.Read) { //create empty file, so it can be opened again with read only right, //otherwise an FilNotFoundException is thrown. var additinalAccessFile = new RandomAccessFile(file, "rw"); } break; } var jMode = (access == FileAccess.Read) ? "r" : "rw"; var randomAccessFile = new RandomAccessFile(file, jMode); switch (mode) { case FileMode.Truncate: randomAccessFile.SetLength(0); break; case FileMode.Append: randomAccessFile.Seek(randomAccessFile.Length()); break; } return(randomAccessFile); }
/// <summary>Corrupt an edit log file after the start segment transaction</summary> /// <exception cref="System.IO.IOException"/> private void CorruptAfterStartSegment(FilePath f) { RandomAccessFile raf = new RandomAccessFile(f, "rw"); raf.Seek(unchecked ((int)(0x20))); // skip version and first tranaction and a bit of next transaction for (int i = 0; i < 1000; i++) { raf.WriteInt(unchecked ((int)(0xdeadbeef))); } raf.Close(); }
/// <exception cref="System.IO.IOException"></exception> public virtual void Write(string path, RandomAccessFile raf, bool writeTrash) { if (_offset == 0) { writeTrash = false; } raf.Seek(_offset); raf.Write(BytesToWrite(_data, writeTrash), 0, _length); Write(FileBasedTransactionLogHandler.LockFileName(path), _lockFileData, writeTrash ); Write(FileBasedTransactionLogHandler.LogFileName(path), _logFileData, writeTrash); }
/// <exception cref="System.IO.IOException"/> public virtual void Corrupt(FilePath editFile) { // Add junk to the end of the file RandomAccessFile rwf = new RandomAccessFile(editFile, "rw"); rwf.Seek(editFile.Length()); rwf.Write(unchecked ((byte)-1)); for (int i = 0; i < 1024; i++) { rwf.Write(padByte); } rwf.Close(); }
public virtual void TestDisplayRecentEditLogOpCodes() { // start a cluster Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; FileSystem fileSys = null; cluster = new MiniDFSCluster.Builder(conf).NumDataNodes(NumDataNodes).EnableManagedDfsDirsRedundancy (false).Build(); cluster.WaitActive(); fileSys = cluster.GetFileSystem(); FSNamesystem namesystem = cluster.GetNamesystem(); FSImage fsimage = namesystem.GetFSImage(); for (int i = 0; i < 20; i++) { fileSys.Mkdirs(new Path("/tmp/tmp" + i)); } Storage.StorageDirectory sd = fsimage.GetStorage().DirIterator(NNStorage.NameNodeDirType .Edits).Next(); cluster.Shutdown(); FilePath editFile = FSImageTestUtil.FindLatestEditsLog(sd).GetFile(); NUnit.Framework.Assert.IsTrue("Should exist: " + editFile, editFile.Exists()); // Corrupt the edits file. long fileLen = editFile.Length(); RandomAccessFile rwf = new RandomAccessFile(editFile, "rw"); rwf.Seek(fileLen - 40); for (int i_1 = 0; i_1 < 20; i_1++) { rwf.Write(FSEditLogOpCodes.OpDelete.GetOpCode()); } rwf.Close(); StringBuilder bld = new StringBuilder(); bld.Append("^Error replaying edit log at offset \\d+. "); bld.Append("Expected transaction ID was \\d+\n"); bld.Append("Recent opcode offsets: (\\d+\\s*){4}$"); try { cluster = new MiniDFSCluster.Builder(conf).NumDataNodes(NumDataNodes).EnableManagedDfsDirsRedundancy (false).Format(false).Build(); NUnit.Framework.Assert.Fail("should not be able to start"); } catch (IOException e) { NUnit.Framework.Assert.IsTrue("error message contains opcodes message", e.Message .Matches(bld.ToString())); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: @Override public int readAt(long position, byte[] buffer, int offset, int size) throws java.io.IOException public int ReadAt(long position, byte[] buffer, int offset, int size) { if (mFile.FilePointer != position) { mFile.Seek(position); } if (size == 0) { return(0); } return(mFile.Read(buffer, 0, size)); }
/// <exception cref="System.IO.IOException"/> private void LoadData() { Preconditions.CheckState(data == null); byte[] rawData = new byte[count]; raf.Seek(dumpFileOffset); int size = raf.Read(rawData, 0, count); if (size != count) { throw new IOException("Data count is " + count + ", but read back " + size + "bytes" ); } data = ByteBuffer.Wrap(rawData); }
public void ReadByteTest() { string filePath = "RAFReadByteTest.arr"; RandomAccessFile target = InitRAF(filePath); byte expected = 88; target.WriteByte(expected); target.Seek(0); byte actual = target.ReadByte(); Assert.AreEqual(expected, actual); target.Close(); }
public void WriteByteTest() { string filePath = "WriteByteTest.arr"; RandomAccessFile target = InitRAF(filePath); byte b = 7; target.WriteByte(b); target.Seek(0); byte actual = target.ReadByte(); Assert.AreEqual(b, actual); target.Close(); }
public void WriteIntTest() { string filePath = "RAFWriteIntTest.arr"; RandomAccessFile target = InitRAF(filePath); int expected = 300; target.WriteInt(expected); target.Seek(0); int actual = target.ReadInt(); Assert.AreEqual(expected, actual); target.Close(); }
private void appendFileData(SaveData data) { RandomAccessFile randomAccessFile; try { randomAccessFile = new RandomAccessFile(lastSaveFile.AbsolutePath, "rw"); long length = randomAccessFile.Length(); randomAccessFile.Seek(length); randomAccessFile.Write(data.NeedParseData, data.OffSet, data.PlayoffSize); } catch (Exception) { } }
/// <summary> /// Open a random access file for the given path, more and access. /// </summary> private static RandomAccessFile Open(string path, FileMode mode, FileAccess access) { var file = new Java.Io.File(path); switch (mode) { case FileMode.CreateNew: if (file.Exists()) throw new IOException("File already exists"); break; case FileMode.Open: if (!file.Exists()) throw new FileNotFoundException(path); break; case FileMode.Append: access = FileAccess.Write; break; } switch (mode) { case FileMode.Create: case FileMode.CreateNew: case FileMode.OpenOrCreate: if (access == FileAccess.Read) { //create empty file, so it can be opened again with read only right, //otherwise an FilNotFoundException is thrown. var additinalAccessFile = new RandomAccessFile(file, "rw"); } break; } var jMode = (access == FileAccess.Read) ? "r" : "rw"; var randomAccessFile = new RandomAccessFile(file, jMode); switch (mode) { case FileMode.Truncate: randomAccessFile.SetLength(0); break; case FileMode.Append: randomAccessFile.Seek(randomAccessFile.Length()); break; } return randomAccessFile; }