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 (ByteArrayOutputStream bos = new ByteArrayOutputStream();
106 ObjectOutputStream oos = new ObjectOutputStream(bos)) {
107
108 // Serialize the "delegate".
109 oos.writeObject(delegate);
110
111 final byte[] state = bos.toByteArray();
112 final int stateSize = state.length; // To allow state recovery.
113 // Compose the size with the state
114 final byte[] sizeAndState = composeStateInternal(NumberFactory.makeByteArray(stateSize),
115 state);
116 return composeStateInternal(sizeAndState,
117 super.getStateInternal());
118 } catch (IOException e) {
119 // Workaround checked exception.
120 throw new IllegalStateException(e);
121 }
122 }
123
124 /** {@inheritDoc} */
125 @Override
126 protected void setStateInternal(byte[] s) {
127 // First obtain the state size
128 final byte[][] s2 = splitStateInternal(s, 4);
129 final int stateSize = NumberFactory.makeInt(s2[0]);
130
131 // Second obtain the state
132 final byte[][] c = splitStateInternal(s2[1], stateSize);
133
134 // Use look-ahead deserialization to validate the state byte[] contains java.util.Random.
135 try (ByteArrayInputStream bis = new ByteArrayInputStream(c[0]);
136 ObjectInputStream ois = new ValidatingObjectInputStream(bis)) {
137
138 delegate = (Random) ois.readObject();
139 } catch (ClassNotFoundException | IOException e) {
140 // Workaround checked exception.
141 throw new IllegalStateException(e);
142 }
143
144 super.setStateInternal(c[1]);
145 }
146 }