You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by ma...@apache.org on 2019/11/13 14:58:01 UTC

[james-project] branch master updated (6e1a572 -> 2877c47)

This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git.


    from 6e1a572  JAMES-2949 Update changelog and upgrade instructions
     new b76cc62  [Refactoring] remove usage of AbstractMailRepository for JDBC to enable refactoring
     new a8ec81d  [Refactoring] fix some visibility issues
     new 3890bfe  [Refactoring] delete some pointless comments
     new 1e321e7  [Refactoring] remove useless assignments
     new acb7dd5  [Refactoring] use try-with-resources
     new 34e5c24  [Refactoring] only method extractions, no code change
     new f8dc39e  [Refactoring] more try-with-resources
     new e918a1b  [Refactoring] remove lock usage from JDBC has it uses transactions
     new 2877c47  Merge remote-tracking branch 'mine/one-fix-per-day-4'

The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../mailrepository/jdbc/JDBCMailRepository.java    | 470 +++++++++++----------
 1 file changed, 241 insertions(+), 229 deletions(-)


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 03/09: [Refactoring] delete some pointless comments

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 3890bfead70ac583f2d04770a2c369f06aa84980
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Fri Nov 8 18:48:24 2019 +0100

    [Refactoring] delete some pointless comments
---
 .../james/mailrepository/jdbc/JDBCMailRepository.java  | 18 ------------------
 1 file changed, 18 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index 9c6e978..9dff687 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -100,16 +100,10 @@ import com.google.common.collect.ImmutableList;
  * <p>
  * Requires a logger called MailRepository.
  * </p>
- * 
- * @version CVS $Revision$ $Date: 2010-12-29 21:47:46 +0100 (Wed, 29
- *          Dec 2010) $
  */
 public class JDBCMailRepository implements MailRepository, Configurable, Initializable {
     private static final Logger LOGGER = LoggerFactory.getLogger(JDBCMailRepository.class);
 
-    /**
-     * Whether 'deep debugging' is turned on.
-     */
     private static final boolean DEEP_DEBUG = false;
 
     /**
@@ -141,25 +135,13 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
      */
     private FilePersistentStreamRepository sr = null;
 
-    /**
-     * The JDBC datasource that provides the JDBC connection
-     */
     private DataSource datasource;
 
-    /**
-     * The name of the datasource used by this repository
-     */
     private String datasourceName;
 
-    /**
-     * Contains all of the sql strings for this component.
-     */
     @VisibleForTesting
     SqlResources sqlQueries;
 
-    /**
-     * The JDBCUtil helper class
-     */
     private JDBCUtil theJDBCUtil;
 
     /**


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 08/09: [Refactoring] remove lock usage from JDBC has it uses transactions

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit e918a1b73193bc4da75957e4c6a9832617bdf0bd
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Tue Nov 12 23:06:25 2019 +0100

    [Refactoring] remove lock usage from JDBC has it uses transactions
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 52 +++-------------------
 1 file changed, 6 insertions(+), 46 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index b5a8e7b..6c1c06f 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -58,7 +58,6 @@ import org.apache.james.filesystem.api.FileSystem;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.mailrepository.api.MailKey;
 import org.apache.james.mailrepository.api.MailRepository;
-import org.apache.james.mailrepository.lib.Lock;
 import org.apache.james.repository.api.Initializable;
 import org.apache.james.repository.file.FilePersistentStreamRepository;
 import org.apache.james.server.core.MailImpl;
@@ -106,12 +105,6 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     private static final boolean DEEP_DEBUG = false;
 
     /**
-     * A lock used to control access to repository elements, locking access
-     * based on the key
-     */
-    private final Lock lock = new Lock();
-
-    /**
      * The table name parsed from the destination URL
      */
     @VisibleForTesting
@@ -226,30 +219,21 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
     }
 
+
     /**
-     * Releases a lock on a message identified the key
-     *
-     * @param key
-     *            the key of the message to be unlocked
-     *
-     * @return true if successfully released the lock, false otherwise
+     * JDBC uses transaction, it doesn't need locks
      */
     @Override
     public boolean unlock(MailKey key) {
-        return lock.unlock(key);
+        return false;
     }
 
     /**
-     * Obtains a lock on a message identified by key
-     *
-     * @param key
-     *            the key of the message to be locked
-     *
-     * @return true if successfully obtained the lock, false otherwise
+     * JDBC uses transaction, it doesn't need locks
      */
     @Override
     public boolean lock(MailKey key) {
-        return lock.lock(key);
+        return false;
     }
 
 
@@ -403,16 +387,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
     @Override
     public MailKey store(Mail mc) throws MessagingException {
-        boolean wasLocked = true;
         MailKey key = MailKey.forMail(mc);
         try {
-            synchronized (this) {
-                wasLocked = lock.isLocked(key);
-                if (!wasLocked) {
-                    // If it wasn't locked, we want a lock during the store
-                    lock(key);
-                }
-            }
             internalStore(mc);
             return key;
         } catch (MessagingException e) {
@@ -421,14 +397,6 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
         } catch (Exception e) {
             LOGGER.error("Exception caught while storing mail {}", key, e);
             throw new MessagingException("Exception caught while storing mail " + key, e);
-        } finally {
-            if (!wasLocked) {
-                // If it wasn't locked, we need to unlock now
-                unlock(key);
-                synchronized (this) {
-                    notify();
-                }
-            }
         }
     }
 
@@ -760,15 +728,7 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
     @Override
     public void remove(MailKey key) throws MessagingException {
-        if (lock(key)) {
-            try {
-                internalRemove(key);
-            } finally {
-                unlock(key);
-            }
-        } else {
-            throw new MessagingException("Cannot lock " + key + " to remove it");
-        }
+        internalRemove(key);
     }
 
     private void internalRemove(MailKey key) throws MessagingException {


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 06/09: [Refactoring] only method extractions, no code change

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 34e5c24a7bbd4fc544a5b10707d16b0cceee86bf
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Tue Nov 12 22:55:14 2019 +0100

    [Refactoring] only method extractions, no code change
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 343 +++++++++++----------
 1 file changed, 183 insertions(+), 160 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index 294792a..dcebcc6 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -441,196 +441,219 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
             // Determine whether the message body has changed, and possibly
             // avoid
             // updating the database.
-            boolean saveBody;
-
-            MimeMessage messageBody = mc.getMessage();
-            // if the message is a CopyOnWrite proxy we check the modified
-            // wrapped object.
-            if (messageBody instanceof MimeMessageCopyOnWriteProxy) {
-                MimeMessageCopyOnWriteProxy messageCow = (MimeMessageCopyOnWriteProxy) messageBody;
-                messageBody = messageCow.getWrappedMessage();
-            }
-            if (messageBody instanceof MimeMessageWrapper) {
-                MimeMessageWrapper message = (MimeMessageWrapper) messageBody;
-                saveBody = message.isModified();
-                if (saveBody) {
-                    message.loadMessage();
-                }
-            } else {
-                saveBody = true;
-            }
+            boolean saveBody = saveBodyRequired(mc);
             MessageInputStream is = new MessageInputStream(mc, sr, inMemorySizeLimit, true);
 
             // Begin a transaction
             conn.setAutoCommit(false);
 
-            PreparedStatement checkMessageExists = null;
-            ResultSet rsExists = null;
-            boolean exists;
-            try {
-                checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
-                checkMessageExists.setString(1, mc.getName());
-                checkMessageExists.setString(2, repositoryName);
-                rsExists = checkMessageExists.executeQuery();
-                exists = rsExists.next() && rsExists.getInt(1) > 0;
-            } finally {
-                theJDBCUtil.closeJDBCResultSet(rsExists);
-                theJDBCUtil.closeJDBCStatement(checkMessageExists);
-            }
+            boolean exists = checkMessageExists(mc, conn);
 
             if (exists) {
                 // MessageInputStream is = new
                 // MessageInputStream(mc,sr,inMemorySizeLimit, true);
-
-                // Update the existing record
-                PreparedStatement updateMessage = null;
-
-                try {
-                    updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true));
-                    updateMessage.setString(1, mc.getState());
-                    updateMessage.setString(2, mc.getErrorMessage());
-                    if (mc.getMaybeSender().isNullSender()) {
-                        updateMessage.setNull(3, java.sql.Types.VARCHAR);
-                    } else {
-                        updateMessage.setString(3, mc.getMaybeSender().get().toString());
-                    }
-                    StringBuilder recipients = new StringBuilder();
-                    for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
-                        recipients.append(i.next().toString());
-                        if (i.hasNext()) {
-                            recipients.append("\r\n");
-                        }
-                    }
-                    updateMessage.setString(4, recipients.toString());
-                    updateMessage.setString(5, mc.getRemoteHost());
-                    updateMessage.setString(6, mc.getRemoteAddr());
-                    updateMessage.setTimestamp(7, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
-                    updateMessage.setString(8, mc.getName());
-                    updateMessage.setString(9, repositoryName);
-                    updateMessage.execute();
-                } finally {
-                    Statement localUpdateMessage = updateMessage;
-                    // Clear reference to statement
-                    theJDBCUtil.closeJDBCStatement(localUpdateMessage);
-                }
+                updateMessage(mc, conn);
 
                 // Determine whether attributes are used and available for
                 // storing
                 if (jdbcMailAttributesReady && mc.hasAttributes()) {
-                    String updateMessageAttrSql = sqlQueries.getSqlString("updateMessageAttributesSQL", false);
-                    PreparedStatement updateMessageAttr = null;
-                    try {
-                        updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
-                        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
-                            if (mc instanceof MailImpl) {
-                                oos.writeObject(((MailImpl) mc).getAttributesRaw());
-                            } else {
-                                Map<String, Serializable> temp = mc.attributes()
-                                    .collect(Guavate.toImmutableMap(
-                                            attribute -> attribute.getName().asString(),
-                                            attribute -> (Serializable) attribute.getValue().value()
-                                    ));
-                                oos.writeObject(temp);
-                            }
-                            oos.flush();
-                            ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
-                            updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
-                        }
-                        updateMessageAttr.setString(2, mc.getName());
-                        updateMessageAttr.setString(3, repositoryName);
-                        updateMessageAttr.execute();
-                    } catch (SQLException sqle) {
-                        LOGGER.info("JDBCMailRepository: Trying to update mail attributes failed.", sqle);
-
-                    } finally {
-                        theJDBCUtil.closeJDBCStatement(updateMessageAttr);
-                    }
+                    updateMailAttributes(mc, conn);
                 }
 
                 if (saveBody) {
-
-                    PreparedStatement updateMessageBody = conn.prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true));
-                    try {
-                        updateMessageBody.setBinaryStream(1, is, (int) is.getSize());
-                        updateMessageBody.setString(2, mc.getName());
-                        updateMessageBody.setString(3, repositoryName);
-                        updateMessageBody.execute();
-
-                    } finally {
-                        theJDBCUtil.closeJDBCStatement(updateMessageBody);
-                    }
+                    updateMessageBody(mc, conn, is);
                 }
 
             } else {
                 // Insert the record into the database
-                PreparedStatement insertMessage = null;
-                try {
-                    String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
-                    insertMessage = conn.prepareStatement(insertMessageSQL);
-                    int numberOfParameters = insertMessage.getParameterMetaData().getParameterCount();
-                    insertMessage.setString(1, mc.getName());
-                    insertMessage.setString(2, repositoryName);
-                    insertMessage.setString(3, mc.getState());
-                    insertMessage.setString(4, mc.getErrorMessage());
-                    if (mc.getMaybeSender().isNullSender()) {
-                        insertMessage.setNull(5, Types.VARCHAR);
-                    } else {
-                        insertMessage.setString(5, mc.getMaybeSender().get().toString());
-                    }
-                    StringBuilder recipients = new StringBuilder();
-                    for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
-                        recipients.append(i.next().toString());
-                        if (i.hasNext()) {
-                            recipients.append("\r\n");
-                        }
-                    }
-                    insertMessage.setString(6, recipients.toString());
-                    insertMessage.setString(7, mc.getRemoteHost());
-                    insertMessage.setString(8, mc.getRemoteAddr());
-                    if (mc.getPerRecipientSpecificHeaders().getHeadersByRecipient().isEmpty()) {
-                        insertMessage.setObject(9, null);
+                insertMessage(mc, conn, is);
+            }
+
+            conn.commit();
+            conn.setAutoCommit(true);
+        } catch (SQLException e) {
+            LOGGER.debug("Failed to store internal mail", e);
+            throw new IOException(e.getMessage());
+        }
+    }
+
+    private void insertMessage(Mail mc, Connection conn, MessageInputStream is) throws SQLException, IOException {
+        PreparedStatement insertMessage = null;
+        try {
+            String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
+            insertMessage = conn.prepareStatement(insertMessageSQL);
+            int numberOfParameters = insertMessage.getParameterMetaData().getParameterCount();
+            insertMessage.setString(1, mc.getName());
+            insertMessage.setString(2, repositoryName);
+            insertMessage.setString(3, mc.getState());
+            insertMessage.setString(4, mc.getErrorMessage());
+            if (mc.getMaybeSender().isNullSender()) {
+                insertMessage.setNull(5, Types.VARCHAR);
+            } else {
+                insertMessage.setString(5, mc.getMaybeSender().get().toString());
+            }
+            StringBuilder recipients = new StringBuilder();
+            for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
+                recipients.append(i.next().toString());
+                if (i.hasNext()) {
+                    recipients.append("\r\n");
+                }
+            }
+            insertMessage.setString(6, recipients.toString());
+            insertMessage.setString(7, mc.getRemoteHost());
+            insertMessage.setString(8, mc.getRemoteAddr());
+            if (mc.getPerRecipientSpecificHeaders().getHeadersByRecipient().isEmpty()) {
+                insertMessage.setObject(9, null);
+            } else {
+                byte[] bytes = SerializationUtils.serialize(mc.getPerRecipientSpecificHeaders());
+                insertMessage.setBinaryStream(9, new ByteArrayInputStream(bytes), bytes.length);
+            }
+            insertMessage.setTimestamp(10, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
+
+            insertMessage.setBinaryStream(11, is, (int) is.getSize());
+
+            // Store attributes
+            if (numberOfParameters > 11) {
+                try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                     ObjectOutputStream oos = new ObjectOutputStream(baos)) {
+                    if (mc instanceof MailImpl) {
+                        oos.writeObject(((MailImpl) mc).getAttributesRaw());
                     } else {
-                        byte[] bytes = SerializationUtils.serialize(mc.getPerRecipientSpecificHeaders());
-                        insertMessage.setBinaryStream(9, new ByteArrayInputStream(bytes), bytes.length);
+                        Map<String, Serializable> temp = mc.attributes()
+                                .collect(Guavate.toImmutableMap(
+                                        attribute -> attribute.getName().asString(),
+                                        attribute -> (Serializable) attribute.getValue().value()
+                                ));
+
+                        oos.writeObject(temp);
                     }
-                    insertMessage.setTimestamp(10, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
+                    oos.flush();
+                    ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
+                    insertMessage.setBinaryStream(12, attrInputStream, baos.size());
+                }
+            }
 
-                    insertMessage.setBinaryStream(11, is, (int) is.getSize());
+            insertMessage.execute();
+        } finally {
+            theJDBCUtil.closeJDBCStatement(insertMessage);
+        }
+    }
 
-                    // Store attributes
-                    if (numberOfParameters > 11) {
-                        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
-                            if (mc instanceof MailImpl) {
-                                oos.writeObject(((MailImpl) mc).getAttributesRaw());
-                            } else {
-                                Map<String, Serializable> temp = mc.attributes()
-                                        .collect(Guavate.toImmutableMap(
-                                                attribute -> attribute.getName().asString(),
-                                                attribute -> (Serializable) attribute.getValue().value()
-                                        ));
+    private void updateMessageBody(Mail mc, Connection conn, MessageInputStream is) throws SQLException {
+        PreparedStatement updateMessageBody = conn.prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true));
+        try {
+            updateMessageBody.setBinaryStream(1, is, (int) is.getSize());
+            updateMessageBody.setString(2, mc.getName());
+            updateMessageBody.setString(3, repositoryName);
+            updateMessageBody.execute();
 
-                                oos.writeObject(temp);
-                            }
-                            oos.flush();
-                            ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
-                            insertMessage.setBinaryStream(12, attrInputStream, baos.size());
-                        }
-                    }
+        } finally {
+            theJDBCUtil.closeJDBCStatement(updateMessageBody);
+        }
+    }
 
-                    insertMessage.execute();
-                } finally {
-                    theJDBCUtil.closeJDBCStatement(insertMessage);
+    private void updateMailAttributes(Mail mc, Connection conn) throws IOException {
+        String updateMessageAttrSql = sqlQueries.getSqlString("updateMessageAttributesSQL", false);
+        PreparedStatement updateMessageAttr = null;
+        try {
+            updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
+            try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                 ObjectOutputStream oos = new ObjectOutputStream(baos)) {
+                if (mc instanceof MailImpl) {
+                    oos.writeObject(((MailImpl) mc).getAttributesRaw());
+                } else {
+                    Map<String, Serializable> temp = mc.attributes()
+                        .collect(Guavate.toImmutableMap(
+                                attribute -> attribute.getName().asString(),
+                                attribute -> (Serializable) attribute.getValue().value()
+                        ));
+                    oos.writeObject(temp);
                 }
+                oos.flush();
+                ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
+                updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
             }
+            updateMessageAttr.setString(2, mc.getName());
+            updateMessageAttr.setString(3, repositoryName);
+            updateMessageAttr.execute();
+        } catch (SQLException sqle) {
+            LOGGER.info("JDBCMailRepository: Trying to update mail attributes failed.", sqle);
 
-            conn.commit();
-            conn.setAutoCommit(true);
-        } catch (SQLException e) {
-            LOGGER.debug("Failed to store internal mail", e);
-            throw new IOException(e.getMessage());
+        } finally {
+            theJDBCUtil.closeJDBCStatement(updateMessageAttr);
+        }
+    }
+
+    private void updateMessage(Mail mc, Connection conn) throws SQLException {
+        // Update the existing record
+        PreparedStatement updateMessage = null;
+
+        try {
+            updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true));
+            updateMessage.setString(1, mc.getState());
+            updateMessage.setString(2, mc.getErrorMessage());
+            if (mc.getMaybeSender().isNullSender()) {
+                updateMessage.setNull(3, Types.VARCHAR);
+            } else {
+                updateMessage.setString(3, mc.getMaybeSender().get().toString());
+            }
+            StringBuilder recipients = new StringBuilder();
+            for (Iterator<MailAddress> i = mc.getRecipients().iterator(); i.hasNext();) {
+                recipients.append(i.next().toString());
+                if (i.hasNext()) {
+                    recipients.append("\r\n");
+                }
+            }
+            updateMessage.setString(4, recipients.toString());
+            updateMessage.setString(5, mc.getRemoteHost());
+            updateMessage.setString(6, mc.getRemoteAddr());
+            updateMessage.setTimestamp(7, new java.sql.Timestamp(mc.getLastUpdated().getTime()));
+            updateMessage.setString(8, mc.getName());
+            updateMessage.setString(9, repositoryName);
+            updateMessage.execute();
+        } finally {
+            Statement localUpdateMessage = updateMessage;
+            // Clear reference to statement
+            theJDBCUtil.closeJDBCStatement(localUpdateMessage);
+        }
+    }
+
+    private boolean checkMessageExists(Mail mc, Connection conn) throws SQLException {
+        PreparedStatement checkMessageExists = null;
+        ResultSet rsExists = null;
+        boolean exists;
+        try {
+            checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
+            checkMessageExists.setString(1, mc.getName());
+            checkMessageExists.setString(2, repositoryName);
+            rsExists = checkMessageExists.executeQuery();
+            exists = rsExists.next() && rsExists.getInt(1) > 0;
+        } finally {
+            theJDBCUtil.closeJDBCResultSet(rsExists);
+            theJDBCUtil.closeJDBCStatement(checkMessageExists);
+        }
+        return exists;
+    }
+
+    private boolean saveBodyRequired(Mail mc) throws MessagingException {
+        boolean saveBody;
+        MimeMessage messageBody = mc.getMessage();
+        // if the message is a CopyOnWrite proxy we check the modified
+        // wrapped object.
+        if (messageBody instanceof MimeMessageCopyOnWriteProxy) {
+            MimeMessageCopyOnWriteProxy messageCow = (MimeMessageCopyOnWriteProxy) messageBody;
+            messageBody = messageCow.getWrappedMessage();
+        }
+        if (messageBody instanceof MimeMessageWrapper) {
+            MimeMessageWrapper message = (MimeMessageWrapper) messageBody;
+            saveBody = message.isModified();
+            if (saveBody) {
+                message.loadMessage();
+            }
+        } else {
+            saveBody = true;
         }
+        return saveBody;
     }
 
     @Override


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 01/09: [Refactoring] remove usage of AbstractMailRepository for JDBC to enable refactoring

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit b76cc624046c6376723f3dde9536c9e021acbf2f
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Fri Nov 8 18:35:00 2019 +0100

    [Refactoring] remove usage of AbstractMailRepository for JDBC to enable refactoring
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 114 +++++++++++++++++++--
 1 file changed, 108 insertions(+), 6 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index f6a7405..822f6c3 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -35,6 +35,7 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.sql.Types;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -55,8 +56,11 @@ import org.apache.commons.configuration2.tree.ImmutableNode;
 import org.apache.commons.lang3.SerializationUtils;
 import org.apache.james.core.MailAddress;
 import org.apache.james.filesystem.api.FileSystem;
+import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.mailrepository.api.MailKey;
-import org.apache.james.mailrepository.lib.AbstractMailRepository;
+import org.apache.james.mailrepository.api.MailRepository;
+import org.apache.james.mailrepository.lib.Lock;
+import org.apache.james.repository.api.Initializable;
 import org.apache.james.repository.file.FilePersistentStreamRepository;
 import org.apache.james.server.core.MailImpl;
 import org.apache.james.server.core.MimeMessageCopyOnWriteProxy;
@@ -68,6 +72,7 @@ import org.apache.mailet.Mail;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.github.fge.lambdas.Throwing;
 import com.github.steveash.guavate.Guavate;
 import com.google.common.collect.ImmutableList;
 
@@ -98,10 +103,21 @@ import com.google.common.collect.ImmutableList;
  * @version CVS $Revision$ $Date: 2010-12-29 21:47:46 +0100 (Wed, 29
  *          Dec 2010) $
  */
-public class JDBCMailRepository extends AbstractMailRepository {
+public class JDBCMailRepository implements MailRepository, Configurable, Initializable {
     private static final Logger LOGGER = LoggerFactory.getLogger(JDBCMailRepository.class);
 
     /**
+     * Whether 'deep debugging' is turned on.
+     */
+    private static final boolean DEEP_DEBUG = false;
+
+    /**
+     * A lock used to control access to repository elements, locking access
+     * based on the key
+     */
+    private final Lock lock = new Lock();
+
+    /**
      * The table name parsed from the destination URL
      */
     protected String tableName;
@@ -169,8 +185,7 @@ public class JDBCMailRepository extends AbstractMailRepository {
     }
 
     @Override
-    protected void doConfigure(HierarchicalConfiguration<ImmutableNode> configuration) throws ConfigurationException {
-        super.doConfigure(configuration);
+    public void configure(HierarchicalConfiguration<ImmutableNode> configuration) throws ConfigurationException {
         LOGGER.debug("{}.configure()", getClass().getName());
         destination = configuration.getString("[@destinationURL]");
 
@@ -225,6 +240,33 @@ public class JDBCMailRepository extends AbstractMailRepository {
     }
 
     /**
+     * Releases a lock on a message identified the key
+     *
+     * @param key
+     *            the key of the message to be unlocked
+     *
+     * @return true if successfully released the lock, false otherwise
+     */
+    @Override
+    public boolean unlock(MailKey key) {
+        return lock.unlock(key);
+    }
+
+    /**
+     * Obtains a lock on a message identified by key
+     *
+     * @param key
+     *            the key of the message to be locked
+     *
+     * @return true if successfully obtained the lock, false otherwise
+     */
+    @Override
+    public boolean lock(MailKey key) {
+        return lock.lock(key);
+    }
+
+
+    /**
      * Initialises the JDBC repository.
      * <ol>
      * <li>Tests the connection to the database.</li>
@@ -328,7 +370,7 @@ public class JDBCMailRepository extends AbstractMailRepository {
      * @throws SQLException
      *             if a fatal situation is met
      */
-    protected void checkJdbcAttributesSupport(DatabaseMetaData dbMetaData) throws SQLException {
+    private void checkJdbcAttributesSupport(DatabaseMetaData dbMetaData) throws SQLException {
         String attributesColumnName = "message_attributes";
         boolean hasUpdateMessageAttributesSQL = false;
         boolean hasRetrieveMessageAttributesSQL = false;
@@ -381,7 +423,37 @@ public class JDBCMailRepository extends AbstractMailRepository {
     }
 
     @Override
-    protected void internalStore(Mail mc) throws IOException, MessagingException {
+    public MailKey store(Mail mc) throws MessagingException {
+        boolean wasLocked = true;
+        MailKey key = MailKey.forMail(mc);
+        try {
+            synchronized (this) {
+                wasLocked = lock.isLocked(key);
+                if (!wasLocked) {
+                    // If it wasn't locked, we want a lock during the store
+                    lock(key);
+                }
+            }
+            internalStore(mc);
+            return key;
+        } catch (MessagingException e) {
+            LOGGER.error("Exception caught while storing mail {}", key, e);
+            throw e;
+        } catch (Exception e) {
+            LOGGER.error("Exception caught while storing mail {}", key, e);
+            throw new MessagingException("Exception caught while storing mail " + key, e);
+        } finally {
+            if (!wasLocked) {
+                // If it wasn't locked, we need to unlock now
+                unlock(key);
+                synchronized (this) {
+                    notify();
+                }
+            }
+        }
+    }
+
+    private void internalStore(Mail mc) throws IOException, MessagingException {
         Connection conn = null;
         try {
             conn = datasource.getConnection();
@@ -726,6 +798,30 @@ public class JDBCMailRepository extends AbstractMailRepository {
     }
 
     @Override
+    public void remove(Mail mail) throws MessagingException {
+        remove(MailKey.forMail(mail));
+    }
+
+    @Override
+    public void remove(Collection<Mail> mails) throws MessagingException {
+        for (Mail mail : mails) {
+            remove(mail);
+        }
+    }
+
+    @Override
+    public void remove(MailKey key) throws MessagingException {
+        if (lock(key)) {
+            try {
+                internalRemove(key);
+            } finally {
+                unlock(key);
+            }
+        } else {
+            throw new MessagingException("Cannot lock " + key + " to remove it");
+        }
+    }
+
     protected void internalRemove(MailKey key) throws MessagingException {
         Connection conn = null;
         PreparedStatement removeMessage = null;
@@ -809,6 +905,12 @@ public class JDBCMailRepository extends AbstractMailRepository {
     }
 
     @Override
+    public void removeAll() throws MessagingException {
+        ImmutableList.copyOf(list())
+            .forEach(Throwing.<MailKey>consumer(this::remove).sneakyThrow());
+    }
+
+    @Override
     public int hashCode() {
         int result = 17;
         if (tableName != null) {


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 04/09: [Refactoring] remove useless assignments

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 1e321e74619cc7bfa16165f33f88f3b399411d74
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Fri Nov 8 18:53:03 2019 +0100

    [Refactoring] remove useless assignments
---
 .../java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java  | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index 9dff687..f7c900a 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -476,7 +476,7 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
             PreparedStatement checkMessageExists = null;
             ResultSet rsExists = null;
-            boolean exists = false;
+            boolean exists;
             try {
                 checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
                 checkMessageExists.setString(1, mc.getName());
@@ -521,7 +521,6 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
                 } finally {
                     Statement localUpdateMessage = updateMessage;
                     // Clear reference to statement
-                    updateMessage = null;
                     theJDBCUtil.closeJDBCStatement(localUpdateMessage);
                 }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 02/09: [Refactoring] fix some visibility issues

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit a8ec81ddc5f34f72c252ed33befb091939cfc953
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Fri Nov 8 18:41:33 2019 +0100

    [Refactoring] fix some visibility issues
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 29 ++++++++++++++--------
 1 file changed, 18 insertions(+), 11 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index 822f6c3..9c6e978 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -74,6 +74,7 @@ import org.slf4j.LoggerFactory;
 
 import com.github.fge.lambdas.Throwing;
 import com.github.steveash.guavate.Guavate;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 
 /**
@@ -120,12 +121,14 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     /**
      * The table name parsed from the destination URL
      */
-    protected String tableName;
+    @VisibleForTesting
+    String tableName;
 
     /**
      * The repository name parsed from the destination URL
      */
-    protected String repositoryName;
+    @VisibleForTesting
+    String repositoryName;
 
     /**
      * The name of the SQL configuration file to be used to configure this
@@ -141,27 +144,28 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     /**
      * The JDBC datasource that provides the JDBC connection
      */
-    protected DataSource datasource;
+    private DataSource datasource;
 
     /**
      * The name of the datasource used by this repository
      */
-    protected String datasourceName;
+    private String datasourceName;
 
     /**
      * Contains all of the sql strings for this component.
      */
-    protected SqlResources sqlQueries;
+    @VisibleForTesting
+    SqlResources sqlQueries;
 
     /**
      * The JDBCUtil helper class
      */
-    protected JDBCUtil theJDBCUtil;
+    private JDBCUtil theJDBCUtil;
 
     /**
      * "Support for Mail Attributes under JDBC repositories is ready" indicator.
      */
-    protected boolean jdbcMailAttributesReady = false;
+    private boolean jdbcMailAttributesReady = false;
 
     /**
      * The size threshold for in memory handling of storing operations
@@ -175,12 +179,14 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     private String destination;
 
     @Inject
-    public void setDatasource(DataSource datasource) {
+    @VisibleForTesting
+    void setDatasource(DataSource datasource) {
         this.datasource = datasource;
     }
 
     @Inject
-    public void setFileSystem(FileSystem fileSystem) {
+    @VisibleForTesting
+    void setFileSystem(FileSystem fileSystem) {
         this.fileSystem = fileSystem;
     }
 
@@ -822,7 +828,7 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
         }
     }
 
-    protected void internalRemove(MailKey key) throws MessagingException {
+    private void internalRemove(MailKey key) throws MessagingException {
         Connection conn = null;
         PreparedStatement removeMessage = null;
         try {
@@ -889,7 +895,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
      * @throws SQLException
      *             if there is an issue with getting the connection
      */
-    protected Connection getConnection() throws SQLException {
+    @VisibleForTesting
+    Connection getConnection() throws SQLException {
         return datasource.getConnection();
     }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 09/09: Merge remote-tracking branch 'mine/one-fix-per-day-4'

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 2877c47202e72c34278152347e94f038a1c46132
Merge: 6e1a572 e918a1b
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Wed Nov 13 15:57:21 2019 +0100

    Merge remote-tracking branch 'mine/one-fix-per-day-4'

 .../mailrepository/jdbc/JDBCMailRepository.java    | 470 +++++++++++----------
 1 file changed, 241 insertions(+), 229 deletions(-)


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 07/09: [Refactoring] more try-with-resources

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit f8dc39e065aaba496330e2bb6c5b4bf46df197fb
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Tue Nov 12 23:02:23 2019 +0100

    [Refactoring] more try-with-resources
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 74 +++++++---------------
 1 file changed, 22 insertions(+), 52 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index dcebcc6..b5a8e7b 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -32,7 +32,6 @@ import java.sql.DatabaseMetaData;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import java.sql.Statement;
 import java.sql.Types;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -478,10 +477,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     }
 
     private void insertMessage(Mail mc, Connection conn, MessageInputStream is) throws SQLException, IOException {
-        PreparedStatement insertMessage = null;
-        try {
-            String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
-            insertMessage = conn.prepareStatement(insertMessageSQL);
+        String insertMessageSQL = sqlQueries.getSqlString("insertMessageSQL", true);
+        try (PreparedStatement insertMessage = conn.prepareStatement(insertMessageSQL)) {
             int numberOfParameters = insertMessage.getParameterMetaData().getParameterCount();
             insertMessage.setString(1, mc.getName());
             insertMessage.setString(2, repositoryName);
@@ -534,62 +531,47 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
             }
 
             insertMessage.execute();
-        } finally {
-            theJDBCUtil.closeJDBCStatement(insertMessage);
         }
     }
 
     private void updateMessageBody(Mail mc, Connection conn, MessageInputStream is) throws SQLException {
-        PreparedStatement updateMessageBody = conn.prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true));
-        try {
+        try (PreparedStatement updateMessageBody = conn.prepareStatement(sqlQueries.getSqlString("updateMessageBodySQL", true))) {
             updateMessageBody.setBinaryStream(1, is, (int) is.getSize());
             updateMessageBody.setString(2, mc.getName());
             updateMessageBody.setString(3, repositoryName);
             updateMessageBody.execute();
-
-        } finally {
-            theJDBCUtil.closeJDBCStatement(updateMessageBody);
         }
     }
 
     private void updateMailAttributes(Mail mc, Connection conn) throws IOException {
         String updateMessageAttrSql = sqlQueries.getSqlString("updateMessageAttributesSQL", false);
-        PreparedStatement updateMessageAttr = null;
-        try {
-            updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
-            try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                 ObjectOutputStream oos = new ObjectOutputStream(baos)) {
-                if (mc instanceof MailImpl) {
-                    oos.writeObject(((MailImpl) mc).getAttributesRaw());
-                } else {
-                    Map<String, Serializable> temp = mc.attributes()
-                        .collect(Guavate.toImmutableMap(
-                                attribute -> attribute.getName().asString(),
-                                attribute -> (Serializable) attribute.getValue().value()
-                        ));
-                    oos.writeObject(temp);
-                }
-                oos.flush();
-                ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
-                updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
+        try (PreparedStatement updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
+             ByteArrayOutputStream baos = new ByteArrayOutputStream();
+             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
+            if (mc instanceof MailImpl) {
+                oos.writeObject(((MailImpl) mc).getAttributesRaw());
+            } else {
+                Map<String, Serializable> temp = mc.attributes()
+                    .collect(Guavate.toImmutableMap(
+                            attribute -> attribute.getName().asString(),
+                            attribute -> (Serializable) attribute.getValue().value()
+                    ));
+                oos.writeObject(temp);
             }
+            oos.flush();
+            ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
+            updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
             updateMessageAttr.setString(2, mc.getName());
             updateMessageAttr.setString(3, repositoryName);
             updateMessageAttr.execute();
         } catch (SQLException sqle) {
             LOGGER.info("JDBCMailRepository: Trying to update mail attributes failed.", sqle);
-
-        } finally {
-            theJDBCUtil.closeJDBCStatement(updateMessageAttr);
         }
     }
 
     private void updateMessage(Mail mc, Connection conn) throws SQLException {
         // Update the existing record
-        PreparedStatement updateMessage = null;
-
-        try {
-            updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true));
+        try (PreparedStatement updateMessage = conn.prepareStatement(sqlQueries.getSqlString("updateMessageSQL", true))) {
             updateMessage.setString(1, mc.getState());
             updateMessage.setString(2, mc.getErrorMessage());
             if (mc.getMaybeSender().isNullSender()) {
@@ -611,28 +593,16 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
             updateMessage.setString(8, mc.getName());
             updateMessage.setString(9, repositoryName);
             updateMessage.execute();
-        } finally {
-            Statement localUpdateMessage = updateMessage;
-            // Clear reference to statement
-            theJDBCUtil.closeJDBCStatement(localUpdateMessage);
         }
     }
 
     private boolean checkMessageExists(Mail mc, Connection conn) throws SQLException {
-        PreparedStatement checkMessageExists = null;
-        ResultSet rsExists = null;
-        boolean exists;
-        try {
-            checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true));
+        try (PreparedStatement checkMessageExists = conn.prepareStatement(sqlQueries.getSqlString("checkMessageExistsSQL", true))) {
             checkMessageExists.setString(1, mc.getName());
             checkMessageExists.setString(2, repositoryName);
-            rsExists = checkMessageExists.executeQuery();
-            exists = rsExists.next() && rsExists.getInt(1) > 0;
-        } finally {
-            theJDBCUtil.closeJDBCResultSet(rsExists);
-            theJDBCUtil.closeJDBCStatement(checkMessageExists);
+            ResultSet rsExists = checkMessageExists.executeQuery();
+            return rsExists.next() && rsExists.getInt(1) > 0;
         }
-        return exists;
     }
 
     private boolean saveBodyRequired(Mail mc) throws MessagingException {


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org


[james-project] 05/09: [Refactoring] use try-with-resources

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

matthieu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit acb7dd5f4a3248e3a41c72586221c0e0dd1bf56f
Author: Matthieu Baechler <ma...@apache.org>
AuthorDate: Fri Nov 8 18:53:14 2019 +0100

    [Refactoring] use try-with-resources
---
 .../mailrepository/jdbc/JDBCMailRepository.java    | 49 ++++------------------
 1 file changed, 9 insertions(+), 40 deletions(-)

diff --git a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
index f7c900a..294792a 100644
--- a/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
+++ b/server/data/data-jdbc/src/main/java/org/apache/james/mailrepository/jdbc/JDBCMailRepository.java
@@ -296,13 +296,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
         theJDBCUtil = new JDBCUtil();
 
-        // Test the connection to the database, by getting the DatabaseMetaData.
-        Connection conn = datasource.getConnection();
-        PreparedStatement createStatement = null;
-
-        try {
+        try (Connection conn = datasource.getConnection()) {
             // Initialise the sql strings.
-
             InputStream sqlFile;
             try {
                 sqlFile = fileSystem.getResource(sqlFileName);
@@ -332,17 +327,14 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
             // Try UPPER, lower, and MixedCase, to see if the table is there.
             if (!(theJDBCUtil.tableExists(dbMetaData, tableName))) {
                 // Users table doesn't exist - create it.
-                createStatement = conn.prepareStatement(sqlQueries.getSqlString("createTable", true));
-                createStatement.execute();
+                try (PreparedStatement createStatement = conn.prepareStatement(sqlQueries.getSqlString("createTable", true))) {
+                    createStatement.execute();
+                }
 
                 LOGGER.info("JdbcMailRepository: Created table '{}'.", tableName);
             }
 
             checkJdbcAttributesSupport(dbMetaData);
-
-        } finally {
-            theJDBCUtil.closeJDBCStatement(createStatement);
-            theJDBCUtil.closeJDBCConnection(conn);
         }
     }
 
@@ -442,9 +434,7 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
     }
 
     private void internalStore(Mail mc) throws IOException, MessagingException {
-        Connection conn = null;
-        try {
-            conn = datasource.getConnection();
+        try (Connection conn = datasource.getConnection()) {
             // Need to determine whether need to insert this record, or update
             // it.
 
@@ -531,9 +521,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
                     PreparedStatement updateMessageAttr = null;
                     try {
                         updateMessageAttr = conn.prepareStatement(updateMessageAttrSql);
-                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                        ObjectOutputStream oos = new ObjectOutputStream(baos);
-                        try {
+                        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                             if (mc instanceof MailImpl) {
                                 oos.writeObject(((MailImpl) mc).getAttributesRaw());
                             } else {
@@ -542,20 +531,11 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
                                             attribute -> attribute.getName().asString(),
                                             attribute -> (Serializable) attribute.getValue().value()
                                     ));
-
                                 oos.writeObject(temp);
                             }
                             oos.flush();
                             ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                             updateMessageAttr.setBinaryStream(1, attrInputStream, baos.size());
-                        } finally {
-                            try {
-                                if (oos != null) {
-                                    oos.close();
-                                }
-                            } catch (IOException ioe) {
-                                LOGGER.debug("JDBCMailRepository: Unexpected exception while closing output stream.", ioe);
-                            }
                         }
                         updateMessageAttr.setString(2, mc.getName());
                         updateMessageAttr.setString(3, repositoryName);
@@ -620,9 +600,8 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
 
                     // Store attributes
                     if (numberOfParameters > 11) {
-                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                        ObjectOutputStream oos = new ObjectOutputStream(baos);
-                        try {
+                        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+                             ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                             if (mc instanceof MailImpl) {
                                 oos.writeObject(((MailImpl) mc).getAttributesRaw());
                             } else {
@@ -637,14 +616,6 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
                             oos.flush();
                             ByteArrayInputStream attrInputStream = new ByteArrayInputStream(baos.toByteArray());
                             insertMessage.setBinaryStream(12, attrInputStream, baos.size());
-                        } finally {
-                            try {
-                                if (oos != null) {
-                                    oos.close();
-                                }
-                            } catch (IOException ioe) {
-                                LOGGER.debug("JDBCMailRepository: Unexpected exception while closing output stream.", ioe);
-                            }
                         }
                     }
 
@@ -659,8 +630,6 @@ public class JDBCMailRepository implements MailRepository, Configurable, Initial
         } catch (SQLException e) {
             LOGGER.debug("Failed to store internal mail", e);
             throw new IOException(e.getMessage());
-        } finally {
-            theJDBCUtil.closeJDBCConnection(conn);
         }
     }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org