CSJCurrent en:File Transfer

Aus Cryptshare Documentation
Version vom 13. Oktober 2021, 11:17 Uhr von Maintenance script (Diskussion | Beiträge) (Imported from text file)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu:Navigation, Suche



General

You can perform both synchronous, as well as asynchronous Cryptshare file transfers using the API. A transfer can contain one or more files that will be encrypted, uploaded to the Cryptshare Server, and then made available to the transfer's recipients for download. Depending on your transfer settings, the recipients and/or sender of the transfer will then be notified by email when the transfer is complete and the files are available for download. Before you can perform a transfer, you have to configure the transfer settings, define the recipients and select the files you wish to include in the transfer (see Preparing a Transfer). Then you can either Perform a Synchronous Transfer or Perform an Asynchronous Transfer.

Preparing a Transfer

Before you can perform a transfer, you have to create a Transfer object with

  • the sender's contact details
    • name
    • phone number
  • the password mode (optional)
  • the recipient notification message that is to be included in the transfer (optional)
  • the recipients
  • the languages of the notification emails (optional)
  • the storage duration (optional)
  • the files that will be transferred

If a recipient is not allowed for the transfer, based on the server's policy settings, an exception will be thrown when trying to perform the transfer. To avoid this, you can check the Policy Rules before attempting to perform a transfer.

About the password modes

The password mode used for the transfer must be one of the allowed password modes defined in the Policy Rules.

Manual password

If the password mode is PasswordMode.MANUAL, then you have to explicitly set a password for the transfer. You can check the password to make sure that it fulfills the requirements of the Password Policy by using the functions described in Password Functions. The recipient will then have to contact the sender of the transfer to find out what the password is, before any files can be downloaded.

Generated password

For password mode PasswordMode.GENERATED, the Client will request a server-generated password and automatically set it for the transfer. The recipient will then have to contact the sender of the transfer to find out what the password is, before any files can be downloaded.

No Password

When using PasswordMode.NONE, you do not have to define a password. The server will automatically generate a password and include it in the download link, so that the recipient does not need to explicitly enter a password to download the files.

This is obviously the least secure method, and should thus be used sparingly.

Notification language

You can specify the languages to use for the default recipient and sender email notifications. The languages are specified with their Locale. You can only specify languages for which there are language packs installed on the server. See Language Resources.

Notification message

You can also set a custom message and subject for the notification emails. The Transfer object has setters for the message and subject fields that take either a String, or an InputStream as a parameter, so you can either directly set a text as the message or subject, or give the setter method an InputStream containing the text, and the text will be automatically read from the stream. The encoding of the stream has to be UTF-8, to ensure that the text can be read in correctly. Once the text is read from the InputStream, the stream will automatically be closed. Your message text can also include HTML markup. For the subject text, only plain text is supported, so using HTML tags in the subject line may lead to unexpected results.

Confidential message

If allowed by the Policy, you may also choose to include a confidential message to the recipients of the transfer. Setting the confidential message and subject is similar to setting the custom notification message on the Transfer object. The parameters for the setter methods of the Transfer object's confidentialMessage and confidentialSubject fields are either a String or an InputStream, so the same rules apply as described above for the custom message and subject. The confidential message is encrypted along with the transfer files and can be viewed by the recipients when they retrieve the transfer.

Expiration Date

When specifiying an expiration date for the transferred files, make sure that it is still within the maximum allowed storage duration as specified in the Policy Rules. The transferred files will only be available for download until the specified expiration date.

Transfer preparation complete

Once the Transfer object has been initialized as described in the example here, it can be used for performing the transfer either synchronously or asynchronously as described in the sections Perform a Synchronous Transfer and Perform an Asynchronous Transfer below.

Example: Preparing a Transfer Object

// First create the Client instance
// Create a WebServiceUri for your Cryptshare Server
WebServiceUri serviceUri = new WebServiceUri("https://cryptshare.yourdomain.com");
  
// Create a CryptshareConnection instance for your WebServiceUri
CryptshareConnection connection = new CryptshareConnection(serviceUri);
  
// Create the Client instance with the sender's email address,
// the CryptshareConnection, and the path to the verification store.
Client client = new Client("john.adams@yourdomain.com", connection, Paths.get("C:\\\\temp\\\\client.store"));

// Create a new Transfer object
Transfer transfer = new Transfer();

// Set the name of the sender
transfer.setSenderName("John Adams");

// Set the sender's phone number
transfer.setSenderPhone("234 5467");

// Set the message text of the mail that is to be included in the transfer.
// The Transfer object's setMessage(..) method takes either an
// actual text string containing the email message, or an InputStream
// which contains the email message text. If specifying an InputStream, the
// stream needs to be UTF-8 encoded, to ensure that the characters can be
// read in and displayed correctly in the email message.
try (FileInputStream inputStream = new FileInputStream("C:\\\\temp\\\\message.txt")) {
	// To illustrate, we'll use the message text from an input stream.
	// Your application may get this input stream from another process, for
	// instance, but in this example, we will just read it in from a file	
    // Set the input stream as the message. The method will read in
    // the text from the stream and automatically close the stream when it's done.
	transfer.setMessage(inputStream);
}
catch (Exception ex) {
    // there was an error reading the text file, so show an error message
    System.err.println("Error reading the message file!");
}

// Set the subject text of the mail that is to be included in the transfer.
transfer.setSubject("Subject of the Transfer");

// Define the recipients
List<String> recipients = new ArrayList<String>();
recipients.addRecipient("jane.doe@abc.com");
recipients.addRecipient("jack.smith@xyz.com");

// Get the policy rule from the server for the given recipients, so we can 
// check to make sure they are allowed            
Policy policy = client.requestPolicy(recipients);

// Check to make sure the recipients are allowed and only add them 
// to the transfer, if they are          
if (policy.getFailedEmailAddresses() != null && !policy.getFailedEmailAddresses().isEmpty()) {
	for (String recipient : recipients) {
    	if (!policy.getFailedEmailAddresses().contains(recipient)) {
        	transfer.addRecipient(new Recipient(recipient));
        } else {
            System.out.println("The recipient is invalid: " + recipient);
        }             
	}
} else {
	// all recipients are valid
   List<Recipient> recipientList = recipients.stream().map(Recipient::new).collect(Collectors.toList()); 
   transfer.addRecipients(recipientList);
}

// If allowed by the policy, we can also send a confidential message to the
// recipients
if (policy.isAllowConfidentialMessage()) {	
    transfer.setConfidentialSubject("Subject of the confidential message");   
    transfer.setConfidentialMessage("This is the text of the confidential message.");
}

// Only continue if we have at least one valid recipient for the transfer
if (transfer.getRecipients() == null || transfer.getRecipients().isEmpty()) {                
	throw new Exception("No valid recipients defined, aborting transfer.");
}

// Set the password mode that will be used for this transfer.
// Must be one of the password modes allowed by the policy.
// We will just pick the most secure mode allowed by the policy
PasswordMode passwordMode;
Set<PasswordMode> allowedPasswordModes = policy.getAllowedStandardPasswordModes();
if (allowedPasswordModes.contains(PasswordMode.GENERATED))
   passwordMode = PasswordMode.GENERATED;
else if (allowedPasswordModes.contains(PasswordMode.MANUAL))
   passwordMode = PasswordMode.MANUAL;
else
   passwordMode = PasswordMode.NONE;
transfer.setPasswordMode(passwordMode);

// If password mode is MANUAL, we have to set a password
if (passwordMode.equals(PasswordMode.MANUAL) {
	// we have to manually set a password for this transfer
	transfer.setPassword("p4$$w0rd");
}

// Define if the file names should be shown in the recipient's
// notification email
transfer.setShowFilenames(true);

// Define if the sender should be notified when the recpients
// download the files
transfer.setInformAboutDownload(true);

// Set the language for the recipient notification email
transfer.setRecipientLanguage(Locale.ENGLISH);

// Set the language for the sender notification email
client.setUserLanguage(Locale.ENGLISH);

// Set the expiration date of the files 
// (how long the files will be available for download)
// We'll just set it to the maximum allowed storage duration
int storageDuration = policy.getStorageDuration();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, storageDuration);
transfer.setExpirationDate(cal.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());

// Add the files for this transfer
// A TransferFile object has to be created for each file you would like to add to the transfer
// Add a file from the file system, specified as a complete file path:
transfer.addFile(new TransferFile(Paths.get("C:\\\\temp\\\\transfer_file_01.txt")));

// Add a stream that contains the data for a file.
// Your application may have received this stream from another process, for instance,
// but for this example, we will just create an input stream from a file
try {
	File inputFile = new File("C:\\\\temp\\\\transfer_file_02.txt");
    FileInputStream inputStream = new FileInputStream(inputFile);
	long streamSize = inputFile.length();

    // Create the TransferFile object for this stream. You also need to specify
	// a name for the file that will be created from the data of this stream, including
	// a file extension, so that the recipient will be able to open it with the correct
	// application, as well as the size of the stream. The stream will be closed
	// automatically, once it has been uploaded to the server.
    TransferFile streamFile = new TransferFile("MyAttachment.txt", inputStream, streamSize);
    transfer.addFile(streamFile);
} catch (Exception ex) {            
    ex.printStackTrace();
}
// Add another file from the file system
transfer.addFile(new TransferFile("C:\\\\temp\\\\transfer_file_03.txt"));

// Now we can use this transfer object to perform the transfer 
// either synchronously or asynchronously
...

Performing a Transfer

Synchronous

Once you have the Transfer object initialized as described in the example Preparing a Transfer above, you can use it to perform a synchronous transfer. A synchronous transfer is performed by calling the Client's method performTransfer(Transfer, ...various callbacks). The method requires a Transfer object containing all the necessary transfer data, as well as multiple callbacks that will be used to inform about the upload progress and any errors encountered during the upload. As this is a synchronous operation, the method will block until all files in the transfer have been uploaded and the transfer is completed.

Example: Performing a Synchronous Transfer

private static void performTransferSynchronous() {
	// First create the Client instance
	// Create a WebServiceUri for your Cryptshare Server 
	WebServiceUri serviceUri = new WebServiceUri("https://cryptshare.server.com");
 
	// Create a CryptshareConnection instance for your WebServiceUri
	CryptshareConnection connection = new CryptshareConnection(serviceUri);
 
	// Create the Client instance with the sender's email address, 
	// the CryptshareConnection, and the path to the verification store.
	Client client = new Client("sender_email@server.com", connection, Paths.get("C:\\\\temp"));

	// Prepare the transfer object as described in the example above
	Transfer transfer = ...

	// Perform a synchronous transfer with four event handlers.
	// Method will block until the transfer is completed.
	client.performTransfer(transfer,
					   new UploadProgressChangedHandler(),
					   new UploadCompleteHandler(),
					   new UploadInterruptedHandler(),
					   new UploadCancelledHandler(),
					   1000);
}

public class UploadProgressChangedHandler implements IUploadProgressChangedHandler {
	@Override
	public void progressChanged(String currentFileNo, String currentFileName, double bytesUploaded, double bytesTotal, long bytesPerSecond) {
		// This method is called repeatedly with the current upload data
		// Our upload listener will just output the current progress to the console
		double percent = ((bytesUploaded / bytesTotal) * 100.0);
		System.out.println("Transfer progress ... " + ((int)percent) + "%");
	}
}

public class UploadCompleteHandler implements IUploadCompleteHandler {
	@Override
	public void uploadComplete(Map<String, String> urlMappings, Map<String, String> smtpMappings, String serverGenPassword, TransferError transferError,
			String trackingId) {
		// this method is called when all files of the transfer have been uploaded
		System.out.println("Upload completed!");
	}
}

public class UploadInterruptedHandler implements IUploadInterruptedHandler {
	@Override
	public void uploadInterrupted(CryptshareException cryptshareException) {
		// this method is called when an exception occurs during the file upload
    	System.out.println("An exception occurred during the upload: " + cryptshareException);
	}
}

public class UploadCancelledHandler implements IUploadCancelledHandler {
	@Override
	public void cancelled() {
		// this method is called when the transfer has been cancelled 
		// using the cancelTransfer() method
		System.out.println("The transfer has been canceled!");
	}
}

Asynchronous

To perform a transfer asynchronously, initialize the Transfer object as described in the example Preparing a Transfer above, and call the Client's method beginTransfer(Transfer, ...various callbacks), giving it the initialized Transfer object containing all the necessary transfer data, as well as handlers that will be informed about the upload progress, the completion of the upload, and any errors encountered during the upload. The method will return immediately after starting a new Thread in the background which will perform the actual transfer. Once the upload completes in the background, the IUploadCompleteHandler's uploadComplete method will be called.

Cancelling a Transfer

If you wish to cancel an ongoing transfer, you may do so by calling the Client's method cancelTransfer(). This method stops the current file upload process and cancels the transfer. A transfer can only be cancelled while it is still in the process of uploading the files. Once all files of a transfer have been uploaded to the server, the transfer will be complete and cannot be cancelled using the API. A transfer that has already been completed from the Client's point of view, can only be revoked by using the "Revoke Transfer" operation.

Example: Performing an Asynchronous Transfer

private static void performTransferSynchronous() {
	// First create the Client instance
	// Create a WebServiceUri for your Cryptshare Server 
	WebServiceUri serviceUri = new WebServiceUri("https://cryptshare.server.com");
 
	// Create a CryptshareConnection instance for your WebServiceUri
	CryptshareConnection connection = new CryptshareConnection(serviceUri);
 
	// Create the Client instance with the sender's email address, 
	// the CryptshareConnection, and the path to the verification store.
	Client client = new Client("sender_email@server.com", connection, Paths.get("C:\\\\temp"));

	// Prepare the transfer object as described in the example above
	Transfer transfer = ...

	// Perform an asynchronous transfer with a new anonymous TransferUploadListener instance
	// Method will return immediately
	client.beginTransfer(transfer,
					   new UploadProgressChangedHandler(),
					   new UploadCompleteHandler(),
					   new UploadInterruptedHandler(),
					   new UploadCancelledHandler(),
					   1000);
}

public class UploadProgressChangedHandler implements IUploadProgressChangedHandler {
	@Override
	public void progressChanged(String currentFileNo, String currentFileName, double bytesUploaded, double bytesTotal, long bytesPerSecond) {
		// This method is called repeatedly with the current upload data
		// Our upload listener will just output the current progress to the console
		double percent = ((bytesUploaded / bytesTotal) * 100.0);
		System.out.println("Transfer progress ... " + ((int)percent) + "%");
	}
}

public class UploadCompleteHandler implements IUploadCompleteHandler {
	@Override
	public void uploadComplete(Map<String, String> urlMappings, Map<String, String> smtpMappings, String serverGenPassword, TransferError transferError,
			String trackingId) {
		// this method is called when all files of the transfer have been uploaded
		System.out.println("Upload completed!");
	}
}

public class UploadInterruptedHandler implements IUploadInterruptedHandler {
	@Override
	public void uploadInterrupted(CryptshareException cryptshareException) {
		// this method is called when an exception occurs during the file upload
    	System.out.println("An exception occurred during the upload: " + cryptshareException);
	}
}

public class UploadCancelledHandler implements IUploadCancelledHandler {
	@Override
	public void cancelled() {
		// this method is called when the transfer has been cancelled 
		// using the cancelTransfer() method
		System.out.println("The transfer has been canceled!");
	}
}