package share.folder.tree.node;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import share.folder.Folder;
public class RecursiveFolderTreeNode extends AbstractFolderTreeNode
{
private static final long serialVersionUID = 3349750267781292264L;
private FolderTreeNodeContainer folders;
public RecursiveFolderTreeNode(Folder folder) throws InterruptedNodeException
{
super(folder);
processSubFolders();
}
public RecursiveFolderTreeNode(AbstractFolderTreeNode source)
throws InterruptedNodeException
{
super(source);
processSubFolders();
}
private void processSubFolders() throws InterruptedNodeException
{
folders = new FolderTreeNodeContainer();
try
{
for (File subFolder : folder.listSubFolders())
{
addSubFolder(subFolder);
}
}
catch (InterruptedException e)
{
throw new InterruptedNodeException(this);
}
}
public AbstractFolderTreeNode switchNode() throws InterruptedNodeException
{
try
{
removeSubfolders();
}
catch (InterruptedException e)
{
return this;
}
return new FolderTreeNode(this);
}
public boolean includesSubfolders()
{
return true;
}
public boolean isFolderParentOf(Folder other)
{
return folder.isParentOf(other);
}
public void remove() throws InterruptedException
{
removeSubfolders();
super.remove();
}
private void removeSubfolders() throws InterruptedException
{
folders.clear();
}
protected void doUpdate() throws InterruptedException
{
super.doUpdate();
updateFolders();
updateSubFolders();
}
private void updateFolders() throws InterruptedException
{
removeInaccessibleFolders();
addNewFolders();
}
private void updateSubFolders() throws InterruptedException
{
folders.update();
}
private void removeInaccessibleFolders() throws InterruptedException
{
Iterator<AbstractFolderTreeNode> iterator = folders.getNodes().iterator();
while (iterator.hasNext())
{
AbstractFolderTreeNode node = iterator.next();
if (!node.folder.isShareable())
{
node.remove();
iterator.remove();
}
}
}
private void addNewFolders() throws InterruptedException
{
for (File path : folder.listSubFolders())
{
Folder folder = new Folder(path);
if (!isFolderAlreadyIndexed(folder))
{
addSubFolder(path);
}
}
}
private void addSubFolder(File path) throws InterruptedException
{
folders.add(new Folder(path), true);
}
private boolean isFolderAlreadyIndexed(Folder folder)
{
for (AbstractFolderTreeNode node : folders.getNodes())
{
if (node.folder.equals(folder))
{
return true;
}
}
return false;
}
protected void doWriteObject(ObjectOutputStream out) throws IOException
{
super.doWriteObject(out);
out.writeObject(folders);
}
protected void doReadObject(ObjectInputStream in) throws IOException,
ClassNotFoundException
{
super.doReadObject(in);
folders = (FolderTreeNodeContainer) in.readObject();
}
}