This project has retired. For details please refer to its Attic page.
RandomInputStream xref

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.workbench;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.util.Random;
24  
25  public class RandomInputStream extends InputStream {
26  
27      private final Random random;
28      private final long length;
29      private long pos;
30  
31      public RandomInputStream(long length) {
32          this(length, System.currentTimeMillis());
33      }
34  
35      public RandomInputStream(long length, long seed) {
36          random = new Random(seed);
37          this.length = length;
38          pos = 0;
39      }
40  
41      @Override
42      public int available() throws IOException {
43          return (int) Math.min(Integer.MAX_VALUE, length - pos);
44      }
45  
46      @Override
47      public long skip(long n) throws IOException {
48          if (n <= 0) {
49              return 0;
50          }
51  
52          for (long l = 0; l < n; l++) {
53              if (read() == -1) {
54                  return l;
55              }
56          }
57  
58          return n;
59      }
60  
61      @Override
62      public int read() throws IOException {
63          if (pos == length) {
64              return -1;
65          }
66  
67          pos++;
68  
69          return random.nextInt(256);
70      }
71  
72      @Override
73      public int read(byte[] b) throws IOException {
74          return read(b, 0, b.length);
75      }
76  
77      @Override
78      public int read(byte[] b, int off, int len) throws IOException {
79          if (b == null) {
80              throw new NullPointerException();
81          } else if ((off < 0) || (len < 0) || (len > b.length - off)) {
82              throw new IndexOutOfBoundsException();
83          }
84  
85          for (int i = 0; i < len; i++) {
86              int r = read();
87              if (r == -1) {
88                  return (i == 0 ? -1 : i);
89              }
90              b[off + i] = (byte) r;
91          }
92  
93          return len;
94      }
95  }