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