Package files

Source Code of files.IndexedFile

package files;


import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import common.files.SerializableFile;
import files.sharing.ShareMap;
import files.sharing.Sharer;

import static main.ServerMain.getFileManager;


@SuppressWarnings("serial")
public class IndexedFile extends SerializableFile
{
  private long chunkLength;

  private ShareMap shareMap;
  private ReentrantReadWriteLock lock;

  protected IndexedFile(SerializableFile source)
  {
    super(source);

    // TODO: is sqrt the best chunking algorithm ?
    chunkLength = (long) Math.sqrt(getLength());

    shareMap = new ShareMap();
    lock = new ReentrantReadWriteLock();
  }

  public void addSharer(Sharer sharer)
  {
    lock.writeLock().lock();
    shareMap.addSharer(sharer);
    lock.writeLock().unlock();

    sharer.registerSharedFile(this);
  }

  public void removeSharer(Sharer sharer)
  {
    lock.writeLock().lock();
    shareMap.removeSharer(sharer);

    lock.readLock().lock();
    lock.writeLock().unlock();

    if (shareMap.isEmpty())
    {
      removeFromServer();
    }

    lock.readLock().unlock();
  }

  private void removeFromServer()
  {
    getFileManager().removeIndexedFile(this);
  }

  public void serializeStatus(int targetId, ObjectOutputStream os) throws IOException
  {
    Sharer targetSharer = getFileManager().getSharerById(targetId);

    lock.readLock().lock();
    shareMap.serialize(targetSharer, os);
    lock.readLock().unlock();
  }

  public long getChunkLength()
  {
    return chunkLength;
  }

}
TOP

Related Classes of files.IndexedFile

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.