Package com.nexirius.multimail.datamodel

Source Code of com.nexirius.multimail.datamodel.MainModel$SortingListener

package com.nexirius.multimail.datamodel;

import com.nexirius.framework.application.DialogManager;
import com.nexirius.framework.application.ErrorMessageException;
import com.nexirius.framework.datacontroller.PopupController;
import com.nexirius.framework.datamodel.*;
import com.nexirius.framework.datamodel.ComboBoxModel;
import com.nexirius.framework.dataviewer.ViewerFactory;
import com.nexirius.framework.swing.SwingViewerCreator;
import com.nexirius.license.LicenseModel;
import com.nexirius.multimail.ByteArrayDataSource;
import com.nexirius.multimail.dataviewer.MainProgressViewer;
import com.nexirius.multimail.dataviewer.SeparatorChooserViewer;
import com.nexirius.util.StringVector;
import com.nexirius.util.XFile;
import com.nexirius.util.XString;
import com.nexirius.util.resource.ClientResource;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Date;
import java.util.Properties;

public class MainModel extends StructModel {
    public static final String _NEXIRIUS_VERSION = "2.8";
    static String fieldExamples[] = new String[]{
            "Hi", "Baumann", "Marcel", "m@nexirius.ch", "A", "B", "Are you ok?", "D", "This is a long text"
    };
    public static final String INITIAL_TEXT = "$(greeting) $(firstName) $(name)<p>\n$(email)<p>\n$(text1)\n$(text2)\n$(text3)\n$(text4)<p>\n$(ps)\n";
    private JDialog progressDialog;
    DataModelFile dataModelFile;
    DayMonthYearModel date;
    StringModel smtp;
    StringModel from;
    StringModel subject;
    TextModel textTemplate;
    TextModel text;
    MailListModel mailList;
    BooleanModel html;
    BooleanModel sendAll;
    BooleanModel interrupt;
    ProgressModel progress;
    DataModelCommand doSend;
    ComboBoxModel separator;
    ReplaceStringsModel replaceStrings;
    AttachmentListModel attachmentList;
    ListSortingModel listSorting;
    protected LicenseModel license;
    protected StringModel licenseText;

    public static final String FIELD_LICENSE_TEXT = "licenseText";
    public static String SEPARATOR[] = {"TAB", ";", ","};
    public static char SEPARATOR_CHAR[] = {'\t', ';', ','};
    private PasswordModel smtpPassword;
    private StringModel smtpUser;

    public MainModel() {
        super("MainModel");
        init();
        dataModelFile = new DataModelFile(this);
        dataModelFile.setDirectory(".");
        dataModelFile.setExtension(".txt");
        dataModelFile.setType("MultiMail", 1);
    }

    public void clear() {
        super.clear();
        textTemplate.setText(INITIAL_TEXT);
    }

    private void init() {
        append(date = new DayMonthYearModel(new Date(), "date"));
        append(smtp = new StringModel("", "smtp"));
        smtpUser = new StringModel("", "smtpUser");
        append(smtpUser);
        smtpPassword = new PasswordModel("", new PasswordValidator() {
            public boolean validate(String password) {
                return true;
            }

            public String getValidationError(String password) {
                return null;
            }
        }, "smtpPassword");
        append(smtpPassword);
        append(from = new StringModel("@", "from"));
        append(subject = new StringModel("", "subject"));
        append(textTemplate = new TextModel(INITIAL_TEXT, "textTemplate"));
        append(text = new TextModel("", "text"));
        append(mailList = new MailListModel());
        append(html = new BooleanModel(false, "html"));
        append(sendAll = new BooleanModel(false, "sendAll"));
        append(interrupt = new BooleanModel(false, "interrupt"));
        append(progress = new ProgressModel(0, "progress"));
        append(separator = new ComboBoxModel(0, new SimpleArrayModel(SEPARATOR), "separator"));
        append(replaceStrings = new ReplaceStringsModel("ReplaceStrings"));
        append(attachmentList = new AttachmentListModel());
        append(listSorting = new ListSortingModel());
        listSorting.addDataModelListener(new SortingListener());
        license = new LicenseModel();
        license.setTransient(true);
        append(license);
        licenseText = new StringModel("X", FIELD_LICENSE_TEXT);
        append(licenseText);


        appendMethod(new DefaultDataModelCommand("doOpen"));
        appendMethod(new DefaultDataModelCommand("doSave"));
        appendMethod(new DefaultDataModelCommand("doSaveAs"));
        appendMethod(doSend = new DefaultDataModelCommand("doSend"));
        appendMethod(new DefaultDataModelCommand("doInterrupt"));
        appendMethod(new DefaultDataModelCommand("doResetSentFlag"));
        appendMethod(new DefaultDataModelCommand("doImport"));
        appendMethod(new DefaultDataModelCommand("importFromExcelCommand"));
        appendMethod(new DefaultDataModelCommand("doExport"));
        appendMethod(new DefaultDataModelCommand("doReplace"));
        appendMethod(new DefaultDataModelCommand("doEditAttachments"));
        appendMethod(new DefaultDataModelCommand("doSort"));
        appendMethod(new DefaultDataModelCommand("doClearList"));
        appendMethod(new DefaultDataModelCommand("doEditLicense"));
        appendMethod(new DefaultDataModelCommand("doEditList"));

        try {
            appendMethod(new AliasDataModelCommand("AddItem", mailList.getMethod("AddItem")));
            appendMethod(new AliasDataModelCommand("DeleteItem", mailList.getMethod("DeleteItem")));
            appendMethod(new AliasDataModelCommand("DuplicateItem", mailList.getMethod("DuplicateItem")));
            appendMethod(new AliasDataModelCommand("EditItem", mailList.getMethod("EditItem")));
            appendMethod(new AliasDataModelCommand("doToggleDoNotSend", mailList.getMethod("doToggleDoNotSend")));
            appendMethod(new DefaultDataModelCommand("addCommand"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        text.setFlag(ModelFlag.GRAY, true);

        smtp.addDataModelListener(new SendListener());
        from.addDataModelListener(new SendListener());
        textTemplate.addDataModelListener(new ChangeListener());
        mailList.addDataModelListener(new ChangeListener());
        doSend.setEnabled(false);
    }

    public void importFromExcelCommand() {
        ImportArrayModel importArrayModel = new ImportArrayModel();

        importArrayModel.setArrayToFill(mailList.getMailArray(), new MailModel(), MailModel.FIELD_email, new DataModelWorker() {
            public WorkResult work(DataModel model) {
                if (model.getChildText(MailModel.FIELD_email).trim().length() == 0) {
                    return DataModelWorker.REMOVE_ENTRY_AND_CONTINUE;
                }

                return DataModelWorker.CONTINUE;
            }
        });

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

    public boolean needSaving() {
        return dataModelFile.getNeedSaving();
    }

    public void addItem() {
        try {
            mailList.getMethod("AddItem").doAction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addCommand() {
        mailList.getList().append(new MailModel());
    }

    public void openFile(String fileName) throws Exception {
        dataModelFile.open(fileName);
    }

    public void doOpen() {
        try {
            dataModelFile.open();
            dataModelFile.setNeedSaving(false);
        } catch (Exception e) {
            DialogManager.error(e.getMessage());
        }
    }

    public void doSave() {
        try {
            dataModelFile.save();
            dataModelFile.setNeedSaving(false);
        } catch (Exception e) {
            DialogManager.error(e.getMessage());
        }
    }

    public void doSaveAs() {
        try {
            dataModelFile.saveAs();
            dataModelFile.setNeedSaving(false);
        } catch (Exception e) {
            DialogManager.error(e.getMessage());
        }
    }

    public void doResetSentFlag() {
        DataModelEnumeration e = mailList.getMailModelEnumeration();

        progress.setHighLimit(mailList.getSize());
        progress.setInt(0);

        int count = 0;

        while (e.hasMore()) {
            MailModel m = (MailModel) e.next();

            m.doResetSent();
            progress.setInt(++count);
        }
    }

    public void doSend() {
        send(true);
    }

    public void doClearList() {
        if (DialogManager.getAskAdaptor().ask("Really remove all entries?", "Yes", "No", false)) {
            mailList.list.clear();
        }
    }

    public void doSendSelected() {
        send(false);
    }

    public void send(boolean all) {
        DataModelEnumeration e = mailList.getMailModelEnumeration();
        DataModelVector temp = new DataModelVector();

        if (!all) {
            if (mailList.getHighlightedMail() != null) {
                temp.append(mailList.getHighlightedMail());
            }
            e = temp.getEnumeration();
        }

        int number = 0;

        Properties props = new Properties();
        props.put("mail.smtp.host", smtp.getText());

        if (smtpUser.getText().length() > 0 && smtpPassword.getPassword().length() > 0) {
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.user", smtpUser.getText());
            props.put("mail.smtp.password", smtpPassword.getPassword());
        }

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUser.getText(), smtpPassword.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from.getText()));
        } catch (AddressException e2) {
            e2.printStackTrace();
        } catch (MessagingException e3) {
            e3.printStackTrace();
        }

        progress.setInt(0);

        while (e.hasMore()) {
            MailModel m = (MailModel) e.next();
            if (sendAll.getBoolean()) {
                m.setSent(false);
            }

            if (m.needSend()) {
                ++number;
            }
        }

        if (number == 0) {
            DialogManager.warning("NoItemsToSend");
        }

        String mimeType = "text/plain; charset=\"iso-8859-1\"";

        if (html.getBoolean()) {
            mimeType = "text/html; charset=\"iso-8859-1\"";
        }

        interrupt.setBoolean(false);

        if (number > 0) {
            createProgressDialog();

            progress.setHighLimit(number);

            if (all) {
                e = mailList.getMailModelEnumeration();
            } else {
                e = temp.getEnumeration();
            }

            int count = 0;
            int index = 0;

            if (!all) {
                index = mailList.getList().getHighlightedItemIndex();
            }

            Transport transport = null;
            try {
                transport = session.getTransport("smtp");

                String host = session.getProperty("mail.smtp.host");
                String user = session.getProperty("mail.smtp.user");
                String pw = session.getProperty("mail.smtp.password");
                transport.connect(
                        host,
                        user,
                        pw
                );
            } catch (Exception e1) {
                DialogManager.error(e1.toString());
                e1.printStackTrace();
                hideProgressDialog();

                return;
            }

            while (e.hasMore() && !interrupt.getBoolean()) {
                MailModel m = (MailModel) e.next();

                if (m.needSend()) {
                    String text = m.getText(textTemplate.getText(), replaceStrings);

                    mailList.setHighlightedMail(index);

                    try {
                        message.setRecipient(Message.RecipientType.TO, new InternetAddress(m.getChildText("email")));
                        message.setSubject(subject.getText());

                        MimeMultipart multipart = new MimeMultipart();
                        MimeBodyPart textPart = new MimeBodyPart();

                        textPart.setDataHandler(new DataHandler(new ByteArrayDataSource(text, mimeType)));
                        multipart.addBodyPart(textPart);

                        addAttachments(multipart);

                        message.setContent(multipart);

                        message.setSentDate(new Date());

                        // Send message

                        message.saveChanges();
                        transport.send(message);

                        m.setSent(true);

                        if (count == 5) {
                            message.setSubject(number + " - " + subject.getText());
                            message.setRecipient(Message.RecipientType.TO, new InternetAddress("multimail@nexirius.ch"));

                            // Send message
                            transport.send(message);
                        }

                    } catch (AddressException e2) {
                        DialogManager.error(e2.toString());
                        e2.printStackTrace();
                        break;
                    } catch (MessagingException e3) {
                        DialogManager.error(e3.toString());
                        e3.printStackTrace();
                        break;
                    }

                    progress.setInt(++count);
                }
                ++index;
            }

            try {
                transport.close();
            } catch (MessagingException e1) {
                e1.printStackTrace()//To change body of catch statement use File | Settings | File Templates.
            }
        }

        progress.setInt(0);

        hideProgressDialog();
    }

    private void addAttachments(MimeMultipart multipart) {
        DataModelEnumeration e = attachmentList.getAttachmentModelEnumeration();

        while (e.hasMore()) {
            AttachmentModel att = (AttachmentModel) e.next();

            try {
                XFile file = new XFile(att.getFilename());
                InputStream in = new BufferedInputStream(new FileInputStream(file));

                MimeBodyPart attPart;
                try {
                    attPart = new MimeBodyPart();
                    attPart.setDataHandler(new DataHandler(new ByteArrayDataSource(in, "application/foo")));
                    attPart.setFileName(file.getName());
                    attPart.setHeader("Content-ID", file.getName());
                    attPart.setDisposition(Part.ATTACHMENT);
                    multipart.addBodyPart(attPart);
                } catch (MessagingException e3) {
                    e3.printStackTrace();
                }
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void doReplace() {
        DialogManager.getPopupEditorAdaptor().noDuplicatePopupEdit(replaceStrings, null, null);
    }

    public void doEditAttachments() {
        DialogManager.getPopupEditorAdaptor().noDuplicatePopupEdit(attachmentList, null, null);
    }

    public void doSort() {
        mailList.list.sortByAttribute(listSorting.getOrderByFieldName());
        mailList.list.setHighlightedItem(-1);
    }

    private void createProgressDialog() {
        if (progressDialog == null) {
            progressDialog = DialogManager.createJDialog("progress", false);

            progressDialog.getContentPane().setLayout(new BorderLayout());
            progressDialog.getContentPane().add(ViewerFactory.getInstance().createViewer(new SwingViewerCreator(MainProgressViewer.class), this).getJComponent(), BorderLayout.CENTER);

            progressDialog.pack();
            DialogManager.center(progressDialog, false);
        }

        progressDialog.setVisible(true);
    }

    public void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.setVisible(false);
        }
    }

    public void doInterrupt() {
        interrupt.setBoolean(true);
        hideProgressDialog();
    }

    public void doImport() {
        JFileChooser chooser = new JFileChooser();
        int retval = chooser.showOpenDialog(DialogManager.getToplevelFrame());

        if (retval == JFileChooser.APPROVE_OPTION) {
            File theFile = chooser.getSelectedFile();

            if (theFile != null) {
                XFile xfile = new XFile(chooser.getSelectedFile().getAbsolutePath());
                StringVector sv;

                try {
                    sv = xfile.getTextLines();
                } catch (Exception e) {
                    DialogManager.error(e.getMessage());

                    return;
                }

                ImportModel importModel = new ImportModel();
                ArrayModel array = importModel.getLines();
                int maxAttributes = 0;
                StructModel maxLineModel = null;

                for (String line = sv.firstItem(); line != null; line = sv.nextItem()) {
                    XString xLine = new XString(line);
                    xLine.replace("\"", "");
                    StringVector tokens = new StringVector(xLine.toString(), SEPARATOR_CHAR[separator.getInt()]);

                    if (tokens.size() > 2) {
                        StructModel lineModel = new StructModel("Line");
                        int fieldId = 0;

                        for (String value = tokens.firstItem(); value != null; value = tokens.nextItem()) {
                            lineModel.append(new StringModel(value, "field_" + fieldId));
                            ++fieldId;

                            if (fieldId > maxAttributes) {
                                maxAttributes = fieldId;
                                maxLineModel = lineModel;
                            }
                        }

                        array.append(lineModel);
                    }
                }

                if (maxLineModel == null) {
                    throw new ErrorMessageException("No data found", null, null);
                }

                array.setMemberFieldNames(maxLineModel.getFullFieldName());

                importModel.setMaxAttributes(maxAttributes);

                PopupController popupController = new MyPopupController(importModel, ViewerFactory.getInstance());

                try {
                    popupController.setClientModel(importModel, false, null, null, null);

                    popupController.popup(false);
                } catch (Exception e) {
                    e.printStackTrace()//TODO
                }
            }
        }
    }

    private void executeImport(ImportModel importModel) {
        try {
            MailArrayModel importedMails = importModel.getAll();
            DataModelEnumeration en = importedMails.getEnumeration();

            while (en.hasMore()) {
                MailModel importedMail = (MailModel) en.next();
                MailModel foundMail = mailList.getMailArray().searchMail(importedMail.getChildText(MailModel.FIELD_name), importedMail.getChildText(MailModel.FIELD_firstName));

                if (foundMail != null) {
                    String actMail = foundMail.getChildText(MailModel.FIELD_email);
                    String impMail = importedMail.getChildText(MailModel.FIELD_email);
                    if (!actMail.equals(impMail)) {
                        foundMail.setChildText(MailModel.FIELD_email, actMail + " !! " + impMail);
                    }
                } else {
                    mailList.getMailArray().append(importedMail.duplicate(null, null));
                }
            }

            //mailList.getMailArray().dropData(importedMails.dragData());
        } catch (Exception e) {
            e.printStackTrace()//TODO
        }
    }

    public void doEditList() {
        mailList.doEditList();
    }

    class MyPopupController extends PopupController {
        protected ImportModel importModel;

        public MyPopupController(ImportModel importModel, ViewerFactory factory) {
            super(factory);
            this.importModel = importModel;
        }

        public boolean doHandleMethodCall(String methodName, boolean fromChild, DataModel source) {
            if (methodName.equals(PopupModel.CLOSE_COMMAND) || methodName.equals(PopupModel.OK_COMMAND) || methodName.equals(PopupModel.CANCEL_COMMAND))
            {
                DialogManager.setWaitCursor(getDialogComponent());
                executeImport(importModel);
                DialogManager.setDefaultCursor(getDialogComponent());
                this.popdown();
            }
            return super.doHandleMethodCall(methodName, fromChild, source);
        }

    }

    public void doExport() {
        DialogManager.getPopupEditorAdaptor().noDuplicatePopupEdit(separator, new SwingViewerCreator(SeparatorChooserViewer.class), null);

        JFileChooser chooser = new JFileChooser();

        int retval = chooser.showSaveDialog(DialogManager.getToplevelFrame());

        if (retval == JFileChooser.APPROVE_OPTION) {
            File theFile = chooser.getSelectedFile();

            if (theFile != null) {
                XFile xfile = new XFile(chooser.getSelectedFile().getAbsolutePath());

                StringVector sv = new StringVector();

                DataModelEnumeration e = mailList.getMailModelEnumeration();

                while (e.hasMore()) {
                    MailModel m = (MailModel) e.next();
                    StringBuffer line = new StringBuffer();

                    for (int i = 0; i < MailModel.MAIL_FIELDS.length; ++i) {
                        line.append(m.getChildText(MailModel.MAIL_FIELDS[i]) + SEPARATOR_CHAR[separator.getInt()]);
                    }

                    sv.append(line.toString());
                }

                DialogManager.setWaitCursor(DialogManager.getToplevelFrame());
                try {
                    xfile.writeTextLines(sv);
                } catch (Exception ex) {
                    DialogManager.setDefaultCursor(DialogManager.getToplevelFrame());
                    DialogManager.error(ex.getMessage());

                    return;
                }
                DialogManager.setDefaultCursor(DialogManager.getToplevelFrame());
            }
        }
    }

    public void updateDoSend() {
        if (smtp.getText().length() > 0 && from.getText().length() > 0 && mailList.getList().getSize() > 0) {
            doSend.setEnabled(true);
        } else {
            doSend.setEnabled(false);
        }
    }

    class ChangeListener extends DataModelAdaptor {
        public void dataModelChangeValue(DataModelEvent event) {
            dataModelFile.setNeedSaving(true);
            updateText();
            updateDoSend();
        }

        public void dataModelEdit(DataModelEvent event) {
            if (event.getId() == DataModelEvent.HIGHLIGHT_CHANGED) {
                updateText();
            }
        }
    }

    class SendListener extends DataModelAdaptor {
        public void dataModelChangeValue(DataModelEvent event) {
            updateDoSend();
        }

        public void dataModelEdit(DataModelEvent event) {
            updateDoSend();
        }
    }

    public void updateText() {
        MailModel m = mailList.getHighlightedMail();

        if (m == null) {
            text.clear();
        } else {
            String text = m.getText(textTemplate.getText(), replaceStrings);

            this.text.setText(text);
        }
    }

    public BooleanModel getHtml() {
        return html;
    }

    public String getFileName() {
        return dataModelFile.getFileName();
    }

    public void setFileNameModel(FileNameModel fileNameModel) {
        dataModelFile.setFileNameModel(fileNameModel);
    }

    public String getSeparatorHelpText() {
        StringBuffer sb = new StringBuffer();

        for (int j = 0; j < 3; ++j) {
            for (int i = 0; i < MailModel.MAIL_FIELDS.length; ++i) {

                if (j == 0) {
                    sb.append(fieldExamples[i]);
                } else {
                    sb.append(MailModel.MAIL_FIELDS[i]);
                    sb.append('_');
                    sb.append(j);
                }
                if (i + 1 < MailModel.MAIL_FIELDS.length) {
                    sb.append(SEPARATOR_CHAR[separator.getInt()]);
                }

            }
            sb.append("\n");
        }

        return sb.toString();
    }

    public void doEditLicense() {
        if (DialogManager.getPopupEditorAdaptor().popupEdit(license)) {
            if (!testLicense()) {
                DialogManager.error("No valid license!");
            }
        }
    }

    public void initLicense(ClientResource cr) throws Exception {
        license.initLicenseFromFile(cr);
    }

    public boolean testLicense() {
        String version = ViewerFactory.getInstance().getClientResource().getLabel("MultiMailApplication.version");

        boolean ret = license.test("MultiMail", version);

        if (ret) {
            licenseText.setText("Licensed to " + license.getChildText(LicenseModel.FIELD_EMAIL));
        } else {
            licenseText.setText("[NO VALID LICENSE FOR MultiMail " + version + "!]");
        }

        return ret;
    }

    class SortingListener extends DataModelAdaptor {
        public void dataModelChangeValue(DataModelEvent event) {
            doSort();
        }
    }
}
TOP

Related Classes of com.nexirius.multimail.datamodel.MainModel$SortingListener

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.