1 31 32 package org.opencms.util; 33 34 import java.io.InputStream ; 35 import java.io.ByteArrayInputStream ; 36 import java.io.IOException ; 37 import java.util.Arrays ; 38 39 import junit.framework.TestCase; 40 41 48 public class TestCmsFileUtil extends TestCase { 49 50 58 private static class TestInputStream extends InputStream { 59 60 private boolean m_closed; 61 private ByteArrayInputStream m_firstChunk; 62 private ByteArrayInputStream m_secondChunk; 63 64 67 TestInputStream() { 68 69 byte[] first = new byte[16]; 70 byte[] second = new byte[8]; 71 72 Arrays.fill(first, (byte)1); 73 Arrays.fill(second, (byte)2); 74 75 this.m_firstChunk = new ByteArrayInputStream (first); 76 this.m_secondChunk = new ByteArrayInputStream (second); 77 } 78 79 82 public int available() { 83 84 if (m_closed) { 85 return 0; 86 } 87 88 int first = m_firstChunk.available(); 89 return first > 0 ? first : m_secondChunk.available(); 90 } 91 92 95 public void close() throws IOException { 96 97 m_closed = true; 99 super.close(); 100 } 101 102 107 public boolean isClosed() { 108 109 return m_closed; 110 } 111 112 115 public int read() throws IOException { 116 117 if (m_closed) { 118 throw new IOException ("Stream was closed"); 119 } 120 121 return m_firstChunk.available() > 0 ? m_firstChunk.read() : m_secondChunk.read(); 122 } 123 124 127 public int read(byte[] b, int off, int len) throws IOException { 128 129 if (m_closed) { 130 throw new IOException ("Stream was closed"); 131 } 132 133 int first = m_firstChunk.available(); 134 if (first > 0) { 135 return m_firstChunk.read(b, off, len); 136 } else { 137 return m_secondChunk.read(b, off, len); 138 } 139 } 140 } 141 142 148 public void testMultiPassReadFully() throws IOException { 149 150 TestInputStream is = new TestInputStream(); 154 byte[] data = CmsFileUtil.readFully(is); 155 assertNotNull("new byte array returned by readFully", data); 156 157 assertEquals("all data returned", 24, data.length); 159 for (int i = 0; i < 16; ++i) { 160 assertEquals("first chunk data[" + i + "] has correct value", 1, data[i]); 161 } 162 for (int i = 16; i < 24; ++i) { 163 assertEquals("second chunk data[" + i + "] has correct value", 2, data[i]); 164 } 165 166 assertTrue("input stream was closed", is.isClosed()); 167 } 168 } | Popular Tags |