The changes to the Java SDK allow for significant improvements to the way uploads are performed. The new upload implementation will allow for streams and the ability to try and control the state of your upload. The feedback the uploader returns allows you to save the state of any upload in progress so you can continue later if you wish to temporarily pause or resume in cases of a crash.
To start using the new uploader your code will need to change somewhat since the interface has changed and the callback mechanism has been rewritten. Below is a sample uploader using the SDK.
//~--- non-JDK imports --------------------------------------------------------
import com.nirvanix.sdk.common.NLogger;
import com.nirvanix.sdk.io.common.*;
import com.nirvanix.sdk.io.upload.*;
import com.nirvanix.sdk.session.Session;
import com.nirvanix.sdk.transport.AccountLogin;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.util.logging.*;
import java.util.HashMap;
public class Upload {
public static void main(String[] args) {
try {
NLogger.setLogger(createLogger("NirvanixJavaSDKSample.log"));
uploadFile("c:\\somefile.txt", "/javaupload", false);
} catch (Exception ex) {
System.out.println(ex);
}
}
private static void uploadFile(String localUploadFilePath, String remoteFolder, boolean useEncryption)
throws Exception {
String userName = "nirvanixusername";
String password = "nirvanixpass";
String appName = "appname";
String appKey = "appkey";
Session session = new Session(userName, password, appKey, appName);
System.out.println("Login");
AccountLogin accountLogin = session.getAccountLogin();
Uploader uploader = new Uploader(accountLogin);
// OPTIONAL: defaults to not allow overwrite an existing file
uploader.setOverwriteExistingFiles(true);
if (useEncryption) {
useEncryption(uploader);
}
// Get fresh upload session
UploadSession uploadSession = uploader.getUploadSession(localUploadFilePath, remoteFolder);
// OPTIONAL: If you are resuming an upload which was interrupted by your
// application crashing, use this alternate UploadSession constructor
// to load transferDataCommitted() uploadContext from your persistant storage where
// you last stored it via transferDataCommitted():
//
//FileInputStream fis = new FileInputStream("yourSaveState.bin");
//ObjectInputStream in = new ObjectInputStream(fis);
//HashMap<String, Object> uploadContext = (HashMap<String, Object>)in.readObject();
//in.close();
//fis.close();
//uploader.setOverwriteExistingFiles(true);
//UploadSession uploadSession = uploader.getUploadSession(localUploadFilePath, remoteFolder, uploadContext);
// Setup listener callbacks
UploadTransferListener listener = new UploadTransferListener(uploadSession);
// OPTIONAL: defaults to 10 as returned by uploader.getUploadPartLengthMB().
// See setUploadPartLengthMB javadoc warnings if you change the size.
//uploadSession.setUploadPartLengthMB(10);
uploadSession.addTransferListener(listener);
try {
// Upload the file
uploadSession.doTransfer();
} finally {
uploadSession.removeTransferListener(listener);
}
}
private static void useEncryption(Uploader uploader) throws Exception {
// To use > 128-bit (16 byte) keys, get JRE extension from
// http://java.sun.com/javase/downloads/index_jdk5.jsp:
// "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 5.0"
// and install per the readme.txt in that zip file.
byte[] encryptionKey = "087mgTI0M3kPgB1X".getBytes();
byte[] encryptionIV = "JKlrtMV2BPYWnutX".getBytes();
uploader.enableEncryption(encryptionKey, encryptionIV);
}
// Create and return a standard Java logger which outputs to a file and to console.
//
// Applet note from http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/guide/util/logging/overview.html :
// Trusted applications are given the appropriate LoggingPermission so they can
// call any of the logging configuration APIs. Untrusted applets are a different
// story. Untrusted applets can create and use named Loggers in the normal way,
// but they are not allowed to change logging control settings, such as adding
// or removing handlers, or changing log levels. However, untrusted applets are
// able to create and use their own "anonymous" loggers, using Logger.getAnonymousLogger.
// These anonymous Loggers are not registered in the global namespace and their
// methods are not access-checked, allowing even untrusted code to change their
// logging control settings.
private static Logger createLogger(String logFilePath) throws IOException {
Logger logger = Logger.getLogger("NirvanixJavaSDKSample");
SimpleFormatter formatter = new SimpleFormatter();
logger.setLevel(Level.WARNING); // set Level.ALL to see all
// Enable log to text file
FileHandler fh = new FileHandler(logFilePath, true);
fh.setLevel(Level.ALL);
fh.setFormatter(formatter);
logger.addHandler(fh);
// Enable log to text console
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.ALL);
ch.setFormatter(formatter);
logger.addHandler(ch);
return logger;
}
}
class UploadTransferListener implements ITransferListener {
private UploadSession uploadSession;
UploadTransferListener(UploadSession uploadSession) {
this.uploadSession = uploadSession;
}
public void transferDataCommitted(long sourceOffset, HashMap<String, Object> uploadContext) {
System.out.format("DataCommitted %d of %d bytes %n%s%n", sourceOffset,
this.uploadSession.getSourceLength(), uploadContext.toString());
// OPTIONAL: If you want the ability to resume an upload which was
// interrupted by your application exiting or crashing, save uploadContext
// object here (e.g. serialize it to disk):
//
//FileOutputStream fos = new FileOutputStream("yourSaveState.bin");
//ObjectOutputStream out = new ObjectOutputStream(fos);
//out.writeObject(uploadContext);
//out.close();
//fos.close();
}
public void transferProgress(long sourceOffset, long sourceLength) {
System.out.format("Uploaded %d of %d bytes%n", sourceOffset, sourceLength);
}
public void transferRetry(long sourceOffset, long sourceLength, int remainingRetryCount, int msecsToNextAttempt, String reason) {
System.out.format("Retrying at %d of %d bytes, %d retries remaining, next attempt in %d msecs, reason: %s%n",
sourceOffset, sourceLength, remainingRetryCount, msecsToNextAttempt, reason);
}
public void transferComplete(long sourceLength, long sinkLength) {
System.out.format("Upload Completed: source length %d, sink length %d%n", sourceLength, sinkLength);
}
public void transferCancelled() {
System.out.println("Upload Cancelled");
}
};
Please let us know if you have any questions about the new upload object or any questions about the sample. All functionality is described in this sample.