>From 50f364715dbe8d4bf0e9f1b16b70ba850a6e2be3 Mon Sep 17 00:00:00 2001
From: Abhishek Koneru <akoneru@redhat.com>
Date: Wed, 20 Jun 2012 13:56:57 -0400
Subject: [PATCH] Fixes for Coverity issues of type Resource Leaks - Remaining

---
 .../src/com/netscape/ca/CertificateAuthority.java  |   11 +-
 .../cms/publish/publishers/FileBasedPublisher.java |   18 ++-
 .../src/com/netscape/cmscore/cert/CertUtils.java   |   33 +++--
 .../cmscore/ldapconn/LdapJssSSLSocketFactory.java  |    7 +
 .../com/netscape/cmscore/security/PWsdrCache.java  |   19 ++-
 .../com/netscape/cmscore/util/FileAsString.java    |   21 +--
 .../src/com/netscape/cmstools/CRMFPopClient.java   |   11 +-
 .../src/com/netscape/cmstools/ExtJoiner.java       |   10 +-
 .../src/com/netscape/cmstools/HttpClient.java      |   56 +++++--
 .../src/com/netscape/cmstools/OCSPClient.java      |  155 +++++++++++---------
 .../src/com/netscape/cmstools/PasswordCache.java   |   14 +-
 base/kra/src/com/netscape/kra/StorageKeyUnit.java  |   11 +-
 .../cmsutil/password/PlainPasswordFile.java        |   25 +++-
 .../cmsutil/password/PlainPasswordReader.java      |   12 +-
 .../cmsutil/password/PlainPasswordWriter.java      |   24 ++-
 base/util/src/com/netscape/cmsutil/util/Utils.java |   24 ++-
 .../security/extensions/GenericASN1Extension.java  |   52 ++++---
 .../extensions/PresenceServerExtension.java        |   75 ++++++----
 .../security/x509/CRLDistributionPoint.java        |   10 +-
 .../x509/CRLDistributionPointsExtension.java       |   13 +-
 .../security/x509/FreshestCRLExtension.java        |   13 +-
 .../security/x509/IssuingDistributionPoint.java    |   11 +-
 .../x509/IssuingDistributionPointExtension.java    |   12 +-
 base/util/src/netscape/security/x509/OIDMap.java   |   23 ++-
 24 files changed, 445 insertions(+), 215 deletions(-)

diff --git a/base/ca/src/com/netscape/ca/CertificateAuthority.java b/base/ca/src/com/netscape/ca/CertificateAuthority.java
index 321fd94108671fe88d3a18868ed17a43a95e4d00..b10c8df1b9fea80dcb0dcff9ca6467222178b932 100644
--- a/base/ca/src/com/netscape/ca/CertificateAuthority.java
+++ b/base/ca/src/com/netscape/ca/CertificateAuthority.java
@@ -1328,10 +1328,13 @@ public class CertificateAuthority implements ICertificateAuthority, ICertAuthori
         File file = new File(path);
         Long l = Long.valueOf(file.length());
         byte[] b = new byte[l.intValue()];
-        FileInputStream in = new FileInputStream(path);
-        in.read(b);
-        in.close();
-
+        FileInputStream in = null;
+        try {
+            in = new FileInputStream(path);
+            in.read(b);
+        } finally {
+            in.close();
+        }
         return b;
     }
 
diff --git a/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java b/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
index c41025b5430e5556274157a7ce4fc55264730ae6..59effbe81698c3732ce734791764b2ce235d3c01 100644
--- a/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
+++ b/base/common/src/com/netscape/cms/publish/publishers/FileBasedPublisher.java
@@ -317,7 +317,7 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
                 String baseName = mDir + File.separator + namePrefix[0];
                 String tempFile = baseName + ".temp";
                 FileOutputStream fos;
-                ZipOutputStream zos;
+                ZipOutputStream zos = null;
                 byte[] encodedArray = null;
                 File destFile = null;
                 String destName = null;
@@ -329,12 +329,16 @@ public class FileBasedPublisher implements ILdapPublisher, IExtendedPluginInfo {
                     fos.write(encodedArray);
                     fos.close();
                     if (mZipCRL) {
-                        zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip"));
-                        zos.setLevel(mZipLevel);
-                        zos.putNextEntry(new ZipEntry(baseName + ".der"));
-                        zos.write(encodedArray, 0, encodedArray.length);
-                        zos.closeEntry();
-                        zos.close();
+                        try {
+                            zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip"));
+                            zos.setLevel(mZipLevel);
+                            zos.putNextEntry(new ZipEntry(baseName + ".der"));
+                            zos.write(encodedArray, 0, encodedArray.length);
+                            zos.closeEntry();
+                        } finally {
+                            if (zos != null)
+                                zos.close();
+                        }
                     }
                     destName = baseName + ".der";
                     destFile = new File(destName);
diff --git a/base/common/src/com/netscape/cmscore/cert/CertUtils.java b/base/common/src/com/netscape/cmscore/cert/CertUtils.java
index d443781ae76fa4402ece6132b6dcf5554d8c8e86..ee1e1568c595da8b264d443426854a856afcb1e3 100644
--- a/base/common/src/com/netscape/cmscore/cert/CertUtils.java
+++ b/base/common/src/com/netscape/cmscore/cert/CertUtils.java
@@ -525,23 +525,34 @@ public class CertUtils {
 
     public static byte[] readFromFile(String fileName)
             throws IOException {
-        FileInputStream fin = new FileInputStream(fileName);
-        int available = fin.available();
-        byte[] ba = new byte[available];
-        int nRead = fin.read(ba);
+        FileInputStream fin = null;
+        try {
+            fin = new FileInputStream(fileName);
+            int available = fin.available();
+            byte[] ba = new byte[available];
+            int nRead = fin.read(ba);
 
-        if (nRead != available)
-            throw new IOException("Error reading data from file: " + fileName);
-        fin.close();
-        return ba;
+            if (nRead != available)
+                throw new IOException("Error reading data from file: " + fileName);
+
+            return ba;
+        } finally {
+            if (fin != null)
+                fin.close();
+        }
     }
 
     public static void storeInFile(String fileName, byte[] ba)
             throws IOException {
-        FileOutputStream fout = new FileOutputStream(fileName);
+        FileOutputStream fout = null;
+        try {
+            fout = new FileOutputStream(fileName);
 
-        fout.write(ba);
-        fout.close();
+            fout.write(ba);
+        } finally {
+            if (fout != null)
+                fout.close();
+        }
     }
 
     public static String toMIME64(X509CertImpl cert) {
diff --git a/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java b/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
index bad9e3b23c4e087f74ca189de705b66dd1f9c37a..38651d0ba170d304957bee6596d5b729933abc39 100644
--- a/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
+++ b/base/common/src/com/netscape/cmscore/ldapconn/LdapJssSSLSocketFactory.java
@@ -78,6 +78,13 @@ public class LdapJssSSLSocketFactory implements LDAPSSLSocketFactoryExt {
             throw new LDAPException(
                     "Cannot Create JSS SSL Socket - Unknown host");
         } catch (IOException e) {
+            if (s != null) {
+                try {
+                    s.close();
+                } catch (IOException e1) {
+                    e1.printStackTrace();
+                }
+            }
             log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_LDAPCONN_IO_ERROR", e.toString()));
             throw new LDAPException("IO Error creating JSS SSL Socket");
         }
diff --git a/base/common/src/com/netscape/cmscore/security/PWsdrCache.java b/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
index 17cc9f0a7cf385be918ba4f4a2cdec4e07efe4f2..f4dbb1866f2dadab4fe56fa0ab03d1187f28d6fd 100644
--- a/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
+++ b/base/common/src/com/netscape/cmscore/security/PWsdrCache.java
@@ -325,13 +325,19 @@ public class PWsdrCache {
                 bos.write(readbuf, 0, numRead);
                 totalRead += numRead;
             }
-            inputs.close();
+
         } catch (FileNotFoundException e) {
             log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
             throw new EBaseException(e.toString() + ": " + mPWcachedb);
         } catch (IOException e) {
             log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
             throw new EBaseException(e.toString() + ": " + mPWcachedb);
+        } finally {
+            try {
+                inputs.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
         }
 
         if (totalRead > 0) {
@@ -354,6 +360,7 @@ public class PWsdrCache {
      * encrypts and writes the whole String buf into pwcache.db
      */
     public void writePWcache(String bufs) throws EBaseException {
+        FileOutputStream outstream = null;
         try {
             Encryptor sdr = new Encryptor(mToken, mKeyID,
                                 Encryptor.DEFAULT_ENCRYPTION_ALG);
@@ -376,10 +383,10 @@ public class PWsdrCache {
                 tmpPWcache.delete();
                 tmpPWcache = new File(mPWcachedb + ".tmp");
             }
-            FileOutputStream outstream = new FileOutputStream(mPWcachedb + ".tmp");
+            outstream = new FileOutputStream(mPWcachedb + ".tmp");
 
             outstream.write(writebuf);
-            outstream.close();
+
 
             File origFile = new File(mPWcachedb);
 
@@ -427,6 +434,12 @@ public class PWsdrCache {
         } catch (Exception e) {
             log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_SECURITY_PW_FILE", mPWcachedb, e.toString()));
             throw new EBaseException(e.toString() + ": " + mPWcachedb);
+        } finally {
+            try {
+                outstream.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
         }
     }
 
diff --git a/base/common/src/com/netscape/cmscore/util/FileAsString.java b/base/common/src/com/netscape/cmscore/util/FileAsString.java
index 7853346f5c723c54a1757bc6de99da8f280c1061..ea8fb796da28eccbf11d35e261e888c72ca3d093 100644
--- a/base/common/src/com/netscape/cmscore/util/FileAsString.java
+++ b/base/common/src/com/netscape/cmscore/util/FileAsString.java
@@ -52,16 +52,19 @@ public class FileAsString {
         BufferedReader br = createBufferedReader(mFilename);
         StringBuffer buf = new StringBuffer();
         int bytesread = 0;
+        try {
+            do {
+                char cbuf[] = new char[16];
 
-        do {
-            char cbuf[] = new char[16];
-
-            bytesread = br.read(cbuf, 0, cbuf.length);
-            if (bytesread > 0) {
-                buf.append(cbuf, 0, bytesread);
-            }
-        } while (bytesread != -1);
-        br.close();
+                bytesread = br.read(cbuf, 0, cbuf.length);
+                if (bytesread > 0) {
+                    buf.append(cbuf, 0, bytesread);
+                }
+            } while (bytesread != -1);
+        } finally {
+            if (br != null)
+                br.close();
+        }
 
         fileContents = new String(buf);
     }
diff --git a/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java b/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
index 1ecaa6bd58ec6ec983c7c1911646d76516a80474..5c4110b1d1ca5e878ad9617c7ac1f107363bd2e8 100644
--- a/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
+++ b/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java
@@ -264,14 +264,23 @@ public class CRMFPopClient {
 
         boolean foundTransport = false;
         String transportCert = null;
+        BufferedReader br = null;
         try {
-            BufferedReader br = new BufferedReader(new FileReader("./transport.txt"));
+            br = new BufferedReader(new FileReader("./transport.txt"));
             transportCert = br.readLine();
             foundTransport = true;
         } catch (Exception e) {
             System.out.println("ERROR: cannot find ./transport.txt, so no key archival");
 
             return;
+        } finally {
+            if (br != null) {
+                try {
+                    br.close();
+                } catch (IOException e) {
+                    e.printStackTrace();
+                }
+            }
         }
 
         try {
diff --git a/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java b/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
index 95c3162f4f9bbaa7a1e6b2446996f66e7ad5380f..5aac69e60755ad96aa09420fe2871b217937af56 100644
--- a/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
+++ b/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java
@@ -20,11 +20,11 @@ package com.netscape.cmstools;
 import java.io.FileInputStream;
 import java.io.IOException;
 
-import com.netscape.cmsutil.util.Utils;
-
 import netscape.security.util.DerOutputStream;
 import netscape.security.util.DerValue;
 
+import com.netscape.cmsutil.util.Utils;
+
 /**
  * This program joins a sequence of extensions together
  * so that the final output can be used in configuration
@@ -93,11 +93,13 @@ public class ExtJoiner {
             throws IOException {
         FileInputStream fis = new FileInputStream(fileName);
 
-        byte data[] = new byte[fis.available()];
+        byte data[] = null;
         try {
+            data = new byte[fis.available()];
             fis.read(data);
         } finally {
-            fis.close();
+            if (fis != null)
+                fis.close();
         }
         return Utils.base64decode(new String(data));
     }
diff --git a/base/java-tools/src/com/netscape/cmstools/HttpClient.java b/base/java-tools/src/com/netscape/cmstools/HttpClient.java
index 2188737a339ae74f9cc6e2824e6ab80c1be1b9bd..69937e32c03904a8f407424818d47dbee868fcd2 100644
--- a/base/java-tools/src/com/netscape/cmstools/HttpClient.java
+++ b/base/java-tools/src/com/netscape/cmstools/HttpClient.java
@@ -74,7 +74,7 @@ public class HttpClient {
 
     public static byte[] getBytesFromFile(String filename) throws IOException {
         File file = new File(filename);
-        FileInputStream is = new FileInputStream(file);
+        FileInputStream is = null;
 
         long length = file.length();
 
@@ -87,34 +87,36 @@ public class HttpClient {
 
         int offset = 0;
         int numRead = 0;
+        is = new FileInputStream(file);
         while (offset < bytes.length
                 && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
             offset += numRead;
         }
-
+        is.close();
         if (offset < bytes.length) {
             throw new IOException("Could not completely read file " + filename);
         }
-
-        is.close();
         return bytes;
     }
 
     public void send(String ifilename, String ofilename, String dbdir,
             String nickname, String password, String servlet, String clientmode)
             throws Exception {
-        byte[] b = getBytesFromFile(ifilename);
-
-        System.out.println("Total number of bytes read = " + b.length);
-
         DataOutputStream dos = null;
         InputStream is = null;
+        PrintStream ps = null;
+        ByteArrayOutputStream bs = null;
+        try{
+        byte[] b = getBytesFromFile(ifilename);
+
+        System.out.println("Total number of bytes read = " + b.length);
         if (_secure) {
+            SSLSocket socket = null;
             try {
                 CryptoManager.InitializationValues vals =
                         new CryptoManager.InitializationValues(dbdir, "", "", "secmod.db");
                 CryptoManager.initialize(vals);
-                SSLSocket socket = new SSLSocket(_host, _port);
+                socket = new SSLSocket(_host, _port);
                 int i;
 
                 for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) {
@@ -159,11 +161,24 @@ public class HttpClient {
             } catch (Exception e) {
                 System.out.println("Exception: " + e.toString());
                 return;
+            } finally {
+                if (socket != null) {
+                    socket.close();
+                }
             }
         } else {
-            Socket socket = new Socket(_host, _port);
+            Socket socket = null;
+            try{
+            socket = new Socket(_host, _port);
             dos = new DataOutputStream(socket.getOutputStream());
             is = socket.getInputStream();
+            }catch(IOException e){
+                e.printStackTrace();
+                return;
+            } finally {
+                if (socket != null)
+                    socket.close();
+            }
         }
 
         // send request
@@ -211,14 +226,31 @@ public class HttpClient {
         byte[] bout = getBytesFromFile(ofilename);
         System.out.println("Total number of bytes read = " + bout.length);
 
-        ByteArrayOutputStream bs = new ByteArrayOutputStream();
-        PrintStream ps = new PrintStream(bs);
+        bs = new ByteArrayOutputStream();
+        ps = new PrintStream(bs);
         ps.print(Utils.base64encode(bout));
         System.out.println(bs.toString());
 
         System.out.println("");
         System.out.println("The response in binary format is stored in " + ofilename);
         System.out.println("");
+        }catch(Exception e){
+            e.printStackTrace();
+            throw e;
+        } finally {
+            if (is != null) {
+                is.close();
+            }
+            if (dos != null) {
+                dos.close();
+            }
+            if (bs != null) {
+                bs.close();
+            }
+            if (ps != null) {
+                ps.close();
+            }
+        }
     }
 
     static void printUsage() {
diff --git a/base/java-tools/src/com/netscape/cmstools/OCSPClient.java b/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
index 7d581fdb81f169f6d1017a418d4def630e2ade18..021f728f56bf937b7768a55bd34c4a526088b995 100644
--- a/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
+++ b/base/java-tools/src/com/netscape/cmstools/OCSPClient.java
@@ -115,80 +115,96 @@ public class OCSPClient {
     }
 
     public void sendOCSPRequest(String uri, String host, int port,
-               byte request_data[], String output) throws Exception {
-        Socket socket = new Socket(host, port);
-
-        // send request
-        System.out.println("URI: " + uri);
-
-        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
-        dos.writeBytes("POST " + uri + " HTTP/1.0\r\n");
-        dos.writeBytes("Content-length: " + request_data.length + "\r\n");
-        dos.writeBytes("\r\n");
-        dos.write(request_data);
-        dos.flush();
-
-        System.out.println("Data Length: " + request_data.length);
-        System.out.println("Data: " + Utils.base64encode(request_data));
-
-        InputStream iiss = socket.getInputStream();
-        FileOutputStream fof = new FileOutputStream(output);
-        boolean startSaving = false;
-        int sum = 0;
-        boolean hack = false;
+            byte request_data[], String output) throws Exception {
+        Socket socket = null;
+        DataOutputStream dos = null;
+        InputStream iiss = null;
+        FileOutputStream fof = null;
+        BufferedInputStream fis = null;
         try {
-            while (true) {
-                int r = iiss.read();
-                if (r == -1)
-                    break;
-                if (r == 10) {
-                    sum++;
-                }
-                if (sum == 6) {
-                    startSaving = true;
-                    continue;
-                }
-                if (startSaving) {
-                    if (hack) {
-                        fof.write(r);
+            socket = new Socket(host, port);
+
+            // send request
+            System.out.println("URI: " + uri);
+
+            dos = new DataOutputStream(socket.getOutputStream());
+            dos.writeBytes("POST " + uri + " HTTP/1.0\r\n");
+            dos.writeBytes("Content-length: " + request_data.length + "\r\n");
+            dos.writeBytes("\r\n");
+            dos.write(request_data);
+            dos.flush();
+
+            System.out.println("Data Length: " + request_data.length);
+            System.out.println("Data: " + Utils.base64encode(request_data));
+
+            iiss = socket.getInputStream();
+            fof = new FileOutputStream(output);
+            boolean startSaving = false;
+            int sum = 0;
+            boolean hack = false;
+            try {
+                while (true) {
+                    int r = iiss.read();
+                    if (r == -1)
+                        break;
+                    if (r == 10) {
+                        sum++;
                     }
-                    if (hack == false) {
-                        hack = true;
+                    if (sum == 6) {
+                        startSaving = true;
+                        continue;
                     }
-                }
-            } // while
-        } catch (IOException e) {
-        }
-        fof.close();
-
-        // parse OCSPResponse
-        BufferedInputStream fis =
-                new BufferedInputStream(
-                        new FileInputStream(output));
-        OCSPResponse resp = (OCSPResponse)
-                OCSPResponse.getTemplate().decode(fis);
-        ResponseBytes bytes = resp.getResponseBytes();
-        BasicOCSPResponse basic = (BasicOCSPResponse)
-                BasicOCSPResponse.getTemplate().decode(
-                        new ByteArrayInputStream(bytes.getResponse().toByteArray()));
-        ResponseData rd = basic.getResponseData();
-        for (int i = 0; i < rd.getResponseCount(); i++) {
-            SingleResponse rd1 = rd.getResponseAt(i);
-            if (rd1 == null) {
-                throw new Exception("No OCSP Response data.");
-            }
-            System.out.println("CertID.serialNumber=" +
-                    rd1.getCertID().getSerialNumber());
-            CertStatus status1 = rd1.getCertStatus();
-            if (status1 instanceof GoodInfo) {
-                System.out.println("CertStatus=Good");
-            }
-            if (status1 instanceof UnknownInfo) {
-                System.out.println("CertStatus=Unknown");
+                    if (startSaving) {
+                        if (hack) {
+                            fof.write(r);
+                        }
+                        if (hack == false) {
+                            hack = true;
+                        }
+                    }
+                } // while
+            } catch (IOException e) {
             }
-            if (status1 instanceof RevokedInfo) {
-                System.out.println("CertStatus=Revoked");
+            // parse OCSPResponse
+            fis = new BufferedInputStream(
+                    new FileInputStream(output));
+            OCSPResponse resp = (OCSPResponse)
+                    OCSPResponse.getTemplate().decode(fis);
+            ResponseBytes bytes = resp.getResponseBytes();
+            BasicOCSPResponse basic = (BasicOCSPResponse)
+                    BasicOCSPResponse.getTemplate().decode(
+                            new ByteArrayInputStream(bytes.getResponse().toByteArray()));
+            ResponseData rd = basic.getResponseData();
+            for (int i = 0; i < rd.getResponseCount(); i++) {
+                SingleResponse rd1 = rd.getResponseAt(i);
+                if (rd1 == null) {
+                    throw new Exception("No OCSP Response data.");
+                }
+                System.out.println("CertID.serialNumber=" +
+                        rd1.getCertID().getSerialNumber());
+                CertStatus status1 = rd1.getCertStatus();
+                if (status1 instanceof GoodInfo) {
+                    System.out.println("CertStatus=Good");
+                }
+                if (status1 instanceof UnknownInfo) {
+                    System.out.println("CertStatus=Unknown");
+                }
+                if (status1 instanceof RevokedInfo) {
+                    System.out.println("CertStatus=Revoked");
+                }
             }
+        } finally {
+            if (socket != null)
+                socket.close();
+            if (dos != null)
+                dos.close();
+            if (iiss != null)
+                iiss.close();
+            if (fof != null)
+                fof.close();
+            if (fis != null)
+                fis.close();
+
         }
     }
 
@@ -240,6 +256,7 @@ public class OCSPClient {
                 System.out.println("File Size: " + fis.available());
                 data = new byte[fis.available()];
                 fis.read(data);
+                fis.close();
             } catch (Exception e1) {
                 System.out.println("Error: Invalid Serial Number or File Name");
                 printUsage();
diff --git a/base/java-tools/src/com/netscape/cmstools/PasswordCache.java b/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
index f5b4e2c2c649f178b6e0e01008860cbed8ad1f13..098d8ddae240f1b91a43a00c90411e10b4ed97d9 100644
--- a/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
+++ b/base/java-tools/src/com/netscape/cmstools/PasswordCache.java
@@ -195,6 +195,7 @@ public class PasswordCache {
                 try {
                     BufferedReader r = new BufferedReader(new FileReader(keyFile));
                     mKeyIdString = r.readLine();
+                    r.close();
                 } catch (Exception e) {
                     System.out.println("Error: " + e.toString());
                     System.exit(1);
@@ -541,13 +542,15 @@ class PWsdrCache {
                 bos.write(readbuf, 0, numRead);
                 totalRead += numRead;
             }
-            inputs.close();
         } catch (FileNotFoundException e) {
             System.out.println("Failed for file " + mPWcachedb + " " + e.toString());
             throw new IOException(e.toString() + ": " + mPWcachedb);
         } catch (IOException e) {
             System.out.println("Failed for file " + mPWcachedb + " " + e.toString());
             throw new IOException(e.toString() + ": " + mPWcachedb);
+        } finally {
+            if (inputs != null)
+                inputs.close();
         }
 
         if (totalRead > 0) {
@@ -578,7 +581,7 @@ class PWsdrCache {
      * encrypts and writes the whole String buf into pwcache.db
      */
     public void writePWcache(String bufs) throws IOException {
-
+        FileOutputStream outstream = null;
         try {
             Encryptor sdr = new Encryptor(mToken, mKeyID,
                                 Encryptor.DEFAULT_ENCRYPTION_ALG);
@@ -600,10 +603,9 @@ class PWsdrCache {
                 // it wasn't removed?
                 tmpPWcache.delete();
             }
-            FileOutputStream outstream = new FileOutputStream(mPWcachedb + ".tmp");
+            outstream = new FileOutputStream(mPWcachedb + ".tmp");
 
             outstream.write(writebuf);
-            outstream.close();
 
             // Make certain that this temporary file has
             // the correct permissions.
@@ -662,6 +664,10 @@ class PWsdrCache {
         } catch (Exception e) {
             System.out.println("sdrPWcache: Error " + e.toString());
             throw new IOException(e.toString());
+        } finally {
+            if (outstream != null) {
+                outstream.close();
+            }
         }
     }
 
diff --git a/base/kra/src/com/netscape/kra/StorageKeyUnit.java b/base/kra/src/com/netscape/kra/StorageKeyUnit.java
index 3d679e3d88c72903c775bed0e07b80dbed03175f..67789e6720ec1e2744861fe35676023dabc95b8f 100644
--- a/base/kra/src/com/netscape/kra/StorageKeyUnit.java
+++ b/base/kra/src/com/netscape/kra/StorageKeyUnit.java
@@ -261,19 +261,26 @@ public class StorageKeyUnit extends EncryptionUnit implements
 
             if (mKeySplitting) {
                 // read private key from the file
+                FileInputStream fi = null;
                 try {
                     File priFile = new File(mConfig.getString(PROP_KEYDB));
 
                     mPrivateKeyData = new byte[
                             (Long.valueOf(priFile.length())).intValue()];
-                    FileInputStream fi = new FileInputStream(priFile);
+                    fi = new FileInputStream(priFile);
 
                     fi.read(mPrivateKeyData);
-                    fi.close();
+
                 } catch (IOException e) {
                     mKRA.log(ILogger.LL_FAILURE,
                             CMS.getLogMessage("CMSCORE_KRA_STORAGE_READ_PRIVATE", e.toString()));
                     throw new EBaseException(CMS.getUserMessage("CMS_BASE_INVALID_KEY_1", e.toString()));
+                } finally {
+                    try {
+                        fi.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
                 }
             }
 
diff --git a/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
index adad6ee37dde5b67ec43dc88991c994093b0e7ba..990d0c156fb1d26092125851e6f8b3c9a99e5133 100644
--- a/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
+++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordFile.java
@@ -37,10 +37,15 @@ public class PlainPasswordFile implements IPasswordStore {
         mPwdStore = new Properties();
         // initialize mPwdStore
         mPwdPath = pwdPath;
-
-        FileInputStream file = new FileInputStream(mPwdPath);
-        mPwdStore.load(file);
-        file.close();
+        FileInputStream file = null;
+        try {
+            file = new FileInputStream(mPwdPath);
+            mPwdStore.load(file);
+        } finally {
+            if (file != null) {
+                file.close();
+            }
+        }
     }
 
     public String getPassword(String tag) {
@@ -63,8 +68,14 @@ public class PlainPasswordFile implements IPasswordStore {
 
     public void commit()
             throws IOException, ClassCastException, NullPointerException {
-        FileOutputStream file = new FileOutputStream(mPwdPath);
-        mPwdStore.store(file, PASSWORD_WRITER_HEADER);
-        file.close();
+        FileOutputStream file = null;
+        try {
+            file = new FileOutputStream(mPwdPath);
+            mPwdStore.store(file, PASSWORD_WRITER_HEADER);
+        } finally {
+            if (file != null) {
+                file.close();
+            }
+        }
     }
 }
diff --git a/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
index 3a75097ec69c054e4eb7eac291505b5d0bff71b9..d4de53bcac3d9486540749583dc0b3cd77cdbeff 100644
--- a/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
+++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordReader.java
@@ -37,9 +37,15 @@ public class PlainPasswordReader implements IPasswordReader {
         mPwdPath = pwdPath;
         mPwdStore = new Properties();
 
-        FileInputStream file = new FileInputStream(mPwdPath);
-        mPwdStore.load(file);
-        file.close();
+        FileInputStream file = null;
+        try {
+            file = new FileInputStream(mPwdPath);
+            mPwdStore.load(file);
+        } finally {
+            if (file != null) {
+                file.close();
+            }
+        }
     }
 
     public String getPassword(String tag) {
diff --git a/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java b/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
index 3ceac4bd6fbd26e705e9d92f77e467b8b92b36bf..0965b7b3171a07964f57ac93af3d3ad7b9236ffe 100644
--- a/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
+++ b/base/util/src/com/netscape/cmsutil/password/PlainPasswordWriter.java
@@ -37,9 +37,15 @@ public class PlainPasswordWriter implements IPasswordWriter {
         mPwdPath = pwdPath;
         mPwdStore = new Properties();
 
-        FileInputStream file = new FileInputStream(mPwdPath);
-        mPwdStore.load(file);
-        file.close();
+        FileInputStream file = null;
+        try {
+            file = new FileInputStream(mPwdPath);
+            mPwdStore.load(file);
+        } finally {
+            if (file != null) {
+                file.close();
+            }
+        }
     }
 
     public Object putPassword(String tag, String password) {
@@ -48,9 +54,13 @@ public class PlainPasswordWriter implements IPasswordWriter {
 
     public void commit()
             throws IOException, ClassCastException, NullPointerException {
-        FileOutputStream file = new FileOutputStream(mPwdPath);
-        mPwdStore.store(file, PASSWORD_WRITER_HEADER);
-        file.close();
+        FileOutputStream file = null;
+        try {
+            file = new FileOutputStream(mPwdPath);
+            mPwdStore.store(file, PASSWORD_WRITER_HEADER);
+        } finally {
+            if (file != null)
+                file.close();
+        }
     }
-
 }
diff --git a/base/util/src/com/netscape/cmsutil/util/Utils.java b/base/util/src/com/netscape/cmsutil/util/Utils.java
index 75e63f2b0bbc130b3c9b7143824d2d3cb1a0d6ea..9ced208cd1603ba885d2b98974f730e0e7e9f00c 100644
--- a/base/util/src/com/netscape/cmsutil/util/Utils.java
+++ b/base/util/src/com/netscape/cmsutil/util/Utils.java
@@ -17,8 +17,6 @@
 // --- END COPYRIGHT BLOCK ---
 package com.netscape.cmsutil.util;
 
-import org.apache.commons.codec.binary.Base64;
-
 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.ByteArrayOutputStream;
@@ -36,6 +34,8 @@ import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Vector;
 
+import org.apache.commons.codec.binary.Base64;
+
 public class Utils {
     /**
      * Checks if this is NT.
@@ -153,9 +153,11 @@ public class Utils {
     }
 
     public static void copy(String orig, String dest) {
+        BufferedReader in = null;
+        PrintWriter out = null;
         try {
-            BufferedReader in = new BufferedReader(new FileReader(orig));
-            PrintWriter out = new PrintWriter(
+            in = new BufferedReader(new FileReader(orig));
+            out = new PrintWriter(
                     new BufferedWriter(new FileWriter(dest)));
             String line = "";
             while (in.ready()) {
@@ -163,9 +165,19 @@ public class Utils {
                 if (line != null)
                     out.println(line);
             }
-            in.close();
-            out.close();
         } catch (Exception ee) {
+            ee.printStackTrace();
+        }
+        if(in != null){
+            try {
+                in.close();
+            } catch (IOException e) {
+                // TODO Auto-generated catch block
+                e.printStackTrace();
+            }
+        }
+        if (out != null){
+            out.close();
         }
     }
 
diff --git a/base/util/src/netscape/security/extensions/GenericASN1Extension.java b/base/util/src/netscape/security/extensions/GenericASN1Extension.java
index 78d29457333ced4dc216d40e8759f89cf3ad6c1b..b51846498cad1426f24c07e3f9202e9418b22842 100644
--- a/base/util/src/netscape/security/extensions/GenericASN1Extension.java
+++ b/base/util/src/netscape/security/extensions/GenericASN1Extension.java
@@ -419,31 +419,37 @@ public class GenericASN1Extension extends Extension
         }
 
         FileInputStream fis = new FileInputStream(fname);
-        int n = 0;
-        while ((n = fis.available()) > 0) {
-            buff = new byte[n];
-            int result = fis.read(buff);
-            if (result == -1)
-                break;
+        try {
+            int n = 0;
+            while ((n = fis.available()) > 0) {
+                buff = new byte[n];
+                int result = fis.read(buff);
+                if (result == -1)
+                    break;
+                s = new String(buff);
+            }
+
+            for (i = 0, j = 0; j < s.length(); j++) {
+                int ch = s.charAt(j);
+                if (ch == 10 || ch == 13 || ch == 9)
+                    continue;
+                i++;
+            }
+            buff = new byte[i];
+            for (i = 0, j = 0; j < s.length(); j++) {
+                int ch = s.charAt(j);
+                if (ch == 10 || ch == 13 || ch == 9)
+                    continue;
+                buff[i++] = (byte) ch;
+            }
+
             s = new String(buff);
-        }
 
-        for (i = 0, j = 0; j < s.length(); j++) {
-            int ch = s.charAt(j);
-            if (ch == 10 || ch == 13 || ch == 9)
-                continue;
-            i++;
-        }
-        buff = new byte[i];
-        for (i = 0, j = 0; j < s.length(); j++) {
-            int ch = s.charAt(j);
-            if (ch == 10 || ch == 13 || ch == 9)
-                continue;
-            buff[i++] = (byte) ch;
+            return s;
+        } finally {
+            if (fis != null) {
+                fis.close();
+            }
         }
-
-        s = new String(buff);
-
-        return s;
     }
 }
diff --git a/base/util/src/netscape/security/extensions/PresenceServerExtension.java b/base/util/src/netscape/security/extensions/PresenceServerExtension.java
index 276c915471fd2611e11c2ab6aaa9fb291c7894b9..aff755460f389f9a2ba81c53f840a86e49bd364a 100644
--- a/base/util/src/netscape/security/extensions/PresenceServerExtension.java
+++ b/base/util/src/netscape/security/extensions/PresenceServerExtension.java
@@ -259,7 +259,7 @@ public class PresenceServerExtension extends Extension implements CertAttrSet {
     public void setOID(String oid) {
     }
 
-    public static void main(String args[]) throws Exception {
+    public static void main(String args[]) {
         /*
            0 30  115: SEQUENCE {
            2 06    9:   OBJECT IDENTIFIER '2 16 840 1 113730 1 100'
@@ -285,36 +285,57 @@ public class PresenceServerExtension extends Extension implements CertAttrSet {
                     :       }
                     :   }
          */
-        boolean critical = false;
-        int version = 1;
-        String streetAddress = "401E Middlefield Rd.,MV,CA94041";
-        String telephoneNumber = "650-111-1111";
-        String rfc822Name = "admin@netscape.com";
-        String ID = "ps-capitol";
-        String hostName = "capitol";
-        int portNumber = 80;
-        int maxUsers = 10;
-        int serviceLevel = 1;
+        ByteArrayOutputStream dos = null;
+        FileOutputStream fos = null;
+        try {
+            boolean critical = false;
+            int version = 1;
+            String streetAddress = "401E Middlefield Rd.,MV,CA94041";
+            String telephoneNumber = "650-111-1111";
+            String rfc822Name = "admin@netscape.com";
+            String ID = "ps-capitol";
+            String hostName = "capitol";
+            int portNumber = 80;
+            int maxUsers = 10;
+            int serviceLevel = 1;
 
-        PresenceServerExtension ext = new PresenceServerExtension(
-                critical,
-                version, streetAddress, telephoneNumber,
-                rfc822Name, ID, hostName, portNumber,
-                maxUsers, serviceLevel);
+            PresenceServerExtension ext = new PresenceServerExtension(
+                    critical,
+                    version, streetAddress, telephoneNumber,
+                    rfc822Name, ID, hostName, portNumber,
+                    maxUsers, serviceLevel);
 
-        // encode
+            // encode
 
-        ByteArrayOutputStream dos = new ByteArrayOutputStream();
-        ext.encode(dos);
-        FileOutputStream fos = new FileOutputStream("pse.der");
-        fos.write(dos.toByteArray());
-        fos.close();
+            dos = new ByteArrayOutputStream();
+            ext.encode(dos);
+            fos = new FileOutputStream("pse.der");
+            fos.write(dos.toByteArray());
+            fos.close();
 
-        Extension ext1 = new Extension(new DerValue(dos.toByteArray()));
-
-        @SuppressWarnings("unused")
-        PresenceServerExtension ext2 = new PresenceServerExtension(
-                Boolean.valueOf(false), ext1.getExtensionValue());
+            Extension ext1 = new Extension(new DerValue(dos.toByteArray()));
 
+            @SuppressWarnings("unused")
+            PresenceServerExtension ext2 = new PresenceServerExtension(
+                    Boolean.valueOf(false), ext1.getExtensionValue());
+        } catch (IOException e) {
+            e.printStackTrace();
+        } catch (CertificateException e) {
+            e.printStackTrace();
+        }
+        if (dos != null) {
+            try {
+                dos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        if (fos != null) {
+            try {
+                fos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 }
diff --git a/base/util/src/netscape/security/x509/CRLDistributionPoint.java b/base/util/src/netscape/security/x509/CRLDistributionPoint.java
index 44295744986407c3ec130d37c912b2ccb96fc9c6..51e6e42b88df5288e33dbe582b912e23e8dfdda9 100644
--- a/base/util/src/netscape/security/x509/CRLDistributionPoint.java
+++ b/base/util/src/netscape/security/x509/CRLDistributionPoint.java
@@ -252,13 +252,14 @@ public class CRLDistributionPoint implements ASN1Value {
     }
 
     public static void main(String args[]) {
+        ByteArrayOutputStream bos = null;
         try {
             if (args.length != 1) {
                 System.out.println("Usage: CRLDistributionPoint <outfile>");
                 System.exit(-1);
             }
 
-            ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            bos = new ByteArrayOutputStream();
 
             SEQUENCE cdps = new SEQUENCE();
 
@@ -337,6 +338,13 @@ public class CRLDistributionPoint implements ASN1Value {
         } catch (Exception e) {
             e.printStackTrace();
         }
+        if (bos != null) {
+            try {
+                bos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java b/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
index 4180473d41e953e7ce34b1b1f2e595a1aa096db0..0ca5131ab4171f9cf3fb77cc19e21227b9d8fbc1 100644
--- a/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
+++ b/base/util/src/netscape/security/x509/CRLDistributionPointsExtension.java
@@ -243,7 +243,7 @@ public class CRLDistributionPointsExtension extends Extension
      * Test driver.
      */
     public static void main(String args[]) {
-
+        BufferedOutputStream bos = null;
         try {
 
             if (args.length != 1) {
@@ -252,7 +252,7 @@ public class CRLDistributionPointsExtension extends Extension
                 System.exit(-1);
             }
 
-            BufferedOutputStream bos = new BufferedOutputStream(
+            bos = new BufferedOutputStream(
                     new FileOutputStream(args[0]));
 
             // URI only
@@ -291,11 +291,16 @@ public class CRLDistributionPointsExtension extends Extension
             crldpExt.setCritical(true);
             crldpExt.encode(bos);
 
-            bos.close();
-
         } catch (Exception e) {
             e.printStackTrace();
         }
+        if (bos != null) {
+            try {
+                bos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/FreshestCRLExtension.java b/base/util/src/netscape/security/x509/FreshestCRLExtension.java
index f108b459948ca836db520f8f4c74910d46e20922..7a2028c17454a45cb36807d7eb82ed716244da49 100644
--- a/base/util/src/netscape/security/x509/FreshestCRLExtension.java
+++ b/base/util/src/netscape/security/x509/FreshestCRLExtension.java
@@ -248,7 +248,7 @@ public class FreshestCRLExtension extends Extension
      * Test driver.
      */
     public static void main(String args[]) {
-
+        BufferedOutputStream bos = null;
         try {
 
             if (args.length != 1) {
@@ -257,7 +257,7 @@ public class FreshestCRLExtension extends Extension
                 System.exit(-1);
             }
 
-            BufferedOutputStream bos = new BufferedOutputStream(
+            bos = new BufferedOutputStream(
                     new FileOutputStream(args[0]));
 
             // URI only
@@ -296,11 +296,16 @@ public class FreshestCRLExtension extends Extension
             crldpExt.setCritical(true);
             crldpExt.encode(bos);
 
-            bos.close();
-
         } catch (Exception e) {
             e.printStackTrace();
         }
+        if (bos != null) {
+            try {
+                bos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 
     /**
diff --git a/base/util/src/netscape/security/x509/IssuingDistributionPoint.java b/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
index 504587bf468cdd5901c4e6fc4ac8cdd290615b67..efff188672d3132df0da75517a41f48c2a7f7aaf 100644
--- a/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
+++ b/base/util/src/netscape/security/x509/IssuingDistributionPoint.java
@@ -272,6 +272,7 @@ public class IssuingDistributionPoint implements ASN1Value {
     }
 
     public static void main(String args[]) {
+        BufferedOutputStream bos = null;
 
         try {
             if (args.length != 1) {
@@ -279,7 +280,7 @@ public class IssuingDistributionPoint implements ASN1Value {
                 System.exit(-1);
             }
 
-            BufferedOutputStream bos = new BufferedOutputStream(
+            bos = new BufferedOutputStream(
                     new FileOutputStream(args[0]));
 
             SEQUENCE idps = new SEQUENCE();
@@ -306,10 +307,16 @@ public class IssuingDistributionPoint implements ASN1Value {
             idps.addElement(idp);
 
             idps.encode(bos);
-            bos.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
+        if (bos != null) {
+            try {
+                bos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 
 }
diff --git a/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java b/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
index 0f8c8835c487739ba03a0f96831f642da329990a..0e53f554651198628020e94fe963bda33e3cba8b 100644
--- a/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
+++ b/base/util/src/netscape/security/x509/IssuingDistributionPointExtension.java
@@ -361,6 +361,7 @@ public class IssuingDistributionPointExtension extends Extension
      */
     public static void main(String args[]) {
 
+        BufferedOutputStream bos = null;
         try {
 
             if (args.length != 1) {
@@ -369,7 +370,7 @@ public class IssuingDistributionPointExtension extends Extension
                 System.exit(-1);
             }
 
-            BufferedOutputStream bos = new BufferedOutputStream(
+            bos = new BufferedOutputStream(
                     new FileOutputStream(args[0]));
 
             // URI only
@@ -410,10 +411,17 @@ public class IssuingDistributionPointExtension extends Extension
             idpExt.setCritical(false);
             idpExt.encode(bos);
 
-            bos.close();
+
 
         } catch (Exception e) {
             e.printStackTrace();
         }
+        if (bos != null) {
+            try {
+                bos.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
     }
 }
diff --git a/base/util/src/netscape/security/x509/OIDMap.java b/base/util/src/netscape/security/x509/OIDMap.java
index 17573a019431b892cf9c27ba2156685bdc6fa8d7..4cebcf2c82f7cba3b773cc4911f1df749f9c1213 100644
--- a/base/util/src/netscape/security/x509/OIDMap.java
+++ b/base/util/src/netscape/security/x509/OIDMap.java
@@ -165,12 +165,20 @@ public class OIDMap {
         if (!namesMap.exists()) {
             loadNamesDefault(props);
         } else {
+            FileInputStream fis = null;
             try {
-                FileInputStream fis = new FileInputStream(namesMap);
+                fis = new FileInputStream(namesMap);
                 props.load(fis);
-                fis.close();
             } catch (IOException e) {
                 loadNamesDefault(props);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
             }
         }
 
@@ -193,11 +201,20 @@ public class OIDMap {
         if (!classMap.exists()) {
             loadClassDefault(props);
         } else {
+            FileInputStream fis = null;
             try {
-                FileInputStream fis = new FileInputStream(classMap);
+                fis = new FileInputStream(classMap);
                 props.load(fis);
             } catch (IOException e) {
                 loadClassDefault(props);
+            } finally {
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    } catch (IOException e) {
+                        e.printStackTrace();
+                    }
+                }
             }
         }
 
-- 
1.7.10.2

