package ds.controller.local;
import java.net.Socket;
import java.rmi.RemoteException;
import java.util.Vector;
import org.apache.log4j.Logger;
import ds.controller.helper.NodeInfo;
import ds.controller.helper.NodeSelecter;
import ds.node.local.StorageActionImpl;
import ds.shared.local.ActionInterface;
import ds.shared.rmi.FileServerInterface;
import ds.util.SimpleFiles;
/**
* Forward files instead of storing on the local file system.
*
* @author save
*/
public class TunnelActionImpl implements ActionInterface {
// Define a static logger variable
private final static Logger LOGGER = Logger.getLogger(StorageActionImpl.class);
// List of registered nodes
private Vector<NodeInfo> nodes = null;
/**
* Constructor
*
* @param nodes
* List of registered nodes
* if the object handle cannot be constructed.
*/
public TunnelActionImpl(Vector<NodeInfo> nodes) {
this.nodes = nodes;
}
/**
* Perform send action in the ClientSocketHandler
* Sending from the node to the client
*
* @param clientSocket
* Socket connection to send/receive files.
* @param file
* The file name
*/
public void send(Socket clientSocket, String file) {
LOGGER.debug("Forwarding file to client " + file);
int loc = NodeSelecter.select_get(file);
NodeInfo info = nodes.get(loc);
FileServerInterface node = info.getNode();
Socket sourceSocket = info.getSocket();
// Request file transfer
boolean response = false;
try {
response = node.getFile(file);
} catch (RemoteException e1) {
e1.printStackTrace();
return;
}
if (response)
LOGGER.debug("Received permission to put file ");
else {
LOGGER.info("Permission denied");
return;
}
// Get file size
long size;
try {
size = node.getFileSize(file);
} catch (RemoteException e1) {
e1.printStackTrace();
return;
}
// Send file
try {
SimpleFiles.forwardBinaryStream(sourceSocket, clientSocket, file, size);
} catch (Exception e) {
e.printStackTrace();
return;
}
LOGGER.debug("File sent ");
}
/**
* Perform receive action in the ClientSocketHandler
* Receiving from the client, to the node.
*
* @param clientSocket
* Socket connection to send/receive files.
* @param path
* The file name
* @param size
* The file size
*/
public void receive(Socket clientSocket, String file, long size) {
LOGGER.debug("Forwarding file to node " + file);
int loc = NodeSelecter.select_put();
LOGGER.debug("Selected node " + loc);
NodeInfo info = nodes.get(loc);
FileServerInterface node = info.getNode();
Socket destinationSocket = info.getSocket();
// Request the file transfer to the node
boolean response = false;
try {
response = node.putFile(file, size);
} catch (RemoteException e1) {
e1.printStackTrace();
}
if (response)
LOGGER.debug("Received permission to forward file ");
else {
LOGGER.info("Permission denied");
return;
}
// Send file
try {
SimpleFiles.forwardBinaryStream(clientSocket, destinationSocket, file, size);
} catch (Exception e) {
e.printStackTrace();
return;
}
LOGGER.debug("File sent ");
}
}