package org.commonjava.indy.filer.def;

import org.commonjava.cdi.util.weft.ThreadContext;
import org.commonjava.indy.metrics.RequestContextHelper;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

public class TimingOutputStream
        extends FilterOutputStream
{
    private long nanos = -1L;

    public TimingOutputStream( final OutputStream stream )
    {
        super( stream );
    }

    @Override
    public void write( final int b )
            throws IOException
    {
        if ( nanos < 0 )
        {
            nanos = System.nanoTime();
        }

        super.write( b );
    }

    @Override
    public void write( final byte[] b )
            throws IOException
    {
        if ( nanos < 0 )
        {
            nanos = System.nanoTime();
        }

        super.write( b );
    }

    @Override
    public void write( final byte[] b, final int off, final int len )
            throws IOException
    {
        if ( nanos < 0 )
        {
            nanos = System.nanoTime();
        }

        super.write( b, off, len );
    }

    @Override
    public void close()
            throws IOException
    {
        super.close();

        RequestContextHelper.setContext( RequestContextHelper.RAW_NANOS, System.nanoTime() - nanos );
    }
}

@@ -354,17 +354,17 @@
 private 
-l
+L
 ong nano
@@ -368,14 +368,8 @@
 anos
- = -1L
 ;%0A%0A 
@@ -563,35 +563,39 @@
      if ( nanos 
-%3C 0
+== null
  )%0A        %7B%0A   
@@ -776,35 +776,39 @@
      if ( nanos 
-%3C 0
+== null
  )%0A        %7B%0A   
@@ -1031,11 +1031,15 @@
 nos 
-%3C 0
+== null
  )%0A 
@@ -1239,16 +1239,59 @@
 ose();%0A%0A
+        if ( nanos != null )%0A        %7B%0A    
         
@@ -1380,20 +1380,30 @@
  - nanos );%0A
+        %7D%0A
     %7D%0A%7D%0A

change initial nanos measurement in TimedOutputStream to null object