DMAAP-83 Initial code import
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / util / RandomString.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dmaap.dbcapi.util;
22
23 import java.util.Random;
24
25 // source: http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
26
27 public class RandomString {
28
29           private static final char[] symbols;
30
31           static {
32             StringBuilder tmp = new StringBuilder();
33             for (char ch = '0'; ch <= '9'; ++ch)
34               tmp.append(ch);
35             for (char ch = 'a'; ch <= 'z'; ++ch)
36               tmp.append(ch);
37             symbols = tmp.toString().toCharArray();
38           }   
39
40           private final Random random = new Random();
41
42           private final char[] buf;
43
44           public RandomString(int length) {
45             if (length < 1)
46               throw new IllegalArgumentException("length < 1: " + length);
47             buf = new char[length];
48           }
49
50           public String nextString() {
51             for (int idx = 0; idx < buf.length; ++idx) 
52               buf[idx] = symbols[random.nextInt(symbols.length)];
53             return new String(buf);
54           }
55         }