king.flow.action.business.InsertCardAction.java Source code

Java tutorial

Introduction

Here is the source code for king.flow.action.business.InsertCardAction.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 king.flow.action.business;

import com.github.jsonj.JsonElement;
import com.github.jsonj.JsonObject;
import com.github.jsonj.JsonPrimitive;
import com.github.jsonj.tools.JsonParser;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.plaf.FontUIResource;
import javax.xml.datatype.XMLGregorianCalendar;
import king.flow.action.DefaultBaseAction;
import king.flow.common.CommonUtil;
import static king.flow.common.CommonUtil.getLogger;
import static king.flow.common.CommonUtil.getResourceMsg;
import static king.flow.common.CommonUtil.getWindowNode;
import king.flow.control.driver.GzCardConductor;
import king.flow.view.Action.InsertICardAction;
import king.flow.view.Component;
import king.flow.view.UiStyle;
import king.flow.view.Window;
import static king.flow.common.CommonUtil.swipeGzICCard;
import king.flow.net.Transportation;
import king.flow.view.DeviceEnum;
import org.apache.commons.lang.StringEscapeUtils;

/**
 *
 * @author liujin
 */
public class InsertCardAction extends DefaultBaseAction {

    private final DeviceEnum cardType;
    private final InsertICardAction.NextStep successfulPage;
    private final InsertICardAction.Exception failedPage;
    private final String animationFile;
    private final ArrayList<Integer> successfulDisplay;
    private final ArrayList<Integer> failedDisplay;

    public InsertCardAction(DeviceEnum cardType, InsertICardAction.NextStep successfulPage,
            InsertICardAction.Exception failedPage, String animation) {
        this.cardType = cardType;
        this.successfulPage = successfulPage;
        this.failedPage = failedPage;
        this.animationFile = animation;
        ArrayList<String> displayList = CommonUtil.buildListParameters(successfulPage.getDisplay());
        successfulDisplay = new ArrayList<>();
        for (String id : displayList) {
            successfulDisplay.add(Integer.parseInt(id));
        }

        displayList = CommonUtil.buildListParameters(failedPage.getDisplay());
        failedDisplay = new ArrayList<>();
        for (String id : displayList) {
            failedDisplay.add(Integer.parseInt(id));
        }
    }

    protected JLabel progressTip;

    @Override
    protected void installButtonAction() {
        JButton btn = (JButton) this.owner;
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (cardType == DeviceEnum.GZ_CARD) {
                    progressTip = new JLabel(
                            getResourceMsg("operation.ic.card.insert.prompt" + "." + DeviceEnum.GZ_CARD.value()));
                } else {
                    progressTip = new JLabel(getResourceMsg("operation.ic.card.insert.prompt"));
                }

                Window windowNode = getWindowNode();
                UiStyle uiStyle = windowNode.getUiStyle();
                if (uiStyle != null && uiStyle.getFont() != null && uiStyle.getFont().getName() != null) {
                    progressTip.setFont(new FontUIResource(uiStyle.getFont().getName(), java.awt.Font.BOLD, 50));
                } else {
                    progressTip.setFont(new FontUIResource("Dialog", java.awt.Font.BOLD, 50));
                }
                progressTip.setHorizontalAlignment(SwingConstants.CENTER);
                progressTip.setVerticalAlignment(SwingConstants.BOTTOM);
                final JDialog progressAnimation = buildAnimationDialog(animationFile);
                progressTip.setBounds(0, 120, progressAnimation.getBounds().width, 80);
                progressAnimation.getContentPane().add(progressTip, 1);
                final ImageIcon bgImage = CommonUtil.getImageIcon("/image/2.jpg");
                //final ImageIcon bgImage = CommonUtil.getDefaultBackgroundImage();
                if (bgImage != null) {
                    progressAnimation.getContentPane().add(new JLabel(bgImage), 2);
                } else {
                    progressAnimation.getContentPane().add(new JLabel(), 2);
                }

                switch (cardType) {
                case GZ_CARD:
                    waitCommunicationTask(new GZReadCardTask(), progressAnimation);
                    break;
                default:
                    getLogger(InsertCardAction.class.getName()).log(Level.WARNING,
                            "Unsupported card type[{0}] for InsertCardAction", cardType.name());
                    handleErr(getResourceMsg(GzCardConductor.GUOZHEN_CARD_OPERATION_PROMPT));
                }
            }
        });
    }

    private void showOnComponent(int componentId, String value) {
        Component meta = (Component) getBlockMeta(componentId);
        getLogger(InsertCardAction.class.getName()).log(Level.INFO, "Display component[{0}] type : {1}",
                new Object[] { String.valueOf(meta.getId()), meta.getType().value() });
        switch (meta.getType()) {
        case LABEL:
            JLabel label = getBlock(meta.getId(), JLabel.class);
            label.setText(StringEscapeUtils.unescapeHtml(value));
            break;
        case TEXT_FIELD:
            JTextField textField = getBlock(meta.getId(), JTextField.class);
            textField.setText(value);
            break;
        case COMBO_BOX:
            JComboBox combo = getBlock(meta.getId(), JComboBox.class);
            if (combo.isEditable()) {
                combo.getEditor().setItem(value);
            }
            break;
        default:
            getLogger(InsertCardAction.class.getName()).log(Level.WARNING,
                    "Unsupported showed component type : {0}", meta.getType());
        }
    }

    private void handleErr(String errPrompt) {
        showOnComponent(failedDisplay.get(0),
                errPrompt == null ? getResourceMsg("operation.ic.card.read.error") : errPrompt);
        panelJump(failedPage.getNextPanel());
    }

    private class GZReadCardTask extends SwingWorker<String, String> {

        @Override
        protected String doInBackground() throws Exception {
            try {
                List<String> debug = successfulPage.getDebug();

                if (debug.isEmpty()) {
                    Thread.sleep(1000);
                    String cardInfo = swipeGzICCard();
                    if (cardInfo != null && cardInfo.equals(GzCardConductor.UNREGISTRY_CARD_TYPE)) {
                        throw new Exception(GzCardConductor.GUOZHEN_CARD_UNREGISTRY_PROMPT);
                    }
                    JsonParser jsonParser = new JsonParser();
                    JsonObject element = jsonParser.parse(cardInfo).asObject();
                    String cardId = element.getString(GzCardConductor.CARD_NO);
                    if (cardId == null || cardId.length() == 0) {
                        throw new Exception("No card number is gotten from this card");
                    }

                    JsonElement gasSurplus = element.get(GzCardConductor.CARD_SPARE);
                    if (gasSurplus == null) {
                        gasSurplus = new JsonPrimitive(GzCardConductor.ZERO_GAS_SURPLUS);
                        element.put(GzCardConductor.CARD_SPARE, gasSurplus);
                    }

                    JsonElement cardType = element.get(GzCardConductor.CARD_FACTORY);
                    if (cardType == null) {
                        cardType = new JsonPrimitive(GzCardConductor.UNSUPPORT_CARD_TYPE);
                        element.put(GzCardConductor.CARD_FACTORY, cardType);
                    }

                    switch (String.valueOf(cardType)) {
                    case GzCardConductor.UNSUPPORT_CARD_TYPE:
                        throw new Exception(GzCardConductor.GUOZHEN_CARD_OPERATION_PROMPT);
                    case GzCardConductor.CARD4_TYPE:
                        if (!CommonUtil.allowCPUCard()) {
                            throw new Exception(GzCardConductor.GUOZHEN_CARD_OPERATION_PROMPT);
                        } else {
                            Transportation.Misc.AllowCPU allowCPUConfig = CommonUtil.getAllowCPUConfig();
                            long start = CommonUtil.convertCalendarToMills(allowCPUConfig.getPeriod().getStart());
                            long end = CommonUtil.convertCalendarToMills(allowCPUConfig.getPeriod().getEnd());
                            long now = System.currentTimeMillis();
                            if (now < start || now > end) {
                                throw new Exception(GzCardConductor.GUOZHEN_CARD_PERIOD_PROMPT);
                            }
                        }
                        break;
                    default:
                        break;
                    }

                    //cache current card information for writing action
                    CommonUtil.cacheCardInfo(element);

                    List<String> displayValues = new ArrayList<>();
                    displayValues.add(cardId);
                    displayValues.add(String.valueOf(gasSurplus));
                    displayValues.add(String.valueOf(cardType));
                    int len = Math.min(displayValues.size(), successfulDisplay.size());
                    for (int i = 0; i < len; i++) {
                        showOnComponent(successfulDisplay.get(i), displayValues.get(i));
                    }
                } else {
                    //debug mode
                    Thread.sleep(3000);
                    int len = Math.min(debug.size(), successfulDisplay.size());
                    for (int i = 0; i < len; i++) {
                        showOnComponent(successfulDisplay.get(i), debug.get(i));
                    }
                }

                Integer hop = successfulPage.getHop();
                if (hop == null) {
                    panelJump(successfulPage.getNextPanel());
                } else {
                    getBlock(hop, JButton.class).doClick();
                }
                return "Success";
            } catch (Throwable t) {
                getLogger(InsertCardAction.class.getName()).log(Level.SEVERE,
                        "Occur problem during reading IC card, root cause comes from \n{0}", t.getMessage());
                String errPrompt = getResourceMsg(t.getMessage());
                handleErr(errPrompt);
                throw new Exception(t);
            }
        }

    }
}