2 * ============LICENSE_START=======================================================
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
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=========================================================
21 package org.openecomp.sdc.common.util;
23 import fj.data.Either;
24 import org.nustaq.serialization.FSTConfiguration;
25 import org.openecomp.sdc.be.config.BeEcompErrorManager;
26 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
27 import org.openecomp.sdc.common.log.wrappers.Logger;
31 public class SerializationUtils {
33 private static Logger log = Logger.getLogger(SerializationUtils.class.getName());
35 private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();
37 public static Either<byte[], Boolean> serialize(Object object) {
39 try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) {
40 out.writeObject(object);
41 return Either.left(bos.toByteArray());
42 } catch (Exception e) {
43 log.debug("Failed to serialize object", e);
44 return Either.right(false);
48 public static Either<Object, Boolean> deserialize(byte[] bytes) {
50 try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) {
51 return Either.left(in.readObject());
52 } catch (Exception e) {
53 log.debug("Failed to deserialize object", e);
54 return Either.right(false);
58 public static Either<byte[], Boolean> serializeExt(Object object) {
60 byte[] value = conf.asByteArray(object);
61 return Either.left(value);
62 } catch (Exception e) {
63 return Either.right(false);
67 public static <T> Either<T, Boolean> deserializeExt(byte[] bytes, Class<T> clazz, String componentName) {
69 Object object = conf.asObject(bytes);
70 T castObject = clazz.cast(object);
71 return Either.left(castObject);
72 } catch (Exception e) {
73 log.debug("Failed to deserialize object of type {} and uid {}",clazz,componentName, e);
74 BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING);
75 return Either.right(false);