2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2021 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.context.schema.avro;
24 import org.apache.avro.Schema;
25 import org.apache.avro.Schema.Type;
26 import org.apache.avro.util.Utf8;
27 import org.onap.policy.apex.context.ContextRuntimeException;
28 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
29 import org.slf4j.ext.XLogger;
30 import org.slf4j.ext.XLoggerFactory;
33 * This class does string mapping from the Avro Utf8 class to the Java String class.
35 * @author Liam Fallon (liam.fallon@ericsson.com)
37 public class AvroStringObjectMapper implements AvroObjectMapper {
38 // Get a reference to the logger
39 private static final XLogger LOGGER = XLoggerFactory.getXLogger(AvroStringObjectMapper.class);
41 // The user keyAvro type for direct mapping
42 private AxKey userKey;
43 private Type avroType;
45 // The Apex compatible class
46 private static final Class<String> schemaClass = String.class;
52 public Class<?> getJavaClass() {
60 public void init(final AxKey initUserKey, final Type initAvroType) {
61 this.userKey = initUserKey;
62 this.avroType = initAvroType;
69 public Object createNewInstance(final Schema avroSchema) {
70 // By default, we do not create an instance, normal Java object creation for strings is
79 public Type getAvroType() {
87 public Object mapFromAvro(final Object avroObject) {
88 // The Avro object should be a Utf8 object
89 if (!(avroObject instanceof Utf8)) {
90 final var returnString = userKey.getId() + ": object \"" + avroObject + "\" of class \""
91 + avroObject.getClass() + "\" cannot be decoded to an object of class \""
92 + schemaClass.getName() + "\"";
93 LOGGER.warn(returnString);
94 throw new ContextRuntimeException(returnString);
97 return avroObject.toString();
104 public Object mapToAvro(final Object object) {
105 if (object == null) {
106 final var returnString = userKey.getId() + ": cannot encode a null object of class \""
107 + schemaClass.getName() + "\"";
108 LOGGER.warn(returnString);
109 throw new ContextRuntimeException(returnString);