Project

General

Profile

« Previous | Next » 

Revision 8304

Added by Matt Jones about 11 years ago

Reviewed code for all uses of FileInputStream, checking to see if the method should be closing the stream, and if so, closing it in the method as well as in the finally clause to ensure we don't leak file descriptors.

View differences:

test/edu/ucsb/nceas/metacat/dataone/RegisterDOITest.java
35 35
import junit.framework.Test;
36 36
import junit.framework.TestSuite;
37 37

  
38
import org.apache.commons.io.IOUtils;
38 39
import org.dataone.client.ObjectFormatCache;
39 40
import org.dataone.configuration.Settings;
40 41
import org.dataone.service.types.v1.Identifier;
......
144 145
		String emlFile = "test/tao.14563.1.xml";
145 146
		InputStream content = null;
146 147
		try {
147
			content = new FileInputStream(emlFile);
148
		    content = new FileInputStream(emlFile);
149
		    testMintAndCreateDOI(content);
150
		    content.close(); 
148 151
		} catch (FileNotFoundException e) {
149 152
			e.printStackTrace();
150 153
			fail(e.getMessage());
154
		} finally {
155
		    IOUtils.closeQuietly(content);
151 156
		}
152
		testMintAndCreateDOI(content);
153 157
	}
154 158
	
155 159
	/**
......
267 271
			InputStream content = null;
268 272
			try {
269 273
				content = new FileInputStream(emlFile);
274
	            
275
	            // create the initial version without DOI
276
	            SystemMetadata sysmeta = createSystemMetadata(guid, session.getSubject(), null);
277
	            sysmeta.setFormatId(ObjectFormatCache.getInstance().getFormat("eml://ecoinformatics.org/eml-2.1.0").getFormatId());
278
	            Identifier pid = MNodeService.getInstance(request).create(session, guid, content, sysmeta);
279
	            assertEquals(guid.getValue(), pid.getValue());
280

  
281
	            // now publish it
282
	            Identifier publishedIdentifier = MNodeService.getInstance(request).publish(session, pid);
283
	            
284
	            // check for the metadata explicitly, using ezid service
285
	            EZIDService ezid = new EZIDService(ezidServiceBaseUrl);
286
	            ezid.login(ezidUsername, ezidPassword);
287
	            HashMap<String, String> metadata = ezid.getMetadata(publishedIdentifier.getValue());
288
	            assertNotNull(metadata);
289
	            assertTrue(metadata.containsKey(DataCiteProfile.TITLE.toString()));
290
	            content.close();
270 291
			} catch (FileNotFoundException e) {
271 292
				e.printStackTrace();
272 293
				fail(e.getMessage());
294
			} finally {
295
			    IOUtils.closeQuietly(content);
273 296
			}
274
			
275
			// create the initial version without DOI
276
			SystemMetadata sysmeta = createSystemMetadata(guid, session.getSubject(), null);
277
	        sysmeta.setFormatId(ObjectFormatCache.getInstance().getFormat("eml://ecoinformatics.org/eml-2.1.0").getFormatId());
278
			Identifier pid = MNodeService.getInstance(request).create(session, guid, content, sysmeta);
279
			assertEquals(guid.getValue(), pid.getValue());
280 297

  
281
			// now publish it
282
			Identifier publishedIdentifier = MNodeService.getInstance(request).publish(session, pid);
283 298
			
284
			// check for the metadata explicitly, using ezid service
285
			EZIDService ezid = new EZIDService(ezidServiceBaseUrl);
286
			ezid.login(ezidUsername, ezidPassword);
287
			HashMap<String, String> metadata = ezid.getMetadata(publishedIdentifier.getValue());
288
			assertNotNull(metadata);
289
			assertTrue(metadata.containsKey(DataCiteProfile.TITLE.toString()));
290
			
291 299
		} catch (Exception e) {
292 300
			e.printStackTrace();
293 301
			fail("Unexpected error: " + e.getMessage());
test/edu/ucsb/nceas/metacattest/client/MetacatClientTest.java
113 113
     */
114 114
    public void setUp()
115 115
    {
116
        FileInputStream fis = null;
116 117
        try {
117
        	FileInputStream fis = new FileInputStream(testfile);
118
        	fis = new FileInputStream(testfile);
118 119
            testdocument = IOUtils.toString(fis);
120
            fis.close();
119 121
        } catch (IOException ioe) {
120 122
            fail("Can't read test data to run the test: " + testfile);
123
        } finally {
124
            IOUtils.closeQuietly(fis);
121 125
        }
122 126

  
123 127
        try {
......
390 394
     * Test to get access control part of a document
391 395
     */
392 396
    public void getAccessControl() {
393
      try {
394
        FileInputStream fis = new FileInputStream(testEMLWithAccess);
395
        String document = IOUtils.toString(fis);
396
        String identifier = newdocid + ".1";
397
        m.login(username, password);
398
        String response = m.insert(identifier,
399
                new StringReader(document), null);
400
        assertTrue(response.indexOf("<success>") != -1);
401
        assertTrue(response.indexOf(identifier) != -1);
402
        response = m.getAccessControl(identifier);
403
        //System.out.println("reponse is "+reponse);
404
        assertTrue(response.indexOf("<permission>read</permission>") != -1);
405
        assertTrue(response.indexOf("<principal>public</principal>") != -1);
406
    } catch (MetacatAuthException mae) {
407
        fail("Authorization failed:\n" + mae.getMessage());
408
    } catch (MetacatInaccessibleException mie) {
409
        fail("Metacat Inaccessible:\n" + mie.getMessage());
410
    } catch (InsufficientKarmaException ike) {
411
        assertTrue(1 == 1);
412
        fail("Insufficient karma:\n" + ike.getMessage());
413
    } catch (MetacatException me) {
414
        fail("Metacat Error:\n" + me.getMessage());
415
    } catch (Exception e) {
416
        fail("General exception:\n" + e.getMessage());
397
        FileInputStream fis = null;
398
        try {
399
            fis = new FileInputStream(testEMLWithAccess);
400
            String document = IOUtils.toString(fis);
401
            String identifier = newdocid + ".1";
402
            m.login(username, password);
403
            String response = m.insert(identifier, new StringReader(document), null);
404
            assertTrue(response.indexOf("<success>") != -1);
405
            assertTrue(response.indexOf(identifier) != -1);
406
            response = m.getAccessControl(identifier);
407
            //System.out.println("reponse is "+reponse);
408
            assertTrue(response.indexOf("<permission>read</permission>") != -1);
409
            assertTrue(response.indexOf("<principal>public</principal>") != -1);
410
            fis.close();
411
        } catch (MetacatAuthException mae) {
412
            fail("Authorization failed:\n" + mae.getMessage());
413
        } catch (MetacatInaccessibleException mie) {
414
            fail("Metacat Inaccessible:\n" + mie.getMessage());
415
        } catch (InsufficientKarmaException ike) {
416
            assertTrue(1 == 1);
417
            fail("Insufficient karma:\n" + ike.getMessage());
418
        } catch (MetacatException me) {
419
            fail("Metacat Error:\n" + me.getMessage());
420
        } catch (Exception e) {
421
            fail("General exception:\n" + e.getMessage());
422
        } finally {
423
            IOUtils.closeQuietly(fis);
424
        }
417 425
    }
418
     
419
  }
420 426
    
421 427
    /**
422 428
     * Test to get access control part of a document
lib/style/skins/kepler/keplerAuthNameSpace.jsp
83 83
					ObjectOutputStream oos = new ObjectOutputStream(os);
84 84
					oos.writeObject( inc );
85 85
					oos.flush();
86
					oos.close();
86 87

  
87 88
					/*
88 89
					 * Print out the incremented Integer as the namespace output
src/edu/ucsb/nceas/metacat/MetacatHandler.java
65 65
import javax.servlet.http.HttpServletResponse;
66 66
import javax.servlet.http.HttpSession;
67 67

  
68
import org.apache.commons.io.IOUtils;
68 69
import org.apache.commons.io.input.XmlStreamReader;
69 70
import org.apache.log4j.Logger;
70 71
import org.dataone.service.types.v1.Identifier;
......
1279 1280
                        out.write(buf, 0, b);
1280 1281
                        b = fin.read(buf);
1281 1282
                    }
1283
                    fin.close();
1282 1284
                } finally {
1283
                    if (fin != null) fin.close();
1285
                    IOUtils.closeQuietly(fin);
1284 1286
                }
1285 1287
                
1286 1288
            } else {
......
1549 1551
                            zout.write(buf, 0, b);
1550 1552
                            b = fin.read(buf);
1551 1553
                        }
1554
                        fin.close();
1552 1555
                    } finally {
1553
                        if (fin != null) fin.close();
1556
                        IOUtils.closeQuietly(fin);
1554 1557
                    }
1555 1558
                    zout.closeEntry();
1556 1559
                    
src/edu/ucsb/nceas/metacat/util/ResponseUtil.java
37 37
import javax.servlet.http.HttpServletRequest;
38 38
import javax.servlet.http.HttpServletResponse;
39 39

  
40
import org.apache.commons.io.IOUtils;
40 41
import org.apache.log4j.Logger;
41 42

  
42 43
import edu.ucsb.nceas.metacat.shared.BaseException;
......
113 114
	public static void writeFileToOutput(HttpServletResponse response, String fileDir, String fileName, int bufferSize)
114 115
			throws MetacatUtilException {
115 116
		String filePath = "";
117
		InputStream inputStream = null;
118
		OutputStream outputStream = null;
116 119
		try {
117 120
			filePath = fileDir + FileUtil.getFS() + fileName;
118 121
			
......
120 123
			String shortFileName = fileName.substring(lastFileSep + 1, fileName.length());
121 124
			response.setHeader("Content-Disposition", "attachment; filename=\"" + shortFileName + "\"");
122 125
			
123
			InputStream inputStream = new FileInputStream(filePath);
124
			OutputStream outputStream = response.getOutputStream();
126
			inputStream = new FileInputStream(filePath);
127
			outputStream = response.getOutputStream();
125 128
			
126 129
			byte[] byteBuffer = new byte[bufferSize]; 
127 130

  
128 131
			int b = 0;
129 132
			while ((b = inputStream.read(byteBuffer)) != -1) {
130 133
				outputStream.write(byteBuffer, 0, b);
131
			}	
134
			}
135
			outputStream.close();
136
			inputStream.close();
132 137
			
133 138
		} catch (FileNotFoundException fnfe) {
134 139
			throw new MetacatUtilException("Error finding file: " + filePath 
......
136 141
		} catch (IOException ioe) {
137 142
			throw new MetacatUtilException("I/O Error when writing: " + filePath 
138 143
					+ "  to output");
144
		} finally {
145
		    IOUtils.closeQuietly(inputStream);
146
		    IOUtils.closeQuietly(outputStream);
139 147
		}
140 148
	}
141 149
	
src/edu/ucsb/nceas/metacat/DBQuery.java
60 60
import javax.servlet.ServletOutputStream;
61 61
import javax.servlet.http.HttpServletResponse;
62 62

  
63
import org.apache.commons.io.IOUtils;
63 64
import org.apache.commons.lang.StringEscapeUtils;
64 65
import org.apache.log4j.Logger;
65 66
import org.dataone.service.exceptions.NotImplemented;
......
2326 2327
            while (b != -1) {
2327 2328
                zipOut.write(buf, 0, b);
2328 2329
                b = fin.read(buf);
2329
            }//while
2330
            }
2331
            fin.close();
2330 2332
            zipOut.closeEntry();
2331 2333
        }//try
2332 2334
        catch (IOException ioe) {
2333 2335
            logMetacat.error("DBQuery.addDataFileToZipOutputStream - I/O error: "
2334 2336
                    + ioe.getMessage());
2335
        }//catch
2337
        } finally {
2338
            IOUtils.closeQuietly(fin);
2339
        }
2336 2340
    }//addDataFileToZipOutputStream()
2337 2341

  
2338 2342
    /**
src/edu/ucsb/nceas/metacat/oaipmh/provider/server/OAIHandler.java
36 36
import javax.xml.transform.TransformerFactory;
37 37
import javax.xml.transform.stream.StreamSource;
38 38

  
39
import org.apache.commons.io.IOUtils;
39 40
import org.apache.log4j.Logger;
40 41
import org.apache.log4j.PropertyConfigurator;
41 42

  
......
358 359
      TransformerFactory tFactory = TransformerFactory.newInstance();
359 360
      Transformer transformer = tFactory.newTransformer(xslSource);
360 361
      attributes.put("OAIHandler.transformer", transformer);
362
      is.close();
361 363
    }
362 364

  
363 365
    return attributes;
......
524 526
   *              there was a problem with initialization
525 527
   */
526 528
  //public void init_debug(ServletConfig config) throws ServletException {
527
  public void init(ServletConfig config) throws ServletException {
528
    super.init(config);
529
    public void init(ServletConfig config) throws ServletException {
530
        super.init(config);
529 531

  
530
    if (isIntegratedWithMetacat()) {
531
      try {
532
        PropertyService.getInstance();
533
      } 
534
      catch (ServiceException se) {
535
        System.err.println("Error in loading properties: " + se.getMessage());
536
      }
537
    }
538
    
539
    ServletContext servletContext = config.getServletContext();
540
    String configDirPath = servletContext.getRealPath(CONFIG_DIR);
541
    String configPath = configDirPath + "/" + CONFIG_NAME;
532
        if (isIntegratedWithMetacat()) {
533
            try {
534
                PropertyService.getInstance();
535
            } catch (ServiceException se) {
536
                System.err.println("Error in loading properties: " + se.getMessage());
537
            }
538
        }
542 539

  
543
    // Initialize the properties file for log4j
544
    String log4jPath = configDirPath + "/" + LOG4J_NAME;
545
    PropertyConfigurator.configureAndWatch(log4jPath);
546
    
547
    // Initialize the directory path to the crosswalk XSLT files
548
    String xsltDirPath = servletContext.getRealPath(XSLT_DIR);
549
    Eml2oai_dc.setDirPath(xsltDirPath);
540
        ServletContext servletContext = config.getServletContext();
541
        String configDirPath = servletContext.getRealPath(CONFIG_DIR);
542
        String configPath = configDirPath + "/" + CONFIG_NAME;
550 543

  
551
    try {
552
      HashMap attributes = null;
553
      Properties properties = null;
554
      InputStream in;
544
        // Initialize the properties file for log4j
545
        String log4jPath = configDirPath + "/" + LOG4J_NAME;
546
        PropertyConfigurator.configureAndWatch(log4jPath);
555 547

  
556
      try {
557
        log.debug("configPath=" + configPath);
558
        in = new FileInputStream(configPath);
559
      } 
560
      catch (FileNotFoundException e) {
561
        log.debug("configPath not found. Try the classpath: " + configPath);
562
        Thread thread = Thread.currentThread();
563
        ClassLoader classLoader = thread.getContextClassLoader();
564
        in = classLoader.getResourceAsStream(configPath);
565
      }
548
        // Initialize the directory path to the crosswalk XSLT files
549
        String xsltDirPath = servletContext.getRealPath(XSLT_DIR);
550
        Eml2oai_dc.setDirPath(xsltDirPath);
551
        InputStream in = null;
566 552

  
567
      if (in != null) {
568
        log.debug("configPath '" + configPath + "' found. Loading properties");
569
        properties = new Properties();
570
        properties.load(in);
571
        attributes = getAttributes(properties);
572
      }
553
        try {
554
            HashMap attributes = null;
555
            Properties properties = null;
556
            
557
            try {
558
                log.debug("configPath=" + configPath);
559
                in = new FileInputStream(configPath);
560
            } catch (FileNotFoundException e) {
561
                log.debug("configPath not found. Try the classpath: " + configPath);
562
                Thread thread = Thread.currentThread();
563
                ClassLoader classLoader = thread.getContextClassLoader();
564
                in = classLoader.getResourceAsStream(configPath);
565
            }
573 566

  
574
      attributesMap.put("global", attributes);
567
            if (in != null) {
568
                log.debug("configPath '" + configPath + "' found. Loading properties");
569
                properties = new Properties();
570
                properties.load(in);
571
                attributes = getAttributes(properties);
572
            }
573

  
574
            attributesMap.put("global", attributes);
575
            in.close();
576
        } catch (FileNotFoundException e) {
577
            e.printStackTrace();
578
            throw new ServletException(e.getMessage());
579
        } catch (ClassNotFoundException e) {
580
            e.printStackTrace();
581
            throw new ServletException(e.getMessage());
582
        } catch (IllegalArgumentException e) {
583
            e.printStackTrace();
584
            throw new ServletException(e.getMessage());
585
        } catch (IOException e) {
586
            e.printStackTrace();
587
            throw new ServletException(e.getMessage());
588
        } catch (Throwable e) {
589
            e.printStackTrace();
590
            throw new ServletException(e.getMessage());
591
        } finally {
592
            IOUtils.closeQuietly(in);
593
        }
575 594
    }
576
    catch (FileNotFoundException e) {
577
      e.printStackTrace();
578
      throw new ServletException(e.getMessage());
579
    } 
580
    catch (ClassNotFoundException e) {
581
      e.printStackTrace();
582
      throw new ServletException(e.getMessage());
583
    } 
584
    catch (IllegalArgumentException e) {
585
      e.printStackTrace();
586
      throw new ServletException(e.getMessage());
587
    } 
588
    catch (IOException e) {
589
      e.printStackTrace();
590
      throw new ServletException(e.getMessage());
591
    } 
592
    catch (Throwable e) {
593
      e.printStackTrace();
594
      throw new ServletException(e.getMessage());
595
    }
596
  }
597 595

  
598 596

  
599 597
  /**
src/edu/ucsb/nceas/metacat/oaipmh/provider/server/crosswalk/Eml2oai_dc.java
21 21
import javax.xml.transform.stream.StreamResult;
22 22
import javax.xml.transform.stream.StreamSource;
23 23

  
24
import org.apache.commons.io.IOUtils;
25

  
24 26
import ORG.oclc.oai.server.crosswalk.Crosswalk;
25 27
import ORG.oclc.oai.server.verb.CannotDisseminateFormatException;
26 28
import ORG.oclc.oai.server.verb.OAIInternalServerError;
......
69 71
    String xsltPath200 = dirPath + "/" + XSLT_NAME_200;
70 72
    String xsltPath201 = dirPath + "/" + XSLT_NAME_201;
71 73
    String xsltPath210 = dirPath + "/" + XSLT_NAME_210;
74
    FileInputStream fileInputStream200 = null;
75
    FileInputStream fileInputStream201 = null;
76
    FileInputStream fileInputStream210 = null;
72 77
    
73 78
    try {
74 79
      TransformerFactory tFactory200 = TransformerFactory.newInstance();
75
      FileInputStream fileInputStream200 = new FileInputStream(xsltPath200);
80
      fileInputStream200 = new FileInputStream(xsltPath200);
76 81
      StreamSource xslSource200 = new StreamSource(fileInputStream200);
77 82
      this.transformer200 = tFactory200.newTransformer(xslSource200);
78

  
83
      fileInputStream200.close();
84
      
79 85
      TransformerFactory tFactory201 = TransformerFactory.newInstance();
80
      FileInputStream fileInputStream201 = new FileInputStream(xsltPath201);
86
      fileInputStream201 = new FileInputStream(xsltPath201);
81 87
      StreamSource xslSource201 = new StreamSource(fileInputStream201);
82 88
      this.transformer201 = tFactory201.newTransformer(xslSource201);
83

  
89
      fileInputStream201.close();
90
      
84 91
      TransformerFactory tFactory210 = TransformerFactory.newInstance();
85
      FileInputStream fileInputStream210 = new FileInputStream(xsltPath210);
92
      fileInputStream210 = new FileInputStream(xsltPath210);
86 93
      StreamSource xslSource210 = new StreamSource(fileInputStream210);
87 94
      this.transformer210 = tFactory210.newTransformer(xslSource210);
95
      fileInputStream210.close();
88 96

  
89 97
    } 
90 98
    catch (Exception e) {
91 99
      e.printStackTrace();
92 100
      throw new OAIInternalServerError(e.getMessage());
101
    } finally {
102
        IOUtils.closeQuietly(fileInputStream200);
103
        IOUtils.closeQuietly(fileInputStream201);
104
        IOUtils.closeQuietly(fileInputStream210);
93 105
    }
94 106
  }
95 107
  
src/edu/ucsb/nceas/metacat/admin/DBAdmin.java
65 65
import edu.ucsb.nceas.utilities.GeneralPropertyException;
66 66
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
67 67

  
68
import org.apache.commons.io.IOUtils;
68 69
import org.apache.log4j.Logger;
69 70

  
70 71
/**
......
976 977
					} while ((fileLine = reader.readLine()) != null);
977 978
				}
978 979
			}
980
			fin.close();
979 981
		} finally {
980
			// Close our input stream
981
			fin.close();
982
			IOUtils.closeQuietly(fin);
982 983
		}
983 984

  
984 985
		return sqlCommands;
src/edu/ucsb/nceas/metacat/replication/ReplicationService.java
1258 1258
			// close file input stream
1259 1259
			fin.close();
1260 1260

  
1261
		}//try
1262
		catch (Exception e) {
1261
		} catch (Exception e) {
1263 1262
			logMetacat.error("ReplicationService.handleGetDataFileRequest - " + ReplicationService.METACAT_REPL_ERROR_MSG);                         
1264 1263
			logReplication.error("ReplicationService.handleGetDataFileRequest - error getting data file from MetacatReplication."
1265 1264
					+ "handlGetDataFileRequest " + e.getMessage());
1266 1265
			e.printStackTrace(System.out);
1267
		}//catch
1266
		} finally {
1267
		    IOUtils.closeQuietly(fin);
1268
		}
1268 1269

  
1269 1270
	}
1270 1271

  

Also available in: Unified diff