* save a file
* @param aConnector
* @param aToken
*/
public void save(WebSocketConnector aConnector, Token aToken) {
TokenServer lServer = getServer();
String lMsg;
if (log.isDebugEnabled()) {
log.debug("Processing 'save'...");
}
// check if user is allowed to run 'save' command
if (!SecurityFactory.checkRight(lServer.getUsername(aConnector), NS_FILESYSTEM + ".save")) {
if (log.isDebugEnabled()) {
log.debug("Returning 'Access denied'...");
}
lServer.sendToken(aConnector, lServer.createAccessDenied(aToken));
return;
}
// instantiate response token
Token lResponse = lServer.createResponse(aToken);
// obtain required parameters for file load operation
String lFilename = aToken.getString("filename");
String lScope = aToken.getString("scope", JWebSocketCommonConstants.SCOPE_PRIVATE);
// TODO: Replace optional variables in path like %JWEBSOCKET_HOME% by env var values!
// scope may be "private" or "public"
String lBaseDir;
if (JWebSocketCommonConstants.SCOPE_PRIVATE.equals(lScope)) {
String lUsername = getUsername(aConnector);
lBaseDir = getSetting(PRIVATE_DIR_KEY, PRIVATE_DIR_DEF);
if (lUsername != null) {
lBaseDir = lBaseDir.replace("{username}", lUsername);
} else {
lMsg = "not authenticated to save private file";
if (log.isDebugEnabled()) {
log.debug(lMsg);
}
lResponse.put("code", -1);
lResponse.put("msg", lMsg);
// send error response to requester
lServer.sendToken(aConnector, lResponse);
return;
}
} else if (JWebSocketCommonConstants.SCOPE_PUBLIC.equals(lScope)) {
lBaseDir = getSetting(PUBLIC_DIR_KEY, PUBLIC_DIR_DEF);
} else {
lMsg = "invalid scope";
if (log.isDebugEnabled()) {
log.debug(lMsg);
}
lResponse.put("code", -1);
lResponse.put("msg", lMsg);
// send error response to requester
lServer.sendToken(aConnector, lResponse);
return;
}
Boolean lNotify = aToken.getBoolean("notify", false);
String lBase64 = aToken.getString("data");
byte[] lBA = null;
if (lBase64 != null) {
lBA = Base64.decodeBase64(lBase64);
}
// complete the response token
String lFullPath = lBaseDir + lFilename;
File lFile = new File(lFullPath);
try {
// prevent two threads at a time writing to the same file
synchronized (this) {
// force create folder if not yet exists
File lDir = new File(FilenameUtils.getFullPath(lFullPath));
FileUtils.forceMkdir(lDir);
FileUtils.writeByteArrayToFile(lFile, lBA);
}
} catch (IOException ex) {
lResponse.put("code", -1);
lResponse.put("msg", ex.getMessage());
}
// send response to requester
lServer.sendToken(aConnector, lResponse);
// send notification event to other affected clients
// to allow to update their content (if desired)
if (lNotify) {
// create token of type "event"
Token lEvent = new Token(Token.TT_EVENT);
// include name space of this plug-in
lEvent.setNS(NS_FILESYSTEM);
lEvent.put("name", "filesaved");
lEvent.put("filename", lFilename);
lEvent.put("sourceId", aConnector.getId());
lEvent.put("url", getSetting(WEB_ROOT_KEY, WEB_ROOT_DEF) + lFilename);
// TODO: Limit notification to desired scope
lServer.broadcastToken(lEvent);
}
}