Package com.nexirius.multimail.datamodel

Source Code of com.nexirius.multimail.datamodel.ImportArrayModel$CounterListener

package com.nexirius.multimail.datamodel;

import com.nexirius.framework.application.DialogManager;
import com.nexirius.framework.datamodel.*;
import com.nexirius.util.StringVector;
import com.nexirius.util.XFile;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

public class ImportArrayModel extends StructModel {
    public static final String FIELD_counter = "counter";
    public static final String FIELD_importCounter = "importCounter";
    public static final String FIELD_stopped = "stopped";
    public static final String FIELD_progress = "progress";
    public static final String COMMAND_importCommand = "importCommand";
    public static final String COMMAND_fillArrayCommand = "fillArrayCommand";
    public static final String FIELD_excelFileName = "excelFileName";
    public static final String FIELD_mapping = "mapping";
    public static final String FIELD_NAME = "ImportArray";

    private FileNameModel excelFileName;
    private DoubleModel progress;
    private IntModel counter;
    private ArrayModel arrayModel;
    private ArrayModel arrayToFill;
    private IntModel importCounter;
    private BooleanModel stopped;
    private StructModel mapping;
    private String foreignKey;
    private DataModel template;
    private StringVector childrenFieldNames;
    private DefaultDataModelCommand importCommand;
    private DefaultDataModelCommand fillArrayCommand;
    private DataModelWorker worker;

    public ImportArrayModel() {
        super(FIELD_NAME);
        init();
    }

    private void init() {
        excelFileName = new FileNameModel("", FIELD_excelFileName);

        excelFileName.addDataModelListener(new DataModelAdaptor() {
            public void dataModelChangeValue(DataModelEvent event) {
                arrayModel = null;
                updateEnabling();
            }
            public void dataModelEdit(DataModelEvent event) {
                if (event.getId() == DataModelEvent.VALUE_EDIT) {
                    arrayModel = null;
                    updateEnabling();
                }
            }
        });
        append(excelFileName);
        append(counter = new IntModel(0, FIELD_counter));
        importCounter = new IntModel(0, FIELD_importCounter);
        append(importCounter);
        stopped = new BooleanModel(false, FIELD_stopped);
        append(stopped);

        counter.addDataModelListener(new CounterListener());
        append(progress = new DoubleModel(0.0, FIELD_progress));

        importCommand = new DefaultDataModelCommand(COMMAND_importCommand);
        appendMethod(importCommand);
        fillArrayCommand = new DefaultDataModelCommand(COMMAND_fillArrayCommand);
        appendMethod(fillArrayCommand);

        updateEnabling();
    }

    public void updateEnabling() {
        boolean hasFile = new File(excelFileName.getText()).exists();
        boolean hasArray = arrayModel != null;

        importCommand.setEnabled(hasFile && !hasArray);
        fillArrayCommand.setEnabled(hasArray);
    }

    public void incCounter() {
        counter.setInt(counter.getInt() + 1);
    }

    public void fillArrayCommand() {
        int foreignKeyIndex = -1;
        try {
            foreignKeyIndex = getForeignKeyIndex();
        } catch (Exception e) {
            e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
        }

        counter.setInt(0);

        for (int i = 0; i < arrayModel.getSize(); ++i) {
            StructModel structModel = (StructModel) arrayModel.getDataModel(i);

            incCounter();

            DataModel nextItem = null;

            if (foreignKeyIndex >= 0) {
                try {
                    String key = structModel.getChildren().getItem(foreignKeyIndex).getChildText(null);

                    nextItem = getChildByKey(arrayToFill, key);
                } catch (Exception e) {
                    e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
                }
            }

            boolean isNew = false;
            if (nextItem == null) {
                nextItem = template.duplicate(null, null);
                arrayToFill.append(nextItem);
                isNew = true;
            }

            DataModelVector mappingChildren = mapping.getChildren();

            for (Iterator iterator = mappingChildren.iterator(); iterator.hasNext();) {
                IntModel indexModel = (IntModel) iterator.next();

                if (indexModel.isEmpty()) {
                    continue;
                }

                int index = indexModel.getInt();

                String fieldName = indexModel.getFieldName();

                if (index >= 0 && index < structModel.getChildren().size()) {
                    String value = structModel.getChildren().getItem(index).getChildText(null);

                    if (value != null) {
                        nextItem.setChildText(fieldName, value);
                    }
                }
            }

            if (worker != null) {
                if (DataModelWorker.REMOVE_ENTRY_AND_CONTINUE == worker.work(nextItem) && isNew) {
                    arrayToFill.removeItem(nextItem);
                }
            }
            //JSchedulePersistence.getInstance().save(nextItem);
        }

        arrayModel = null;
        updateEnabling();
    }

    private DataModel getChildByKey(ArrayModel arrayToFill, String key) {
        if (key == null || key.length() == 0) {
            return null;
        }
        DataModelEnumeration en = arrayToFill.getEnumeration();

        while (en.hasMore()) {
            DataModel model = (DataModel) en.next();

            String foreignKey = model.getChildText(this.foreignKey);

            if (key.equals(foreignKey)) {
                return model;
            }
        }

        return null;
    }


    public void incImportCounter() {
        importCounter.setInt(importCounter.getInt() + 1);
    }

    public boolean isStopped() {
        return stopped.getBoolean();
    }

    public ArrayModel getArrayModel() {
        return arrayModel;
    }

    public ArrayModel createArrayFromExcel(boolean readAll) throws IOException, BiffException {
        String fileName = excelFileName.getText();
        XFile file = new XFile(fileName);

        if (!file.canRead()) {
            DialogManager.error("CannotRead{0}", fileName);

            return null;
        }

        Workbook workbook = Workbook.getWorkbook(file);

        Sheet sheet = workbook.getSheets()[0];

        Cell[] headerCells = sheet.getRow(0);

        StructModel s = new StructModel("A");

        for (int i = 0; i < headerCells.length; i++) {
            Cell headerCell = headerCells[i];

            s.append(new StringModel("", headerCell.getContents()));
        }

        ArrayModel arr = new ArrayModel(s.getFullFieldName());

        int rows = sheet.getRows();

        for (int i = 1; i < rows; ++i) {
            Cell[] cells = sheet.getRow(i);

            s = new StructModel("A");

            for (int j = 0; j < cells.length; j++) {
                Cell cell = cells[j];

                s.append(new StringModel(cell.getContents(), headerCells[j].getContents()));
            }

            arr.append(s);
        }

        return arr;
    }

    public void importCommand() throws IOException, BiffException {
        showTextFile();

        arrayModel = createArrayModel(true);

        updateEnabling();
    }

    public ArrayModel createArrayModel(boolean readAll) throws IOException, BiffException {
        if (excelFileName.getText().toUpperCase().endsWith(".XLS")) {
            return createArrayFromExcel(readAll);
        }

        String fileName = excelFileName.getText();
        XFile file = new XFile(fileName);

        if (!file.canRead()) {
            DialogManager.error("CannotRead{0}", fileName);

            return null;
        }

        StringVector sv;

        try {
            sv = new StringVector();
            BufferedInputStream in = file.getBufferedInputStream();
            ByteArrayOutputStream line = new ByteArrayOutputStream(102400);

            int oldc = 0;

            while (true) {
                int c = in.read();

                if (c < 0) {
                    break;
                }

                if (c == '\n' && oldc != '\r') {
                    //String s = line.toString("ISO-8859-1");
                    String s = line.toString("Cp1252");
                    //String str = new String(bytes, "ISO-8859-1");
                    sv.append(s);
                    line.reset();
                } else {
                    line.write(c);
                }

                oldc = c;
            }

        } catch (Exception e) {
            DialogManager.error(e.getMessage());

            return null;
        }

        ArrayModel arr = null;
        String[] columnNames = null;

        for (String line = sv.firstItem(); line != null; line = sv.nextItem()) {

            StringVector tokens = new StringVector(line, ';', false);

            if (tokens.size() < 2) {
                continue;
            }

            StructModel s = new StructModel("A");
            if (columnNames == null) {
                StringVector columnNamesVector = null;

                columnNamesVector = tokens;

                columnNames = new String[tokens.size()];

                int i = 0;
                for (i = 0; i < columnNames.length; ++i) {
                    if (columnNamesVector != null && i < columnNamesVector.size()) {
                        columnNames[i] = columnNamesVector.getItem(i);
                    } else {
                        columnNames[i] = Integer.toString(i);
                    }

                    s.append(new StringModel("", columnNames[i]));
                }
            } else {
                boolean cont = readOneLine(tokens, columnNames, s);

                if (cont == true) {
                    continue;
                }
            }
            if (arr == null) {
                arr = new ArrayModel(s.getFullFieldName());
            } else {
                arr.append(s);
            }
        }
        return arr;
    }

    private boolean readOneLine(StringVector tokens, String[] columnNames, StructModel s) {
        int i = 0;
        boolean cont = false;
        for (String value = tokens.firstItem(); i < columnNames.length && value != null; value = tokens.nextItem()) {
//            if (trimValues()) {
//                value = value.trim();
//            }

//            if (doFilter) {
//                if (filterColumnIndex == i) {
//                    try {
//                        if (!columnFilter.match(value)) {
//                            cont = true;
//                            continue;
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }

            if (columnNames[i].trim().length() == 0) {
                try {
                    DayMonthYearModel date = new DayMonthYearModel(new Date(), columnNames[i]);

                    date.setText(value);

                    s.append(date);
                } catch (Exception e) {
                    s.append(new StringModel(value, columnNames[i]));
                }
            } else {
                s.append(new StringModel(value, columnNames[i]));
            }
            i++;
        }
        return cont;
    }

    public void showTextFile() throws IOException, BiffException {
        ArrayModel arr = createArrayModel(false);

        DialogManager.getPopupEditorAdaptor().noDuplicatePopupEdit(arr, null, null);
    }

    public void setArrayToFill(ArrayModel arrayToFill, DataModel template, String foreignKey, DataModelWorker worker) {
        this.arrayToFill = arrayToFill;
        this.template = template;
        this.worker = worker;

        mapping = new StructModel(FIELD_mapping);
        append(mapping);

        childrenFieldNames = template.getChildrenFieldNames();

        int i = 0;

        for (Iterator iterator = childrenFieldNames.iterator(); iterator.hasNext();) {
            String fn = (String) iterator.next();

            try {
                if (!template.getChild(fn).getFlag(ModelFlag.TRANSIENT)) {
                    mapping.append(new IntModel(i++, fn));
                }
            } catch (Exception e) {
                e.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
            }
        }

        this.foreignKey = foreignKey;
    }

    private int getForeignKeyIndex() throws Exception {
        IntModel index = (IntModel) mapping.getChild(foreignKey);

        return index.getInt();
    }

    class CounterListener extends DataModelAdaptor {
        public void dataModelChangeValue(DataModelEvent event) {
            int size = getArrayModel().getSize();
            if (size == 0) {
                progress.setDouble(0.0);
            } else {
                progress.setDouble((double) counter.getInt() / (double) size);
            }
        }
    }
}
TOP

Related Classes of com.nexirius.multimail.datamodel.ImportArrayModel$CounterListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.