Search in sources :

Example 16 with SdkBytes

use of software.amazon.awssdk.core.SdkBytes in project aws-doc-sdk-examples by awsdocs.

the class SendMessage method send.

public void send(byte[] attachment, String emailAddress) throws MessagingException, IOException {
    MimeMessage message = null;
    Session session = Session.getDefaultInstance(new Properties());
    // Create a new MimeMessage object
    message = new MimeMessage(session);
    // Add subject, from and to lines
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
    // Create a multipart/alternative child container
    MimeMultipart msgBody = new MimeMultipart("alternative");
    // Create a wrapper for the HTML and text parts
    MimeBodyPart wrap = new MimeBodyPart();
    // Define the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");
    // Define the HTML part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");
    // Add the text and HTML parts to the child container
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);
    // Add the child container to the wrapper object
    wrap.setContent(msgBody);
    // Create a multipart/mixed parent container
    MimeMultipart msg = new MimeMultipart("mixed");
    // Add the parent container to the message
    message.setContent(msg);
    // Add the multipart/alternative part to the message
    msg.addBodyPart(wrap);
    // Define the attachment
    MimeBodyPart att = new MimeBodyPart();
    DataSource fds = new ByteArrayDataSource(attachment, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    att.setDataHandler(new DataHandler(fds));
    String reportName = "WorkReport.xls";
    att.setFileName(reportName);
    // Add the attachment to the message
    msg.addBodyPart(att);
    // Send the email
    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
        Region region = Region.US_WEST_2;
        SesClient client = SesClient.builder().credentialsProvider(EnvironmentVariableCredentialsProvider.create()).region(region).build();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);
        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);
        SdkBytes data = SdkBytes.fromByteArray(arr);
        RawMessage rawMessage = RawMessage.builder().data(data).build();
        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder().rawMessage(rawMessage).build();
        client.sendRawEmail(rawEmailRequest);
    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    System.out.println("Email sent with attachment");
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SesClient(software.amazon.awssdk.services.ses.SesClient) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) ByteBuffer(java.nio.ByteBuffer) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) SdkBytes(software.amazon.awssdk.core.SdkBytes) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Region(software.amazon.awssdk.regions.Region) SendRawEmailRequest(software.amazon.awssdk.services.ses.model.SendRawEmailRequest) MimeBodyPart(javax.mail.internet.MimeBodyPart) RawMessage(software.amazon.awssdk.services.ses.model.RawMessage) SesException(software.amazon.awssdk.services.ses.model.SesException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Session(javax.mail.Session)

Example 17 with SdkBytes

use of software.amazon.awssdk.core.SdkBytes in project aws-doc-sdk-examples by awsdocs.

the class AnalyzePhotos method detectLabels.

// Returns a list of GearItem objects that contains PPE information.
public ArrayList<GearItem> detectLabels(byte[] bytes, String key) {
    Region region = Region.US_EAST_2;
    RekognitionClient rekClient = RekognitionClient.builder().region(region).build();
    ArrayList<GearItem> gearList = new ArrayList<>();
    try {
        SdkBytes sourceBytes = SdkBytes.fromByteArray(bytes);
        // Create an Image object for the source image.
        Image souImage = Image.builder().bytes(sourceBytes).build();
        ProtectiveEquipmentSummarizationAttributes summarizationAttributes = ProtectiveEquipmentSummarizationAttributes.builder().minConfidence(80F).requiredEquipmentTypesWithStrings("FACE_COVER", "HAND_COVER", "HEAD_COVER").build();
        DetectProtectiveEquipmentRequest request = DetectProtectiveEquipmentRequest.builder().image(souImage).summarizationAttributes(summarizationAttributes).build();
        DetectProtectiveEquipmentResponse result = rekClient.detectProtectiveEquipment(request);
        List<ProtectiveEquipmentPerson> persons = result.persons();
        // Create a GearItem object.
        GearItem gear;
        for (ProtectiveEquipmentPerson person : persons) {
            List<ProtectiveEquipmentBodyPart> bodyParts = person.bodyParts();
            if (bodyParts.isEmpty()) {
                System.out.println("\tNo body parts detected");
            } else
                for (ProtectiveEquipmentBodyPart bodyPart : bodyParts) {
                    List<EquipmentDetection> equipmentDetections = bodyPart.equipmentDetections();
                    if (equipmentDetections.isEmpty()) {
                        System.out.println("\t\tNo PPE Detected on " + bodyPart.name());
                    } else {
                        for (EquipmentDetection item : equipmentDetections) {
                            gear = new GearItem();
                            gear.setKey(key);
                            String itemType = item.type().toString();
                            String confidence = item.confidence().toString();
                            String myDesc = "Item: " + item.type() + ". Confidence: " + item.confidence().toString();
                            String bodyPartDes = "Covers body part: " + item.coversBodyPart().value().toString() + ". Confidence: " + item.coversBodyPart().confidence().toString();
                            gear.setName(itemType);
                            gear.setConfidence(confidence);
                            gear.setItemDescription(myDesc);
                            gear.setBodyCoverDescription(bodyPartDes);
                            // push the object.
                            gearList.add(gear);
                        }
                    }
                }
        }
        if (gearList.isEmpty())
            return null;
        else
            return gearList;
    } catch (RekognitionException e) {
        System.out.println(e.getMessage());
        System.exit(1);
    }
    return null;
}
Also used : ProtectiveEquipmentSummarizationAttributes(software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentSummarizationAttributes) RekognitionException(software.amazon.awssdk.services.rekognition.model.RekognitionException) ArrayList(java.util.ArrayList) ProtectiveEquipmentBodyPart(software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentBodyPart) Image(software.amazon.awssdk.services.rekognition.model.Image) DetectProtectiveEquipmentRequest(software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentRequest) SdkBytes(software.amazon.awssdk.core.SdkBytes) EquipmentDetection(software.amazon.awssdk.services.rekognition.model.EquipmentDetection) ProtectiveEquipmentPerson(software.amazon.awssdk.services.rekognition.model.ProtectiveEquipmentPerson) Region(software.amazon.awssdk.regions.Region) RekognitionClient(software.amazon.awssdk.services.rekognition.RekognitionClient) ArrayList(java.util.ArrayList) List(java.util.List) DetectProtectiveEquipmentResponse(software.amazon.awssdk.services.rekognition.model.DetectProtectiveEquipmentResponse)

Example 18 with SdkBytes

use of software.amazon.awssdk.core.SdkBytes in project aws-doc-sdk-examples by awsdocs.

the class EncryptDataKey method encryptData.

// snippet-start:[kms.java2_encrypt_data.main]
public static SdkBytes encryptData(KmsClient kmsClient, String keyId) {
    try {
        SdkBytes myBytes = SdkBytes.fromByteArray(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 });
        EncryptRequest encryptRequest = EncryptRequest.builder().keyId(keyId).plaintext(myBytes).build();
        EncryptResponse response = kmsClient.encrypt(encryptRequest);
        String algorithm = response.encryptionAlgorithm().toString();
        System.out.println("The encryption algorithm is " + algorithm);
        // Get the encrypted data.
        SdkBytes encryptedData = response.ciphertextBlob();
        return encryptedData;
    } catch (KmsException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    return null;
}
Also used : SdkBytes(software.amazon.awssdk.core.SdkBytes) EncryptResponse(software.amazon.awssdk.services.kms.model.EncryptResponse) KmsException(software.amazon.awssdk.services.kms.model.KmsException) EncryptRequest(software.amazon.awssdk.services.kms.model.EncryptRequest)

Example 19 with SdkBytes

use of software.amazon.awssdk.core.SdkBytes in project aws-doc-sdk-examples by awsdocs.

the class SendMessageAttachment method sendemailAttachment.

// snippet-start:[ses.java2.sendmessageattachment.main]
public static void sendemailAttachment(SesClient client, String sender, String recipient, String subject, String bodyText, String bodyHTML, String fileLocation) throws AddressException, MessagingException, IOException {
    java.io.File theFile = new java.io.File(fileLocation);
    byte[] fileContent = Files.readAllBytes(theFile.toPath());
    Session session = Session.getDefaultInstance(new Properties());
    // Create a new MimeMessage object
    MimeMessage message = new MimeMessage(session);
    // Add subject, from and to lines
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
    // Create a multipart/alternative child container
    MimeMultipart msgBody = new MimeMultipart("alternative");
    // Create a wrapper for the HTML and text parts
    MimeBodyPart wrap = new MimeBodyPart();
    // Define the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");
    // Define the HTML part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");
    // Add the text and HTML parts to the child container
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);
    // Add the child container to the wrapper object
    wrap.setContent(msgBody);
    // Create a multipart/mixed parent container
    MimeMultipart msg = new MimeMultipart("mixed");
    // Add the parent container to the message
    message.setContent(msg);
    // Add the multipart/alternative part to the message
    msg.addBodyPart(wrap);
    // Define the attachment
    MimeBodyPart att = new MimeBodyPart();
    DataSource fds = new ByteArrayDataSource(fileContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    att.setDataHandler(new DataHandler(fds));
    String reportName = "WorkReport.xls";
    att.setFileName(reportName);
    // Add the attachment to the message.
    msg.addBodyPart(att);
    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);
        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);
        SdkBytes data = SdkBytes.fromByteArray(arr);
        RawMessage rawMessage = RawMessage.builder().data(data).build();
        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder().rawMessage(rawMessage).build();
        client.sendRawEmail(rawEmailRequest);
    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    System.out.println("Email sent with attachment");
// snippet-end:[ses.java2.sendmessageattachment.main]
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) ByteBuffer(java.nio.ByteBuffer) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) SdkBytes(software.amazon.awssdk.core.SdkBytes) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SendRawEmailRequest(software.amazon.awssdk.services.ses.model.SendRawEmailRequest) MimeBodyPart(javax.mail.internet.MimeBodyPart) RawMessage(software.amazon.awssdk.services.ses.model.RawMessage) SesException(software.amazon.awssdk.services.ses.model.SesException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Session(javax.mail.Session)

Example 20 with SdkBytes

use of software.amazon.awssdk.core.SdkBytes in project aws-doc-sdk-examples by awsdocs.

the class DetectDocumentText method detectDocText.

// snippet-start:[textract.java2._detect_doc_text.main]
public static void detectDocText(TextractClient textractClient, String sourceDoc) {
    try {
        InputStream sourceStream = new FileInputStream(new File(sourceDoc));
        SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
        // Get the input Document object as bytes
        Document myDoc = Document.builder().bytes(sourceBytes).build();
        DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder().document(myDoc).build();
        // Invoke the Detect operation
        DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest);
        List<Block> docInfo = textResponse.blocks();
        Iterator<Block> blockIterator = docInfo.iterator();
        while (blockIterator.hasNext()) {
            Block block = blockIterator.next();
            System.out.println("The block type is " + block.blockType().toString());
        }
        DocumentMetadata documentMetadata = textResponse.documentMetadata();
        System.out.println("The number of pages in the document is " + documentMetadata.pages());
    } catch (TextractException | FileNotFoundException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) TextractException(software.amazon.awssdk.services.textract.model.TextractException) FileNotFoundException(java.io.FileNotFoundException) Document(software.amazon.awssdk.services.textract.model.Document) DetectDocumentTextRequest(software.amazon.awssdk.services.textract.model.DetectDocumentTextRequest) FileInputStream(java.io.FileInputStream) DetectDocumentTextResponse(software.amazon.awssdk.services.textract.model.DetectDocumentTextResponse) SdkBytes(software.amazon.awssdk.core.SdkBytes) DocumentMetadata(software.amazon.awssdk.services.textract.model.DocumentMetadata) Block(software.amazon.awssdk.services.textract.model.Block) File(java.io.File)

Aggregations

SdkBytes (software.amazon.awssdk.core.SdkBytes)37 InputStream (java.io.InputStream)14 FileInputStream (java.io.FileInputStream)13 FileNotFoundException (java.io.FileNotFoundException)13 Image (software.amazon.awssdk.services.rekognition.model.Image)13 RekognitionException (software.amazon.awssdk.services.rekognition.model.RekognitionException)10 ByteArrayOutputStream (java.io.ByteArrayOutputStream)9 ByteBuffer (java.nio.ByteBuffer)9 Properties (java.util.Properties)9 Session (javax.mail.Session)9 InternetAddress (javax.mail.internet.InternetAddress)9 MimeBodyPart (javax.mail.internet.MimeBodyPart)9 MimeMessage (javax.mail.internet.MimeMessage)9 MimeMultipart (javax.mail.internet.MimeMultipart)9 Region (software.amazon.awssdk.regions.Region)9 RawMessage (software.amazon.awssdk.services.ses.model.RawMessage)9 SendRawEmailRequest (software.amazon.awssdk.services.ses.model.SendRawEmailRequest)9 SesException (software.amazon.awssdk.services.ses.model.SesException)9 DataHandler (javax.activation.DataHandler)6 DataSource (javax.activation.DataSource)6