IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JDBC Java Discussion :

NetBeans ne m'affiche pas le contenu de ma table : problème ODBC


Sujet :

JDBC Java

  1. #481
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Cette application est en fonctionnement depuis 2 ans.
    Dans un premier temps, je suis censé refaire fonctionner cette application avec MySQL.

    L'objectif correction de code se fera par la suite mais j'entends bien coder proprement

  2. #482
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Petit soucis de connexion (une dernière ).
    J'ai volontairement changé l'IP du server SQL pour voir la réaction de l'application.
    => mauvaise nouvelle, elle plante complètement (impossible de fermer etc...) !

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    public Connection getConnexion() {
            try {
                String fichier          = Utilitaire.lienApplication()+"SYSTEM/connexion.xml";
                FileInputStream ips     = new FileInputStream(fichier);
                InputStreamReader ipsr  = new InputStreamReader(ips);
                BufferedReader br       = new BufferedReader(ipsr);
                String addServeur       = br.readLine();
                //System.out.print("\n addServer(Connexion.java):"+addServeur);
                br.close();
     
                String pilote = "com.mysql.jdbc.Driver";
                Class.forName(pilote);
     
                String DBurl        = "jdbc:mysql://"+addServeur;
                String login        = "xxx";
                String password     = "xxx";
                con = DriverManager.getConnection(DBurl,login,password);
                java.util.Properties prop = new java.util.Properties();
                prop.put("charSet", "ISO-8859-1");
                con.setClientInfo(prop);
     
                return con;
            } catch (Exception e) {
                System.err.println("Erreur de connexion à la base de données!");
                e.printStackTrace();
                return con;
            }
    }
    On est bien dans un try catch alors les erreurs devraient isolé le dysfonctionnement pour "au moins" fermer l'appli non ?
    => je vais essayer de faire une petite fenetre dans le catch : Erreur de connexion à la base de donnée !

  3. #483
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    Tu dois utiliser la clause finally dans ton try/catch
    Cette clause s'exécute toujours.

    Aller, c'est mon jour de bonté.
    Si tu veux simplement tester la connexion, ajoute cette méthode à la classe Connexion

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
        public boolean testConnexion(String addServeur, String login, String password) {
             String DBurl        = "jdbc:mysql://"+addServeur;
            Connection connexionTest= null;
            boolean result = false;
            try {
                String pilote = "com.mysql.jdbc.Driver";
                Class.forName(pilote);
     
                connexionTest= DriverManager.getConnection(DBurl,login,password);      // ici ça plante si échec -> on passe alors dans le catch
                result = true;
            } catch (SQLException ex) {
                ex.printStackTrace();
                result = false;
            } finally {
                try {
                    if (connexionTest!= null) {
                        connexionTest.close();
                    }
                } catch (SQLException e_sql) {
                    System.out.println("Fermeture ratée");
                    e_sql.printStackTrace();
                }
                return result;      //   ici ça te retourne le résultat du test qu'il soit bon ou mauvais
            }
        }
    pour utiliser le test :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
                String addServeur = "000.000.00.00";
                String login        = "xxx";
                String password     = "xxx";
                Connexion connexion = new Connexion();
                System.out.println("Est-ce que je suis connecté : " + connexion.testConnexion(addServeur, login, password);
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  4. #484
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Ah super, c'est son jour de bonté ! Faut profiter de lui au maximum alors

    J'ai bidouillé ceci mais ca plante toujours :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    
    
    package coactivite4;
    
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.sql.*;
    
    public class Connexion {
    
        private Connection con;
    
        public boolean testConnexion(String addServeur, String login, String password) {
            String DBurl        = "jdbc:mysql://"+addServeur;
            Connection connexionTest= null;
            boolean result = false;
            try {
                String pilote = "com.mysql.jdbc.Driver";
                Class.forName(pilote);
    
                connexionTest= DriverManager.getConnection(DBurl,login,password);      // ici ça plante si échec -> on passe alors dans le catch
                result = true;
            } catch (SQLException ex) {
                ex.printStackTrace();
                result = false;
            } finally {
                try {
                    if (connexionTest!= null) {
                        connexionTest.close();
                    }
                } catch (SQLException e_sql) {
                    System.out.println("Fermeture ratée");
                    e_sql.printStackTrace();
                }
                return result;      //   ici ça te retourne le résultat du test qu'il soit bon ou mauvais
            }
        }
    
        public Connection getConnexion() {
            String addServeur = "";
            try{
                String fichier          = Utilitaire.lienApplication()+"SYSTEM/connexion.xml";
                FileInputStream ips     = new FileInputStream(fichier);
                InputStreamReader ipsr  = new InputStreamReader(ips);
                BufferedReader br       = new BufferedReader(ipsr);
                addServeur              = br.readLine();
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            String login        = "xxx";
            String password     = "xxx";
            Connexion connexion = new Connexion();
            if (connexion.testConnexion(addServeur, login, password)) {
                try {
                    String pilote = "com.mysql.jdbc.Driver";
                    Class.forName(pilote);
    
                    String DBurl        = "jdbc:mysql://"+addServeur;
                    con = DriverManager.getConnection(DBurl,login,password);
                    java.util.Properties prop = new java.util.Properties();
                    prop.put("charSet", "ISO-8859-1");
                    con.setClientInfo(prop);
    
                    return con;
                } catch (Exception e) {
                    System.err.println("Erreur de connexion à la base de données!");
                    e.printStackTrace();
                    return con;
                }
            } else {
                System.out.print("\n Connexion invalide \n");
                return null;
            }
        }
    
        public ResultSet getResultSet(String sql) {
            try {
                Statement requete   = getConnexion().createStatement();
                ResultSet rs        = requete.executeQuery(sql);
                return rs;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public void execSql(String sql) {
            try {
                Statement requete = getConnexion().createStatement();
                requete.executeUpdate(sql);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void closeConn() {
            if(con != null) {
                try {
                 con.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
            at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989)
            at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
            at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2251)
            at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
            at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
            at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
            at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
            at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
            at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
            at java.sql.DriverManager.getConnection(DriverManager.java:582)
            at java.sql.DriverManager.getConnection(DriverManager.java:185)
            at coactivite4.Connexion.testConnexion(Connexion.java:27)
    Mais bon c'est pas urgent ca je pense si ?

  5. #485
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Mettons ce soucis de coté, j'ai beaucoup plus urgent !

    Je suis sur le mail qu'on envoi SI il y a risque de coactivité !
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
        public void envoyerCharge(Annexe annexe, ChargeAffaire charge) throws MessagingException, SQLException, Exception{
            this.setServeur();
            Connexion connexion = new Connexion();
            System.out.print("\n\n Fonction envoyerCharge:\n\n");
            ResultSet resultats = connexion.getResultSet("" +
                "SELECT MailCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"';");
            while(resultats.next()) {
                mailRecepteur   = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailRecepteur+"\n");
                mailExpediteur  = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailExpediteur+"\n");
            }
            resultats.close();
            resultats = connexion.getResultSet("" +
                "SELECT NomCharge, PrenomCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"'");
            while(resultats.next()){
                charge.setNom(resultats.getString(1));
                charge.setPrenom(resultats.getString(2));
            }
            resultats.close();
            System.out.print("La requete foireuse :\n");
            System.out.print("SELECT IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin, NomCharge, PrenomCharge, NatureIntervention " +
                    "\n FROM ChargeAffaire, Annexe, Zone, Installation " +
                    "\n WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                    "\n AND ChargeAffaire.Matricule = Annexe.Matricule " +
                    "\n AND Zone.IdZone = Annexe.IdZone " +
                    "\n AND Zone.IdInstallation = Installation.IdInstallation " +
                    "\n AND('"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin " +
                    "\n OR '"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin);\n");
            resultats = connexion.getResultSet("" +
                    "SELECT IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin, NomCharge, PrenomCharge, NatureIntervention " +
                    "FROM ChargeAffaire, Annexe, Zone, Installation " +
                    "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                    "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                    "AND Zone.IdZone = Annexe.IdZone " +
                    "AND Zone.IdInstallation = Installation.IdInstallation " +
                    "AND('"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin " +
                    "OR '"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin);");
            System.out.print("\nAnnexe:"+annexe.getIdAnnexe()+"\n");
            while(resultats.next()){
                String sujet = "Risque de co-activité pour l'annexe n°"+annexe.getIdAnnexe();
                System.out.print("\nSujet :"+sujet+"\n");
                this.setSujet(sujet);
                this.setTexte("L'annexe n°"+annexe.getIdAnnexe()+" se trouvant à l'installation : "+resultats.getString(2)+" et dans la zone : "+resultats.getString(3)+" et ayant lieu entre le "+Utilitaire.formaterDate(resultats.getDate(4))+" et le "+Utilitaire.formaterDate(resultats.getDate(5))+" comporte un risque de co-activité avec l'annexe "+resultats.getInt(1)+" ("+ resultats.getString(8)+"). Veuillez contacter votre responsable afin de prendre les mesures nécessaires.");
                message.setFrom(new InternetAddress(mailExpediteur));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
                System.out.print("envoi du mail à "+mailRecepteur);
                Transport.send(message);
                ResultSet res = connexion.getResultSet("" +
                        "SELECT MailCharge " +
                        "FROM ChargeAffaire " +
                        "WHERE Matricule = 'xxx'");
                while(res.next()){
                    mailRecepteur = res.getString(1);
                    message.setFrom(new InternetAddress(mailExpediteur));
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
    		System.out.print("envoi du mail à "+mailRecepteur);
                    Transport.send(message);
                }
            }
            resultats.close();
            connexion.closeConn();
        }
    Pour je fais l'echo et tout semble ok :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    Sujet :Risque de co-activité pour l'annexe n°1502
    java.lang.NullPointerException
            at coactivite4.Mail.setSujet(Mail.java:41)
            at coactivite4.Mail.envoyerCharge(Mail.java:169)

  6. #486
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    testConnexion n'est pas prévu pour cela : tu ne vas pas re-tester l'existence du serveur à chaque connexion !

    Je l'utilise dans le lancement de l'application (méthode main).
    Si je n'ai pas de connexion, j'affiche une boîte de dialogue avertissant l'utilisateur qu'il n'a pas de connexion avec le serveur
    et ensuite je quitte l'application (pas de plantage bloquant donc)

    remets ton getConnexion dans l'état précédent (il fonctionnait bien)
    et ajoute-lui le finally pour que ce ne soit pas bloquant en cas de problème avec le serveur en cours d'utilisation.
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  7. #487
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    c'est dans la méthode setSujet que se situe le problème ...
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  8. #488
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Ben la method à l'air plutôt normale :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
        /* Modifier l'objet du mail */
        public void setSujet(String sujet) throws MessagingException{
            message.setSubject(sujet);
        }
    C'est peu être parce qu'on réutilise message ? Faudrait pas vider la variable avant de la réutiliser ?

  9. #489
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    qu'on réutilise message
    ???
    Ce serait plutôt que message n'est pas initialisé du tout -> null pointer du coup
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  10. #490
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Je comprend pas là, d'un coté il faisait comme ca :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
        public void updateUpload() throws IOException, MessagingException{
            try {
                Annexe a = new Annexe();
                Connexion connexion = new Connexion();
                connexion.execSql("UPDATE Annexe SET Upload = "+upload+" WHERE IdAnnexe = "+idAnnexe+";");
                connexion.closeConn();
                JOptionPane.showMessageDialog(null,"Votre fichier est bien mise à jour");
     
                String serveur      = null;
                String envoyerpar   = null;
                String recu         = null;
                String mailTo       = null;
                String ligne1       = null;
                String serveur2     = null;
     
                Properties props        = new Properties();
                String mailFrom         = Utilitaire.lienApplication()+"SYSTEM/mail/001_mailFrom.txt";
                FileInputStream ips2    = new FileInputStream(mailFrom);
                InputStreamReader ipsr2 = new InputStreamReader(ips2);
                BufferedReader br2      = new BufferedReader(ipsr2);
                envoyerpar              = br2.readLine();
                props.put("mail.from", envoyerpar);
                br2.close();
     
                String fichier          = Utilitaire.lienApplication()+"SYSTEM/serveurMail.xml";
                FileInputStream ips     = new FileInputStream(fichier);
                InputStreamReader ipsr  = new InputStreamReader(ips);
                BufferedReader br       = new BufferedReader(ipsr);
                serveur                 = br.readLine();
                props.put("mail.smtp.host", serveur);
                br.close();
     
                props.load(new FileInputStream(Utilitaire.lienApplication()+"Upload/"+recupereAnnee()+"/PlanDePrevention"+idAnnexe+".xls"));
                String fichier1            = Utilitaire.lienApplication()+"/SYSTEM/mail/002_mailTo.txt";
                Session session            = Session.getInstance(props);
                Message message            = new MimeMessage(session);
                FileInputStream ips1       = new FileInputStream(fichier1);
                InputStreamReader ipsr1    = new InputStreamReader(ips1);
                BufferedReader br1         = new BufferedReader(ipsr1);
     
                String chaine="";
                while ((ligne1 = br1.readLine())!= null)
                chaine+=ligne1+"\n";
                System.out.println("\n Annexe:"+chaine);
                message.setRecipients(Message.RecipientType.CC,  InternetAddress.parse(chaine, false));
                br1.close();
     
                message.setSubject("Mise à jour du Plan de prevention "+idAnnexe );
                Fenetre f = new Fenetre();
                // Partie 1: Le texte
                MimeBodyPart mbp1 = new MimeBodyPart();
                try {
                    mbp1.setText("Bonjour," + "\n" + "Une mise à jour du plan de prévention "+idAnnexe + "  vient d'être effectuée.\n" +"\n" +
                    "Merci de bien vouloir SVP le consulter et ne pas hésiter à consulter le chargé d'affaire pour de plus amples informations. \n"
                    + "PS: Ceci est un mail automatique, ne pas répondre.\n" + "  Gestion des Annexes de Plans de Prevention "+"version: "+f.versioning+"");
                } catch (MessagingException ex) {
                    ex.printStackTrace();
                    Logger.getLogger(Fenetre.class.getName()).log(Level.SEVERE, null, ex);
                }
     
                // Partie 2: Le fichier joint
                Annexe annexeUp = new Annexe();
                MimeBodyPart mbp2 = new MimeBodyPart();
                String file = Utilitaire.lienApplication()+"Upload/"+recupereAnnee()+"/PlanDePrevention"+idAnnexe+".xls";
                mbp2.attachFile(file);
     
                // On regroupe les deux dans le message
                MimeMultipart mp = new MimeMultipart();
                try {
                    mp.addBodyPart(mbp1);
                    mp.addBodyPart(mbp2);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    Logger.getLogger(Fenetre.class.getName()).log(Level.SEVERE, null, e);
                }
                try {
                    message.setContent(mp);
                } catch (MessagingException e) {
                    e.printStackTrace();
                    Logger.getLogger(Fenetre.class.getName()).log(Level.SEVERE, null, e);
                }
                try {
                    Transport.send(message);
                } catch (MessagingException ex) {
                    Logger.getLogger(Fenetre.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch(Exception e) {
                e.printStackTrace();
                System.out.println("Annexe : Erreur lors de l'upload de l'annexe! "+e.getMessage());
            }
        }
    et de l'autre il utilise la classe mail...
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    package coactivite4;
     
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import java.sql.*;
    import java.util.Properties;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.*;
     
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
     
    /**
     * @author xxx
     * @fixed by xxx
     */
    public class Mail{
        private String mailExpediteur;
        private String mailRecepteur;
        private MimeMessage message;
        private Properties props;
        private Session session;
     
        public Mail(){
            try {
                props = System.getProperties();
                setServeur();
                //session = Session.getDefaultInstance(props, null);
                //message = new MimeMessage(session);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
     
        /* Modifier l'objet du mail */
        public void setSujet(String sujet) throws MessagingException{
            message.setSubject(sujet);
        }
     
        /* Modifier le contenu du mail */
        public void setTexte(String texte) throws MessagingException{
            message.setText(texte);
        }
     
        public void setServeur() {
            try{
                String serveur = null;
                String fichier = Utilitaire.lienApplication()+"SYSTEM/serveurMail.xml";
                FileInputStream ips = new FileInputStream(fichier);
                InputStreamReader ipsr = new InputStreamReader(ips);
                BufferedReader br = new BufferedReader(ipsr);
                serveur = br.readLine();
                props.put("mail.smtp.host", serveur);
                br.close();
    	} catch (Exception e) {
                e.printStackTrace();
    	}
        }
     
        /* Fonction effectuant l'envoi du mail */
        @SuppressWarnings("static-access")
        public void envoyer(Annexe annexe, ChargeAffaire charge){
            try{
                System.out.print("\nOn passe par envoyer\n");
                this.setServeur();
                Connexion connexion = new Connexion();
                ResultSet resultats = connexion.getResultSet("" +
                        "SELECT MailCharge " +
                        "FROM ChargeAffaire " +
                        "WHERE Matricule = '"+charge.getMatricule()+"';");
                while(resultats.next()){
                    mailExpediteur = resultats.getString(1);
                }
                resultats.close();
                resultats = connexion.getResultSet("" +
                        "SELECT NomCharge, PrenomCharge " +
                        "FROM ChargeAffaire " +
                        "WHERE Matricule = '"+charge.getMatricule()+"'");
                while(resultats.next()) {
                    charge.setNom(resultats.getString(1));
                    charge.setPrenom(resultats.getString(2));
                }
                resultats.close();
                System.out.print("\n" +
                        "SELECT MailCharge, IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin " +
                        "FROM ChargeAffaire, Annexe, Zone, Installation " +
                        "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                        "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                        "AND Zone.IdZone = Annexe.IdZone " +
                        "AND Zone.IdInstallation = Installation.IdInstallation " +
                        "AND ("+Utilitaire.dateToDB(annexe.getDateDeb())+" BETWEEN DateDeb AND DateFin " +
                        "OR "+Utilitaire.dateToDB(annexe.getDateFin())+" BETWEEN DateDeb AND DateFin);" +
                        "\n");
                resultats = connexion.getResultSet("" +
                        "SELECT MailCharge, IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin " +
                        "FROM ChargeAffaire, Annexe, Zone, Installation " +
                        "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                        "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                        "AND Zone.IdZone = Annexe.IdZone " +
                        "AND Zone.IdInstallation = Installation.IdInstallation " +
                        "AND ("+Utilitaire.dateToDB(annexe.getDateDeb())+" BETWEEN DateDeb AND DateFin " +
                        "OR "+Utilitaire.dateToDB(annexe.getDateFin())+" BETWEEN DateDeb AND DateFin);");
                while(resultats.next()){
                    mailRecepteur = resultats.getString(1);
                    this.setSujet("Risque de co-activité pour l'annexe n°"+resultats.getInt(2));
                    this.setTexte("L'annexe n°"+resultats.getInt(2)+" se trouvant à l'installation : "+resultats.getString(3)+" et dans la zone : "+resultats.getString(4)+" et ayant lieu entre le "+Utilitaire.formaterDate(resultats.getDate(5))+" et le "+Utilitaire.formaterDate(resultats.getDate(6))+" comporte un risque de co-activité avec l'annexe "+annexe.getIdAnnexe()+" ("+ annexe.getNatureIntervention()+"). Veuillez contacter votre responsable afin de prendre les mesures nécessaires.");
                    message.setFrom(new InternetAddress(mailExpediteur));
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
                    System.out.print("\n envoi du mail à "+mailRecepteur+"\n");
                    Transport.send(message);
                }
                resultats.close();
                connexion.closeConn();
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
     
        public void envoyerCharge(Annexe annexe, ChargeAffaire charge) throws MessagingException, SQLException, Exception{
            this.setServeur();
            Connexion connexion = new Connexion();
            System.out.print("\n\n Fonction envoyerCharge:\n\n");
            ResultSet resultats = connexion.getResultSet("" +
                "SELECT MailCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"';");
            while(resultats.next()) {
                mailRecepteur   = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailRecepteur+"\n");
                mailExpediteur  = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailExpediteur+"\n");
            }
            resultats.close();
            resultats = connexion.getResultSet("" +
                "SELECT NomCharge, PrenomCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"'");
            while(resultats.next()){
                charge.setNom(resultats.getString(1));
                charge.setPrenom(resultats.getString(2));
            }
            resultats.close();
            System.out.print("La requete foireuse :\n");
            System.out.print("SELECT IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin, NomCharge, PrenomCharge, NatureIntervention " +
                    "\n FROM ChargeAffaire, Annexe, Zone, Installation " +
                    "\n WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                    "\n AND ChargeAffaire.Matricule = Annexe.Matricule " +
                    "\n AND Zone.IdZone = Annexe.IdZone " +
                    "\n AND Zone.IdInstallation = Installation.IdInstallation " +
                    "\n AND('"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin " +
                    "\n OR '"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin);\n");
            resultats = connexion.getResultSet("" +
                    "SELECT IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin, NomCharge, PrenomCharge, NatureIntervention " +
                    "FROM ChargeAffaire, Annexe, Zone, Installation " +
                    "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                    "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                    "AND Zone.IdZone = Annexe.IdZone " +
                    "AND Zone.IdInstallation = Installation.IdInstallation " +
                    "AND('"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin " +
                    "OR '"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin);");
            System.out.print("\nAnnexe:"+annexe.getIdAnnexe()+"\n");
            while(resultats.next()){
                String sujet = "Risque de co-activité pour l'annexe n°"+annexe.getIdAnnexe();
                System.out.print("\nSujet :"+sujet+"\n");
                this.setSujet(sujet);
                this.setTexte("L'annexe n°"+annexe.getIdAnnexe()+" se trouvant à l'installation : "+resultats.getString(2)+" et dans la zone : "+resultats.getString(3)+" et ayant lieu entre le "+Utilitaire.formaterDate(resultats.getDate(4))+" et le "+Utilitaire.formaterDate(resultats.getDate(5))+" comporte un risque de co-activité avec l'annexe "+resultats.getInt(1)+" ("+ resultats.getString(8)+"). Veuillez contacter votre responsable afin de prendre les mesures nécessaires.");
                message.setFrom(new InternetAddress(mailExpediteur));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
                System.out.print("envoi du mail à "+mailRecepteur);
                Transport.send(message);
                ResultSet res = connexion.getResultSet("" +
                        "SELECT MailCharge " +
                        "FROM ChargeAffaire " +
                        "WHERE Matricule = 'xxx'");
                while(res.next()){
                    mailRecepteur = res.getString(1);
                    message.setFrom(new InternetAddress(mailExpediteur));
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
    		System.out.print("envoi du mail à "+mailRecepteur);
                    Transport.send(message);
                }
            }
            resultats.close();
            connexion.closeConn();
        }
    }
    Je pense que le plus propre serait de bosser avec la classe mail.
    Effectivement, la variable message est instanciée mais jamais initialisé...

  11. #491
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    Dans updateUpload il y a une pièce attachée que je ne vois pas dans la classe Mail
    Mais il est facile d'étendre la classe Mail pour qu'elle accepte les pièces attachées

    Je pense que le plus propre serait de bosser avec la classe mail.
    Oui ce serait beaucoup mieux car tu n'as pas de risque de "superposition" de contenu de message.
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  12. #492
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Ok, donc je vais essayer de faire marcher cette classe tout en laissant ce qui marche à peu près bien ailleurs...

    Pour commencer, comment je fais pour savoir qui est this ? (CTRL + Clique non fonctionnel)
    L'initialisation de message ressemble à ca ? (pour éviter le nullException)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    Session session            = Session.getInstance(props);
                Message message            = new MimeMessage(session);

  13. #493
    Rédacteur/Modérateur
    Avatar de andry.aime
    Homme Profil pro
    Inscrit en
    Septembre 2007
    Messages
    8 391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Ile Maurice

    Informations forums :
    Inscription : Septembre 2007
    Messages : 8 391
    Points : 15 059
    Points
    15 059
    Par défaut
    Me revoilà avec des critiques conseils, et comme d'habitude, je n'ai fait qu'une lecture diagonale .
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @SuppressWarnings("static-access")
    Cette code ne fait que cacher un warning pour un accès à une méthode ou attribut static à partir d'une instance. Or pour les méthodes ou attribut static, tu n'as pas besoin d'un instance pour l'utiliser puisque ce serait partagé pour tous les instances. Je ne sais pas quelle méthode ou attribut static tu utilises mais tu peux l'utiliser directement comme ça:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    NomClasse.methode();
    NomClasse.attribut;
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    System.out.print("\n" +
                        "SELECT MailCharge, IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin " +
                        "FROM ChargeAffaire, Annexe, Zone, Installation " +
                        "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                        "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                        "AND Zone.IdZone = Annexe.IdZone " +
                        "AND Zone.IdInstallation = Installation.IdInstallation " +
                        "AND ("+Utilitaire.dateToDB(annexe.getDateDeb())+" BETWEEN DateDeb AND DateFin " +
                        "OR "+Utilitaire.dateToDB(annexe.getDateFin())+" BETWEEN DateDeb AND DateFin);" +
                        "\n");
                resultats = connexion.getResultSet("" +
                        "SELECT MailCharge, IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin " +
                        "FROM ChargeAffaire, Annexe, Zone, Installation " +
                        "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                        "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                        "AND Zone.IdZone = Annexe.IdZone " +
                        "AND Zone.IdInstallation = Installation.IdInstallation " +
                        "AND ("+Utilitaire.dateToDB(annexe.getDateDeb())+" BETWEEN DateDeb AND DateFin " +
                        "OR "+Utilitaire.dateToDB(annexe.getDateFin())+" BETWEEN DateDeb AND DateFin);");
    Met la requête dans une variable String, que tu utiliseras ensuite dans le println et la requête. Tu auras plus de visibilité sur ton code et ne modifieras que cette variable en cas d'erreur.

    A+.

  14. #494
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    this désigne l'objet en cours. Si tu es à l'intérieur de la classe Mail, cela désigne l'objet Mail instancié.
    (voir cours élémentaire de java )
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  15. #495
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Ok merci pour vos conseils

    Je rencontre encore un petit soucis (je n'ai finalement pas utilisé la classe mail... et je sais que ca aurait été mieux )
    ==> attention andry, il y a du rouge dans le texte, met tes lunettes de soleil !
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
        public void envoyerCharge(Annexe annexe, ChargeAffaire charge) throws MessagingException, SQLException, Exception{
            this.setServeur();
            Connexion connexion = new Connexion();
            System.out.print("\n\n Fonction envoyerCharge:\n\n");
            ResultSet resultats = connexion.getResultSet("" +
                "SELECT MailCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"';");
            while(resultats.next()) {
                mailRecepteur   = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailRecepteur+"\n");
                mailExpediteur  = resultats.getString(1);
                System.out.print("mailRecepteur:"+mailExpediteur+"\n");
            }
            resultats.close();
            resultats = connexion.getResultSet("" +
                "SELECT NomCharge, PrenomCharge " +
                "FROM ChargeAffaire " +
                "WHERE Matricule = '"+charge.getMatricule()+"'");
            while(resultats.next()){
                charge.setNom(resultats.getString(1));
                charge.setPrenom(resultats.getString(2));
            }
            resultats.close();
            System.out.print("La requete foireuse :\n");
            resultats = connexion.getResultSet("" +
                    "SELECT IdAnnexe, NomInstallation, NomZone, DateDeb, DateFin, NomCharge, PrenomCharge, NatureIntervention " +
                    "FROM ChargeAffaire, Annexe, Zone, Installation " +
                    "WHERE Annexe.IdZone = "+annexe.getIdZone()+" " +
                    "AND ChargeAffaire.Matricule = Annexe.Matricule " +
                    "AND Zone.IdZone = Annexe.IdZone " +
                    "AND Zone.IdInstallation = Installation.IdInstallation " +
                    "AND('"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin " +
                    "OR '"+Utilitaire.dateToDB(annexe.getDateDeb())+"' BETWEEN dateDeb AND dateFin);");
            System.out.print("\nAnnexe:"+annexe.getIdAnnexe()+"\n");
            String fichier          = Utilitaire.lienApplication()+"SYSTEM/serveurMail.xml";
            FileInputStream ips     = new FileInputStream(fichier);
            InputStreamReader ipsr  = new InputStreamReader(ips);
            BufferedReader br       = new BufferedReader(ipsr);
            String serveur          = br.readLine();
            props.put("mail.smtp.host", serveur);
            while(resultats.next()){
                Properties props    = new Properties();
                MimeMessage msg     = new MimeMessage(Session.getDefaultInstance(props));
                msg.setFrom(new InternetAddress(mailExpediteur));
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
                msg.setSubject("Risque de co-activité pour l'annexe n°"+annexe.getIdAnnexe());
                msg.setText("L'annexe n°"+annexe.getIdAnnexe()+" se trouvant à l'installation : "+resultats.getString(2)+" et dans la zone : "+resultats.getString(3)+" et ayant lieu entre le "+Utilitaire.formaterDate(resultats.getDate(4))+" et le "+Utilitaire.formaterDate(resultats.getDate(5))+" comporte un risque de co-activité avec l'annexe "+resultats.getInt(1)+" ("+ resultats.getString(8)+"). Veuillez contacter votre responsable afin de prendre les mesures nécessaires.");
                Transport.send(msg);
    
                //String sujet = "Risque de co-activité pour l'annexe n°"+annexe.getIdAnnexe();
                //System.out.print("\nSujet :"+sujet+"\n");
                //this.setSujet(sujet);
                //this.setTexte("L'annexe n°"+annexe.getIdAnnexe()+" se trouvant à l'installation : "+resultats.getString(2)+" et dans la zone : "+resultats.getString(3)+" et ayant lieu entre le "+Utilitaire.formaterDate(resultats.getDate(4))+" et le "+Utilitaire.formaterDate(resultats.getDate(5))+" comporte un risque de co-activité avec l'annexe "+resultats.getInt(1)+" ("+ resultats.getString(8)+"). Veuillez contacter votre responsable afin de prendre les mesures nécessaires.");
                //message.setFrom(new InternetAddress(mailExpediteur));
                //message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
                //System.out.print("envoi du mail à "+mailRecepteur);
                //Transport.send(message);
                ResultSet res = connexion.getResultSet("" +
                        "SELECT MailCharge " +
                        "FROM ChargeAffaire " +
                        "WHERE Matricule = 'xxx'");
                while(res.next()){
                    mailRecepteur = res.getString(1);
                    msg.setFrom(new InternetAddress(mailExpediteur));
                    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailRecepteur));
    		System.out.print("envoi du mail à "+mailRecepteur);
                    Transport.send(msg);
                }
            }
            resultats.close();
            connexion.closeConn();
        }
    La petite trace qui va bien :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
      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:295)
            at javax.mail.Service.connect(Service.java:176)
            at javax.mail.Service.connect(Service.java:125)
            at javax.mail.Transport.send0(Transport.java:194)
            at javax.mail.Transport.send(Transport.java:124)
            at coactivite4.Mail.envoyerCharge(Mail.java:161)
    je comprends que ma connexion n'est pas acceptée. Dois je en conclure qu'il faudrait s'authentifier quelque part ?

  16. #496
    Rédacteur/Modérateur
    Avatar de andry.aime
    Homme Profil pro
    Inscrit en
    Septembre 2007
    Messages
    8 391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Ile Maurice

    Informations forums :
    Inscription : Septembre 2007
    Messages : 8 391
    Points : 15 059
    Points
    15 059
    Par défaut
    javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
    Tu dois te connecter à un serveur SMPT, je ne pense pas que ton poste local(localhost) l'est, avec l'authentification qui va avec.
    Regarde où tu as la connexion SMTP et corrige le.

    A+.

  17. #497
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    attention andry, il y a du rouge dans le texte, met tes lunettes de soleil !
    Galopin !!!!

    Tu ferais mieux d'avoir un œil critique sur ton code !!!
    Que penses-tu de cela :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
                Properties props    = new Properties();
                MimeMessage msg     = new MimeMessage(Session.getDefaultInstance(props));
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

  18. #498
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    C'est bien cette instruction qui paramètre les propriétés du server SMTP non ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    props.put("mail.smtp.host", serveur);

    => avec serveur contenant le nom du serveur...

  19. #499
    Nouveau membre du Club
    Homme Profil pro
    Développeur Web
    Inscrit en
    Octobre 2015
    Messages
    340
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2015
    Messages : 340
    Points : 31
    Points
    31
    Par défaut
    Citation Envoyé par Népomucène Voir le message
    Que penses-tu de cela :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
                Properties props    = new Properties();
                MimeMessage msg     = new MimeMessage(Session.getDefaultInstance(props));
    Manque pas ca entre deux par hasard ? ^^
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Session session            = Session.getInstance(props);

  20. #500
    Modérateur

    Homme Profil pro
    Développeur java, access, sql server
    Inscrit en
    Octobre 2005
    Messages
    2 710
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur java, access, sql server
    Secteur : Industrie

    Informations forums :
    Inscription : Octobre 2005
    Messages : 2 710
    Points : 4 794
    Points
    4 794
    Par défaut
    Re-galopin !!!
    Regarde le cheminement du programme :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
            ...
            props.put("mail.smtp.host", serveur);
            while(resultats.next()){
                Properties props    = new Properties();       //     après cela que contient props à ton avis ???
                MimeMessage msg     = new MimeMessage(Session.getDefaultInstance(props));
                ...
    Labor improbus omnia vincit un travail acharné vient à bout de tout - Ambroise Paré (1510-1590)

    Consulter sans modération la FAQ ainsi que les bons ouvrages : http://jmdoudoux.developpez.com/cours/developpons/java/

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. ListView qui change de taille mais n'affiche pas le contenu d'une ObservableCollection
    Par Atellane dans le forum Windows Presentation Foundation
    Réponses: 4
    Dernier message: 14/08/2014, 10h46
  2. DataGrid n'affiche pas le contenu de certaines colonnes d'un Datatable
    Par alucia dans le forum Windows Presentation Foundation
    Réponses: 3
    Dernier message: 20/09/2013, 13h39
  3. .load qui n'affiche pas le contenu de la page
    Par tonydu91 dans le forum jQuery
    Réponses: 4
    Dernier message: 06/04/2013, 23h58
  4. [SimpleXML] Problème avec simpleXML : il n'affiche pas le contenu de mon élément
    Par ploxien dans le forum Bibliothèques et frameworks
    Réponses: 1
    Dernier message: 05/05/2007, 19h43
  5. GUI Java par netbeans - ne s'affiche pas
    Par G_angel dans le forum AWT/Swing
    Réponses: 4
    Dernier message: 31/01/2007, 11h38

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo