de.adorsys.jwebsane.controller.WebsaneController.java Source code

Java tutorial

Introduction

Here is the source code for de.adorsys.jwebsane.controller.WebsaneController.java

Source

/**
 * Copyright (C) 2012 Svetoslav Batchovski sba@adorsys.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.adorsys.jwebsane.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.List;

import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import au.com.southsky.jfreesane.RangeConstraint;
import au.com.southsky.jfreesane.SaneDevice;
import au.com.southsky.jfreesane.SaneOption;
import au.com.southsky.jfreesane.SaneSession;

import com.google.common.base.Charsets;
import com.google.common.base.Strings;

import de.adorsys.jwebsane.bean.ScanOptionsBean;
import de.adorsys.jwebsane.common.OptionConstants;

/**
 * 
 * @author Svetoslav Batchovski
 */
@Named
@ApplicationScoped
public class WebsaneController implements Serializable {

    private static final long serialVersionUID = 883783909478149750L;

    private Log log = LogFactory.getLog(WebsaneController.class.getName());

    @Inject
    private ScanOptionsBean scanOptionsBean;

    public void find() {
        try {
            createSession();
            openDevice();
            setResolutions();
            setScanModes();

            if (log.isDebugEnabled()) {
                listOptions();
            }

            closeDevice();
        } catch (IOException e) {
            log.error(e);
        }
    }

    public void preview() {
        try {
            openDevice();
            setPreviewDpi();

            // set max area
            setPreviewScanArea();

            // save preview image
            File outputfile = getFilePath(ScanOptionsBean.PREVIEW_FILE);
            BufferedImage image = scanOptionsBean.getDevice().acquireImage();
            ImageIO.write(image, "png", outputfile);
            scanOptionsBean.setImgFile(ScanOptionsBean.PREVIEW_FILE);
            log.debug("Preview image written in: " + outputfile.getAbsolutePath());
        } catch (Exception e) {
            log.error(e);
        } finally {
            closeDevice();
        }
    }

    private File getFilePath(String fileName) {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        ServletContext sc = (ServletContext) ec.getContext();
        File outputfile = new File(sc.getRealPath("/content/"), fileName);
        return outputfile;
    }

    private void setPreviewScanArea() throws IOException {
        setScanArea(
                scanOptionsBean.getDevice().getOption(OptionConstants.TL_X).getRangeConstraints().getMinimumFixed(),
                scanOptionsBean.getDevice().getOption(OptionConstants.TL_Y).getRangeConstraints().getMinimumFixed(),
                scanOptionsBean.getDevice().getOption(OptionConstants.BR_X).getRangeConstraints().getMaximumFixed(),
                scanOptionsBean.getDevice().getOption(OptionConstants.BR_Y).getRangeConstraints()
                        .getMaximumFixed());
    }

    public void scan() {
        try {
            openDevice();
            scanOptionsBean.getDevice().getOption(OptionConstants.RESOLUTION)
                    .setIntegerValue(scanOptionsBean.getDpi());
            setScanArea(scanOptionsBean.getTopLx(), scanOptionsBean.getTopLy(), scanOptionsBean.getBottomRx(),
                    scanOptionsBean.getBottomRy());
            scanOptionsBean.getDevice().getOption(OptionConstants.MODE).setStringValue(scanOptionsBean.getMode());
            File outputfile = File.createTempFile("scan", "png");
            BufferedImage image = scanOptionsBean.getDevice().acquireImage();

            FacesContext facesContext = FacesContext.getCurrentInstance();
            ExternalContext externalContext = facesContext.getExternalContext();
            HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

            response.setContentType("image/png");
            response.setHeader("Content-disposition", "attachment; filename=\"name.png\"");

            // Write file to response.
            OutputStream output = response.getOutputStream();
            ImageIO.write(image, "png", output);

            // Inform JSF to not take the response in hands.
            facesContext.responseComplete(); //
            log.debug("Scan image written in: " + outputfile.getAbsolutePath());
        } catch (Exception e) {
            log.error(e);
        } finally {
            closeDevice();
        }
    }

    private void setResolutions() throws IOException {
        RangeConstraint dpis = scanOptionsBean.getDevice().getOption(OptionConstants.RESOLUTION)
                .getRangeConstraints();

        scanOptionsBean.setMaxDpi(dpis.getMaximumInteger());
        scanOptionsBean.setMinDpi(dpis.getMinimumInteger());
    }

    private void setPreviewDpi() throws IOException {
        openDevice();

        if (scanOptionsBean.getDevice().getOption(OptionConstants.PREVIEW) != null) {
            scanOptionsBean.getDevice().getOption(OptionConstants.PREVIEW).setBooleanValue(true);
        }
        scanOptionsBean.getDevice().getOption(OptionConstants.RESOLUTION)
                .setIntegerValue(scanOptionsBean.getMinDpi());
    }

    private void createSession() {
        SaneSession session;
        try {
            session = SaneSession.withRemoteSane(InetAddress.getByName(scanOptionsBean.getServerAdress()));

            List<SaneDevice> devices = session.listDevices();

            if (CollectionUtils.isNotEmpty(devices)) {
                scanOptionsBean.setDevice(devices.get(0));
            }
        } catch (Exception e) {
            log.error(e);
        }
    }

    private void openDevice() {
        if (!scanOptionsBean.getDevice().isOpen()) {
            try {
                scanOptionsBean.getDevice().open();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

    private void closeDevice() {
        if (scanOptionsBean.getDevice().isOpen()) {
            try {
                scanOptionsBean.getDevice().close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }

    private void setScanModes() throws IOException {
        List<String> scanerModes = scanOptionsBean.getDevice().getOption(OptionConstants.MODE)
                .getStringContraints();

        if (CollectionUtils.isNotEmpty(scanerModes)) {
            for (String mode : scanOptionsBean.getDevice().getOption(OptionConstants.MODE).getStringContraints())
                if (!Strings.isNullOrEmpty(mode)) {
                    scanOptionsBean.getModes().put(mode, mode);
                }
        }
    }

    private void setScanArea(double tLX, double tLY, double bRX, double bRY) throws IOException {
        scanOptionsBean.getDevice().getOption(OptionConstants.TL_X).setFixedValue(tLX);
        scanOptionsBean.getDevice().getOption(OptionConstants.TL_Y).setFixedValue(tLY);
        scanOptionsBean.getDevice().getOption(OptionConstants.BR_X).setFixedValue(bRX);
        scanOptionsBean.getDevice().getOption(OptionConstants.BR_Y).setFixedValue(bRY);
    }

    private void listOptions() throws IOException {
        List<SaneOption> listOptions = scanOptionsBean.getDevice().listOptions();
        for (Iterator<SaneOption> iterator = listOptions.iterator(); iterator.hasNext();) {
            SaneOption option = (SaneOption) iterator.next();
            StringBuffer sb = new StringBuffer(option.getName() + ":" + option.getDescription());

            if (!option.isActive()) {
                sb.append(" [inactive]");
            } else {
                switch (option.getType()) {
                case INT:
                    sb.append("-" + option.getIntegerValue());
                    RangeConstraint range = option.getRangeConstraints();
                    if (range != null)
                        sb.append("-Range:" + range.getMinimumInteger() + "-" + range.getMaximumInteger());
                    break;
                case STRING:
                    sb.append("-" + option.getStringValue(Charsets.US_ASCII));
                    break;
                case BOOLEAN:
                    sb.append("-" + option.getBooleanValue());
                    break;
                case FIXED:
                    sb.append("-" + option.getFixedValue());
                    RangeConstraint range1 = option.getRangeConstraints();
                    if (range1 != null)
                        sb.append("-Range:" + range1.getMinimumFixed() + "-" + range1.getMaximumFixed());
                    break;
                default:
                    break;
                }
            }

            log.debug(sb.toString());
        }
    }
}