MailJava в новой теме - PullRequest
       2

MailJava в новой теме

0 голосов
/ 08 декабря 2018

Я пытаюсь получить электронные письма из CSV-файла и начать процесс рассылки.Все работает нормально, если я делаю это в основном потоке.Но если я запускаю новый поток и пытаюсь это сделать, это дает мне NullPointer в этой строке:

 email.sendEmail(readerEmail.myList, mailingSubject, mailingText);

По какой-то причине он не может получить список электронных писем.Полный код здесь:

package com.company;


import javax.mail.MessagingException;
import javax.swing.*;

import static com.company.MainFormAppearance.mailingSubject;
import static com.company.MainFormAppearance.mailingText;


public class NewThead implements Runnable {

public JTextArea jTextAreaStatus;
public Reader readerEmail;

private boolean doStop = false;

public synchronized void doStop() {
    this.doStop = true;
}

private synchronized boolean keepRunning() {
    return this.doStop == false;
}

@Override
public void run() {
    while (keepRunning()){
        Email email = new Email();
        try {
            email.sendEmail(readerEmail.myList, mailingSubject, mailingText);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    jTextAreaStatus.setText("completed");
}
}

Основной класс:

public class MainFormAppearance {

private JTextArea jTextAreaText;
private JTextArea jTextAreaSubject;
private JTextArea jTextAreaEmail;
private JTextArea jTextAreaStatus;
private JLabel blueLabel;
private JLabel copyRightLabel;
public JButton parceButton;
private JButton mailButton;
private JButton stopButton;
private String FILE_PATH_TEXT = "c:/Users/R2D2/Desktop/Main.txt";
private String FILE_PATH_SUBJECT = "c:/Users/R2D2/Desktop/Subject.txt";
public String CsvEmailsPath = "C:\\Users\\R2D2\\Desktop\\Emailstest.csv";
public String CsvBusinessesPath = "C:\\Users\\R2D2\\Desktop\\Businessestest.csv";
public static String mailingText = null;
public static String mailingSubject = null;
public Reader readerEmail;
public Reader readerBusiness;
public JPanel createContentPanel() {

    JPanel totalGui = new JPanel();
    totalGui.setLayout(null);
    totalGui.setBackground(new Color(72, 209, 204));

    jTextAreaText = new JTextArea();
    jTextAreaSubject = new JTextArea();
    jTextAreaEmail = new JTextArea();
    jTextAreaStatus = new JTextArea();
    blueLabel = new JLabel("Java Mailing Program");
    copyRightLabel = new JLabel("\u00a9" + " Alex B - 2018");
    parceButton = new JButton("Upload");
    mailButton = new JButton("!Start!");
    stopButton = new JButton("Stop");
    readerEmail = new Reader();
    readerBusiness = new Reader();

    NewThead newThead = new NewThead();
    Thread thread = new Thread(newThead);

    //set program label
    copyRightLabel.setLocation(10, 230);
    copyRightLabel.setSize(400, 20);
    copyRightLabel.setFont(new Font("Courier New", Font.ITALIC, 12));
    copyRightLabel.setHorizontalAlignment(SwingConstants.CENTER);
    totalGui.add(copyRightLabel);

    //set program label
    blueLabel.setLocation(10, 10);
    blueLabel.setSize(400, 20);
    blueLabel.setFont(new Font("Courier New", Font.ITALIC, 15));
    blueLabel.setHorizontalAlignment(SwingConstants.CENTER);
    totalGui.add(blueLabel);

    //set Button 1 and click
    parceButton.setLocation(270, 50);
    parceButton.setSize(100, 30);
    totalGui.add(parceButton);
    parceButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            //parce data from files to Strings
            mailingText = readLineByLineJava8(FILE_PATH_TEXT);
            mailingSubject = readLineByLineJava8(FILE_PATH_SUBJECT);
            try {
                readerEmail.readCsvFile(CsvEmailsPath);
                readerBusiness.readCsvFile(CsvBusinessesPath);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            if (isNullOrEmpty(mailingText)) {
                jTextAreaText.setText("Text is empty! Check it!!!");
            } else {
                jTextAreaText.setText("***Text is Ready***");
            }
            if (isNullOrEmpty(mailingSubject)) {
                jTextAreaSubject.setText("Subject is empty! Check it!!!");
            } else {
                jTextAreaSubject.setText("***Subject is Ready***");
            }
        }
    });

    //set Button 2 and click
    mailButton.setLocation(270, 100);
    mailButton.setSize(100, 30);
    totalGui.add(mailButton);
    mailButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            thread.start();
        }
    });

    stopButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            newThead.doStop();
            jTextAreaStatus.setText("Stopped");
        }
    });

    stopButton.setLocation(270, 150);
    stopButton.setSize(100, 30);
    totalGui.add(stopButton);

    jTextAreaText.setLocation(20, 52);
    jTextAreaText.setSize(200, 16);
    jTextAreaText.setFont(new Font("Courier New", Font.ITALIC, 12));
    jTextAreaText.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
    totalGui.add(jTextAreaText);

    jTextAreaSubject.setLocation(20, 82);
    jTextAreaSubject.setSize(200, 16);
    jTextAreaSubject.setFont(new Font("Courier New", Font.ITALIC, 12));
    jTextAreaSubject.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
    totalGui.add(jTextAreaSubject);

    jTextAreaEmail.setLocation(20, 112);
    jTextAreaEmail.setSize(200, 16);
    jTextAreaEmail.setFont(new Font("Courier New", Font.ITALIC, 12));
    jTextAreaEmail.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
    totalGui.add(jTextAreaEmail);

    jTextAreaStatus.setLocation(20, 182);
    jTextAreaStatus.setSize(200, 16);
    jTextAreaStatus.setFont(new Font("Courier New", Font.ITALIC, 12));
    jTextAreaStatus.setBorder(BorderFactory.createLineBorder(new Color(169, 169, 169)));
    totalGui.add(jTextAreaStatus);

    totalGui.setOpaque(true);

    return totalGui;
}


public static boolean isNullOrEmpty(String str) {
    if (str != null && !str.isEmpty())
        return false;
    return true;
}
}

Класс, который читает электронные письма из csv (должен быть верным):

package com.company;


import au.com.bytecode.opencsv.CSVReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

public class Reader {

public CSVReader reader;
public  LinkedList myList;

public void readCsvFile(String path) throws IOException {
    try {

        reader = new CSVReader(new FileReader(path));
        String[] column;
        myList = new LinkedList<>();
        LinkedList <String> map;

        while ((column = reader.readNext()) != null) {
            map = new LinkedList<String>();
            map.add(column[0]);
            myList.add(String.valueOf(map).replace("[","").replace("]",""));
            //myList.add(String.valueOf(map));
        }
        reader.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
}

Почему я это делаюэто в другой ветке?Потому что я хочу иметь возможность остановить процесс рассылки, нажав на кнопку «Стоп» и убив новую ветку.

...