2 * ============LICENSE_START=======================================================
3 * PNF-REGISTRATION-HANDLER
4 * ================================================================================
5 * Copyright (C) 2018 Nokia. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.pnfsimulator.simulator;
22 import com.google.gson.Gson;
23 import com.google.gson.JsonElement;
24 import com.google.gson.stream.JsonReader;
25 import com.google.gson.stream.JsonToken;
26 import com.google.gson.stream.JsonWriter;
27 import java.io.IOException;
28 import java.io.StringReader;
29 import java.io.StringWriter;
30 import org.springframework.stereotype.Component;
33 public class KeywordsHandler {
35 private KeywordsExtractor keywordsExtractor;
36 private IncrementProvider incrementProvider;
38 public KeywordsHandler(KeywordsExtractor keywordsExtractor, IncrementProvider incrementProvider) {
39 this.keywordsExtractor = keywordsExtractor;
40 this.incrementProvider = incrementProvider;
43 public JsonElement substituteKeywords(JsonElement jsonBody, String jobId) {
44 int counter = incrementProvider.getAndIncrement(jobId);
46 JsonReader reader = new JsonReader(new StringReader(jsonBody.toString()));
47 StringWriter stringWriter = new StringWriter();
48 JsonWriter jsonWriter = new JsonWriter(stringWriter);
50 modify(reader, jsonWriter, counter);
51 return new Gson().fromJson(stringWriter.getBuffer().toString(), JsonElement.class);
52 } catch (IOException e) {
53 throw new RuntimeException(e);
57 private void modify(JsonReader reader, JsonWriter writer, int incrementValue) throws IOException {
58 JsonTokenProcessor jsonTokenProcessor;
60 JsonToken token = reader.peek();
61 jsonTokenProcessor = JsonTokenProcessor.getProcessorFor(token);
62 jsonTokenProcessor.process(reader, writer, incrementValue, keywordsExtractor);
63 } while (isJsonProcessingFinished(jsonTokenProcessor));
66 private boolean isJsonProcessingFinished(JsonTokenProcessor jsonTokenProcessor) {
67 return !jsonTokenProcessor.isProcessorFor(JsonToken.END_DOCUMENT);