package com.sterlingcommerce.woodstock.services.integration;
import jarjar.orgapachecommonsio.IOUtils;
import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.SQLException; import java.util.List;
import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.sterlingcommerce.woodstock.mailbox.MailboxException; import com.sterlingcommerce.woodstock.mailbox.MailboxFactory; import com.sterlingcommerce.woodstock.mailbox.repository.IRepository; import com.sterlingcommerce.woodstock.mailbox.repository.Message; import com.sterlingcommerce.woodstock.services.IService; import com.sterlingcommerce.woodstock.util.frame.log.LogService; import com.sterlingcommerce.woodstock.util.frame.log.Logger; import com.sterlingcommerce.woodstock.workflow.Document; import com.sterlingcommerce.woodstock.workflow.DocumentNotFoundException; import com.sterlingcommerce.woodstock.workflow.WorkFlowContext; import com.sterlingcommerce.woodstock.workflow.WorkFlowException; import com.sterlingcommerce.woodstock.util.frame.Manager;
public class AWSS3ClientService implements IService { private Document primaryDoc = null; private InputStream docAsStream = null; protected static Logger log; static { log = LogService.getLogger("integrationservices"); } private static boolean isOK = true; private static final String SUFFIX = "/";
public WorkFlowContext processData(WorkFlowContext wfc) throws WorkFlowException {
isOK = true; try { wfc.harnessRegister(); String action = wfc.getParm("operation");//PUT, GET, DELETE, MKDIR String local_path = wfc.getParm("local_path");//Path to read file from for uploading String messageId = wfc.getParm("messageId");//Message ID for mailbox String s3_bucketname = wfc.getParm("s3_bucketname");//Bucket name in S3 area String s3_key = wfc.getParm("s3_key"); //Name with which resource resides in S3 area String s3_folderName = wfc.getParm("s3_foldername");//Folder name OR structure
log.log("AWSS3ClientService.processData(): local_path:" + local_path); log.log("AWSS3ClientService.processData(): s3_key:" + s3_key); log.log("AWSS3ClientService.processData(): action:" + action); log.log("AWSS3ClientService.processData(): messageId:" + messageId); log.log("AWSS3ClientService.processData(): s3_bucketname:" + s3_bucketname); log.log("AWSS3ClientService.processData(): s3_folderName:" + s3_folderName);
String accessKey = Manager.getProperties("integrationservices").getProperty("awss3.accessKey"); String secretKey = Manager.getProperties("integrationservices").getProperty("awss3.secretKey");
log.log("AccessKey for AWS S3 area: " + accessKey); log.log("SecretKey for AWS S3 area: " + secretKey); AWSCredentials credentials = new BasicAWSCredentials( accessKey, // access key secretKey); // secret key
// create a client connection based on credentials AmazonS3 s3Client = new AmazonS3Client(credentials);
// create bucket - name must be unique for all S3 users s3Client.createBucket(s3_bucketname);
// list buckets for (Bucket bucket : s3Client.listBuckets()) { log.log(" - " + bucket.getName()); }
if ("put".equalsIgnoreCase(action)) { if ( wfc.getPrimaryDocument() != null ){ docAsStream = wfc.getPrimaryDocument().getBodyInputStream(); putFileToS3(docAsStream, s3_key, s3Client, s3_bucketname); } else if (local_path != null && !"".equalsIgnoreCase(local_path)) {// put file from FS to S3 docAsStream = new FileInputStream( new File( local_path )); putFileToS3(docAsStream, s3_key, s3Client, s3_bucketname); } else if (messageId != null && !"".equalsIgnoreCase(messageId) && !"null".equalsIgnoreCase(messageId)) { putFileFromMailboxToS3(messageId, s3_key, s3Client, s3_bucketname); }
} else if ("get".equalsIgnoreCase(action)) { log.log("Usage: s3client read <s3_key>"); readFileFromS3(s3_key, s3Client, s3_bucketname); wfc.putPrimaryDocument(primaryDoc); } else if ("delete".equalsIgnoreCase(action)) { log.log("Usage: s3client delete <s3_key>"); delete(s3_bucketname, s3_folderName, s3Client, s3_key); } else if ("mkdir".equalsIgnoreCase(action)) {// create folder into bucket log.log("Usage: s3client mkdir <s3_key>"); createFolder(s3_bucketname, s3_folderName, s3Client); } else { log.log("Usage: s3client put/read/delete/mkdir" + " [<local_path> <s3_key>]"); //System.exit(1); }
log.log("Done!"); } catch (Exception e) { isOK = false; log.log(e.getMessage()); log.logException(e); wfc.setBasicStatus(1); throw new WorkFlowException(e.toString()); } finally { wfc.unregisterThread(); if (isOK) { wfc.setBasicStatusSuccess(); } else { wfc.setBasicStatusError(); } } return wfc; }
public void createFolder(String bucketName, String folderName, AmazonS3 client) { // create meta-data for your folder and set content-length to 0 ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(0);
// create empty content InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
// create a PutObjectRequest passing the folder name suffixed by / PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folderName + SUFFIX, emptyContent, metadata);
// send request to S3 to create folder client.putObject(putObjectRequest); } public void putFileToS3(InputStream source, String key, AmazonS3 s3client, String bucketName) throws IOException { s3client.putObject(new PutObjectRequest(bucketName, key, source, null).withCannedAcl(CannedAccessControlList.PublicRead)); }
public void putFileFromMailboxToS3(String messageId, String key, AmazonS3 s3client, String bucketName) throws IOException { IRepository repos = MailboxFactory.getRepository(); String filename = null; Message message = null; Document batchDoc = null; try { log.log("AWSS3Client.putFileFromMailboxToS3():messageId:" + messageId); message = repos.getMessage(Long.parseLong(messageId));// source here is messageid log.log("AWSS3Client.putFileFromMailboxToS3(): message:" + message.toString()); String docId = message.getDocumentId(); log.log("AWSS3Client.putFileFromMailboxToS3(): docId:" + docId); filename = message.getMessageName(); log.log("AWSS3Client.putFileFromMailboxToS3():filename:" + filename); if (docId != null) { batchDoc = new Document(docId, true); } log.log("AWSS3Client.putFileFromMailboxToS3(): batchDoc:" + batchDoc); } catch (NumberFormatException nfe) { log.logException(nfe); } catch (MailboxException me) { log.logException(me); } catch (DocumentNotFoundException dnfe) { log.logException(dnfe); } catch (SQLException sqle) { log.logException(sqle); }
InputStream in = batchDoc.getInputStream(); final File aFile = File.createTempFile("tmp", "txt"); aFile.deleteOnExit(); try{ FileOutputStream out = new FileOutputStream(aFile); IOUtils.copy(in, out); } catch (IOException ioe) { log.logException(ioe); } s3client.putObject(new PutObjectRequest(bucketName, key, aFile).withCannedAcl(CannedAccessControlList.PublicRead)); }
public void readFileFromS3(String key, AmazonS3 s3Client, String bucketName) throws IOException {
S3Object object = s3Client.getObject( new GetObjectRequest(bucketName, key)); InputStream in = object.getObjectContent(); //Process the objectData stream.
String filename = key.substring(key.lastIndexOf('/') + 1, key.length());
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filename)));
byte[] b = new byte[1024]; int numBytes = 0; while ((numBytes = in.read(b)) > 0) { out.write(b, 0, numBytes); } in.close(); out.close(); primaryDoc = new Document(); primaryDoc.setBody(b); }
/** * If key is null - This method first deletes all the files in given folder and then the folder itself * If key is not null - This method deletes the given fileName */ public void delete(String bucketName, String folderName, AmazonS3 client, String fileName) { List<S3ObjectSummary> fileList = client.listObjects(bucketName, folderName).getObjectSummaries(); if(fileName!=null){ for (S3ObjectSummary file : fileList) { log.log("AWSS3ClientMain.delete(): fileName:"+fileName); log.log("AWSS3ClientMain.delete(): file.getKey():"+file.getKey()); if (file.getKey().contains(fileName)) { client.deleteObject(bucketName, file.getKey()); } } }else{ log.log("AWSS3ClientMain.delete(): fileName:"+fileName); for (S3ObjectSummary file : fileList) { client.deleteObject(bucketName, file.getKey()); } client.deleteObject(bucketName, folderName); }
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|