7a5e45b60f158097ff19b88e8066ba38470238dc
[nonrtric.git] / sample-services / ics-producer-consumer / producer / src / main / java / com / demo / producer / messages / MessageHelper.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  *
5  * Copyright (C) 2024: OpenInfra Foundation Europe
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 com.demo.producer.messages;
22
23 import java.util.Properties;
24 import java.util.Random;
25 import org.json.simple.JSONObject;
26
27 public class MessageHelper {
28
29     private static Properties props;
30
31     public static String getRandomString() {
32         int leftLimit = 48; // numeral '0'
33         int rightLimit = 122; // letter 'z'
34         int targetStringLength = 10;
35         Random random = new Random();
36
37         return random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
38                 .limit(targetStringLength)
39                 .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
40     }
41
42     @SuppressWarnings("unchecked") // Using only strings
43     public static JSONObject getMessageLogEntryJSON(String source, String topic, String key, String message)
44             throws Exception {
45         JSONObject obj = new JSONObject();
46         String bootstrapServers = getProperties().getProperty("bootstrap.servers");
47         obj.put("bootstrapServers", bootstrapServers);
48         obj.put("source", source);
49         obj.put("topic", topic);
50         obj.put("key", key);
51         obj.put("message", message);
52
53         return obj;
54     }
55
56
57     @SuppressWarnings("unchecked")
58     public static JSONObject getSimpleJSONObject(String message){
59         JSONObject obj = new JSONObject();
60         obj.put("message", message);
61         return obj;
62     }
63
64     protected static Properties getProperties() throws Exception {
65         if (props == null) {
66             props = PropertiesHelper.getProperties();
67         }
68         return props;
69     }
70
71 }