package controller;

import dao.CheckDAO;
import entity.Users;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.CipherText;
import model.UserService;

public class Registration extends HttpServlet implements Runnable{
    @Resource(name = "gmail")
    private Session gmail;
    public static Users user = new Users();
    public static UserService userService = new UserService();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config); //To change body of generated methods, choose Tools | Templates.
    }




    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {

            String email = request.getParameter("email_id");
            String password = request.getParameter("password");
            String conpass = request.getParameter("conpass");
            String fullName = request.getParameter("fullName");
            String dob = request.getParameter("dob");
            String gender = request.getParameter("gender");
            String currentLoc = request.getParameter("location");
            String mobNo = request.getParameter("MobNo");

            boolean emailErr, passErr, conpErr, conpMatchErr, fNameErr, dobErr, curLocErr, mobNoErr;
            emailErr = passErr = conpErr = conpMatchErr = fNameErr = dobErr = curLocErr = mobNoErr = false;

            String pattern = "yyyy-MM-dd";
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                java.util.Date date = format.parse(dob);

            Pattern pt = Pattern.compile("");
            Matcher match = pt.matcher(email);

            boolean existingMail = userService.checkExistingEmail(email);

            if(existingMail)
            {
                emailErr = true;
                request.setAttribute("emailError", "Provided email already exists.");
            }

            pt = Pattern.compile("[a-zA-Z0-9]{8,30}");
            match = pt.matcher(password);

            if(!match.matches())
            {
                passErr = true;
                request.setAttribute("passError", "Password field must only contain alphabets & numbers.");

            }
            match = pt.matcher(conpass);

            if(!match.matches())
            {
                conpErr = true;
                request.setAttribute("conpassError", "Confirm password is either blank or does not contains alphabets & numbers.");
            }

            if(!password.equals(conpass))
            {
                conpMatchErr = true;
                request.setAttribute("conpassMatchError", "Passwords do not match");
            }

            pt = Pattern.compile("[a-zA-z ]{10,100}+");
            match = pt.matcher(fullName);

            if(!match.matches())
            {
                fNameErr = true;
                request.setAttribute("nameError", "Full Name field is either blank or Does contain numbers.");
            }

            if(currentLoc.equals("Choose City"))
            {
                curLocErr = true;
                request.setAttribute("locError", "Location is Choose City");
            }

            pt = Pattern.compile("[0-9]{10}");
            match = pt.matcher(mobNo);

            if(!match.matches())
            {
                mobNoErr = true;
                request.setAttribute("mobnoError", "Mobile Number field is either blank or contains alphabetic characters.");
            }

            java.sql.Date dateOfBirth = new java.sql.Date(date.getTime());
            java.util.Date date2 = format.parse("1996-01-01");
            if(dateOfBirth.after(date2))
            {
                dobErr = true;
                request.setAttribute("dobError", "Too young to apply for job.");
            }

            if(emailErr || passErr || conpErr || conpMatchErr || fNameErr || mobNoErr || curLocErr || dobErr)
            {
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
            else
            {
                user.setFullName(fullName);
                user.setGender(gender);
                user.setEmail(email);
                user.setPassword(CipherText.encrypt(password));
                Registration reg = new Registration();
                Thread t = new Thread(reg);
                t.start();

                user.setDateOfBirth(dateOfBirth);
                user.setCurrentLocation(currentLoc);
                user.setMobileNumber(mobNo);
                user.setUserType("guest");
                user.setLastLogin(new Date(new java.util.Date().getTime()));


                long id = userService.addNewUser(user);


                user.setUserID(id);





                request.getRequestDispatcher("RegistraionSuccess.jsp").forward(request, response);

            }


        }
        catch(Exception ex)
        {
            request.setAttribute("RegError", ex);
                request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        finally {            

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void sendMail(String email, String subject, String body) throws NamingException, MessagingException {
        MimeMessage message = new MimeMessage(gmail);
        message.setSubject(subject);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email, false));
        message.setText(body);
        Transport.send(message);
    }

    @Override
    public void run() {
        try
        {
            Thread.sleep(0);
        }
        catch(Exception ex)
        {

        }
        String body = userService.createBody(user);
        String subject = "Account Creation at OCRM";

        try
        {
            String Email = user.getEmail();
            System.out.println("Before send");
                sendMail(Email, subject, body);
                System.out.println("After send");
        }
        catch(Exception ex)
        {
            System.out.println(ex);

        }

    }
}

This is my code.
When my servlet try to run sendMail() method it is giving me following error.

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
    at javax.mail.Service.connect(Service.java:345)
    at javax.mail.Service.connect(Service.java:226)
    at javax.mail.Service.connect(Service.java:175)
    at javax.mail.Transport.send0(Transport.java:253)
    at javax.mail.Transport.send(Transport.java:124)
    at controller.Registration.sendMail(Registration.java:219)
    at controller.Registration.run(Registration.java:239)
    at java.lang.Thread.run(Thread.java:724)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:297)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:229)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
    ... 9 more

sendMail() runs perfectly when used inside service() but it is not working when used inside run()
This is the error i am recieving.
Connection is refused but why? Can anyone give me a hint to make this work?

well ... it is possible that the configuration is different depending on from where you call it. have you debugged your code and checked whether or not all the information you need to provide is available when running it from run?

also:

catch(Exception ex)
        {
        }

is about the worst thing you can do. no matter what goes wrong, it's normal you don't know what or why, because you are merely hiding the error.
log what goes wrong there, maybe that 'll answer your question.

some personal advice:

catch(Exception ex)
    {
        System.out.println(ex);
    }

don't print it to the console. once your app is deployed on a server, you might not be able to check that. write what goes wrong in a log file, with a timestamp, so you can easily find out what went wrong when.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.