dataMappers.PictureDataMapper.java Source code

Java tutorial

Introduction

Here is the source code for dataMappers.PictureDataMapper.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dataMappers;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Nicolai
 */
public class PictureDataMapper {

    private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 140; // 140MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 150; // 150MB
    private static final String AMAZON_ACCESS_KEY = "AKIAJFBWBVEBFBAWW4MQ";
    private static final String AMAZON_SECRET_KEY = "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";
    private static final String S3_BUCKET_NAME = "polygon-img";

    // private static final Logger LOGGER = Logger.getLogger("AddPicture");
    public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
            throws FileUploadException, IOException, SQLException {

        if (!ServletFileUpload.isMultipartContent(request)) {
            System.out.println("Invalid upload request");
            return;
        }

        // Define limits for disk item
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);

        // Define limit for servlet upload
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);

        FileItem itemFile = null;
        int reportID = 0;

        // Get list of items in request (parameters, files etc.)
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // Loop items
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                itemFile = item; // If not form field, must be item
            } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
                try {
                    System.out.println(item.getString());
                    reportID = Integer.parseInt(item.getString());
                } catch (NumberFormatException e) {
                    reportID = 0;
                }
            }
        }

        // This will be null if no fields were declared as image/upload.
        // Also, reportID must be > 0
        if (itemFile != null || reportID == 0) {

            try {

                // Create credentials from final vars
                BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

                // Create client with credentials
                AmazonS3 s3client = new AmazonS3Client(awsCredentials);
                // Set region
                s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

                // Set content length (size) of file
                ObjectMetadata om = new ObjectMetadata();
                om.setContentLength(itemFile.getSize());

                // Get extension for file
                String ext = FilenameUtils.getExtension(itemFile.getName());
                // Generate random filename
                String keyName = UUID.randomUUID().toString() + '.' + ext;

                // This is the actual upload command
                s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

                // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
                PreparedStatement stmt = dbconnector.getCon()
                        .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

                stmt.setInt(1, reportID);
                stmt.setString(2, keyName);

                stmt.executeUpdate();

                stmt.close();

            } catch (AmazonServiceException ase) {

                System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                        + "to Amazon S3, but was rejected with an error response" + " for some reason.");
                System.out.println("Error Message:    " + ase.getMessage());
                System.out.println("HTTP Status Code: " + ase.getStatusCode());
                System.out.println("AWS Error Code:   " + ase.getErrorCode());
                System.out.println("Error Type:       " + ase.getErrorType());
                System.out.println("Request ID:       " + ase.getRequestId());

            } catch (AmazonClientException ace) {

                System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                        + "an internal error while trying to " + "communicate with S3, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message: " + ace.getMessage());

            }

        }
    }
}