public void CloseTest()
        {
            string           filePath = "RAFCloseTest.arr";
            RandomAccessFile target   = InitRAF(filePath);

            target.Close();

            Assert.IsTrue(File.Exists(filePath));

            target.Close();
        }
 /// <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);
     }
 }
        public void ReadFromStorageTest()
        {
            IStorage storage = new RandomAccessFile(File.Open("ReadFromStorage", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None));

            int size = 8;

            byte[] data = new byte[] { byte.MaxValue, byte.MinValue };
            ReadFromStorageTestAssert(storage, size, data);

            int size2 = 1000000;

            byte[] data2 = new byte[] { };
            ReadFromStorageTestAssert(storage, size2, data2);

            try
            {
                ReadFromStorageTestAssert(storage, -1, data2);
                Assert.Fail("Should throw exception");
            }
            catch (InvalidUserHeaderException) { }

            int size3 = 10;

            byte[] data3 = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ReadFromStorageTestAssert(storage, size3, data3);

            storage.Close();
        }
Ejemplo n.º 4
0
        public static byte[] ReadFileFromPath(File file)
        {
            // Open file
            var f = new RandomAccessFile(file, "r");

            try
            {
                // Get and check length
                var longlength = f.Length();
                var length     = (int)longlength;
                if (length != longlength)
                {
                    throw new IOException("Tamanho do arquivo excede o permitido!");
                }
                // Read file and return data
                var data = new byte[length];
                f.ReadFully(data);
                return(data);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
                return(null);
            }
            finally
            {
                f.Close();
                f.Dispose();
            }
        }
Ejemplo n.º 5
0
        public static RandomAccessFile NewRandomAccessFile(string path, bool readOnly, bool lockFile)
        {
            RandomAccessFile raf = null;
            var ok = false;

            try
            {
                raf = new RandomAccessFile(path, readOnly, lockFile);
                if (lockFile)
                {
                    Platform4.LockFile(path, raf);
                }
                ok = true;
                return(raf);
            }
            catch (IOException x)
            {
                if (new File(path).Exists())
                {
                    throw new DatabaseFileLockedException(path, x);
                }
                throw new Db4oIOException(x);
            }
            finally
            {
                if (!ok && raf != null)
                {
                    raf.Close();
                }
            }
        }
Ejemplo n.º 6
0
        public bool IsGZipped(BlobKey key)
        {
            int      magic = 0;
            string   path  = PathForKey(key);
            FilePath file  = new FilePath(path);

            if (file.CanRead())
            {
                try
                {
                    var raf = new RandomAccessFile(file, "r");
                    magic = raf.Read() & unchecked ((0xff)) | ((raf.Read() << 8) & unchecked ((0xff00)));
                    raf.Close();
                }
                catch (Exception e)
                {
                                        #if PORTABLE
                    Runtime.PrintStackTrace(e);
                                        #else
                    Runtime.PrintStackTrace(e, Console.Error);
                                        #endif
                }
            }
            return(magic == GZIPInputStream.GzipMagic);
        }
Ejemplo n.º 7
0
        public static byte [] readFile(Java.IO.File file)
        {
            // Open file
            var f = new RandomAccessFile(file, "r");

            try {
                // Get and check length
                long longlength = f.Length();
                var  length     = (int)longlength;

                if (length != longlength)
                {
                    throw new Java.IO.IOException("Filesize exceeds allowed size");
                }
                // Read file and return data
                byte [] data = new byte [length];
                f.ReadFully(data);
                return(data);
            } catch (Exception ex) {
                System.Diagnostics.Debug.Write(ex);
                return(new byte [0]);
            } finally {
                f.Close();
            }
        }
Ejemplo n.º 8
0
        public static byte[] readFile(File file)
        {
            // Open file
            var f = new RandomAccessFile(file, "r");

            try
            {
                // Get and check length
                long longlength = f.Length();
                var  length     = (int)longlength;

                if (length != longlength)
                {
                    throw new IOException("Filesize exceeds allowed size");
                }
                // Read file and return data
                byte[] data = new byte[length];
                f.ReadFully(data);
                return(data);
            }
            finally
            {
                f.Close();
            }
        }
Ejemplo n.º 9
0
        /// <summary>Truncate the given file to the given length</summary>
        /// <exception cref="System.IO.IOException"/>
        private void TruncateFile(FilePath logFile, long newLength)
        {
            RandomAccessFile raf = new RandomAccessFile(logFile, "rw");

            raf.SetLength(newLength);
            raf.Close();
        }
Ejemplo n.º 10
0
        /// <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();
        }
Ejemplo n.º 11
0
        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
        }
Ejemplo n.º 12
0
        public static byte[] readFile(Java.IO.File file)
        {
            // Open file
            RandomAccessFile f = new RandomAccessFile(file, "r");

            try
            {
                // Get and check length
                long longlength = f.Length();
                int  length     = (int)longlength;
                if (length != longlength)
                {
                    throw new Java.IO.IOException("Tamanho do arquivo excede o permitido!");
                }
                // Read file and return data
                byte[] data = new byte[length];
                f.ReadFully(data);
                return(data);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
                return(new byte[0]);
            }
            finally
            {
                f.Close();
            }
        }
Ejemplo n.º 13
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         try { file.Close(); }
         catch {}
     }
 }
        public void RandomAccessFileConstructorTest()
        {
            string           filePath = "RAFCtor.arr";
            RandomAccessFile target   = InitRAF(filePath);

            Assert.IsNotNull(target);

            target.Close();
        }
Ejemplo n.º 15
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void TestReadOnlyLocked()
        {
            byte[]           bytes = new byte[1];
            RandomAccessFile raf   = RandomAccessFileFactory.NewRandomAccessFile(TempFile(), true
                                                                                 , true);

            Assert.Expect(typeof(IOException), new _ICodeBlock_43(raf, bytes));
            raf.Close();
        }
Ejemplo n.º 16
0
 /// <exception cref="System.IO.IOException"></exception>
 private byte[] ReadAllBytes(string fileName)
 {
     var length = (int) new Sharpen.IO.File(fileName).Length();
     var raf = new RandomAccessFile(fileName, "rw");
     var buffer = new byte[length];
     raf.Read(buffer);
     raf.Close();
     return buffer;
 }
Ejemplo n.º 17
0
        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) {
            }
        }
Ejemplo n.º 18
0
            /// <exception cref="System.IO.IOException"/>
            public virtual void Corrupt(FilePath editFile)
            {
                // Corrupt the last edit
                long             fileLen = editFile.Length();
                RandomAccessFile rwf     = new RandomAccessFile(editFile, "rw");

                rwf.SetLength(fileLen - 1);
                rwf.Close();
            }
Ejemplo n.º 19
0
        //private static String readInstallationFile(File installation)
        //{
        //    RandomAccessFile f = new RandomAccessFile(installation, "r");
        //    byte[] bytes = new byte[(int)f.Length()];
        //    f.ReadFully(bytes);
        //    f.Close();
        //    return new Java.Lang.String(bytes).ToString();
        //}
        private static String readInstallationFile(Java.IO.File installation)
        {
            RandomAccessFile f = new RandomAccessFile(installation, "r");

            byte[] bytes = new byte[(int)f.Length()];
            f.ReadFully(bytes);
            f.Close();
            return(new Java.Lang.String(bytes).ToString());
        }
Ejemplo n.º 20
0
        private static string readInstallationFile(File installation)
        {
            RandomAccessFile f = new RandomAccessFile(installation, "r");

            byte[] bytes = new byte[(int)f.Length()];
            f.ReadFully(bytes);
            f.Close();
            System.Text.UTF8Encoding en = new UTF8Encoding();
            return(en.GetString(bytes));
        }
        public void SeekTest()
        {
            string           filePath = "RAFSeekTest.arr";
            RandomAccessFile target   = InitRAF(filePath);
            int position = 3;

            target.Seek(position);

            target.Close();
        }
Ejemplo n.º 22
0
        /// <exception cref="System.IO.IOException"></exception>
        private byte[] ReadAllBytes(string fileName)
        {
            var length = (int)new Sharpen.IO.File(fileName).Length();
            var raf    = new RandomAccessFile(fileName, "rw");
            var buffer = new byte[length];

            raf.Read(buffer);
            raf.Close();
            return(buffer);
        }
Ejemplo n.º 23
0
        internal async Task <double> AverageCpuUsage()
        {
            try
            {
                string coresPercent = System.String.Empty;

                double countCorePercent = 0;
                double averageUsage     = 0;
                double core             = 0;

                CpuCores = System.Environment.ProcessorCount;
                int coresCpu = CpuCores - 1;

                while (coresCpu > 0)
                {
                    using (RandomAccessFile scalingCurFreq = new RandomAccessFile($"/sys/devices/system/cpu/cpu{coresCpu}/cpufreq/scaling_cur_freq", "r"))
                    {
                        using (RandomAccessFile cpuInfoMaxFreq = new RandomAccessFile($"/sys/devices/system/cpu/cpu{coresCpu}/cpufreq/cpuinfo_max_freq", "r"))
                        {
                            string curfreg = await scalingCurFreq.ReadLineAsync();

                            string maxfreg = await cpuInfoMaxFreq.ReadLineAsync();

                            double currentFreq = double.Parse(curfreg) / 1000;
                            double maxFreq     = double.Parse(maxfreg) / 1000;

                            core = currentFreq * 100 / maxFreq;

                            cpuInfoMaxFreq.Close();
                        }

                        scalingCurFreq.Close();
                    }

                    countCorePercent += core;

                    coresPercent += $"core number {coresCpu}: {core}%\n";

                    coresCpu--;
                }

                averageUsage = countCorePercent / 100 * System.Environment.ProcessorCount;

                return(averageUsage);
            }
            catch (System.Exception ex)
            {
                #region Logging
                LogRuntimeAttribute.InLogFiles(typeof(PartLoadInfo), ex);
                #endregion

                return(0);
            }
            finally { }
        }
Ejemplo n.º 24
0
        public static void WritFile2(string fileName, byte[] data)
        {
            if (data == null && data.Length > 0)
            {
                return;
            }
            Java.IO.File file2 = new Java.IO.File(PATH);
            if (!file2.Exists())
            {
                bool rss = file2.Mkdirs();
            }
            string filePath = PATH + fileName;

            Java.IO.File file = new Java.IO.File(filePath);
            if (!file.Exists())
            {
                try
                {
                    // String aaa=    mkdirs2(PATH);

                    file.CreateNewFile();
                    Runtime runtime = Runtime.GetRuntime();
                    runtime.Exec("chmod 0666 " + file);
                }
                catch (Java.Lang.Exception ex)
                {
                    ex.PrintStackTrace();
                }
            }
            RandomAccessFile randomAccessFile = null;

            try
            {
                randomAccessFile = new RandomAccessFile(filePath, "rw");
                randomAccessFile.Write(data);
            }
            catch (Java.Lang.Exception e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                try
                {
                    if (randomAccessFile != null)
                    {
                        randomAccessFile.Close();
                    }
                }
                catch (Java.Lang.Exception e)
                {
                }
            }
        }
Ejemplo n.º 25
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void TestLockDatabaseFileFalse()
        {
            IObjectContainer container = OpenObjectContainer(false);
            RandomAccessFile raf       = RandomAccessFileFactory.NewRandomAccessFile(TempFile(), false
                                                                                     , false);

            byte[] bytes = new byte[1];
            raf.Read(bytes);
            raf.Close();
            container.Close();
        }
 public virtual void DeleteTempFile()
 {
     if (_tempFile == null && _randomAccessFile == null)
     {
         return;
     }
     _randomAccessFile.Close();
     Sharpen.Tests.IsTrue("Unable to delete temp file used during unit test: " + _tempFile.GetAbsolutePath(), _tempFile.Delete());
     _tempFile         = null;
     _randomAccessFile = null;
 }
Ejemplo n.º 27
0
        /// <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();
        }
Ejemplo n.º 28
0
        public static PsdHeaderDirectory ProcessBytes(string file)
        {
            Com.Drew.Metadata.Metadata metadata         = new Com.Drew.Metadata.Metadata();
            RandomAccessFile           randomAccessFile = new RandomAccessFile(new FilePath(file), "r");

            new PsdReader().Extract(new RandomAccessFileReader(randomAccessFile), metadata);
            randomAccessFile.Close();
            PsdHeaderDirectory directory = metadata.GetDirectory <PsdHeaderDirectory>();

            NUnit.Framework.Assert.IsNotNull(directory);
            return(directory);
        }
Ejemplo n.º 29
0
        /// <exception cref="System.IO.IOException"></exception>
        public static byte FileHeaderVersion(string testFile)
        {
            RandomAccessFile raf = new RandomAccessFile(testFile, "r");

            byte[] bytes = new byte[1];
            raf.Read(bytes);
            // readByte() doesn't convert to .NET.
            byte db4oHeaderVersion = bytes[0];

            raf.Close();
            return(db4oHeaderVersion);
        }
Ejemplo n.º 30
0
            /// <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();
            }
Ejemplo n.º 31
0
        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()));
            }
        }
Ejemplo n.º 32
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual int WriteVersions(string file, bool writeTrash)
 {
     var count = 0;
     var rcount = 0;
     var lastFileName = file + "0";
     var rightFileName = file + "R";
     File4.Copy(lastFileName, rightFileName);
     var syncIter = _writes.GetEnumerator();
     while (syncIter.MoveNext())
     {
         rcount++;
         var writesBetweenSync = (Collection4) syncIter.Current;
         var rightRaf = new RandomAccessFile(rightFileName, "rw");
         var singleForwardIter = writesBetweenSync.GetEnumerator();
         while (singleForwardIter.MoveNext())
         {
             var csw = (CrashSimulatingWrite) singleForwardIter.Current;
             csw.Write(rightFileName, rightRaf, false);
         }
         rightRaf.Close();
         var singleBackwardIter = writesBetweenSync.GetEnumerator();
         while (singleBackwardIter.MoveNext())
         {
             count++;
             var csw = (CrashSimulatingWrite) singleBackwardIter.Current;
             var currentFileName = file + "W" + count;
             File4.Copy(lastFileName, currentFileName);
             var raf = new RandomAccessFile(currentFileName, "rw");
             csw.Write(currentFileName, raf, writeTrash);
             raf.Close();
             lastFileName = currentFileName;
         }
         File4.Copy(rightFileName, rightFileName + rcount);
         lastFileName = rightFileName;
     }
     return count;
 }