1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.rng.core.source32;
18
19 import java.util.Random;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.ObjectOutputStream;
23 import java.io.ObjectStreamClass;
24 import java.io.ObjectInputStream;
25 import java.io.ByteArrayOutputStream;
26
27 import org.apache.commons.rng.core.util.NumberFactory;
28
29 import java.io.ByteArrayInputStream;
30
31 /**
32 * A provider that uses the {@link Random#nextInt()} method of the JDK's
33 * {@link Random} class as the source of randomness.
34 *
35 * <p>
36 * <b>Caveat:</b> All the other calls will be redirected to the methods
37 * implemented within this library.
38 * </p>
39 *
40 * <p>
41 * The state of this source of randomness is saved and restored through
42 * the serialization of the {@link Random} instance.
43 * </p>
44 *
45 * @since 1.0
46 */
47 public class JDKRandom extends IntProvider {
48 /** Delegate. Cannot be "final" (to allow serialization). */
49 private Random delegate;
50
51 /**
52 * An <code>ObjectInputStream</code> that's restricted to deserialize
53 * only {@link java.util.Random} using look-ahead deserialization.
54 *
55 * <p>Adapted from o.a.c.io.serialization.ValidatingObjectInputStream.</p>
56 *
57 * @see <a href="http://www.ibm.com/developerworks/library/se-lookahead/">
58 * IBM DeveloperWorks Article: Look-ahead Java deserialization</a>
59 */
60 private static class ValidatingObjectInputStream extends ObjectInputStream {
61 /**
62 * @param in Input stream
63 * @throws IOException Signals that an I/O exception has occurred.
64 */
65 ValidatingObjectInputStream(final InputStream in) throws IOException {
66 super(in);
67 }
68
69 /** {@inheritDoc} */
70 @Override
71 protected Class<?> resolveClass(final ObjectStreamClass osc) throws IOException,
72 ClassNotFoundException {
73 // For legacy reasons the Random class is serialized using only primitives
74 // even though modern implementations use AtomicLong.
75 // The only expected class is java.util.Random.
76 if (!Random.class.getName().equals(osc.getName())) {
77 throw new IllegalStateException("Stream does not contain java.util.Random: " + osc.getName());
78 }
79 return super.resolveClass(osc);
80 }
81 }
82
83 /**
84 * Creates an instance with the given seed.
85 *
86 * @param seed Initial seed.
87 */
88 public JDKRandom(Long seed) {
89 delegate = new Random(seed);
90 }
91
92 /**
93 * {@inheritDoc}
94 *
95 * @see Random#nextInt()
96 */
97 @Override
98 public int next() {
99 return delegate.nextInt();
100 }
101
102 /** {@inheritDoc} */
103 @Override
104 protected byte[] getStateInternal() {
105 try {
106 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
107 final ObjectOutputStream oos = new ObjectOutputStream(bos);
108
109 // Serialize the "delegate".
110 oos.writeObject(delegate);
111
112 final byte[] state = bos.toByteArray();
113 final int stateSize = state.length; // To allow state recovery.
114 // Compose the size with the state
115 final byte[] sizeAndState = composeStateInternal(NumberFactory.makeByteArray(stateSize),
116 state);
117 return composeStateInternal(sizeAndState,
118 super.getStateInternal());
119 } catch (IOException e) {
120 // Workaround checked exception.
121 throw new IllegalStateException(e);
122 }
123 }
124
125 /** {@inheritDoc} */
126 @Override
127 protected void setStateInternal(byte[] s) {
128 // First obtain the state size
129 final byte[][] s2 = splitStateInternal(s, 4);
130 final int stateSize = NumberFactory.makeInt(s2[0]);
131
132 // Second obtain the state
133 final byte[][] c = splitStateInternal(s2[1], stateSize);
134
135 // Use look-ahead deserialization to validate the state byte[] contains java.util.Random.
136 try {
137 final ByteArrayInputStream bis = new ByteArrayInputStream(c[0]);
138 final ObjectInputStream ois = new ValidatingObjectInputStream(bis);
139
140 delegate = (Random) ois.readObject();
141 } catch (ClassNotFoundException e) {
142 // Workaround checked exception.
143 throw new IllegalStateException(e);
144 } catch (IOException e) {
145 // Workaround checked exception.
146 throw new IllegalStateException(e);
147 }
148
149 super.setStateInternal(c[1]);
150 }
151 }