share-updates/src/main/java/org/gcube/portlets/user/shareupdates/server/UploadToWorkspaceThread.java

91 lines
2.8 KiB
Java

package org.gcube.portlets.user.shareupdates.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.exceptions.ItemAlreadyExistException;
import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author Massimiliano Assante ISTI-CNR
*
*/
public class UploadToWorkspaceThread implements Runnable {
private static Logger _log = LoggerFactory.getLogger(UploadToWorkspaceThread.class);
/**
* the identifier of the workspace you are putting
*/
private String username;
/**
* the name of the file you are putting
*/
private String fileName;
/**
* the path (with name) of the file you are putting
*/
private String fileabsolutePathOnServer;
/**
*
* @param sClient the instance of the storage client
* @param fileToUpload the absolute path of the file
*/
public UploadToWorkspaceThread(String username, String fileName, String fileabsolutePathOnServer) {
super();
this.username = username;
this.fileName = fileName;
this.fileabsolutePathOnServer = fileabsolutePathOnServer;
}
@Override
public void run() {
try {
String currScope = ScopeProvider.instance.get();
ScopeProvider.instance.set("/"+PortalContext.getConfiguration().getInfrastructureName());
Workspace ws = HomeLibrary
.getHomeManagerFactory()
.getHomeManager()
.getHome(username).getWorkspace();
_log.info("File to upload="+fileabsolutePathOnServer);
File file = new File(fileabsolutePathOnServer);
String mimeType = FilePreviewer.getMimeType(file, fileName);
InputStream fileData = new FileInputStream(file);
String theId = "";
_log.info("mimeType="+mimeType + " fileData null? " + (fileData == null) );
try {
theId = ws.createExternalFile(fileName ,"File added automatically by Share Updates" , mimeType ,fileData, ws.getRoot().getId()).getId();
}
catch (NullPointerException exn) {
_log.warn("null pointer");
exn.printStackTrace();
}
catch (ItemAlreadyExistException ex) {
_log.warn("fileName " + fileName + " exists, appending timestamp");
theId = ws.createExternalFile(fileName+" ("+ new Date()+")" ,"File added automatically by Share Updates" , mimeType ,fileData, ws.getRoot().getId()).getId();
ex.printStackTrace();
} finally {
fileData.close();
}
fileData.close();
_log.debug("Uploaded " + fileName + " - Returned Workspace id=" + theId);
ScopeProvider.instance.set(currScope);
}
catch (Exception e) {
e.printStackTrace();
_log.error("Something wrong while uploading " + fileName + " in Workspace " + e.getMessage());
}
}
}