Package share.folder.tree.node

Source Code of share.folder.tree.node.HashedFile

package share.folder.tree.node;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import main.settings.Settings;

import common.files.FileDigest;
import common.files.NamedFile;


public class HashedFile extends NamedFile
{
  private static final long serialVersionUID = -145759719768789719L;

  private static final String ALGORYTHM = "SHA-256";

  private File file;
  private long lastModified;

  public static HashedFile createHashedFile(File name) throws NoSuchAlgorithmException,
      InterruptedException, CloneNotSupportedException, IOException
  {
    return new HashedFile(name, generateHash(name));
  }

  private HashedFile(File name, FileDigest digest)
  {
    super(name.length(), digest, name.getName());

    this.file = name;
    lastModified = name.lastModified();
  }

  private static FileDigest generateHash(File file) throws InterruptedException,
      NoSuchAlgorithmException, CloneNotSupportedException, IOException
  {
    DigestInputStream stream;
    MessageDigest instance = (MessageDigest) MessageDigest.getInstance(ALGORYTHM)
        .clone();
    stream = new DigestInputStream(
        new BufferedInputStream(new FileInputStream(file)), instance);

    while (stream.read() >= 0)
    {
      checkPoint();
    }

    return new FileDigest(stream.getMessageDigest().digest());
  }

  private static void checkPoint() throws InterruptedException
  {
    if (Thread.currentThread().isInterrupted())
    {
      throw new InterruptedException();
    }
  }

  public File getFile()
  {
    return file;
  }

  public boolean isShareable()
  {
    return file.exists() && file.isFile() && file.canRead()
        && (!file.isHidden() || Settings.share.share_hidden_files);
  }

  public boolean isModified()
  {
    return lastModified != file.lastModified();
  }

  public void rehash() throws NoSuchAlgorithmException, InterruptedException,
      CloneNotSupportedException, IOException
  {
    setHashData(generateHash(file));
  }

  protected void doWriteObject(ObjectOutputStream out) throws IOException
  {
    super.doWriteObject(out);
    out.writeObject(file);
    out.writeLong(lastModified);
  }

  protected void doReadObject(ObjectInputStream in) throws IOException,
      ClassNotFoundException
  {
    super.doReadObject(in);
    file = (File) in.readObject();
    lastModified = in.readLong();
  }

}
TOP

Related Classes of share.folder.tree.node.HashedFile

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.