diff options
author | avigaffa <avi.gaffa@amdocs.com> | 2017-12-31 15:07:39 +0200 |
---|---|---|
committer | vempo <vitaliy.emporopulo@amdocs.com> | 2018-01-02 09:41:41 +0200 |
commit | da5dfcd1a354807d13849c7f4ead535ccfa722fa (patch) | |
tree | b4ef0b97d4c25a38bf4a7a8aa5d3626d6b820a17 /openecomp-be/lib/openecomp-core-lib | |
parent | 25ca73d85757869a6d9cc33861070778503ff153 (diff) |
Fixing sonar Exception Handling
Change-Id: I04eb047973a3f5c07dd9dc410cb13af974e8ded1
Issue-ID: SDC-810
Signed-off-by: avigaffa <avi.gaffa@amdocs.com>
Signed-off-by: vempo <vitaliy.emporopulo@amdocs.com>
Diffstat (limited to 'openecomp-be/lib/openecomp-core-lib')
9 files changed, 297 insertions, 516 deletions
diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java index 7b53f3416a..cff9da0d5c 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java @@ -1,26 +1,23 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ +/* + * Copyright © 2016-2017 European Support Limited + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ============LICENSE_END========================================================= */ package org.openecomp.core.factory.impl; +import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -29,7 +26,6 @@ import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import static org.openecomp.core.utilities.CommonMethods.isEmpty; import static org.openecomp.core.utilities.CommonMethods.newInstance; public abstract class AbstractFactoryBase { @@ -39,13 +35,12 @@ public abstract class AbstractFactoryBase { * types to allow unloading of those classes from memory by garbage collector if factory is not * actually used. */ - private static Map<String, String> registry = new ConcurrentHashMap<String, String>(); + private static final Map<String, String> REGISTRY = new ConcurrentHashMap<>(); /** * Cached factory instances. */ - private static Map<String, AbstractFactoryBase> factoryMap = - new ConcurrentHashMap<String, AbstractFactoryBase>(); + private static final Map<String, AbstractFactoryBase> FACTORY_MAP = new ConcurrentHashMap<>(); /** * Registers implementor for an abstract factory. The method accepts Java classes rather then @@ -69,15 +64,15 @@ public abstract class AbstractFactoryBase { new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input impl.") .withCategory(ErrorCategory.SYSTEM).build()); } - if (factoryMap != null && factoryMap.containsKey(factory.getName())) { - factoryMap.remove(factory.getName()); + if (FACTORY_MAP.containsKey(factory.getName())) { + FACTORY_MAP.remove(factory.getName()); } - registry.put(factory.getName(), impl.getName()); + REGISTRY.put(factory.getName(), impl.getName()); } // registerFactory // TODO: Remove protected static void registerFactory(String factoryName, String implName) { - registry.put(factoryName, implName); + REGISTRY.put(factoryName, implName); } // registerFactory /** @@ -92,9 +87,8 @@ public abstract class AbstractFactoryBase { new ErrorCode.ErrorCodeBuilder().withId("E0001").withMessage("Mandatory input factory.") .withCategory(ErrorCategory.SYSTEM).build()); } - if (factoryMap != null) { - factoryMap.remove(factory.getName()); - } + + FACTORY_MAP.remove(factory.getName()); } /** @@ -115,18 +109,18 @@ public abstract class AbstractFactoryBase { } // Pick up factory instance from cache - F factory = (F) factoryMap.get(factoryType.getName()); + F factory = (F) FACTORY_MAP.get(factoryType.getName()); // Check for the first time access if (factory == null) { // Synchronize factory instantiation synchronized (factoryType) { // Re-check the factory instance - factory = (F) factoryMap.get(factoryType.getName()); + factory = (F) FACTORY_MAP.get(factoryType.getName()); if (factory == null) { // Get the implementation class name - String implName = registry.get(factoryType.getName()); + String implName = REGISTRY.get(factoryType.getName()); - if (isEmpty(implName)) { + if (StringUtils.isEmpty(implName)) { throw new CoreException( new ErrorCode.ErrorCodeBuilder().withId("E0001") .withMessage("Mandatory input factory implementation.") @@ -138,7 +132,7 @@ public abstract class AbstractFactoryBase { factory.init(); // Cache the instantiated singleton - factoryMap.put(factoryType.getName(), factory); + FACTORY_MAP.put(factoryType.getName(), factory); } } } @@ -164,14 +158,14 @@ public abstract class AbstractFactoryBase { .build()); } // Pick up factory instance from cache - F factory = (F) factoryMap.get(factoryType.getName()); + F factory = (F) FACTORY_MAP.get(factoryType.getName()); // Check for the first time access if (factory != null) { isFactoryRegistered = true; } else { // Get the implementation class name - String implName = registry.get(factoryType.getName()); - if (!isEmpty(implName)) { + String implName = REGISTRY.get(factoryType.getName()); + if (StringUtils.isNotEmpty(implName)) { isFactoryRegistered = true; } } @@ -182,16 +176,20 @@ public abstract class AbstractFactoryBase { * Stop all. */ public static void stopAll() { - Collection<AbstractFactoryBase> factorylist = factoryMap.values(); + Collection<AbstractFactoryBase> factorylist = FACTORY_MAP.values(); for (AbstractFactoryBase factory : factorylist) { factory.stop(); } } protected void init() { + // allows custom initialization + // noop by default } protected void stop() { + // allows custom shutdown + // noop by default } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java index b9d03f4d1a..15b9f8c1c8 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java @@ -1,21 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ +/* + * Copyright © 2016-2017 European Support Limited + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ============LICENSE_END========================================================= */ package org.openecomp.core.factory; @@ -24,6 +20,7 @@ package org.openecomp.core.factory; import org.openecomp.core.factory.api.FactoriesConfiguration; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.common.errors.SdcConfigurationException; import java.io.IOException; import java.io.InputStream; @@ -36,7 +33,7 @@ public final class FactoriesConfigImpl implements FactoriesConfiguration { private static final String FACTORY_CONFIG_FILE_NAME = "factoryConfiguration.json"; - private static Map factoryMap = new HashMap(); + private static final Map FACTORY_MAP = new HashMap(); private static boolean initialized = false; @SuppressWarnings("unchecked") @@ -48,7 +45,7 @@ public final class FactoriesConfigImpl implements FactoriesConfiguration { initialized = true; } } - return factoryMap; + return FACTORY_MAP; } private void init() { @@ -57,9 +54,9 @@ public final class FactoriesConfigImpl implements FactoriesConfiguration { for (URL factoryConfigUrl : factoryConfigUrlList) { try (InputStream stream = factoryConfigUrl.openStream()) { - factoryMap.putAll(JsonUtil.json2Object(stream, Map.class)); + FACTORY_MAP.putAll(JsonUtil.json2Object(stream, Map.class)); } catch (IOException e) { - throw new RuntimeException(e); + throw new SdcConfigurationException("Failed to initialize Factory from '" + factoryConfigUrl.getPath() +"'", e); } } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java index 102c6db572..24f71e7953 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java @@ -16,6 +16,7 @@ package org.openecomp.core.factory.api; +import org.apache.commons.lang3.StringUtils; import org.openecomp.core.factory.FactoryConfig; import org.openecomp.core.factory.impl.AbstractFactoryBase; import org.openecomp.core.utilities.CommonMethods; @@ -66,7 +67,7 @@ public abstract class AbstractComponentFactory<I> extends AbstractFactory<I> { String abstractClassName = entry.getKey(); String concreteTypeName = entry.getValue(); - if (CommonMethods.isEmpty(concreteTypeName)) { + if (StringUtils.isEmpty(concreteTypeName)) { throw new CoreException( new ErrorCode.ErrorCodeBuilder().withId("E0003") .withMessage("Missing configuration value:" + concreteTypeName + ".") diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java index 519d7b160b..c6b9160bad 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java @@ -1,21 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ +/* + * Copyright © 2016-2017 European Support Limited + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ============LICENSE_END========================================================= */ package org.openecomp.core.nosqldb.impl.cassandra; @@ -28,147 +24,143 @@ import com.datastax.driver.core.Session; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import com.datastax.driver.core.policies.LoadBalancingPolicy; import com.datastax.driver.core.policies.TokenAwarePolicy; -import com.google.common.base.Optional; import org.openecomp.core.nosqldb.util.CassandraUtils; +import org.openecomp.sdc.common.errors.SdcConfigurationException; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyManagementException; import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; import java.util.Objects; +import java.util.Optional; public class CassandraSessionFactory { - private static final Logger log = (Logger) LoggerFactory.getLogger - (CassandraSessionFactory.class.getName()); - - public static Session getSession() { - return ReferenceHolder.CASSANDRA; - } - - /** - * New cassandra session session. - * - * @return the session - */ - public static Session newCassandraSession() { - Cluster.Builder builder = Cluster.builder(); - String[] addresses = CassandraUtils.getAddresses(); - for (String address : addresses) { - builder.addContactPoint(address); - } + private static final Logger LOGGER = LoggerFactory.getLogger(CassandraSessionFactory.class); - //Check if ssl - Boolean isSsl = CassandraUtils.isSsl(); - if (isSsl) { - builder.withSSL(getSslOptions().get()); + private CassandraSessionFactory() { + // static methods, cannot be instantiated } - int port = CassandraUtils.getCassandraPort(); - if (port > 0) { - builder.withPort(port); + + public static Session getSession() { + return ReferenceHolder.CASSANDRA; } - //Check if user/pass - Boolean isAuthenticate = CassandraUtils.isAuthenticate(); - if (isAuthenticate) { - builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword()); + + /** + * New cassandra session session. + * + * @return the session + */ + public static Session newCassandraSession() { + Cluster.Builder builder = Cluster.builder(); + String[] addresses = CassandraUtils.getAddresses(); + for (String address : addresses) { + builder.addContactPoint(address); + } + + //Check if ssl + Boolean isSsl = CassandraUtils.isSsl(); + if (isSsl) { + builder.withSSL(getSslOptions()); + } + int port = CassandraUtils.getCassandraPort(); + if (port > 0) { + builder.withPort(port); + } + //Check if user/pass + Boolean isAuthenticate = CassandraUtils.isAuthenticate(); + if (isAuthenticate) { + builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword()); + } + + setConsistencyLevel(builder, addresses); + + setLocalDataCenter(builder); + + + Cluster cluster = builder.build(); + String keyStore = CassandraUtils.getKeySpace(); + return cluster.connect(keyStore); } - setConsistencyLevel(builder, addresses); + private static void setLocalDataCenter(Cluster.Builder builder) { + String localDataCenter = CassandraUtils.getLocalDataCenter(); + if (Objects.nonNull(localDataCenter)) { + LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " + + "local.", localDataCenter); + + LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy( + DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build()); + builder.withLoadBalancingPolicy(tokenAwarePolicy); + } else { + LOGGER.info( + "localDatacenter was provided, the driver will use the datacenter of the first contact " + + "point that was reached at initialization"); + } + } - setLocalDataCenter(builder); + private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) { + if (addresses != null && addresses.length > 1) { + String consistencyLevel = CassandraUtils.getConsistencyLevel(); + if (Objects.nonNull(consistencyLevel)) { + LOGGER.info( + "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" + + " as " + , consistencyLevel); + builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf + (consistencyLevel))); + } + } + } + private static SSLOptions getSslOptions() { - Cluster cluster = builder.build(); - String keyStore = CassandraUtils.getKeySpace(); - return cluster.connect(keyStore); - } + Optional<String> trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore()); + if (!trustStorePath.isPresent()) { + throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath"); + } - private static void setLocalDataCenter(Cluster.Builder builder) { - String localDataCenter = CassandraUtils.getLocalDataCenter(); - if (Objects.nonNull(localDataCenter)) { - log.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as " + - "local.", localDataCenter); + Optional<String> trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword()); + if (!trustStorePassword.isPresent()) { + throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword"); + } - LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy( - DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build()); - builder.withLoadBalancingPolicy(tokenAwarePolicy); - } else { - log.info( - "localDatacenter was provided, the driver will use the datacenter of the first contact point that was reached at initialization"); - } - } - - private static void setConsistencyLevel(Cluster.Builder builder, String[] addresses) { - if (addresses != null && addresses.length > 1) { - String consistencyLevel = CassandraUtils.getConsistencyLevel(); - if (Objects.nonNull(consistencyLevel)) { - log.info( - "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" + - " as " - , consistencyLevel); - builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf - (consistencyLevel))); - } + SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get()); + String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}; + return new SSLOptions(context, css); } - } - - private static Optional<SSLOptions> getSslOptions() { - Optional<String> truststorePath = Optional.of(CassandraUtils.getTruststore()); - Optional<String> truststorePassword = Optional.of(CassandraUtils.getTruststorePassword()); - - if (truststorePath.isPresent() && truststorePassword.isPresent()) { - SSLContext context; - try { - context = getSslContext(truststorePath.get(), truststorePassword.get()); - } catch (UnrecoverableKeyException | KeyManagementException - | NoSuchAlgorithmException | KeyStoreException | CertificateException - | IOException exception) { - throw new RuntimeException(exception); - } - String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"}; - return Optional.of(new SSLOptions(context, css)); - } - return Optional.absent(); - } - - private static SSLContext getSslContext(String truststorePath, String truststorePassword) - throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, - UnrecoverableKeyException, KeyManagementException { - FileInputStream tsf = null; - SSLContext ctx = null; - try { - tsf = new FileInputStream(truststorePath); - ctx = SSLContext.getInstance("SSL"); - - KeyStore ts = KeyStore.getInstance("JKS"); - ts.load(tsf, truststorePassword.toCharArray()); - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ts); - - ctx.init(null, tmf.getTrustManagers(), new SecureRandom()); - } catch (Exception exception) { - log.debug("", exception); - } finally { - if (tsf != null) { - tsf.close(); - } + + private static SSLContext getSslContext(String truststorePath, String trustStorePassword) { + + try (FileInputStream tsf = new FileInputStream(truststorePath)) { + + SSLContext ctx = SSLContext.getInstance("SSL"); + + KeyStore ts = KeyStore.getInstance("JKS"); + ts.load(tsf, trustStorePassword.toCharArray()); + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ts); + + ctx.init(null, tmf.getTrustManagers(), new SecureRandom()); + return ctx; + + } catch (Exception exception) { + throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception); + } } - return ctx; - } - private static class ReferenceHolder { - private static final Session CASSANDRA = newCassandraSession(); - } + private static class ReferenceHolder { + + private ReferenceHolder() { + // prevent instantiation + } + + private static final Session CASSANDRA = newCassandraSession(); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java index 5a17f887d9..7f207c59a9 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java @@ -16,21 +16,12 @@ package org.openecomp.core.utilities; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.PrintWriter; -import java.io.Serializable; -import java.io.StringWriter; import java.lang.reflect.Array; -import java.net.URL; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -49,7 +40,6 @@ public class CommonMethods { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); /** * Private default constructor to prevent instantiation of the class objects. @@ -58,108 +48,6 @@ public class CommonMethods { } /** - * Serializes an object instance into byte array. - * - * @param object An instance to be serialized. - * @return Java array of bytes. - * @see #deserializeObject(byte[]) #deserializeObject(byte[]) - */ - public static byte[] serializeObject(Serializable object) { - ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048); - try { - ObjectOutputStream ds = new ObjectOutputStream(byteArray); - ds.writeObject(object); - ds.close(); - } catch (IOException exception) { - throw new RuntimeException(exception); - } - - return byteArray.toByteArray(); - } // serializeObject - - /** - * Deserializes an object instance. - * - * @param bytes Java array of bytes. - * @return Deserialized instance of an object. - * @see #serializeObject(Serializable) #serializeObject(Serializable) - */ - public static Serializable deserializeObject(byte[] bytes) { - Serializable obj = null; - try { - ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - obj = (Serializable) stream.readObject(); - stream.close(); - } catch (IOException | ClassNotFoundException exception) { - throw new RuntimeException(exception); - } - - return obj; - } // deserializeObject - - /** - * Encodes binary byte stream to ASCII format. - * - * @param binary An Java array of bytes in binary format. - * @return An Java array of bytes encoded in ASCII format. - * @see #decode(byte[]) #decode(byte[]) - */ - public static byte[] encode(byte[] binary) { - return Base64.encodeBase64(binary); - } - - /** - * Decodes ASCII byte stream into binary format. - * - * @param ascii An Java array of bytes in ASCII format. - * @return An Java array of bytes encoded in binary format. - * @see #encode(byte[]) #encode(byte[]) - */ - public static byte[] decode(byte[] ascii) { - return Base64.decodeBase64(ascii); - } - - /** - * Checks whether the given <tt>Object</tt> is empty. - * - * @param obj Object to be checked. - * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise. - */ - public static boolean isEmpty(Object obj) { - return obj == null; - } - - /** - * Checks whether the given <tt>Object</tt> is empty. - * - * @param byteArray Object to be checked. - * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise. - */ - public static boolean isEmpty(byte[] byteArray) { - return byteArray == null || byteArray.length == 0; - } - - /** - * Checks whether the given <tt>String</tt> is empty. - * - * @param str String object to be checked. - * @return <tt>true</tt> - if the String is null or empty, <tt>false</tt> - otherwise. - */ - public static boolean isEmpty(String str) { - return str == null || str.length() == 0; - } - - /** - * Checks whether the given Java array is empty. - * - * @param array Java array to be checked. - * @return <tt>true</tt> - if the array is null or empty, <tt>false</tt> - otherwise. - */ - public static boolean isEmpty(Object[] array) { - return array == null || array.length == 0; - } - - /** * Checks whether the given collection is empty. * * @param collection A collection to be checked. @@ -170,49 +58,6 @@ public class CommonMethods { } /** - * Checks whether the given map is empty. - * - * @param map A map to be checked. - * @return <tt>true</tt> - if the map is null or empty, <tt>false</tt> - otherwise. - */ - public static boolean isEmpty(Map<?, ?> map) { - return map == null || map.isEmpty(); - } - - /** - * Converts the array with Long elements to the array with long (primitive type). - * - * @param array input array with Long elements - * @return array with the same elements converted to the long type (primitive) - */ - public static long[] toPrimitive(Long[] array) { - if (array == null) { - return null; - } - - long[] result = new long[array.length]; - for (int i = 0; i < array.length; i++) { - result[i] = array[i] != null ? array[i] : 0L; - } - return result; - } - - /** - * Converts a collection to Java array. - * - * @param <T> Java type of the collection element. - * @param col Collection to be converted to array - * @param type Java type of collection/array element - * @return An Java array of collection elements, or empty array if collection is null or empty. - */ - @SuppressWarnings("unchecked") - public static <T> T[] toArray(Collection<? extends T> col, Class<T> type) { - int length = isEmpty(col) ? 0 : col.size(); - T[] array = (T[]) Array.newInstance(type, length); - return col != null ? col.toArray(array) : array; - } - - /** * Gets an universally unique identifier (UUID). * * @return String representation of generated UUID. @@ -233,7 +78,7 @@ public class CommonMethods { long nextByte = value & 0xF000000000000000L; value <<= 4; boolean isNegative = nextByte < 0; - nextByte = rightShift(nextByte, 60); + nextByte = nextByte >>> 60; if (isNegative) { nextByte |= 0x08; @@ -243,10 +88,6 @@ public class CommonMethods { } } - private static long rightShift(long lng, int num) { - return lng >>> num; - } - /** * Concatenates two Java arrays. The method allocates a new array and copies * all elements to it or returns one of input arrays if another one is @@ -264,9 +105,9 @@ public class CommonMethods { public static <T> T[] concat(T[] left, T[] right) { T[] res; - if (isEmpty(left)) { + if (ArrayUtils.isEmpty(left)) { res = right; - } else if (isEmpty(right)) { + } else if (ArrayUtils.isEmpty(right)) { res = left; } else { res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length); @@ -278,36 +119,6 @@ public class CommonMethods { } // concat /** - * Casts an object to the class or interface represented by the specified - * <tt>Class</tt> object. The method logic is similar to Java method - * <tt>Class.cast(Object)</tt> with the only difference that unlike Java's - * version the type name of the current object instance is specified in the - * error message if casting fails to simplify error tracking. - * - * @param <B> the type parameter - * @param <D> the type parameter - * @param b1 An object instance to be casted to the specified Java type. - * @param cls Target Java type. - * @return Object instance safely casted to the requested Java type. - * @throws ClassCastException In case which is the given object is not instance of the specified - * Java type. - */ - @SuppressWarnings("unchecked") - public static <B, D> D cast(B b1, Class<D> cls) { - D d1 = null; - if (b1 != null) { - if (!cls.isInstance(b1)) { - throw new ClassCastException(String - .format("Failed to cast from '%s' to '%s'", b1.getClass().getName(), cls.getName())); - } else { - d1 = (D) b1; - } - } - - return d1; - } // cast - - /** * New instance object. * * @param classname the classname @@ -328,7 +139,7 @@ public class CommonMethods { @SuppressWarnings("unchecked") public static <T> T newInstance(String classname, Class<T> cls) { - if (isEmpty(classname)) { + if (StringUtils.isEmpty(classname)) { throw new IllegalArgumentException(); } @@ -368,33 +179,6 @@ public class CommonMethods { } /** - * Gets resources path. - * - * @param resourceName the resource name - * @return the resources path - */ - public static String getResourcesPath(String resourceName) { - URL resourceUrl = CommonMethods.class.getClassLoader().getResource(resourceName); - return resourceUrl != null ? resourceUrl.getPath() - .substring(0, resourceUrl.getPath().lastIndexOf("/") + 1) : null; - } - - /** - * Gets stack trace. - * - * @param throwable the throwable - * @return the stack trace - */ - public static String getStackTrace(Throwable throwable) { - if (null == throwable) { - return ""; - } - StringWriter sw = new StringWriter(); - throwable.printStackTrace(new PrintWriter(sw)); - return sw.toString(); - } - - /** * Print stack trace string. * * @return the string @@ -410,25 +194,6 @@ public class CommonMethods { } /** - * Is equal object boolean. - * - * @param obj1 the obj 1 - * @param obj2 the obj 2 - * @return the boolean - */ - public static boolean isEqualObject(Object obj1, Object obj2) { - boolean isEqualValue = false; - if (obj1 == null && obj2 == null) { - isEqualValue = true; - } - - if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) { - isEqualValue = true; - } - return isEqualValue; - } - - /** * Converts array of strings to comma-separated string. * * @param arr array of strings @@ -445,9 +210,7 @@ public class CommonMethods { * @return the string */ public static String collectionToCommaSeparatedString(Collection<String> elementCollection) { - List<String> list = new ArrayList<>(); - list.addAll(elementCollection); - return listToSeparatedString(list, ','); + return String.join(",", elementCollection); } /** @@ -458,7 +221,7 @@ public class CommonMethods { * @return the string */ public static String arrayToSeparatedString(String[] arr, char separator) { - return listToSeparatedString(Arrays.asList(arr), separator); + return String.join(Character.toString(separator), arr); } /** @@ -469,19 +232,7 @@ public class CommonMethods { * @return the string */ public static String listToSeparatedString(List<String> list, char separator) { - String res = null; - if (null != list) { - StringBuilder sb = new StringBuilder(); - int sz = list.size(); - for (int i = 0; i < sz; i++) { - if (i > 0) { - sb.append(separator); - } - sb.append(list.get(i)); - } - res = sb.toString(); - } - return res; + return String.join(Character.toString(separator), list); } /** @@ -506,23 +257,6 @@ public class CommonMethods { } /** - * Bytes to hex string. - * - * @param bytes the bytes - * @return the string - */ - public static String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int var = bytes[j] & 0xFF; - int x1 = j << 1; - hexChars[x1] = hexArray[var >>> 4]; - hexChars[x1 + 1] = hexArray[var & 0x0F]; - } - return new String(hexChars); - } - - /** * To single element set set. * * @param <T> the class of the objects in the set diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java index 786def961a..e70ad923a2 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java @@ -1,21 +1,17 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ +/* + * Copyright © 2016-2017 European Support Limited + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * ============LICENSE_END========================================================= */ package org.openecomp.core.utilities.file; @@ -189,7 +185,7 @@ public class FileUtils { return IOUtils.toByteArray(input); } catch (IOException exception) { throw new RuntimeException( - "error will convertion input stream to byte array:" + exception.getMessage()); + "error while converting input stream to byte array", exception); } } @@ -203,7 +199,7 @@ public class FileUtils { if (!fileName.contains(".")) { return fileName; } - return fileName.substring(0, fileName.lastIndexOf(".")); + return fileName.substring(0, fileName.lastIndexOf('.')); } public static String getFileExtension(String filename) { @@ -264,7 +260,7 @@ public class FileUtils { */ YML("yml"); - private String displayName; + private final String displayName; FileExtension(String displayName) { this.displayName = displayName; diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java index c675f8927f..ff3584a8a1 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java @@ -18,14 +18,100 @@ package org.openecomp.core.utilities; import org.testng.annotations.Test; +import java.util.Arrays; +import java.util.Collections; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class CommonMethodsTest { + + private static final String[] ARRAY = { "A", "B", "C" }; + @Test - public void testPrintStackTrace() throws Exception { - assertTrue(CommonMethods.printStackTrace().contains("org.openecomp.core.utilities" + + public void testPrintStackTrace() { + + String trace = CommonMethods.printStackTrace(); + assertTrue(trace.contains("org.openecomp.core.utilities" + ".CommonMethods.printStackTrace(CommonMethods.java:")); - assertTrue(CommonMethods.printStackTrace().contains("org.openecomp.core.utilities" + + assertTrue(trace.contains("org.openecomp.core.utilities" + ".CommonMethodsTest.testPrintStackTrace(CommonMethodsTest.java")); } + + @Test + public void testArrayToCommaSeparatedString() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(ARRAY), "A,B,C"); + } + + @Test + public void testArrayToCommaSeparatedStringEmpty() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[0]), ""); + } + + @Test + public void testArrayToCommaSeparatedStringNulls() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] { null, null }), "null,null"); + } + + @Test + public void testArrayToCommaSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] { "", "" }), ","); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testArrayToCommaSeparatedStringNull() { + CommonMethods.arrayToCommaSeparatedString(null); + } + + @Test + public void testArrayToSeparatedString() { + assertEquals(CommonMethods.arrayToSeparatedString(ARRAY, '/'),"A/B/C"); + } + + @Test + public void testArrayToSeparatedStringEmpty() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[0], '/'),""); + } + + @Test + public void testArrayToSeparatedStringNulls() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[] {null, null}, '/'),"null/null"); + } + + @Test + public void testArrayToSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[] {"", ""}, '/'),"/"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testArrayToSeparatedStringNull() { + CommonMethods.arrayToSeparatedString(null, '/'); + } + + @Test + public void testCollectionToCommaSeparatedString() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(ARRAY)), "A,B,C"); + } + + @Test + public void testCollectionToCommaSeparatedStringNulls() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(null, null)), "null,null"); + } + + @Test + public void testCollectionToCommaSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList("", "")), ","); + } + + @Test + public void testCollectionToCommaSeparatedStringEmtpy() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Collections.emptySet()), ""); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testCollectionToCommaSeparatedStringNull() { + assertNull(CommonMethods.collectionToCommaSeparatedString(null)); + } + } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java index fc0c2a18ab..e05d02d1e7 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java @@ -43,6 +43,7 @@ import com.amdocs.zusammen.datatypes.response.ReturnCode; import org.openecomp.core.zusammen.db.ZusammenConnector; import org.openecomp.core.zusammen.impl.CassandraConnectionInitializer; import org.openecomp.core.zusammen.impl.ItemElementLoggerTargetServiceName; +import org.openecomp.sdc.common.errors.SdcRuntimeException; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -87,7 +88,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { public Collection<Item> listItems(SessionContext context) { Response<Collection<Item>> response = itemAdaptorFactory.createInterface(context).list(context); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( "Failed to list Items. message:" + response.getReturnCode().toString()); } return response.getValue(); @@ -97,7 +98,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { public Item getItem(SessionContext context, Id itemId) { Response<Item> response = itemAdaptorFactory.createInterface(context).get(context, itemId); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( "Failed to get Item. message:" + response.getReturnCode().toString()); } return response.getValue(); @@ -107,7 +108,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { public Id createItem(SessionContext context, Info info) { Response<Id> response = itemAdaptorFactory.createInterface(context).create(context, info); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( "Failed to create Item. message:" + response.getReturnCode().toString()); } return response.getValue(); @@ -119,7 +120,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { itemAdaptorFactory.createInterface(context).update(context, itemId, info); if (!response.isSuccessful()) { - throw new RuntimeException("failed to update Item . ItemId:" + itemId + "" + + throw new SdcRuntimeException("failed to update Item . ItemId:" + itemId + "" + " message:" + response.getReturnCode().toString()); } } @@ -131,7 +132,8 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!versions.isSuccessful()) { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ITEM_VERSION_RETRIEVAL, versions .getReturnCode()); - throw new RuntimeException(versions.getReturnCode().toString()); + throw new SdcRuntimeException("failed to list public versions. message: " + + versions.getReturnCode().toString()); } return versions.getValue(); } @@ -141,7 +143,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<ItemVersion> response = versionAdaptorFactory.createInterface(context) .get(context, Space.PUBLIC, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( String.format("failed to get public Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -156,7 +158,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (response.isSuccessful()) { return response.getValue(); } else { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to create Item Version. ItemId: %s, base versionId: %s, message: %s", itemId.getValue(), baseVersionId.getValue(), response.getReturnCode().toString())); } @@ -168,7 +170,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = versionAdaptorFactory.createInterface(context) .update(context, itemId, versionId, itemVersionData); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( String.format("failed to update Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -179,7 +181,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<ItemVersion> response = versionAdaptorFactory.createInterface(context) .get(context, Space.PRIVATE, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( String.format("failed to get Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -191,7 +193,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<ItemVersionStatus> response = versionAdaptorFactory.createInterface(context).getStatus(context, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( String.format("failed to get Item Version status. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -203,7 +205,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = versionAdaptorFactory.createInterface(context) .tag(context, itemId, versionId, null, tag); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to tag Item Version with tag %s. ItemId: %s, versionId: %s, message: %s", tag.getName(), itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); @@ -216,7 +218,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = versionAdaptorFactory.createInterface(context) .resetRevision(context, itemId, versionId, revisionId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to reset Item Version back to revision: %s. ItemId: %s, versionId: %s, message:" + " %s", revisionId.getValue(), itemId.getValue(), versionId.getValue(), @@ -230,7 +232,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = versionAdaptorFactory.createInterface(context) .revertRevision(context, itemId, versionId, revisionId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to revert Item Version back to revision: %s. ItemId: %s, versionId: %s, " + "message: %s", revisionId.getValue(), itemId.getValue(), versionId.getValue(), @@ -245,7 +247,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { versionAdaptorFactory.createInterface(context) .listRevisions(context, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to list revisions of Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -258,7 +260,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = versionAdaptorFactory.createInterface(context).publish(context, itemId, versionId, message); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to publish item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -269,7 +271,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<MergeResult> response = versionAdaptorFactory.createInterface(context).sync(context, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to sync item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -280,7 +282,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<MergeResult> response = versionAdaptorFactory.createInterface(context).forceSync(context, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "failed to force sync item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -291,7 +293,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<ItemVersionConflict> response = versionAdaptorFactory.createInterface(context).getConflict(context, itemId, versionId); if (!response.isSuccessful()) { - throw new RuntimeException(String + throw new SdcRuntimeException(String .format("failed to get Item Version conflict. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } @@ -309,7 +311,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { } else { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ELEMENT_GET_BY_PROPERTY, response.getReturnCode()); - throw new RuntimeException(response.getReturnCode().toString()); + throw new SdcRuntimeException(response.getReturnCode().toString()); } } @@ -345,7 +347,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<ElementConflict> response = elementAdaptorFactory.createInterface(context) .getConflict(context, elementContext, elementId); if (!response.isSuccessful()) { - throw new RuntimeException(String.format( + throw new SdcRuntimeException(String.format( "Failed to get element conflict. Item Id: %s, version Id: %s, element Id: %s message: %s", elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), elementId.getValue(), response.getReturnCode().toString())); @@ -359,7 +361,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Element> response = elementAdaptorFactory.createInterface(context) .save(context, elementContext, element, message); if (!response.isSuccessful()) { - throw new RuntimeException(String + throw new SdcRuntimeException(String .format("Failed to create element %s. ItemId: %s, versionId: %s, message: %s", element.getElementId().getValue(), elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), response.getReturnCode().toString())); @@ -374,7 +376,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { Response<Void> response = elementAdaptorFactory.createInterface(context) .resolveConflict(context, elementContext, element, resolution); if (!response.isSuccessful()) { - throw new RuntimeException( + throw new SdcRuntimeException( "Failed to resolve conflict. message:" + response.getReturnCode().toString()); } } @@ -385,14 +387,14 @@ public class ZusammenConnectorImpl implements ZusammenConnector { // no-op, required by the interface } - private RuntimeException buildGetElementException(ElementContext elementContext, Id elementId, + private SdcRuntimeException buildGetElementException(ElementContext elementContext, Id elementId, String zusammenErrorMessage) { if (elementContext.getRevisionId() == null) { - return new RuntimeException(String.format(GET_ELEMENT_ERR_MSG, + return new SdcRuntimeException(String.format(GET_ELEMENT_ERR_MSG, elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), elementId.getValue(), zusammenErrorMessage)); } - return new RuntimeException(String.format(GET_ELEMENT_IN_REV_ERR_MSG, + return new SdcRuntimeException(String.format(GET_ELEMENT_IN_REV_ERR_MSG, elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), elementContext.getRevisionId().getValue(), elementId.getValue(), zusammenErrorMessage)); diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java index a973590eb5..c285bf8fae 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java @@ -24,16 +24,15 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionChange; import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementConflict; import com.amdocs.zusammen.sdk.state.types.StateElement; import com.amdocs.zusammen.sdk.types.ElementDescriptor; import com.amdocs.zusammen.utils.fileutils.FileUtils; import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; +import org.openecomp.sdc.common.errors.SdcRuntimeException; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; @@ -46,6 +45,10 @@ import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_EL public class ZusammenPluginUtil { + private ZusammenPluginUtil() { + // prevent instantiation + } + public static String getSpaceName(SessionContext context, Space space) { switch (space) { case PUBLIC: @@ -69,14 +72,6 @@ public class ZusammenPluginUtil { public static VersionEntity convertToVersionEntity(Id versionId, Id baseVersionId, Date creationTime, Date modificationTime) { - - return convertToVersionEntity(versionId, null, baseVersionId, - creationTime, modificationTime); - } - - public static VersionEntity convertToVersionEntity(Id versionId, Id revisionId, Id baseVersionId, - Date creationTime, - Date modificationTime) { VersionEntity version = new VersionEntity(versionId); version.setBaseId(baseVersionId); version.setCreationTime(creationTime); @@ -180,25 +175,6 @@ public class ZusammenPluginUtil { return versionChange; } - public static ItemVersionDataConflict getVersionConflict(ElementEntity localVesionData, - ElementEntity remoteVersionData) { - ItemVersionDataConflict versionConflict = new ItemVersionDataConflict(); - versionConflict.setLocalData(convertToVersionData(localVesionData)); - versionConflict.setRemoteData(convertToVersionData(remoteVersionData)); - return versionConflict; - } - - public static CollaborationElementConflict getElementConflict(ElementContext elementContext, - ElementEntity localElement, - ElementEntity remoteElement) { - CollaborationElementConflict elementConflict = new CollaborationElementConflict(); - elementConflict - .setLocalElement(convertToCollaborationElement(elementContext, localElement)); - elementConflict.setRemoteElement( - convertToCollaborationElement(elementContext, remoteElement)); - return elementConflict; - } - public static ItemVersionData convertToVersionData(ElementEntity versionDataElement) { ItemVersionData versionData = new ItemVersionData(); versionData.setInfo(versionDataElement.getInfo()); @@ -219,7 +195,8 @@ public class ZusammenPluginUtil { } public static String calculateElementHash(ElementEntity elementEntity) { - StringBuffer elementHash = new StringBuffer(); + + StringBuilder elementHash = new StringBuilder(); if (elementEntity.getData() != null) { elementHash.append(calculateSHA1(elementEntity.getData().array())); } else { @@ -258,13 +235,11 @@ public class ZusammenPluginUtil { } private static String calculateSHA1(byte[] content2Convert) { - MessageDigest md = null; try { - md = MessageDigest.getInstance("SHA-1"); + return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest(content2Convert)); } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); + throw new SdcRuntimeException(e); } - return Base64.getEncoder().encodeToString(md.digest(content2Convert)); } |