/*
 * Created on 11. jan.. 2007
 *
 * Copyright (c) 2005, Karl Trygve Kalleberg <karltk near strategoxt.org>
 * 
 * Licensed under the GNU Lesser General Public License, v2.1
 */
package org.spoofax.interpreter.library.ssl;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.terms.io.binary.SAFWriter;
import org.spoofax.terms.util.TermUtils;

public class SSL_write_term_to_stream_saf extends AbstractPrimitive {

    SSL_write_term_to_stream_saf() {
        super("SSL_write_term_to_stream_saf", 0, 2);
        
    }
    @Override
    public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] targs)
            throws InterpreterException {
        
        if(!TermUtils.isInt(targs[0]))
            return false;
        
        SSLLibrary or = (SSLLibrary) env.getOperatorRegistry(SSLLibrary.REGISTRY_NAME);
        OutputStream out = or.getIOAgent().internalGetOutputStream(TermUtils.toJavaInt(targs[0]));
        BufferedOutputStream bout = new BufferedOutputStream(out);
        if(out == null)
            return false;
        
        try {
            SAFWriter.writeTermToSAFStream(targs[1], bout);
            bout.close();
            
        } catch(IOException e) {
            throw new InterpreterException(e);
        }
        
        env.setCurrent(targs[0]);
        return true;
    }

}

@@ -1450,34 +1450,8 @@
 t);%0A
-            bout.close();%0A
     
@@ -1451,32 +1451,32 @@
 );%0A            %0A
+
         %7D catch(
@@ -1488,24 +1488,24 @@
 eption e) %7B%0A
-
             
@@ -1539,16 +1539,186 @@
 ion(e);%0A
+        %7D finally %7B%0A            try %7B%0A                bout.close();%0A            %7D catch(IOException e) %7B%0A                throw new InterpreterException(e);%0A            %7D%0A
         

Make sure to close stream even when exception occurs