1 package org.apache.maven.plugin.surefire.report;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.nio.ByteBuffer;
25 import java.nio.CharBuffer;
26 import java.nio.charset.Charset;
27
28 import org.apache.commons.io.output.DeferredFileOutputStream;
29
30
31
32
33
34
35
36 class Utf8RecodingDeferredFileOutputStream
37 {
38 private DeferredFileOutputStream deferredFileOutputStream;
39
40 private boolean closed = false;
41
42 private static final Charset UTF8 = Charset.forName( "UTF-8" );
43
44 @SuppressWarnings( "checkstyle:magicnumber" )
45 public Utf8RecodingDeferredFileOutputStream( String channel )
46 {
47 this.deferredFileOutputStream = new DeferredFileOutputStream( 1000000, channel, "deferred", null );
48 }
49
50 public synchronized void write( byte[] buf, int off, int len )
51 throws IOException
52 {
53 if ( closed )
54 {
55 return;
56 }
57
58 if ( !Charset.defaultCharset().equals( UTF8 ) )
59 {
60 CharBuffer decodedFromDefaultCharset = Charset.defaultCharset().decode( ByteBuffer.wrap( buf, off, len ) );
61 ByteBuffer utf8Encoded = UTF8.encode( decodedFromDefaultCharset );
62
63 if ( utf8Encoded.hasArray() )
64 {
65 byte[] convertedBytes = utf8Encoded.array();
66
67 deferredFileOutputStream.write( convertedBytes, utf8Encoded.position(), utf8Encoded.remaining() );
68 }
69 else
70 {
71 byte[] convertedBytes = new byte[utf8Encoded.remaining()];
72 utf8Encoded.get( convertedBytes, 0, utf8Encoded.remaining() );
73
74 deferredFileOutputStream.write( convertedBytes, 0, convertedBytes.length );
75 }
76 }
77 else
78 {
79 deferredFileOutputStream.write( buf, off, len );
80 }
81 }
82
83 public long getByteCount()
84 {
85 return deferredFileOutputStream.getByteCount();
86 }
87
88 public synchronized void close()
89 throws IOException
90 {
91 closed = true;
92 deferredFileOutputStream.close();
93 }
94
95 public synchronized void writeTo( OutputStream out )
96 throws IOException
97 {
98 if ( closed )
99 {
100 deferredFileOutputStream.writeTo( out );
101 }
102 }
103
104 public synchronized void free()
105 {
106 if ( null != deferredFileOutputStream && null != deferredFileOutputStream.getFile() )
107 {
108 try
109 {
110 closed = true;
111 deferredFileOutputStream.close();
112 if ( !deferredFileOutputStream.getFile().delete() )
113 {
114 deferredFileOutputStream.getFile().deleteOnExit();
115 }
116 }
117 catch ( IOException ioe )
118 {
119 deferredFileOutputStream.getFile().deleteOnExit();
120
121 }
122 }
123 }
124 }