com.kahlon.guard.controller.PersonImageManager.java Source code

Java tutorial

Introduction

Here is the source code for com.kahlon.guard.controller.PersonImageManager.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 com.kahlon.guard.controller;

import com.kahlon.guard.entity.Person;
import com.kahlon.guard.entity.PersonImage;
import com.prime.exception.GuardException;
import com.prime.exception.MessageEnum;
import com.kahlon.guard.service.ImageService;
import com.kahlon.guard.service.PersonService;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import org.apache.commons.io.IOUtils;
import org.primefaces.event.CaptureEvent;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.CroppedImage;

/**
 * Person Image Manager
 *
 * @author prime
 */
@Named("personImage")
@ViewScoped
public class PersonImageManager implements Serializable {

    private static final long serialVersionUID = 9196263323752494128L;

    private static final int IMG_WIDTH = 220;
    private static final int IMG_HEIGHT = 280;

    @Inject
    ImageService service;

    @Inject
    PersonService personService;

    @Inject
    GuardSessionContext context;

    @Inject
    Logger logger;

    @Inject
    FacesContext facesContext;

    private Person selectedPerson;

    private PersonImage newImage = new PersonImage();
    private PersonImage selectedImage;

    private List<PersonImage> images = new ArrayList<>();

    private List<PersonImage> filteredValues;

    private CroppedImage croppedImage;
    private String newImageName;
    private boolean imageUpload = true;
    private String photo;

    private List<String> fileNames = new ArrayList<>();

    @PostConstruct
    public void init() {
        logger.log(Level.INFO, "Initialize Person Profile Image Manager");
        if (context.getSelectedPerson() != null) {
            selectedPerson = context.getSelectedPerson();
            images = findPersonImages(selectedPerson);
            imageUpload = true;
        }
    }

    /**
     * Upload person image file
     *
     * @param event
     * @throws java.io.IOException
     */
    public void onUpload(FileUploadEvent event) throws IOException {
        photo = getRandomImageName();
        byte[] data = IOUtils.toByteArray(event.getFile().getInputstream());

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
                + "image" + File.separator + "temp" + File.separator + photo + ".png";
        if (fileNames == null) {
            fileNames = new ArrayList<>();
        }
        fileNames.add(newFileName);

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();

            BufferedImage originalImage = ImageIO.read(new File(newFileName));
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImagePng = resizeImageWithHint(originalImage, type);
            ImageIO.write(resizeImagePng, "png", new File(newFileName));

        } catch (Exception e) {
            throw new FacesException("Error in writing captured image.");
        }
        FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        imageUpload = false;
    }

    /**
     * Capture Image
     * 
     * @param captureEvent
     */
    public void onCapture(CaptureEvent captureEvent) {

        photo = getRandomImageName();
        byte[] data = captureEvent.getData();

        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
                + "image" + File.separator + "temp" + File.separator + photo + ".png";
        if (fileNames == null) {
            fileNames = new ArrayList<>();
        }
        fileNames.add(newFileName);

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            imageUpload = false;
        } catch (Exception e) {
            throw new FacesException("Error in writing captured image.");
        }
    }

    /**
     * Crop Image
     * @return
     */
    public String crop() {
        if (croppedImage == null) {
            return null;
        }

        setNewImageName(getRandomImageName());
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String newFileName = servletContext.getRealPath("") + File.separator + "resources" + File.separator
                + "image" + File.separator + "temp" + File.separator + getNewImageName() + ".png";
        if (fileNames == null) {
            fileNames = new ArrayList<>();
        }
        fileNames.add(newFileName);

        FileImageOutputStream imageOutput;
        try {
            imageOutput = new FileImageOutputStream(new File(newFileName));
            imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
            imageOutput.close();
        } catch (FileNotFoundException e) {
            throw new FacesException("File not found.", e.getCause());
        } catch (IOException e) {
            throw new FacesException("IO Exception found.", e.getCause());
        }

        return null;
    }

    private String getRandomImageName() {
        int i = (int) (Math.random() * 100000);

        return String.valueOf(i);
    }

    /**
     * Upload new person Image
     * 
     */
    public void doUpload() {
        try {
            if (croppedImage == null) {
                throw new GuardException("Crop image before upload");

            }
            byte[] data = croppedImage.getBytes();

            PersonImage image = new PersonImage();
            image.setImageDate(new Date());
            image.setContent(data);
            selectedPerson.setPersonImage(image);
            personService.update(selectedPerson);
            deleteImages();
            MessageEnum.SUCCESS.toString();
            context.refresh();
            init();
        } catch (GuardException e) {
            logger.log(Level.INFO, e.getMessage());
        }
    }

    /**
     * Delete temporary image files
     * 
     * @return 
     */
    private boolean deleteImages() {
        for (String fl : fileNames) {
            File file = new File(fl);
            boolean success = file.delete();
            if (!success) {
                return Boolean.FALSE;
            }
        }
        return Boolean.TRUE;
    }

    /**
     * Reset
     *
     * @param event
     */
    public void reset(ActionEvent event) {
        init();

    }

    /**
     * Create new Profile Image
     *
     * @param event
     */
    public void doCreate(ActionEvent event) {
        try {
            newImage.setPerson(selectedPerson);
            service.createImage(newImage);
            ;
            MessageEnum.SUCCESS.toString();
            newImage = new PersonImage();
            init();
        } catch (GuardException e) {
            logger.log(Level.INFO, e.getMessage());
        }
    }

    /**
     * Return Person Images
     *
     * @param person
     * @return
     */
    public List<PersonImage> findPersonImages(Person person) {
        return service.getPersonImages(person);
    }

    private BufferedImage resizeImage(BufferedImage originalImage, int type) {
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();

        return resizedImage;
    }

    private BufferedImage resizeImageWithHint(BufferedImage originalImage, int type) {

        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        return resizedImage;
    }

    //getter's and setter's
    public Person getSelectedPerson() {
        return selectedPerson;
    }

    public void setSelectedPerson(Person selectedPerson) {
        this.selectedPerson = selectedPerson;
    }

    public PersonImage getNewImage() {
        return newImage;
    }

    public void setNewImage(PersonImage newImage) {
        this.newImage = newImage;
    }

    public PersonImage getSelectedImage() {
        return selectedImage;
    }

    public void setSelectedImage(PersonImage selectedImage) {
        this.selectedImage = selectedImage;
    }

    public List<PersonImage> getImages() {
        return images;
    }

    public void setImages(List<PersonImage> images) {
        this.images = images;
    }

    public List<PersonImage> getFilteredValues() {
        return filteredValues;
    }

    public void setFilteredValues(List<PersonImage> filteredValues) {
        this.filteredValues = filteredValues;
    }

    public CroppedImage getCroppedImage() {
        return croppedImage;
    }

    public void setCroppedImage(CroppedImage croppedImage) {
        this.croppedImage = croppedImage;
    }

    public String getNewImageName() {
        return newImageName;
    }

    public void setNewImageName(String newImageName) {
        this.newImageName = newImageName;
    }

    public boolean isImageUpload() {
        return imageUpload;
    }

    public void setImageUpload(boolean imageUpload) {
        this.imageUpload = imageUpload;
    }

    public List<String> getFileNames() {
        return fileNames;
    }

    public void setFileNames(List<String> fileNames) {
        this.fileNames = fileNames;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }

}