All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.asprise.imaging.core.Request Maven / Gradle / Ivy

Go to download

Acquire images from and have total control on almost all kinds of scanners on both Windows 32bit and 64bit.

There is a newer version: 12.0.20.3
Show newest version
/**********************************************************************************************
 *
 * Asprise Scanning and Imaging API - http://asprise.com/document-scanner-image-pdf/java-scanning-api-overview.html
 * Copyright (C) 1998-2018. Asprise Inc. 
 *
 * This file is licensed under the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation.
 *
 * 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.
 *
 * You should have received a copy of the GNU Affero General Public License.  If not, please
 * visit .
 *
 **********************************************************************************************/
package com.asprise.imaging.core;

import com.asprise.imaging.core.scan.twain.TwainConstants;
import com.asprise.imaging.core.scan.twain.TwainUtil;
import com.asprise.imaging.core.util.JsonUtils;
import com.asprise.imaging.core.util.system.StringUtils;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.jr.ob.JSON;

import javax.swing.*;
import java.awt.Dimension;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Represents a scan request.
 */
public class Request implements Cloneable {

    public static final double DEFAULT_BLANK_PAGE_THRESHOLD = 0.02;
    public static final int DEFAULT_BLANK_PAGE_MARGIN_PERCENT = 8;

    public static final String SEP_MARKER_NEW = "NEW";
    public static final String SEP_MARKER_NEW_SEP = "NEW_SEP";
    public static final String SEP_MARKER_NO = "NO";

    /** Request ID */
    String id;
    /** Custom request data */
    Object data;

    /**
     * By default images will be processed after each scan; Set to true to process images after all scans.
     * Processing images after all scan could speed up the scanning process.
     */
    boolean processImagesAfterAllScans = false;

    /** Whether to prompt scan more dialog. */
    boolean promptScanMore = false;

    /** Whether blank pages should be detected. */
    boolean detectBlankPages = false;

    /** What to do with blank page? */
    String blankPagePolicy;

    /** Ink coverage threshold to determine if a page is blank. */
    double blankPageThreshold = DEFAULT_BLANK_PAGE_THRESHOLD;

    /** Percentage of margin to be excluded when calculating ink coverage. */
    int blankPageMarginPercent = DEFAULT_BLANK_PAGE_MARGIN_PERCENT;

    /** Whether barcodes should be recognized. */
    boolean recognizeBarcodes;

    int barcodesDpi;
    Object barcodesSettings;

    /** Map of cap name (could be appended with operation and priority, e.g., /RESET, /SET/3456) */
    Map twainCapSetting = new HashMap();

    /** Names of caps to be retrieved. */
    Set retrieveCaps = new HashSet();

    /** Name of extended image attributes to be retrieved. */
    Set retrieveExtendedImageAttributes = new HashSet();

    /** Output specifications. */
    List outputItems = new ArrayList();

    /** List of image files. */
    List imageFiles = new ArrayList();
    /** Corresponding item to imageFiles if any */
    List imageFilesItems = new ArrayList();

    Boolean useAspriseDialog = null;
    String dialogTitle = null;
    int dialogWidth = -1;
    int dialogHeight = -1;
    String instruction;
    Boolean showScannerUI = null;
    Boolean modalScannerUI = null;
    String sourceName = null;
    Boolean onWebServer = null;

    int adfMaxPages = -1;

    /** Display logging window in case of error. */
    Boolean showLoggingOnError = null;

    /** "doc_separators": ["TWEI_PATCHCODE:5:DOC_SEP", "blank:DOC_SEP", "barcode:abc*:DOC_NEW"]. */
    List docSeparators = null;

    Boolean selectOutputTypeAndFileName;
    /** e.g., "Attach|Insert" */
    String selectOutputActions;
    /** e.g., ".pdf|.jpg" */
    String selectOutputType;
    /** any file name without extension */
    String selectOutputFileName;

    /** i18n */
    Properties i18n = new Properties();

    /** ui_controls_config */
    Properties uiControlsConfig = new Properties();

    /** The root of JSON object that this request is deserialized from. */
    Map sourceJson;

    /** Whether to enable 'Use last scanned' button */
    Boolean enableUseLastScanned;

    public static String I18N_PROPS_PREFIX = "ascan_trans";

    /** Message appears on scan more dialog */
    public static String I18N_SCAN_MORE_DIALOG_MESSAGE = "scan_more_dialog_message";
    public static String I18N_SCAN_MORE_DIALOG_TITLE = "scan_more_dialog_title";

    public static String I18N_SELECT_SOURCE_TITLE = "select_source_title";
    public static String I18N_SELECT_SOURCE_SOURCES = "select_source_sources";
    public static String I18N_SELECT_SOURCE_WIA_SOURCES = "select_source_wia_sources";
    public static String I18N_SELECT_SOURCE_SELECT = "select_source_select";
    public static String I18N_SELECT_SOURCE_CANCEL = "select_source_cancel";
    public static String I18N_SELECT_SOURCE_REFRESH = "select_source_refresh";
    public static String I18N_SELECT_SOURCE_CANCEL_MESG = "select_source_cancel_mesg";
    public static String I18N_SELECT_SOURCE_CANCEL_TITLE = "select_source_cancel_title";

    public static String I18N_SCAN_PANEL_SCANNER = "scan_panel_scanner";
    public static String I18N_SCAN_PANEL_PAPER_SOURCE = "scan_panel_paper_source";
    /** Map of key to value; entry separated by | and key/value separated by = */
    public static String I18N_SCAN_PANEL_PAPER_SOURCE_ELEMENTS = "scan_panel_paper_source_elements";
    public static String I18N_SCAN_PANEL_PAPER_SIZE = "scan_panel_paper_size";
    public static String I18N_SCAN_PANEL_PAPER_SIZE_ELEMENTS = "scan_panel_paper_size_elements";
    public static String I18N_SCAN_PANEL_COLOR_MODE = "scan_panel_color_mode";
    public static String I18N_SCAN_PANEL_COLOR_MODE_ELEMENTS = "scan_panel_color_mode_elements";
    public static String I18N_SCAN_PANEL_RESOLUTION = "scan_panel_resolution";
    public static String I18N_SCAN_PANEL_RESOLUTION_FORMAT = "scan_panel_resolution_format";
    public static String I18N_SCAN_PANEL_BRIGHTNESS = "scan_panel_brightness";
    public static String I18N_SCAN_PANEL_CONTRAST = "scan_panel_contrast";
    public static String I18N_SCAN_PANEL_PROMPT_SCAN_MORE = "scan_panel_prompt_scan_more";
    public static String I18N_SCAN_PANEL_REMOVE_BLANK = "scan_panel_remove_blank";
    public static String I18N_SCAN_PANEL_SCANNER_UI = "scan_panel_scanner_ui";
    public static String I18N_SCAN_PANEL_SCAN = "scan_panel_scan";
    public static String I18N_SCAN_PANEL_SCAN_TOOLTIP = "scan_panel_scan_tooltip";
    public static String I18N_SCAN_PANEL_REFRESH_TOOLTIP = "scan_panel_refresh_tooltip";
    public static String I18N_SCAN_PANEL_NO_SCANNER_FOUND = "scan_panel_no_scanner_found";

    public static String I18N_IMAGE_THUMB_EDIT = "image_thumb_edit";
    public static String I18N_IMAGE_THUMB_DELETE = "image_thumb_delete";
    public static String I18N_IMAGE_THUMB_MARK_DOC_SEP = "image_thumb_mark_doc_sep";
    public static String I18N_IMAGE_THUMB_MARK_NEW_DOC = "image_thumb_mark_new_doc";
    public static String I18N_IMAGE_THUMB_UNMARK = "image_thumb_unmark";
    public static String I18N_IMAGE_THUMB_TOOLTIP_DND = "image_thumb_tooltip_dnd";

    public static String I18N_SCAN_UI_TITLE = "scan_ui_title";
    public static String I18N_SCAN_UI_OK = "scan_ui_ok";
    public static String I18N_SCAN_UI_CANCEL = "scan_ui_cancel";
    public static String I18N_SCAN_UI_USE_LAST_SCANNED = "scan_use_last_scanned";
    public static String I18N_SCAN_UI_PAGES_FORMAT = "scan_ui_pages_format";

    public static String I18N_SCAN_UI_DISCARD_MESSAGE = "scan_ui_discard_mesg";
    public static String I18N_SCAN_UI_DISCARD_TITLE = "scan_ui_discard_title";
    public static String I18N_SCAN_UI_REMOVE_MESSAGE = "scan_ui_remove_mesg";
    public static String I18N_SCAN_UI_REMOVE_TITLE = "scan_ui_remove_title";
    public static String I18N_SCAN_UI_INSTRUCTION_PANEL = "scan_ui_instruction_panel";
    public static String I18N_SCAN_UI_SCAN_PANEL = "scan_ui_scan_panel";
    public static String I18N_SCAN_UI_NO_IMAGE_SCANNED = "scan_ui_no_image_scanned";

    public static String I18N_STATUS_READY = "status_ready";
    public static String I18N_STATUS_MEMORY = "status_memory";
    public static String I18N_STATUS_MEMORY_FORMAT_2 = "status_memory_format_2";

    public static String I18N_OPERATION_IN_PROGRESS = "operation_in_progress";

    public static String I18N_SCAN_SELECT_FORMAT_ACTIONS_ELEMENTS = "scan_select_format_actions_elements";

    public static String I18N_LANG = "lang";
    public static String I18N_LANG_ENGLISH = "en";
    public static String I18N_LANG_FRENCH = "fr";
    public static String I18N_LANG_GERMAN = "de";
    public static String I18N_LANG_ITALIAN = "it";
    public static String I18N_LANG_PORTUGUESE = "pt";
    public static String I18N_LANG_SPANISH = "es";
    public static String I18N_LANG_RUSSIAN = "ru";

    public static String I18N_LANG_JAPANESE = "ja";
    public static String I18N_LANG_CHINESE_SIMPLIFIED = "zh";

    /** User's locale */
    public static String I18N_LANG_USER = "user";

    @Override
    public Object clone() throws CloneNotSupportedException {
        Request clone = (Request) super.clone();
        clone.twainCapSetting = (Map) ((HashMap)twainCapSetting).clone();
        clone.retrieveCaps = (Set) ((HashSet)retrieveCaps).clone();
        clone.retrieveExtendedImageAttributes = (Set) ((HashSet)retrieveExtendedImageAttributes).clone();
        clone.outputItems = new ArrayList();
        for(RequestOutputItem item : outputItems) {
            clone.outputItems.add((RequestOutputItem) item.clone());
        }
        clone.imageFiles = new ArrayList(imageFiles);
        clone.imageFilesItems = new ArrayList(imageFilesItems);
        if(docSeparators != null) {
            clone.docSeparators = new ArrayList(docSeparators);
        }
        clone.i18n = (Properties) (i18n).clone();
        //clone.uiControlsConfig = new Properties(uiControlsConfig); // (Properties) (uiControlsConfig).clone();
        return clone;
    }

    /**
     * Constructor.
     */
    public Request() {
        id = Long.toString(System.currentTimeMillis());
    }

    public String toJson(boolean pretty) {
        return JsonUtils.jsonSerialize(toJsonObject(), pretty);
    }

    public static Request fromJson(String spec) throws IOException {
        JsonParser parser = new JsonFactory().enable(JsonParser.Feature.ALLOW_COMMENTS).createParser(spec);
        Map json = JSON.std.mapFrom(parser);

        Request request = new Request();
        request.id = JsonUtils.attrValue(json, "request_id", null);
        request.data = json.get("request_data");
        request.processImagesAfterAllScans = "after-all-scans".equals(JsonUtils.attrValue(json, "processing_strategy", null));
        request.promptScanMore = JsonUtils.attrValueAsBoolean(json, "prompt_scan_more", false);
        request.detectBlankPages = JsonUtils.attrValueAsBoolean(json, "detect_blank_pages", false);
        request.blankPagePolicy = JsonUtils.attrValue(json, "blank_page_policy", null);
        request.blankPageThreshold = JsonUtils.attrValueAsDouble(json, "blank_page_threshold", DEFAULT_BLANK_PAGE_THRESHOLD);
        request.blankPageMarginPercent = JsonUtils.attrValueAsInt(json, "blank_page_margin_percent", DEFAULT_BLANK_PAGE_MARGIN_PERCENT);
        request.recognizeBarcodes = JsonUtils.attrValueAsBoolean(json, "recognize_barcodes", false);

        request.barcodesDpi = JsonUtils.attrValueAsInt(json, "barcodes_dpi", -1);
        request.barcodesSettings = json.get("barcodes_settings");

        request.useAspriseDialog = JsonUtils.attrValueAsBoolean(json, "use_asprise_dialog", null);
        request.showScannerUI = JsonUtils.attrValueAsBoolean(json, "show_scanner_ui", null);
        request.modalScannerUI = JsonUtils.attrValueAsBoolean(json, "modal_scanner_ui", null);
        request.dialogTitle = JsonUtils.attrValueAsString(json, "dialog_title", null);
        request.dialogWidth = JsonUtils.attrValueAsInt(json, "dialog_width", -1);
        request.dialogHeight = JsonUtils.attrValueAsInt(json, "dialog_height", -1);
        request.instruction = JsonUtils.attrValueAsString(json, "instruction", null);
        request.sourceName = JsonUtils.attrValue(json, "source_name", null);

        request.adfMaxPages = JsonUtils.attrValueAsInt(json, "adf_max_pages", -1);

        request.showLoggingOnError = JsonUtils.attrValueAsBoolean(json, "show_logging_on_error", true);

        request.onWebServer = JsonUtils.attrValueAsBoolean(json, "on_web_server", false);
        request.selectOutputTypeAndFileName = JsonUtils.attrValueAsBoolean(json, "select_output_type_file_name", false);
        request.selectOutputActions = JsonUtils.attrValue(json, "select_output_action", null);
        request.selectOutputType = JsonUtils.attrValue(json, "select_output_type", null);
        request.selectOutputFileName = JsonUtils.attrValue(json, "select_output_file_name", null);

        request.enableUseLastScanned = JsonUtils.attrValueAsBoolean(json, "enable_use_last_scanned", false);

        List jsonDocSeps = (List)json.get("doc_separators");
        for(int i = 0; jsonDocSeps != null && i < jsonDocSeps.size(); i++) {
            if(request.docSeparators == null) {
                request.docSeparators = new ArrayList();
            }
            request.docSeparators.add((String)jsonDocSeps.get(i));
        }

        Map caps = (Map) json.get("twain_cap_setting");
        if(caps != null) {
            request.twainCapSetting.putAll(caps);
        }

        List outputs = (List) json.get("output_settings");
        for(int i = 0; outputs != null && i < outputs.size(); i++) {
            request.outputItems.add(RequestOutputItem.fromJsonMap((Map) outputs.get(i)));
        }

        if(json.get("retrieve_caps") instanceof Collection) {
            request.retrieveCaps.addAll((Collection) json.get("retrieve_caps"));
        }

        if(json.get("retrieve_extended_image_attrs") instanceof Collection) {
            request.retrieveExtendedImageAttributes.addAll((Collection) json.get("retrieve_extended_image_attrs"));
        }

        List imgFiles = (List)json.get("image_files");
        for(int i = 0; imgFiles != null && i < imgFiles.size(); i++) {
            request.imageFiles.add(new File((String)imgFiles.get(i)));
        }

        List imgFilesItems = (List)json.get("image_files_items");
        for(int i = 0; imgFilesItems != null && i < imgFilesItems.size(); i++) {
            request.imageFilesItems.add(new ResultImageItem((Map) imgFilesItems.get(i)));
        }

        Map mapI18n = (Map) json.get("i18n");
        if(mapI18n != null) {
            for(Object key : mapI18n.keySet()) {
                if(key != null) {
                    Object value = mapI18n.get(key);
                    request.i18n.setProperty(key.toString(), value == null ? "" : value.toString());
                }
            }
            request.i18n.putAll(mapI18n);
        }

        Map mapUiControlsConfig = (Map) json.get("ui_controls_config");
        if(mapUiControlsConfig != null) {
            for (Object key : mapUiControlsConfig.keySet()) {
                if(key != null) {
                    Object value = mapUiControlsConfig.get(key);
                    request.uiControlsConfig.setProperty(key.toString(), value == null ? "" : value.toString());
                }
            }
        }

        request.sourceJson = json;
        return request;
    }

    public Map toJsonObject() {
        Map json = new HashMap();
        json.put("request_id", id);
        if(data != null) {
            json.put("request_data", data);
        }
        if(processImagesAfterAllScans) {
            json.put("processing_strategy", "after-all-scans");
        }

        if(twainCapSetting.size() > 0) {
            json.put("twain_cap_setting", twainCapSetting);
        }

        json.put("prompt_scan_more", promptScanMore);
        json.put("detect_blank_pages", detectBlankPages);
        json.put("blank_page_policy", blankPagePolicy);
        json.put("blank_page_threshold", blankPageThreshold);
        json.put("blank_page_margin_percent", blankPageMarginPercent);

        json.put("recognize_barcodes", recognizeBarcodes);

        if(barcodesDpi > 0) {
            json.put("barcodes_dpi", barcodesDpi);
        }

        if(barcodesSettings != null) {
            json.put("barcodes_settings", barcodesSettings);
        }

        if(onWebServer != null && onWebServer) {
            json.put("on_web_server", onWebServer);
        }

        List outputJsons = new ArrayList();
        for(int o = 0; outputItems != null && o < outputItems.size(); o++) {
            outputJsons.add(outputItems.get(o).toJsonObject());
        }
        json.put("output_settings", outputJsons);

        json.put("retrieve_caps", retrieveCaps);

        json.put("retrieve_extended_image_attrs", retrieveExtendedImageAttributes);

        List imgFilesJson = new ArrayList();
        for(int i = 0; imageFiles != null && i < imageFiles.size(); i++) {
            imgFilesJson.add(imageFiles.get(i).getAbsolutePath());
        }
        if(imgFilesJson.size() > 0) {
            json.put("image_files", imgFilesJson);
        }

        List imgFileItemsJson = new ArrayList();
        for(int i = 0; imageFilesItems != null && i < imageFilesItems.size(); i++) {
            imgFileItemsJson.add(imageFilesItems.get(i).toJsonObject());
        }
        if(imgFileItemsJson.size() > 0) {
            json.put("image_files_items", imgFileItemsJson);
        }

        if(useAspriseDialog != null) {
            json.put("use_asprise_dialog", useAspriseDialog);
        }
        if(dialogTitle != null) {
            json.put("dialog_title", dialogTitle);
        }
        if(dialogWidth > 0) {
            json.put("dialog_width", dialogWidth);
        }
        if(dialogHeight > 0) {
            json.put("dialog_height", dialogWidth);
        }
        if(instruction != null) {
            json.put("instruction", instruction);
        }
        if(showScannerUI != null) {
            json.put("show_scanner_ui", showScannerUI);
        }
        if(showLoggingOnError != null && !showLoggingOnError) {
            json.put("show_logging_on_error", showLoggingOnError);
        }
        if(modalScannerUI != null) {
            json.put("modal_scanner_ui", modalScannerUI);
        }
        if(sourceName != null) {
            json.put("source_name", sourceName);
        }

        if(adfMaxPages > 0) {
            json.put("adf_max_pages", adfMaxPages);
        }

        if(docSeparators != null) {
            json.put("doc_separators", docSeparators);
        }

        if(i18n.size() > 0) {
            json.put("i18n", i18n);
        }

        if(uiControlsConfig.size() > 0) {
            json.put("ui_controls_config", uiControlsConfig);
        }

        if(selectOutputTypeAndFileName != null && selectOutputTypeAndFileName) {
            json.put("select_output_type_file_name", selectOutputTypeAndFileName);
            if(! StringUtils.isEmpty(selectOutputActions)) {
                json.put("select_output_action", selectOutputActions);
            }
            if(! StringUtils.isEmpty(selectOutputType)) {
                json.put("select_output_type", selectOutputType);
            }
            if(! StringUtils.isEmpty(selectOutputFileName)) {
                json.put("select_output_file_name", selectOutputFileName);
            }
        }

        return json;
    }

    static String[] keywordsWithExtras;

    public static String[] getKeywordsWithExtras() {
        if(keywordsWithExtras == null) {
            String[] array1 = getKeywords();
            String[] array2 = TwainConstants.getConstants();
            keywordsWithExtras = new String[array1.length + array2.length];
            System.arraycopy(array1, 0, keywordsWithExtras, 0, array1.length);
            System.arraycopy(array2, 0, keywordsWithExtras, array1.length, array2.length);
        }
        return keywordsWithExtras;
    }

    static String[] keywords;

    public static String[] getKeywords() {
        if(keywords == null) {
            keywords = new String[]{
                    "request_id", "request_data",
                    "processing_strategy", "after-all-scans",
                    "twain_cap_setting",
                    "prompt_scan_more",
                    "detect_blank_pages",
                    "blank_page_policy",
                    "blank_page_threshold",
                    "blank_page_margin_percent",
                    "recognize_barcodes",
                    "barcodes_dpi",
                    "barcodes_settings",
                    "output_settings",
                    "retrieve_caps",
                    "retrieve_extended_image_attrs",
                    "image_files",

                    "type", "return-base64", "return-base64-thumbnail", "return-handle", "return-handle-thumbnail", "save", "save-thumbnail", "upload", "upload-thumbnail",
                    "format", "jpg", "png", "bmp", "tif", "pdf",
                    "thumbnail_height",
                    "save_path",
                    "jpeg_quality",
                    "tiff_compression", "G3", "G4", "LZW", "RLE", "NONE", "PACKBITS", "ZIP",
                    "tiff_force_single_page",
                    "pdf_force_black_white",
                    "pdfa_compliant",
                    "pdf_owner_password",
                    "pdf_user_password",
                    "pdf_text_line",
                    "exif", "DocumentName", "ImageDescription", "EquipMake", "EquipModel", "Copyright", "UserComment",
                    "bits_per_pixel",
                    "encoding_fs_limit",

                    "upload_after_all_done",
                    "upload_one_by_one",
                    "upload_threads",
                    "upload_target",

                    "url",
                    "max_retries",
                    "post_fields",
                    "post_file_field_name",
                    "post_files",
                    "cookies",
                    "auth",
                    "headers",
                    "log_file", "stdout", "stderr",
                    "to_file",
                    "max_operation_time",

                    "use_asprise_dialog",
                    "dialog_title",
                    "dialog_width",
                    "dialog_height",
                    "instruction",
                    "show_scanner_ui",
                    "modal_scanner_ui",
                    "source_name",
                    "doc_separators",
                    "i18n",
                    "ui_controls_config",
                    "adf_max_pages",

                    "show_logging_on_error",

                    "select_output_type_file_name",
                    "select_output_action",
                    "select_output_type",
                    "select_output_file_name",

                    "enable_use_last_scanned"
            };
            Arrays.sort(keywords);
        }
        return keywords;
    }

    /** Request ID */
    public String getId() {
        return id;
    }

    /** Request ID */
    public Request setId(String id) {
        this.id = id;
        return this;
    }

    /** Request data */
    public Object getData() {
        return data;
    }

    /** Request data */
    public Request setData(Object data) {
        this.data = data;
        return this;
    }

    /**
     * By default images will be processed after each scan; Set to true to process images after all scans.
     * Processing images after all scan could speed up the scanning process.
     */
    public boolean isProcessImagesAfterAllScans() {
        return processImagesAfterAllScans;
    }

    /**
     * By default images will be processed after each scan; Set to true to process images after all scans.
     * Processing images after all scan could speed up the scanning process.
     */
    public Request setProcessImagesAfterAllScans(boolean processImagesAfterAllScan) {
        this.processImagesAfterAllScans = processImagesAfterAllScan;
        return this;
    }

    /** Whether to prompt scan more dialog. */
    public boolean isPromptScanMore() {
        return promptScanMore;
    }

    /** Whether to prompt scan more dialog. */
    public Request setPromptScanMore(boolean promptScanMore) {
        this.promptScanMore = promptScanMore;
        return this;
    }

    /** Whether blank pages should be detected. */
    public boolean isDetectBlankPages() {
        return detectBlankPages;
    }

    /** Whether blank pages should be detected. */
    public Request setDetectBlankPages(boolean detectBlankPages) {
        this.detectBlankPages = detectBlankPages;
        return this;
    }

    /** Ink coverage threshold to determine if a page is blank. */
    public double getBlankPageThreshold() {
        return blankPageThreshold;
    }

    /** Ink coverage threshold to determine if a page is blank. */
    public Request setBlankPageThreshold(double blankPageThreshold) {
        this.blankPageThreshold = blankPageThreshold;
        return this;
    }

    /** Percentage of margin to be excluded when calculating ink coverage. */
    public int getBlankPageMarginPercent() {
        return blankPageMarginPercent;
    }

    /** Percentage of margin to be excluded when calculating ink coverage. */
    public Request setBlankPageMarginPercent(int blankPageMarginPercent) {
        this.blankPageMarginPercent = blankPageMarginPercent;
        return this;
    }

    /** Whether barcodes should be recognized. */
    public boolean isRecognizeBarcodes() {
        return recognizeBarcodes;
    }

    /** Whether barcodes should be recognized. */
    public Request setRecognizeBarcodes(boolean recognizeBarcodes) {
        this.recognizeBarcodes = recognizeBarcodes;
        return this;
    }

    /** The DPI at which level to recognize barcodes. */
    public Request setBarcodesDpi(int value) {
        this.barcodesDpi = value;
        return this;
    }

    /** Additional barcodes settings */
    public Request setBarcodesSettings(Object value) {
        this.barcodesSettings = value;
        return this;
    }

    public boolean isOnWebServer() {
        return onWebServer != null && onWebServer;
    }

    public Request setOnWebServer(boolean value) {
        onWebServer = value;
        return this;
    }

    public boolean getSelectOutputTypeAndFileName() {
        return selectOutputTypeAndFileName != null && selectOutputTypeAndFileName;
    }

    public Request setSelectOutputTypeAndFileName(Boolean selectOutputTypeAndFileName) {
        this.selectOutputTypeAndFileName = selectOutputTypeAndFileName;
        return this;
    }

    public String getSelectOutputActions() {
        return selectOutputActions;
    }

    public Request setSelectOutputActions(String selectOutputActions) {
        this.selectOutputActions = selectOutputActions;
        return this;
    }

    public String getSelectOutputType() {
        return selectOutputType;
    }

    public Request setSelectOutputType(String selectOutputType) {
        this.selectOutputType = selectOutputType;
        return this;
    }

    public String getSelectOutputFileName() {
        return selectOutputFileName;
    }

    public Request setSelectOutputFileName(String selectOutputFileName) {
        this.selectOutputFileName = selectOutputFileName;
        return this;
    }

    /** Map of cap name (could be appended with operation and priority, e.g., /RESET, /SET/3456) */
    public Map getTwainCapSetting() {
        return twainCapSetting;
    }

    /**
     * Set or reset twain capability.
     * @param capCode e.g., {@linkplain TwainConstants#ICAP_PIXELTYPE}
     * @param value support raw value and twain constant expansion; support fall back values e.g., "TWPT_GRAY,TWPT_BW"
     * @param reset true to set operation RESET instead of SET.
     */
    public Request setTwainCap(int capCode, Object value, boolean reset) {
        this.twainCapSetting.put(TwainConstants.getCapName(capCode) + (reset ? "/RESET" : ""), value == null ? null : value.toString());
        return this;
    }

    /**
     * Set twain capability.
     * @param capCode e.g., {@linkplain TwainConstants#ICAP_PIXELTYPE}
     * @param value support raw value and twain constant expansion; support fall back values e.g., "TWPT_GRAY,TWPT_BW"
     */
    public Request setTwainCap(int capCode, Object value) {
        return setTwainCap(capCode, value, false);
    }

    /**
     * Returns the cap value setting specified in the request as int or -1 if failed to convert to int.
     * @param capCode
     * @return
     */
    public int getTwainCapValueAsInt(int capCode) {
        Object value = twainCapSetting.get(TwainConstants.getCapName(capCode));
        if(value instanceof String) {
            String sVal = (String)value;
            if(sVal.contains(",")) {
                sVal = sVal.substring(0, sVal.indexOf(","));
            }
            if(sVal.contains("TW")) {
                Integer intVal = TwainConstants.getConstantValue(sVal.trim());
                return intVal == null ? -1 : intVal;
            }
        }
        return TwainUtil.toInteger(value, -1);
    }

    /** Names of caps to be retrieved. */
    public Set getRetrieveCaps() {
        return retrieveCaps;
    }

    /** Add a cap to be retrieved. */
    public Request retrieveCap(int capCode) {
        String capName = TwainConstants.getCapName(capCode);
        if(capName == null) {
            System.err.println("Invalid cap code: " + capCode);
            return this;
        }
        this.retrieveCaps.add(capName);
        return this;
    }

    /** Name of extended image attributes to be retrieved. */
    public Set getRetrieveExtendedImageAttributes() {
        return retrieveExtendedImageAttributes;
    }

    /** Adds an extended image attribute to be retrieved. */
    public Request retrieveExtendedImageAttributes(int tweiCode) {
        String tweiName = TwainConstants.getTweiName(tweiCode);
        if(tweiName == null) {
            System.err.println("Invalid twei code: " + tweiCode);
            return this;
        }
        this.retrieveExtendedImageAttributes.add(tweiName);
        return this;
    }

    /** Output specifications. */
    public List getOutputItems() {
        return outputItems;
    }

    /** Adds an output specification. */
    public Request addOutputItem(RequestOutputItem outputItem) {
        this.outputItems.add(outputItem);
        return this;
    }

    /** Adds output specifications. */
    public Request addOutputItems(List items) {
        this.outputItems.addAll(items);
        return this;
    }

    public Request removeAllOutputItems() {
        this.outputItems.clear();
        return this;
    }

    public List getImageFiles() {
        return imageFiles;
    }

    /**
     *  Adds an image file
     *  @throws IllegalArgumentException if the file is not readable
     */
    public Request addImageFile(File imageFile) {
        if(imageFile == null || !imageFile.exists()) {
            throw new IllegalArgumentException("File doesn't exist: " + imageFile.getAbsolutePath());
        }
        if(!imageFile.canRead()) {
            throw new IllegalArgumentException("File isn't readable: " + imageFile);
        }
        if(!isAllASCII(imageFile.getAbsolutePath())) {
            throw new IllegalArgumentException("File path contains non-ASCII char(s): " + imageFile.getAbsolutePath());
        }

        this.imageFiles.add(imageFile);
        return this;
    }

    /**
     * Adds list of image files.
     * @param imageFiles list of image files or null.
     * @param imgFilesItems The associated {@linkplain ResultImageItem} if any.
     * @throws IllegalArgumentException if any of the file in the list is not readable
     */
    public Request addImageFiles(List imageFiles, List imgFilesItems) {
        if(imageFiles == null) {
            return this;
        }

        if(imageFiles != null && imgFilesItems != null && imageFiles.size() != imgFilesItems.size()) {
            throw new IllegalArgumentException("Quantity of image files and item don't match: " + imageFiles.size() + " != " + imgFilesItems.size());
        }

        for(File file : imageFiles) {
            addImageFile(file);
        }

        if(imgFilesItems != null) {
            for(ResultImageItem item : imgFilesItems) {
                this.imageFilesItems.add(item);
            }
        }
        return this;
    }

    private static boolean isAllASCII(String input) {
        boolean isASCII = true;
        for (int i = 0; i < input.length(); i++) {
            int c = input.charAt(i);
            if (c > 0x7F) {
                isASCII = false;
                break;
            }
        }
        return isASCII;
    }

    public Request setUseAspriseDialog(Boolean useAspriseDialog) {
        this.useAspriseDialog = useAspriseDialog;
        return this;
    }

    public Request setDialogTitle(String dialogTitle) {
        this.dialogTitle = dialogTitle;
        return this;
    }

    public Request setInstruction(String instruction) {
        this.instruction = instruction;
        return this;
    }

    public Request setDialogWidth(int dialogWidth) {
        this.dialogWidth = dialogWidth;
        return this;
    }

    public Request setDialogHeight(int dialogHeight) {
        this.dialogHeight = dialogHeight;
        return this;
    }

    public Request setShowScannerUI(Boolean showScannerUI) {
        this.showScannerUI = showScannerUI;
        return this;
    }

    public Request setModalScannerUI(Boolean modalScannerUI) {
        this.modalScannerUI = modalScannerUI;
        return this;
    }

    public Request setSourceName(String sourceName) {
        this.sourceName = sourceName;
        return this;
    }

    public Boolean getUseAspriseDialog() {
        return useAspriseDialog;
    }

    public Boolean getShowLoggingOnError() {
        return showLoggingOnError == null ? true : showLoggingOnError;
    }

    public Request setShowLoggingOnError(Boolean showLoggingOnError) {
        this.showLoggingOnError = showLoggingOnError;
        return this;
    }

    public String getDialogTitle() {
        return dialogTitle;
    }

    public String getInstruction() {
        return instruction;
    }

    public int getDialogWidth() {
        return dialogWidth;
    }

    public int getDialogHeight() {
        return dialogHeight;
    }

    public Boolean getShowScannerUI() {
        return showScannerUI;
    }

    public Boolean getModalScannerUI() {
        return modalScannerUI;
    }

    public String getSourceName() {
        return sourceName;
    }

    public int getAdfMaxPages() {
        return adfMaxPages;
    }

    public Request setAdfMaxPages(int adfMaxPages) {
        this.adfMaxPages = adfMaxPages;
        return this;
    }

    public boolean isEnableUseLastScanned() {
        return enableUseLastScanned != null && enableUseLastScanned;
    }

    public Request setEnableUseLastScanned(Boolean enableUseLastScanned) {
        this.enableUseLastScanned = enableUseLastScanned;
        return this;
    }

    /**
     * Adds an i18n record.
     */
    public Request setI18n(String key, String text) {
        this.i18n.put(key, text);
        return this;
    }

    /**
     * Removes an i18n record.
     * @param key the specific key to remove or null to clear all keys.
     */
    public Request clearI18n(String key) {
        if(key == null) {
            this.i18n.clear();
        } else {
            this.i18n.remove(key);
        }
        return this;
    }

    public boolean isI18nSet(String key) {
        return this.i18n.containsKey(key);
    }

    /**
     * Adds an entry to ui_controls_config with value of // "I"nvisble | "U"editable | "E"ditable
     * @param key the control id
     * @param invisible whether the control should be invisible
     * @param uneditable if not invisible, whether it's uneditable?
     */
    public Request setUiControlConfig(String key, boolean invisible, boolean uneditable) {
        this.uiControlsConfig.put(key, invisible ? "I" : (uneditable ? "U" : "E")); // "I"nvisble | "U"editable | "E"ditable
        return this;
    }

    /**
     * Configures components' visibility and enable status according to spec in ui_controls_config.
     * Does nothing if there is no spec is provided for the given key.
     * @param key
     * @param components list of components associated with the key
     */
    public void configUiControl(String key, JComponent... components) {
        String value = uiControlsConfig.getProperty(key);
        if(value == null || value.trim().length() == 0) {
            return;
        }
        char firstChar = (value == null || value.trim().length() == 0) ? 'E' : value.trim().charAt(0);
        if(firstChar == 'I' || firstChar == 'i') { // Invisible
            for(JComponent comp : components) {
                comp.setVisible(false);
            }
        } else if(firstChar == 'U' || firstChar == 'u') { // Uneditable - we use Disabled
            for (JComponent comp : components) {
                comp.setVisible(true);
                comp.setEnabled(false);
            }
        } else if(firstChar == 'E' || firstChar == 'e') { // Editable
            for (JComponent comp : components) {
                comp.setVisible(true);
                comp.setEnabled(true);
            }
        } else {
            // doesn't nothing if not specified
        }
    }

    public List getDocSeparators() {
        return docSeparators;
    }

    public Request setDocSeparators(String... separators) {
        if(this.docSeparators == null) {
            this.docSeparators = new ArrayList();
        }
        if(separators != null) {
            for(String sep : separators) {
                this.docSeparators.add(sep);
            }
        }
        return this;
    }

    public Properties getI18n() {
        return i18n;
    }

    /**
     * Dimension from dialog width and dialog height or null if either is not greater than 0.
     * @return
     */
    public Dimension getSpecifiedDialogSize() {
        return dialogWidth > 0 && dialogHeight > 0 ? new Dimension(dialogWidth, dialogHeight) : null;
    }

    /**
     * Returns empty string or values like "DOC=NEW" or "DOC=NEW_SEP".
     * Make as private: we use the custom_props passed from native instead.
     */
    private String computeDocSeparateProp(ResultImageItem item) {
        // Ref: C:\J\dev\asprise\scan\projects\c\scan\scan-core\asprise_scan_twain_callback.cpp#getDocSeparateProp
        if (docSeparators == null || docSeparators.size() == 0) {
            return null;
        }

        for (String sepConfig : docSeparators) {
            if (sepConfig.length() == 0) {
                continue;
            }

            String[] parts = StringUtils.split(sepConfig, ":");
            String part0 = parts[0];
            String part1 = parts.length > 1 ? parts[1] : "";
            String part2 = parts.length > 2 ? parts[2] : "";

            if (part0.toUpperCase().startsWith("TWEI_")) { // TWEI_PATCHCODE:5:DOC_SEP
                String tweiValue = item.getTweiValue(part0.toUpperCase());
                if (StringUtils.patternMatchString(part1, tweiValue, true)) {
                    return "DOC=" + (part2.contains(SEP_MARKER_NEW) ? SEP_MARKER_NEW : SEP_MARKER_NEW_SEP); // default is sep for TWEI
                }
            }
            else if (part0.toUpperCase().startsWith("BLANK")) {
                if (item.isBlank()) {
                    return "DOC=" + SEP_MARKER_NEW_SEP; // always skip for blank page
                }
            }
            else if (part0.equalsIgnoreCase("BARCODE")) {
                List> barcodes = item.getBarcodes();
                if(barcodes != null && barcodes.size() > 0) {
                    for(Map barcode : barcodes) {
                        String barcodeData = (String) barcode.get("data");
                        if(barcodeData != null && StringUtils.patternMatchString(part1, barcodeData, true)) {
                            return "DOC=" + (part2.contains("SEP") ? SEP_MARKER_NEW_SEP : SEP_MARKER_NEW); // default is new for BARCODE
                        }
                    }
                }
            }
        }

        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy