Konuyu görüntüle
IUCODERS FORUM > Programlama > JAVA > Java Bugs Problem
Yazar
visibleberat


avatar
Vienna
Kayıt: 03.02.2009
07.02.2009-22:50 #56820
asagidaki kodda, cok basit bir bug hatasi var, try catch ile duzeltiliyor. yanliz nedense sorun yasiyorum.

Bug olan satir:
106: String test = readFile(new FileRead(filename_test));

Any tips ??


BUG REPORT
:[M X OBL] Method may fail to
clean up stream or resource
[OBL_UNSATISFIED_OBLIGATI
ON]
This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation.

In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.

This bug pattern is essentially the same as the OS_OPEN_STREAM and ODR_OPEN_DATABASE_RESOURCE bug patterns, but is based on a different (and hopefully better) static analysis technique. We are interested is getting feedback about the usefulness of this bug pattern. To send feedback, either:


package findbugs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import at.ac.tuwien.ifs.bpse.basis.export_import.HtmlExport;
import at.ac.tuwien.ifs.bpse.basis.helper.Constants;
import at.ac.tuwien.ifs.bpse.domain.Student;

/**
 * Class containing the TestCases for the HTML Exporter. Because we have no
 * import-mechanism for HTML we can only compare the generated HTML-File to a
 * file which was checked manualy.
 * 
 * @author The SE-Team
 * @version 1.0
 */
public class HtmlExportTest extends TestCase {

	//private static Log log = LogFactory.getLog(HtmlExportTest.class);
	private XmlBeanFactory xbf;
	private List<Student> studenten;

	/**
	 * This method is executen before every TestCase
	 */
	protected void setUp() throws Exception {
		super.setUp();
		ClassPathResource res = new ClassPathResource(Constants.SPRINGBEANS_TEST);
		xbf = new XmlBeanFactory(res);
		studenten = new ArrayList<Student>();
		Student s1 = (Student) xbf.getBean("StudentAlexanderSchatten");
		s1.setId(Integer.valueOf(1));
		Student s2 = (Student) xbf.getBean("StudentHubertMeixner");
		s2.setId(Integer.valueOf(2));
		studenten.add(s1);
		studenten.add(s2);
	}

	/**
	 * This method is invoced after each TestCase
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
		xbf.destroySingletons();
	}

	/**
	 * Reads a file into a String.
	 * 
	 * @param filename
	 *            the File to read.
	 * @return The content of the file as String.
	 */
	private String readFile(Reader r) {
		StringBuffer fcb = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(r);

			String line;
			while ((line = br.readLine()) != null) {
				fcb.append(line);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fcb.toString();
	}

	/**
	 * TestCase to creating an HTML-File. Because we have no importer for HTML,
	 * we compare the result with a file that was manually checked.
	 * @throws IOException 
	 * 
	 */
	public void testWrite() throws IOException {
		String filename_test = "test/export.html";
		
		// export test data to html file
		HtmlExport he = new HtmlExport();
		he.setTitle("Html Export");
		try {
			he.write(studenten, filename_test);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// check if export is correct

		InputStream ipCorrect = getClass().getResourceAsStream("/test/html-export.html");

		String correct = readFile(new InputStreamReader(ipCorrect));
		String test = readFile(new FileRead(filename_test));                              
                                assertEquals(correct, test);
		
		ipCorrect.close();
		
		// delete file
	
		try {
		new File(filename_test).delete();
		} catch(Exception e){
		System.out.println("file not found");
		e.printStackTrace();
		}

	
		}
	}







“You can’t manage what you can’t measure”, Tom DeMarco
– “What is not measurable make measurable”, Galileo Galilei

Yazar
audtou


avatar
malatya
Kayıt: 31.08.2006
08.02.2009-12:56 #56822
readFile fonksiyonunu içine şunu yazıp denermisin.
BufferedReader br = new BufferedReader(r);

satırından sonra şunları ekle:

			try{
				String line;	
				while((line = br.readLine()) != null){
					fcb.append(line);
				}
			}
			finally{
				br.close();
			}






bitiyo lan!
Yazar
audtou


avatar
malatya
Kayıt: 31.08.2006
08.02.2009-13:01 #56823
readFile şöyle olacak yani:

private String readFile(Reader r) {
        StringBuffer fcb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(r);
            try {
                String line;
                while ((line = br.readLine()) != null) {
                    fcb.append(line);
                }
            } finally {
                br.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fcb.toString();
    }






bitiyo lan!
Yazar
visibleberat


avatar
Vienna
Kayıt: 03.02.2009
08.02.2009-13:49 #56824
yazdigini denedim fakan ayni satrida bug hala duruyor. Problem In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns. dedigi satırda anlatildigi gibi ama,

ipCorrect.close olayinda dusunmeliyiz.





“You can’t manage what you can’t measure”, Tom DeMarco
– “What is not measurable make measurable”, Galileo Galilei

Yazar
neurorebel


avatar

Kayıt: 15.08.2007
08.02.2009-22:15 #56829
hiç java bilmem ama;

String test = readFile(new FileRead(filename_test));

bu satırda parametre olarak geçtiğin "new FileRead(filename_test)" nesnesini önce bir değişkende saklarsan daha iyi olur sanırım.

FileRead fr = new FileRead(filename_test);

String test = readFile(fr);
....

// kullandıktan sonra
fr.Close(); // gibi birşeyler yapman gerekir sanırım


----------------

bir problem de şu olabilir;

filename_test adındaki dosyayı

he.write(studenten, filename_test);

satırı ile daha önce kullanıyorsun. HtmlExport sınıfı bu dosyayı açtıktan sonra kapatmıyor olabilir ve he:HtmlExport nesnesi scope dışına çıkmadığı için yokedilmediğinden dosya handleı bırakılmamış olabilir. HtmlExport sınıfı senin yazdığın bir sınıf ise bu sınıfın dosya işlemleri yapan metodlarında dosyaların kapandığından emin ol. Tabi bu söylediklerime gerek kalmayadabilir ilk söylediğim şeyi yaparsan. Bilemedim :P Ama merak ediyorum bunun çözümünü. Çözersen haber ver :)


edit:
Bug reporttan anladığım kadarıyla ilk söylediğim bu sorunu çözebilir (gerçi exception koruması yine yok). Zaten raporda da "Bunu bir try catch finally bloğuna al ki bir problem çıktığında dosya akışı açık kalmasın." diyor.

edit2: hatta test yazılımının 2. teorime istinaden he.write(studenten, filename_test) metodundan şikayetçi olmamasının sebebi bu satırın try catch bloğu içerisinde olması galiba. bu arada javayla hiç bir alakam yok ona göre dikkate al söylediklerimi hehe coffee





Do weird and difficult things.

Yazar
visibleberat


avatar
Vienna
Kayıt: 03.02.2009
08.02.2009-23:43 #56832
Her iki soylediginde olayı cozumleyebilir, zaten olay try catch finally ile cozumlenmesi gerekiyor. Sonucu merak ediyorum bende, bu arada bu Technische Universitat Wien software qualitat sicherung Vorlesung(lecture) icin hazirladigimiz odevin bir parcasi..

Cozum onerilerin icin tesekkurler






“You can’t manage what you can’t measure”, Tom DeMarco
– “What is not measurable make measurable”, Galileo Galilei

Del.icio.us
Digg
Facebook
Furl
Google
Blink
Simpy
Spurl
Y! MyWeb