Esempio n. 1
0
 // TODO dispose pattern
 public void Dispose()
 {
     if (Channel != null)
     {
         Channel.Close();
     }
 }
Esempio n. 2
0
        /// <summary>
        /// Close all the files.
        /// </summary>
        /// <exception cref="SecurityException">  if a security manager exists and if
        ///             the caller does not have <tt>LoggingPermission("control")</tt>. </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public synchronized void close() throws SecurityException
        public override void Close()
        {
            lock (this)
            {
                base.Close();
                // Unlock any lock file.
                if (LockFileName == null)
                {
                    return;
                }
                try
                {
                    // Close the lock file channel (which also will free any locks)
                    LockFileChannel.Close();
                }
                catch (Exception)
                {
                    // Problems closing the stream.  Punt.
                }
                lock (Locks)
                {
                    Locks.Remove(LockFileName);
                }
                if (System.IO.Directory.Exists(LockFileName))
                {
                    System.IO.Directory.Delete(LockFileName, true);
                }
                else
                {
                    System.IO.File.Delete(LockFileName);
                }
                LockFileName    = null;
                LockFileChannel = null;
            }
        }
Esempio n. 3
0
 /// <exception cref="System.IO.IOException"/>
 public override void Close()
 {
     if (fp == null)
     {
         throw new IOException("Trying to use aborted output stream");
     }
     try
     {
         // close should have been called after all pending transactions
         // have been flushed & synced.
         // if already closed, just skip
         if (doubleBuf != null)
         {
             doubleBuf.Close();
             doubleBuf = null;
         }
         // remove any preallocated padding bytes from the transaction log.
         if (fc != null && fc.IsOpen())
         {
             fc.Truncate(fc.Position());
             fc.Close();
             fc = null;
         }
         fp.Close();
         fp = null;
     }
     finally
     {
         IOUtils.Cleanup(Log, fc, fp);
         doubleBuf = null;
         fc        = null;
         fp        = null;
     }
     fp = null;
 }
Esempio n. 4
0
        static long CopyFileStream(FileInputStream @is, FileOutputStream os)
        {
            FileChannel srcChannel  = null;
            FileChannel destChannel = null;
            long        length;

            try
            {
                srcChannel  = @is.Channel;
                destChannel = os.Channel;
                length      = srcChannel.TransferTo(0L, srcChannel.Size(), destChannel);
            }
            finally
            {
                if (srcChannel != null)
                {
                    srcChannel.Close();
                }
                if (destChannel != null)
                {
                    destChannel.Close();
                }
            }
            return(length);
        }
Esempio n. 5
0
        /// <exception cref="System.Exception"/>
        public virtual void TestMlock()
        {
            Assume.AssumeTrue(NativeIO.IsAvailable());
            FilePath TestFile = new FilePath(new FilePath(Runtime.GetProperty("test.build.data"
                                                                              , "build/test/data")), "testMlockFile");
            int BufLen = 12289;

            byte[] buf    = new byte[BufLen];
            int    bufSum = 0;

            for (int i = 0; i < buf.Length; i++)
            {
                buf[i]  = unchecked ((byte)(i % 60));
                bufSum += buf[i];
            }
            FileOutputStream fos = new FileOutputStream(TestFile);

            try
            {
                fos.Write(buf);
                fos.GetChannel().Force(true);
            }
            finally
            {
                fos.Close();
            }
            FileInputStream fis     = null;
            FileChannel     channel = null;

            try
            {
                // Map file into memory
                fis     = new FileInputStream(TestFile);
                channel = fis.GetChannel();
                long             fileSize = channel.Size();
                MappedByteBuffer mapbuf   = channel.Map(FileChannel.MapMode.ReadOnly, 0, fileSize);
                // mlock the buffer
                NativeIO.POSIX.Mlock(mapbuf, fileSize);
                // Read the buffer
                int sum = 0;
                for (int i_1 = 0; i_1 < fileSize; i_1++)
                {
                    sum += mapbuf.Get(i_1);
                }
                Assert.Equal("Expected sums to be equal", bufSum, sum);
                // munmap the buffer, which also implicitly unlocks it
                NativeIO.POSIX.Munmap(mapbuf);
            }
            finally
            {
                if (channel != null)
                {
                    channel.Close();
                }
                if (fis != null)
                {
                    fis.Close();
                }
            }
        }
Esempio n. 6
0
 /// <exception cref="System.IO.IOException"/>
 public virtual void Close()
 {
     if (ch != null)
     {
         ch.Close();
         ch = null;
     }
 }
Esempio n. 7
0
        /// <summary>
        /// Closes this file input stream and releases any system resources
        /// associated with the stream.
        ///
        /// <para> If this stream has an associated channel then the channel is closed
        /// as well.
        ///
        /// </para>
        /// </summary>
        /// <exception cref="IOException">  if an I/O error occurs.
        ///
        /// @revised 1.4
        /// @spec JSR-51 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void close() throws IOException
        public override void Close()
        {
            lock (CloseLock)
            {
                if (Closed)
                {
                    return;
                }
                Closed = true;
            }
            if (Channel_Renamed != null)
            {
                Channel_Renamed.Close();
            }

            Fd.CloseAll(new CloseableAnonymousInnerClassHelper(this));
        }
        /// <summary>Write content of index to disk.</summary>
        /// <remarks>Write content of index to disk.</remarks>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual void Write()
        {
            CheckWriteOk();
            FilePath tmpIndex = new FilePath(cacheFile.GetAbsoluteFile() + ".tmp");
            FilePath Lock     = new FilePath(cacheFile.GetAbsoluteFile() + ".lock");

            if (!Lock.CreateNewFile())
            {
                throw new IOException(JGitText.Get().indexFileIsInUse);
            }
            try
            {
                FileOutputStream fileOutputStream = new FileOutputStream(tmpIndex);
                FileChannel      fc  = fileOutputStream.GetChannel();
                ByteBuffer       buf = ByteBuffer.Allocate(4096);
                MessageDigest    newMessageDigest = Constants.NewMessageDigest();
                header = new GitIndex.Header(entries);
                header.Write(buf);
                buf.Flip();
                newMessageDigest.Update(((byte[])buf.Array()), buf.ArrayOffset(), buf.Limit());
                fc.Write(buf);
                buf.Flip();
                buf.Clear();
                for (Iterator i = entries.Values.Iterator(); i.HasNext();)
                {
                    GitIndex.Entry e = (GitIndex.Entry)i.Next();
                    e.Write(buf);
                    buf.Flip();
                    newMessageDigest.Update(((byte[])buf.Array()), buf.ArrayOffset(), buf.Limit());
                    fc.Write(buf);
                    buf.Flip();
                    buf.Clear();
                }
                buf.Put(newMessageDigest.Digest());
                buf.Flip();
                fc.Write(buf);
                fc.Close();
                fileOutputStream.Close();
                if (cacheFile.Exists())
                {
                    if (db.FileSystem.RetryFailedLockFileCommit())
                    {
                        // file deletion fails on windows if another
                        // thread is reading the file concurrently
                        // So let's try 10 times...
                        bool deleted = false;
                        for (int i_1 = 0; i_1 < 10; i_1++)
                        {
                            if (cacheFile.Delete())
                            {
                                deleted = true;
                                break;
                            }
                            try
                            {
                                Sharpen.Thread.Sleep(100);
                            }
                            catch (Exception)
                            {
                            }
                        }
                        // ignore
                        if (!deleted)
                        {
                            throw new IOException(JGitText.Get().couldNotRenameDeleteOldIndex);
                        }
                    }
                    else
                    {
                        if (!cacheFile.Delete())
                        {
                            throw new IOException(JGitText.Get().couldNotRenameDeleteOldIndex);
                        }
                    }
                }
                if (!tmpIndex.RenameTo(cacheFile))
                {
                    throw new IOException(JGitText.Get().couldNotRenameTemporaryIndexFileToIndex);
                }
                changed       = false;
                statDirty     = false;
                lastCacheTime = cacheFile.LastModified();
                db.FireEvent(new IndexChangedEvent());
            }
            finally
            {
                if (!Lock.Delete())
                {
                    throw new IOException(JGitText.Get().couldNotDeleteLockFileShouldNotHappen);
                }
                if (tmpIndex.Exists() && !tmpIndex.Delete())
                {
                    throw new IOException(JGitText.Get().couldNotDeleteTemporaryIndexFileShouldNotHappen
                                          );
                }
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Open the set of output files, based on the configured
        /// instance variables.
        /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void openFiles() throws java.io.IOException
        private void OpenFiles()
        {
            LogManager manager = LogManager.LogManager;

            manager.CheckPermission();
            if (Count < 1)
            {
                throw new IllegalArgumentException("file count = " + Count);
            }
            if (Limit < 0)
            {
                Limit = 0;
            }

            // We register our own ErrorManager during initialization
            // so we can record exceptions.
            InitializationErrorManager em = new InitializationErrorManager();

            ErrorManager = em;

            // Create a lock file.  This grants us exclusive access
            // to our set of output files, as long as we are alive.
            int unique = -1;

            for (;;)
            {
                unique++;
                if (unique > MAX_LOCKS)
                {
                    throw new IOException("Couldn't get lock for " + Pattern);
                }
                // Generate a lock file name from the "unique" int.
                LockFileName = Generate(Pattern, 0, unique).ToString() + ".lck";
                // Now try to lock that filename.
                // Because some systems (e.g., Solaris) can only do file locks
                // between processes (and not within a process), we first check
                // if we ourself already have the file locked.
                lock (Locks)
                {
                    if (Locks.Contains(LockFileName))
                    {
                        // We already own this lock, for a different FileHandler
                        // object.  Try again.
                        continue;
                    }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.nio.file.Path lockFilePath = java.nio.file.Paths.get(lockFileName);
                    Path        lockFilePath = Paths.Get(LockFileName);
                    FileChannel channel      = null;
                    int         retries      = -1;
                    bool        fileCreated  = false;
                    while (channel == null && retries++ < 1)
                    {
                        try
                        {
                            channel     = FileChannel.Open(lockFilePath, CREATE_NEW, WRITE);
                            fileCreated = true;
                        }
                        catch (FileAlreadyExistsException)
                        {
                            // This may be a zombie file left over by a previous
                            // execution. Reuse it - but only if we can actually
                            // write to its directory.
                            // Note that this is a situation that may happen,
                            // but not too frequently.
                            if (Files.IsRegularFile(lockFilePath, LinkOption.NOFOLLOW_LINKS) && IsParentWritable(lockFilePath))
                            {
                                try
                                {
                                    channel = FileChannel.Open(lockFilePath, WRITE, APPEND);
                                }
                                catch (NoSuchFileException)
                                {
                                    // Race condition - retry once, and if that
                                    // fails again just try the next name in
                                    // the sequence.
                                    continue;
                                }
                                catch (IOException)
                                {
                                    // the file may not be writable for us.
                                    // try the next name in the sequence
                                    break;
                                }
                            }
                            else
                            {
                                // at this point channel should still be null.
                                // break and try the next name in the sequence.
                                break;
                            }
                        }
                    }

                    if (channel == null)                     // try the next name;
                    {
                        continue;
                    }
                    LockFileChannel = channel;

                    bool available;
                    try
                    {
                        available = LockFileChannel.TryLock() != null;
                        // We got the lock OK.
                        // At this point we could call File.deleteOnExit().
                        // However, this could have undesirable side effects
                        // as indicated by JDK-4872014. So we will instead
                        // rely on the fact that close() will remove the lock
                        // file and that whoever is creating FileHandlers should
                        // be responsible for closing them.
                    }
                    catch (IOException)
                    {
                        // We got an IOException while trying to get the lock.
                        // This normally indicates that locking is not supported
                        // on the target directory.  We have to proceed without
                        // getting a lock.   Drop through, but only if we did
                        // create the file...
                        available = fileCreated;
                    }
                    catch (OverlappingFileLockException)
                    {
                        // someone already locked this file in this VM, through
                        // some other channel - that is - using something else
                        // than new FileHandler(...);
                        // continue searching for an available lock.
                        available = false;
                    }
                    if (available)
                    {
                        // We got the lock.  Remember it.
                        Locks.Add(LockFileName);
                        break;
                    }

                    // We failed to get the lock.  Try next file.
                    LockFileChannel.Close();
                }
            }

            Files = new File[Count];
            for (int i = 0; i < Count; i++)
            {
                Files[i] = Generate(Pattern, i, unique);
            }

            // Create the initial log file.
            if (Append)
            {
                Open(Files[0], true);
            }
            else
            {
                Rotate();
            }

            // Did we detect any exceptions during initialization?
            Exception ex = em.LastException;

            if (ex != null)
            {
                if (ex is IOException)
                {
                    throw (IOException)ex;
                }
                else if (ex is SecurityException)
                {
                    throw (SecurityException)ex;
                }
                else
                {
                    throw new IOException("Exception: " + ex);
                }
            }

            // Install the normal default ErrorManager.
            ErrorManager = new ErrorManager();
        }
Esempio n. 10
0
 public void Close()
 {
     _serverChannel.Close();
 }
Esempio n. 11
0
        public static void LoadDict(Context context)
        {
            try
            {
                bool resaveEntries = false;
                dictParts   = new List <byte[]>();
                dictIndexes = new List <int>();

                File dictFd = new File(context.FilesDir, "dict.db");
                if (!dictFd.Exists())
                { // || dictFd.length() != 4961308) {
                    System.Console.WriteLine("DOES NOT EXIST!!!!!");
                    CopyFile(context, "dict.db");
                    dictFd        = new File(context.FilesDir, "dict.db");
                    resaveEntries = true;
                }
                dictFile = new RandomAccessFile(dictFd, "r");

                File idxFd = new File(context.FilesDir, "idx.db");
                if (!idxFd.Exists())
                { // || idxFd.length() != 3145553) {
                    CopyFile(context, "idx.db");
                    idxFd         = new File(context.FilesDir, "idx.db");
                    resaveEntries = true;
                }
                FileInputStream idxBuf = new FileInputStream(idxFd);

                if (!new File(context.FilesDir, "entries.bin").Exists() || !new File(context.FilesDir, "parts.bin").Exists())
                {
                    resaveEntries = true;
                }

                entries = IntBuffer.Allocate(1649830);

                int index = 0;
                //System.Console.WriteLine("LoadDict STEP 1");

                if (idxBuf != null)
                {
                    int    readLen, offset = 0, partLen = 200000;
                    byte[] dictPart  = new byte[partLen];
                    int    totalRead = 0;
                    int    totalLen  = (int)idxFd.Length();

                    while (totalRead < totalLen && (readLen = idxBuf.Read(dictPart, offset, dictPart.Length - offset)) > 0)
                    {
                        //System.Console.WriteLine("LoadDict \ntotalRead = " + totalRead + "\ntotalLen = " + totalLen + "\nreadLen = " + readLen + "\nidxBuf.Read = " + idxBuf.Read(dictPart, offset, dictPart.Length - offset));

                        totalRead += readLen;
                        int j = offset + readLen - 1;

                        byte[] newDictPart = null;

                        if (readLen == partLen - offset)
                        {
                            //System.Console.WriteLine("LoadDict STEP 4.1 " + dictPart[j] + " :: j => " + j);

                            while (dictPart[j] > 0)
                            {
                                //System.Console.WriteLine("j = " + j + "\ndictPart[j] = " + dictPart[j]);

                                j--;
                            }
                            //System.Console.WriteLine("LoadDict STEP 4.2");

                            while (dictPart[j] < 0)
                            {
                                System.Console.WriteLine("j = " + j);

                                j--;
                            }
                            //System.Console.WriteLine("LoadDict STEP 4.3");

                            offset = partLen - j - 1;
                            //System.Console.WriteLine("LoadDict STEP 4.4");

                            newDictPart = new byte[Math.Min(totalLen - totalRead + offset, partLen)];
                            //System.Console.WriteLine("LoadDict STEP 4.5");

                            Java.Lang.JavaSystem.Arraycopy(dictPart, j + 1, newDictPart, 0, offset);
                            //Array.Copy(dictPart, j + 1, newDictPart, 0, offset);
                        }
                        else
                        {
                            offset = 0;
                        }
                        //System.Console.WriteLine("LoadDict STEP 5");

                        if (resaveEntries)
                        {
                            dictIndexes.Add(index);
                            //System.Console.WriteLine("LoadDict STEP 6");

                            int i = 0;
                            while (i <= j)
                            {
                                entries.Put(index++, i);

                                while (i <= j && dictPart[i] < 0)
                                {
                                    i++;
                                }
                                while (i <= j && dictPart[i] >= 0)
                                {
                                    i++;
                                }
                            }
                        }
                        //System.Console.WriteLine("LoadDict STEP 7");

                        dictParts.Add(dictPart);
                        dictPart = newDictPart;
                        //System.Console.WriteLine("LoadDict STEP 8");
                    }
                    idxBuf.Close();
                }

                if (resaveEntries)
                {
                    //System.Console.WriteLine("LoadDict STEP 9");

                    DataOutputStream entriesOut = null, partsOut = null;
                    //System.Console.WriteLine("LoadDict STEP 10");

                    entriesOut = new DataOutputStream(context.OpenFileOutput("entries.bin", FileCreationMode.Private));
                    int count = entries.Capacity();
                    for (int i = 0; i < count; i++)
                    {
                        entriesOut.WriteInt(entries.Get(i));
                    }
                    //System.Console.WriteLine("LoadDict STEP 11");


                    partsOut = new DataOutputStream(context.OpenFileOutput("parts.bin", FileCreationMode.Private));
                    foreach (int i in dictIndexes)
                    {
                        partsOut.WriteInt(i);
                    }
                    //System.Console.WriteLine("LoadDict STEP 12");

                    if (entriesOut != null)
                    {
                        entriesOut.Flush();
                        entriesOut.Close();
                    }
                    if (partsOut != null)
                    {
                        partsOut.Flush();
                        partsOut.Close();
                    }
                }
                else
                {
                    //System.Console.WriteLine("LoadDict NOW RESAVING ENTRIES");

                    string       documentpath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    Java.IO.File sdpath       = global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryDownloads);

                    File entriesDB = new File(documentpath, "entries.bin");
                    File partsDB   = new File(documentpath, "parts.bin");

                    FileInputStream entriesIn = null, partsIn = null;

                    //entriesIn = context.OpenFileInput("entries.bin");
                    entriesIn = new FileInputStream(entriesDB);
                    //entriesIn = new FileInputStream(new File("entries.bin"));
                    FileChannel file = entriesIn.Channel;
                    ByteBuffer  bb   = ByteBuffer.Allocate(4 * 1649830);
                    file.Read(bb);
                    bb.Rewind();
                    entries = bb.AsIntBuffer();
                    file.Close();

                    partsIn = new FileInputStream(partsDB);
                    //partsIn = new FileInputStream(new File("parts.bin"));
                    //partsIn = (context.OpenFileInput("parts.bin");
                    file = partsIn.Channel;
                    bb   = ByteBuffer.Allocate((int)file.Size());
                    file.Read(bb);
                    bb.Rewind();
                    IntBuffer ib    = bb.AsIntBuffer();
                    int       count = ib.Capacity();
                    //System.Console.WriteLine("LoadDict STEP 99 " + count);

                    for (int i = 0; i < count; i++)
                    {
                        dictIndexes.Add(ib.Get(i));
                    }
                    file.Close();

                    if (entriesIn != null)
                    {
                        entriesIn.Close();
                    }
                    if (partsIn != null)
                    {
                        partsIn.Close();
                    }
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine("Dict LoadDict ERROR => " + e.Message);

                Log.Equals("chinesreader", e.Message);
            }

            byteBuffer = new byte[1090];

            sharedPrefs = PreferenceManager.GetDefaultSharedPreferences(context);
        }
 public void Close()
 {
     _clientChannel.Close();
 }