Clean up for Sonar 07/70807/6
authorelinuxhenrik <henrik.b.andersson@est.tech>
Fri, 19 Oct 2018 11:04:36 +0000 (13:04 +0200)
committerelinuxhenrik <henrik.b.andersson@est.tech>
Thu, 15 Nov 2018 09:40:09 +0000 (10:40 +0100)
Change-Id: I5daa606cd974e43c899b7e35b14d268a255c7102
Issue-ID: DCAEGEN2-835
Signed-off-by: elinuxhenrik <henrik.b.andersson@est.tech>
30 files changed:
datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/configuration/FtpesConfig.java
datafile-app-server/src/main/java/org/onap/dcaegen2/collectors/datafile/tasks/RetryTimer.java
datafile-commons/src/main/java/org/onap/dcaegen2/collectors/datafile/model/ConsumerDmaapModelForUnitTest.java [deleted file]
datafile-commons/src/test/java/org/onap/dcaegen2/collectors/datafile/model/CommonFunctionsTest.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/config/DmaapConsumerConfiguration.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/config/DmaapPublisherConfiguration.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ftp/ErrorData.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ftp/FileCollectClient.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ftp/FtpsClient.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClient.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/io/FileSystemResourceWrapper.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/io/IFileSystemResource.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/FileSystemResourceWrapper.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IFileSystemResource.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IRestTemplate.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategy.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RequestResponseLoggingInterceptor.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RestTemplateWrapper.java [deleted file]
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ssl/IKeyManagerUtils.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ssl/IKeyStore.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ssl/KeyManagerUtilsWrapper.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/ssl/KeyStoreWrapper.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/web/IRestTemplate.java
datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/web/RestTemplateWrapper.java
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/ErrorDataTest.java
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FileCollectResultTest.java [new file with mode: 0644]
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FtpsClientTest.java
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/DmaapProducerReactiveHttpClientTest.java
datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategyTest.java [deleted file]

index b993f20..7e08f12 100644 (file)
@@ -2,17 +2,15 @@
  * ============LICENSE_START======================================================================
  * Copyright (C) 2018 Nordix Foundation. All rights reserved.
  * ===============================================================================================
- * 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
+ * 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
+ * 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.
+ * 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========================================================================
  */
 
@@ -22,9 +20,8 @@ public class RetryTimer {
     public void waitRetryTime() {
         try {
             Thread.sleep(60000);
-        } catch (Exception e) {
-            // Nothing, no one will interrupt.
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
         }
-
     }
 }
diff --git a/datafile-commons/src/main/java/org/onap/dcaegen2/collectors/datafile/model/ConsumerDmaapModelForUnitTest.java b/datafile-commons/src/main/java/org/onap/dcaegen2/collectors/datafile/model/ConsumerDmaapModelForUnitTest.java
deleted file mode 100644 (file)
index 62e6b1b..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.model;
-
-public class ConsumerDmaapModelForUnitTest implements ConsumerDmaapModel {
-    private final String name;
-    private final String location;
-    private final String compression;
-    private final String fileFormatType;
-    private final String fileFormatVersion;
-
-    public ConsumerDmaapModelForUnitTest() {
-        this.name = "A20161224.1030-1045.bin.gz";
-        this.location = "target/A20161224.1030-1045.bin.gz";
-        this.compression = "gzip";
-        this.fileFormatType = "org.3GPP.32.435#measCollec";
-        this.fileFormatVersion = "V10";
-    }
-
-    @Override
-    public String getName() {
-        return name;
-    }
-
-    @Override
-    public String getLocation() {
-        return location;
-    }
-
-    @Override
-    public String getCompression() {
-        return compression;
-    }
-
-    @Override
-    public String getFileFormatType() {
-        return fileFormatType;
-    }
-
-    @Override
-    public String getFileFormatVersion() {
-        return fileFormatVersion;
-    }
-}
index f27e3b6..7ec6f50 100644 (file)
@@ -21,11 +21,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import org.junit.jupiter.api.Test;
 
 class CommonFunctionsTest {
-    private ConsumerDmaapModel model = new ConsumerDmaapModelForUnitTest();
+    private ConsumerDmaapModel model = ImmutableConsumerDmaapModel.builder().name("A20161224.1030-1045.bin.gz")
+            .location("target/A20161224.1030-1045.bin.gz").compression("gzip")
+            .fileFormatType("org.3GPP.32.435#measCollec").fileFormatVersion("V10").build();
     private static final String EXPECTED_RESULT =
             "{\"name\":\"A20161224.1030-1045.bin.gz\",\"location\":\"target/A20161224.1030-1045.bin.gz\","
-            + "\"compression\":\"gzip\",\"fileFormatType\":\"org.3GPP.32.435#measCollec\","
-            + "\"fileFormatVersion\":\"V10\"}";
+                    + "\"compression\":\"gzip\",\"fileFormatType\":\"org.3GPP.32.435#measCollec\","
+                    + "\"fileFormatVersion\":\"V10\"}";
 
     @Test
     void createJsonBody_shouldReturnJsonInString() {
index dd7519f..568d4ec 100644 (file)
@@ -44,22 +44,4 @@ public abstract class DmaapConsumerConfiguration implements DmaapCustomConfig {
 
     @Value.Parameter
     public abstract Integer messageLimit();
-
-
-    public interface Builder
-            extends DmaapCustomConfig.Builder<DmaapConsumerConfiguration, DmaapConsumerConfiguration.Builder> {
-
-        Builder consumerId(String consumerId);
-
-        Builder consumerGroup(String consumerGroup);
-
-        Builder timeoutMS(Integer timeoutMS);
-
-        Builder messageLimit(Integer messageLimit);
-    }
-
-    public static DmaapConsumerConfiguration.Builder builder() {
-        return ImmutableDmaapConsumerConfiguration.builder();
-    }
-
 }
index d091844..06d20f7 100644 (file)
@@ -30,13 +30,4 @@ import org.immutables.value.Value;
 public abstract class DmaapPublisherConfiguration implements DmaapCustomConfig {
 
     private static final long serialVersionUID = 1L;
-
-    interface Builder
-            extends DmaapCustomConfig.Builder<DmaapPublisherConfiguration, DmaapPublisherConfiguration.Builder> {
-
-    }
-
-    public static DmaapPublisherConfiguration.Builder builder() {
-        return ImmutableDmaapPublisherConfiguration.builder();
-    }
 }
index 2585bbc..c62f349 100644 (file)
@@ -34,7 +34,13 @@ public class ErrorData {
     public String toString() {
         StringBuilder message = new StringBuilder();
         for (int i = 0; i < errorMessages.size(); i++) {
-            message.append(errorMessages.get(i)).append(" Cause: ").append(errorCauses.get(i)).append("\n");
+            message.append(errorMessages.get(i));
+            if (errorCauses.get(i) != null) {
+                message.append(" Cause: ").append(errorCauses.get(i));
+            }
+            if (i < errorMessages.size() -1) {
+                message.append("\n");
+            }
         }
         return message.toString();
     }
index b50b045..42addbf 100644 (file)
@@ -20,8 +20,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * @author
- *
+ * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
  */
 public abstract class FileCollectClient {
     protected static final Logger logger = LoggerFactory.getLogger(FtpsClient.class);
index 120868c..8247bcc 100644 (file)
@@ -19,7 +19,6 @@ package org.onap.dcaegen2.collectors.datafile.ftp;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.security.GeneralSecurityException;
 import java.security.KeyStoreException;
 import java.security.NoSuchAlgorithmException;
 
@@ -31,6 +30,7 @@ import org.onap.dcaegen2.collectors.datafile.io.IFileSystemResource;
 import org.onap.dcaegen2.collectors.datafile.io.IOutputStream;
 import org.onap.dcaegen2.collectors.datafile.io.OutputStreamWrapper;
 import org.onap.dcaegen2.collectors.datafile.ssl.IKeyManagerUtils;
+import org.onap.dcaegen2.collectors.datafile.ssl.IKeyManagerUtils.KeyManagerException;
 import org.onap.dcaegen2.collectors.datafile.ssl.IKeyStore;
 import org.onap.dcaegen2.collectors.datafile.ssl.ITrustManagerFactory;
 import org.onap.dcaegen2.collectors.datafile.ssl.KeyManagerUtilsWrapper;
@@ -94,7 +94,7 @@ public class FtpsClient extends FileCollectClient {
             keyManagerUtils.setCredentials(keyCertPath, keyCertPassword);
             ftps.setKeyManager(keyManagerUtils.getClientKeyManager());
             keyManagerSet = true;
-        } catch (GeneralSecurityException | IOException e) {
+        } catch (KeyManagerException e) {
             addError("Unable to use own key store " + keyCertPath, e);
             result = false;
         }
@@ -184,7 +184,7 @@ public class FtpsClient extends FileCollectClient {
             try {
                 outfile.delete();
             } catch (Exception e) {
-                // Nothing
+                logger.trace("Unable to delete file {}.", localFile, e);
             }
             result = false;
         }
@@ -199,7 +199,7 @@ public class FtpsClient extends FileCollectClient {
                 ftps.disconnect();
             }
         } catch (Exception e) {
-            // Do nothing, file has been collected.
+            logger.trace("Unable to logout and close connection.", e);
         }
     }
 
index 18b2834..e8fc695 100644 (file)
@@ -76,6 +76,7 @@ public class SftpClient extends FileCollectClient {
             session.connect();
         } catch (JSchException e) {
             addError("Unable to set up SFTP connection to xNF. Data: " + fileServerData, e);
+            session = null;
         }
         return session;
     }
index fa794e9..95de2de 100644 (file)
@@ -23,13 +23,10 @@ import java.io.InputStream;
 
 import org.springframework.core.io.FileSystemResource;
 
-/**
- * @author
- *
- */
 public class FileSystemResourceWrapper implements IFileSystemResource {
     private FileSystemResource realResource;
 
+    @Override
     public void setPath(String path) {
         realResource = new FileSystemResource(path);
     }
index 99fe13e..db30396 100644 (file)
@@ -19,10 +19,6 @@ package org.onap.dcaegen2.collectors.datafile.io;
 import java.io.IOException;
 import java.io.InputStream;
 
-/**
- * @author
- *
- */
 public interface IFileSystemResource {
 
     public void setPath(String filePath);
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/FileSystemResourceWrapper.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/FileSystemResourceWrapper.java
deleted file mode 100644 (file)
index 6349691..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.springframework.core.io.FileSystemResource;
-
-/**
- * @author
- *
- */
-public class FileSystemResourceWrapper implements IFileSystemResource {
-    private FileSystemResource realResource;
-
-    public FileSystemResourceWrapper(String path) {
-        realResource = new FileSystemResource(path);
-    }
-    @Override
-    public InputStream getInputStream() throws IOException {
-        return realResource.getInputStream();
-    }
-}
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IFileSystemResource.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IFileSystemResource.java
deleted file mode 100644 (file)
index 8c41946..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author
- *
- */
-@FunctionalInterface
-public interface IFileSystemResource {
-
-    InputStream getInputStream() throws IOException;
-}
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IRestTemplate.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/IRestTemplate.java
deleted file mode 100644 (file)
index 98e6ab4..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import java.net.URI;
-
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-
-/**
- * @author
- *
- */
-@FunctionalInterface
-public interface IRestTemplate {
-    public ResponseEntity<String> exchange(URI url, HttpMethod method, HttpEntity<byte[]> requestEntity,
-            Class<String> responseType);
-}
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategy.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategy.java
deleted file mode 100644 (file)
index ff3a03b..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import java.net.URI;
-
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.ProtocolException;
-import org.apache.http.annotation.Contract;
-import org.apache.http.annotation.ThreadingBehavior;
-import org.apache.http.client.methods.HttpDelete;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpHead;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpPut;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.client.methods.RequestBuilder;
-import org.apache.http.impl.client.DefaultRedirectStrategy;
-import org.apache.http.protocol.HttpContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * PublishRedirectStrategy implementation
- * that automatically redirects all HEAD, GET, POST, PUT, and DELETE requests.
- * This strategy relaxes restrictions on automatic redirection of
- * POST methods imposed by the HTTP specification.
- *
- */
-@Contract(threading = ThreadingBehavior.IMMUTABLE)
-public class PublishRedirectStrategy extends DefaultRedirectStrategy {
-
-    public static final PublishRedirectStrategy INSTANCE = new PublishRedirectStrategy();
-    private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
-    /**
-     * Redirectable methods.
-     */
-    private static final String[] REDIRECT_METHODS = new String[] {
-        HttpPut.METHOD_NAME,
-        HttpGet.METHOD_NAME,
-        HttpPost.METHOD_NAME,
-        HttpHead.METHOD_NAME,
-        HttpDelete.METHOD_NAME
-    };
-
-    @Override
-    protected boolean isRedirectable(final String method) {
-        for (final String m: REDIRECT_METHODS) {
-            if (m.equalsIgnoreCase(method)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    @Override
-    public HttpUriRequest getRedirect(
-            final HttpRequest request,
-            final HttpResponse response,
-            final HttpContext context) throws ProtocolException {
-        final URI uri = getLocationURI(request, response, context);
-        logger.trace("getRedirect...: {}", request.toString());
-        return RequestBuilder.copy(request).setUri(uri).build();
-    }
-
-}
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RequestResponseLoggingInterceptor.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RequestResponseLoggingInterceptor.java
deleted file mode 100644 (file)
index bf40700..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-import java.io.IOException;
-import java.nio.charset.Charset;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.http.HttpRequest;
-import org.springframework.http.client.ClientHttpRequestExecution;
-import org.springframework.http.client.ClientHttpRequestInterceptor;
-import org.springframework.http.client.ClientHttpResponse;
-import org.springframework.util.StreamUtils;
-
-public class RequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {
-
-    private final Logger log = LoggerFactory.getLogger(this.getClass());
-
-    @Override
-    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
-        logRequest(request, body);
-        ClientHttpResponse response = execution.execute(request, body);
-        logResponse(response);
-        return response;
-    }
-
-    private void logRequest(HttpRequest request, byte[] body) throws IOException {
-        if (log.isDebugEnabled()) {
-            log.debug("===========================request begin================================================");
-            log.debug("URI         : {}", request.getURI());
-            log.debug("Method      : {}", request.getMethod());
-            log.debug("Headers     : {}", request.getHeaders());
-            log.debug("Request body: {}", new String(body, "UTF-8"));
-            log.debug("==========================request end================================================");
-        }
-    }
-
-    private void logResponse(ClientHttpResponse response) throws IOException {
-        if (log.isDebugEnabled()) {
-            log.debug("============================response begin==========================================");
-            log.debug("Status code  : {}", response.getStatusCode());
-            log.debug("Status text  : {}", response.getStatusText());
-            log.debug("Headers      : {}", response.getHeaders());
-            log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
-            log.debug("=======================response end=================================================");
-        }
-    }
-}
\ No newline at end of file
diff --git a/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RestTemplateWrapper.java b/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/RestTemplateWrapper.java
deleted file mode 100644 (file)
index 298f669..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import java.net.URI;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.util.Collections;
-
-import javax.net.ssl.SSLContext;
-
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.ssl.SSLContextBuilder;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
-import org.springframework.web.client.RestTemplate;
-
-/**
- * @author
- *
- */
-public class RestTemplateWrapper implements IRestTemplate {
-    private RestTemplate restTemplate;
-
-    public RestTemplateWrapper() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
-        SSLContext sslContext =
-                new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
-        CloseableHttpClient httpClient =
-                HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier())
-                        .setRedirectStrategy(new PublishRedirectStrategy()).build();
-
-        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
-        requestFactory.setHttpClient(httpClient);
-
-        restTemplate = new RestTemplate(requestFactory);
-        restTemplate.setInterceptors(Collections.singletonList(new RequestResponseLoggingInterceptor()));
-
-    }
-
-    @Override
-    public ResponseEntity<String> exchange(URI url, HttpMethod method, HttpEntity<byte[]> requestEntity,
-            Class<String> responseType) {
-        return restTemplate.exchange(url,  method, requestEntity, responseType);
-    }
-
-}
index 38ea681..8c4525e 100644 (file)
 
 package org.onap.dcaegen2.collectors.datafile.ssl;
 
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-
 import javax.net.ssl.KeyManager;
 
-/**
- * @author
- *
- */
 public interface IKeyManagerUtils {
-    public void setCredentials(String keyStorePath, String keyStorePass) throws IOException, GeneralSecurityException;
+    public void setCredentials(String keyStorePath, String keyStorePass) throws KeyManagerException;
 
     public KeyManager getClientKeyManager();
+
+    public static class KeyManagerException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        public KeyManagerException(Exception e) {
+            super(e);
+        }
+    }
 }
index 01fb6c5..0e54cec 100644 (file)
 
 package org.onap.dcaegen2.collectors.datafile.ssl;
 
-import java.io.IOException;
 import java.io.InputStream;
 import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
 
 public interface IKeyStore {
-    public void load(InputStream arg0, char[] arg1)
-            throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException;
+    public void load(InputStream arg0, char[] arg1) throws KeyStoreLoadException;
 
     public KeyStore getKeyStore();
+
+    public static class KeyStoreLoadException extends Exception {
+        private static final long serialVersionUID = 1L;
+
+        public KeyStoreLoadException(Exception e) {
+            super(e);
+        }
+    }
 }
index 9eeaa92..93a7a2f 100644 (file)
@@ -26,16 +26,16 @@ import javax.net.ssl.KeyManager;
 
 import org.apache.commons.net.util.KeyManagerUtils;
 
-/**
- * @author
- *
- */
 public class KeyManagerUtilsWrapper implements IKeyManagerUtils {
     private KeyManager keyManager;
 
     @Override
-    public void setCredentials(String keyStorePath, String keyStorePass) throws IOException, GeneralSecurityException {
-        keyManager = KeyManagerUtils.createClientKeyManager(new File(keyStorePath), keyStorePass);
+    public void setCredentials(String keyStorePath, String keyStorePass) throws KeyManagerException {
+        try {
+            keyManager = KeyManagerUtils.createClientKeyManager(new File(keyStorePath), keyStorePass);
+        } catch (IOException | GeneralSecurityException e) {
+            throw new KeyManagerException(e);
+        }
     }
 
     @Override
index 0a6ff20..a8eebea 100644 (file)
@@ -32,8 +32,12 @@ public class KeyStoreWrapper implements IKeyStore {
 
     @Override
     public void load(InputStream stream, char[] password)
-            throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
-        keyStore.load(stream, password);
+            throws KeyStoreLoadException {
+        try {
+            keyStore.load(stream, password);
+        } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
+            throw new KeyStoreLoadException(e);
+        }
     }
 
     @Override
index e700633..07e7563 100644 (file)
@@ -22,10 +22,6 @@ import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.ResponseEntity;
 
-/**
- * @author
- *
- */
 @FunctionalInterface
 public interface IRestTemplate {
     public ResponseEntity<String> exchange(URI url, HttpMethod method, HttpEntity<byte[]> requestEntity,
index a1b4284..99ead84 100644 (file)
@@ -34,10 +34,6 @@ import org.springframework.http.ResponseEntity;
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.web.client.RestTemplate;
 
-/**
- * @author
- *
- */
 public class RestTemplateWrapper implements IRestTemplate {
     private RestTemplate restTemplate;
 
index e40d7d7..b4edf82 100644 (file)
@@ -1,57 +1,43 @@
 /*
  * ============LICENSE_START======================================================================
- * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
+ * Copyright (C) 2018 Nordix Foundation. All rights reserved.
  * ===============================================================================================
- * 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
+ * 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
+ *      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.
+ * 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.onap.dcaegen2.collectors.datafile.ftp;
 
-import static org.mockito.Mockito.mock;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
 public class ErrorDataTest {
-    private List<String> errorMessages = new ArrayList<>();
-    private List<Throwable> errorCauses = new ArrayList<>();
-    private ErrorData errorData = new ErrorData();
-
-    @BeforeEach
-    protected void setUp() {
-        int testSize = 3;
-        for (int i = 0; i < testSize; i++) {
-            errorMessages.add("test");
-            errorCauses.add(mock(Throwable.class));
-        }
-        for (int i = 0; i < testSize; i++) {
-            errorData.addError(errorMessages.get(i), errorCauses.get(i));
-        }
-    }
 
-    public String getMessageAsString() {
-        StringBuilder message = new StringBuilder();
-        for (int i = 0; i < errorMessages.size(); i++) {
-            message.append(errorMessages.get(i)).append(" Cause: ").append(errorCauses.get(i)).append("\n");
-        }
-        return message.toString();
+    @Test
+    public void emptyData() {
+        ErrorData dataUnderTest = new ErrorData();
+
+        assertEquals("", dataUnderTest.toString());
     }
 
     @Test
-    public void testToString_returnExpectedString() {
-        Assertions.assertEquals(getMessageAsString(), errorData.toString());
+    public void withData() {
+        ErrorData dataUnderTest = new ErrorData();
+        dataUnderTest.addError("Error", null);
+        dataUnderTest.addError("Null", new NullPointerException("Null"));
+
+        assertEquals("Error\nNull Cause: java.lang.NullPointerException: Null", dataUnderTest.toString());
     }
 }
+
diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FileCollectResultTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FileCollectResultTest.java
new file mode 100644 (file)
index 0000000..083727e
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * ============LICENSE_START======================================================================
+ * Copyright (C) 2018 Nordix Foundation. All rights reserved.
+ * ===============================================================================================
+ * 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.onap.dcaegen2.collectors.datafile.ftp;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import org.junit.jupiter.api.Test;
+
+public class FileCollectResultTest {
+
+    @Test
+    public void successfulResult() {
+        FileCollectResult resultUnderTest = new FileCollectResult();
+        assertTrue(resultUnderTest.downloadSuccessful());
+        assertEquals("FileCollectResult: true Error data: ", resultUnderTest.toString());
+    }
+
+    @Test
+    public void unSuccessfulResult() {
+        ErrorData errorData = new ErrorData();
+        errorData.addError("Error", null);
+        errorData.addError("Null", new NullPointerException());
+        FileCollectResult resultUnderTest = new FileCollectResult(errorData);
+        assertFalse(resultUnderTest.downloadSuccessful());
+        assertEquals("FileCollectResult: false Error data: " + errorData.toString(), resultUnderTest.toString());
+    }
+}
index 66d3b00..2157e17 100644 (file)
@@ -135,7 +135,7 @@ public class FtpsClientTest {
 
     @Test
     public void collectFileFaultyOwnKey_shouldFail() throws Exception {
-        doThrow(new GeneralSecurityException())
+        doThrow(new IKeyManagerUtils.KeyManagerException(new GeneralSecurityException()))
                 .when(keyManagerUtilsMock).setCredentials(FTP_KEY_PATH, FTP_KEY_PASSWORD);
 
         ImmutableFileServerData fileServerData = ImmutableFileServerData.builder().serverAddress(XNF_ADDRESS)
index 13f1fbb..e9e68bb 100644 (file)
@@ -21,6 +21,8 @@ package org.onap.dcaegen2.collectors.datafile.ftp;
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.apache.commons.io.IOUtils.toByteArray;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule;
 import com.jcraft.jsch.ChannelSftp;
@@ -63,6 +65,38 @@ public class SftpClientTest {
         assertThat(new String(localFile, UTF_8)).isEqualTo(DUMMY_CONTENT);
     }
 
+    @Test
+    public void collectFile_withWrongUserName_shouldFail() throws IOException, JSchException, SftpException {
+        SftpClient sftpClient = new SftpClient();
+        sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8);
+        byte[] file = downloadFile(sftpServer, REMOTE_DUMMY_FILE);
+        FileServerData expectedFileServerData = ImmutableFileServerData.builder().serverAddress("127.0.0.1")
+                .userId("Wrong").password(PASSWORD).port(sftpServer.getPort()).build();
+        FileCollectResult actualResult = sftpClient.collectFile(expectedFileServerData, REMOTE_DUMMY_FILE,
+                LOCAL_DUMMY_FILE);
+
+        assertFalse(actualResult.downloadSuccessful());
+        String expectedErrorMessage = "Unable to set up SFTP connection to xNF. Data: "
+                + "FileServerData{serverAddress=127.0.0.1, userId=Wrong, password=123, port=";
+        assertTrue(actualResult.getErrorData().toString().startsWith(expectedErrorMessage));
+    }
+
+    @Test
+    public void collectFile_withWrongFileName_shouldFail() throws IOException, JSchException, SftpException {
+        SftpClient sftpClient = new SftpClient();
+        sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8);
+        byte[] file = downloadFile(sftpServer, REMOTE_DUMMY_FILE);
+        FileServerData expectedFileServerData = ImmutableFileServerData.builder().serverAddress("127.0.0.1")
+                .userId(USERNAME).password(PASSWORD).port(sftpServer.getPort()).build();
+        FileCollectResult actualResult = sftpClient.collectFile(expectedFileServerData, "wrong",
+                LOCAL_DUMMY_FILE);
+
+        assertFalse(actualResult.downloadSuccessful());
+        String expectedErrorMessage = "Unable to get file from xNF. Data: FileServerData{serverAddress=127.0.0.1, "
+                + "userId=bob, password=123, port=";
+        assertTrue(actualResult.getErrorData().toString().startsWith(expectedErrorMessage));
+    }
+
     private static Session connectToServer(FakeSftpServerRule sftpServer) throws JSchException {
         return connectToServerAtPort(sftpServer.getPort());
     }
index ba42462..87c99f8 100644 (file)
@@ -39,7 +39,7 @@ import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration;
 import org.onap.dcaegen2.collectors.datafile.io.IFileSystemResource;
 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
-import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModelForUnitTest;
+import org.onap.dcaegen2.collectors.datafile.model.ImmutableConsumerDmaapModel;
 import org.onap.dcaegen2.collectors.datafile.web.IRestTemplate;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
@@ -74,7 +74,7 @@ class DmaapProducerReactiveHttpClientTest {
     private DmaapProducerReactiveHttpClient dmaapProducerReactiveHttpClient;
 
     private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class);
-    private ConsumerDmaapModel consumerDmaapModel = new ConsumerDmaapModelForUnitTest();
+    private ConsumerDmaapModel consumerDmaapModel;
 
     private IFileSystemResource fileSystemResourceMock = mock(IFileSystemResource.class);
     private IRestTemplate restTemplateMock = mock(IRestTemplate.class);
@@ -92,6 +92,10 @@ class DmaapProducerReactiveHttpClientTest {
         when(dmaapPublisherConfigurationMock.dmaapContentType()).thenReturn(APPLICATION_OCTET_STREAM_CONTENT_TYPE);
         when(dmaapPublisherConfigurationMock.dmaapTopicName()).thenReturn(PUBLISH_TOPIC);
 
+        consumerDmaapModel = ImmutableConsumerDmaapModel.builder().name(FILE_NAME)
+                .location("target/A20161224.1030-1045.bin.gz").compression("gzip")
+                .fileFormatType("org.3GPP.32.435#measCollec").fileFormatVersion("V10").build();
+
         dmaapProducerReactiveHttpClient = new DmaapProducerReactiveHttpClient(dmaapPublisherConfigurationMock);
         dmaapProducerReactiveHttpClient.setFileSystemResource(fileSystemResourceMock);
         dmaapProducerReactiveHttpClient.setRestTemplate(restTemplateMock);
@@ -99,7 +103,7 @@ class DmaapProducerReactiveHttpClientTest {
 
     @Test
     void getHttpResponse_Success() throws Exception {
-        mockWebClientDependantObject();
+        mockWebClientDependantObject(true);
 
         StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel))
                 .expectNext(HttpStatus.OK.toString()).verifyComplete();
@@ -130,11 +134,23 @@ class DmaapProducerReactiveHttpClientTest {
         verifyNoMoreInteractions(restTemplateMock);
     }
 
-    private void mockWebClientDependantObject() throws IOException {
+    @Test
+    void getHttpResponse_Fail() throws Exception {
+        mockWebClientDependantObject(false);
+
+        StepVerifier.create(dmaapProducerReactiveHttpClient.getDmaapProducerResponse(consumerDmaapModel))
+                .verifyComplete();
+    }
+
+    private void mockWebClientDependantObject(boolean success) throws IOException {
         fileStream = new ByteArrayInputStream(FILE_CONTENT.getBytes());
         when(fileSystemResourceMock.getInputStream()).thenReturn(fileStream);
 
-        when(restTemplateMock.exchange(any(), any(), any(), any())).thenReturn(responseEntityMock);
-        when(responseEntityMock.getStatusCode()).thenReturn(HttpStatus.OK);
+        if (success) {
+            when(restTemplateMock.exchange(any(), any(), any(), any())).thenReturn(responseEntityMock);
+            when(responseEntityMock.getStatusCode()).thenReturn(HttpStatus.OK);
+        } else {
+            when(restTemplateMock.exchange(any(), any(), any(), any())).thenThrow(new RuntimeException());
+        }
     }
 }
diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategyTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/PublishRedirectStrategyTest.java
deleted file mode 100644 (file)
index 74ad672..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * ============LICENSE_START======================================================================
- * Copyright (C) 2018 Nordix Foundation. All rights reserved.
- * ===============================================================================================
- * 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.onap.dcaegen2.collectors.datafile.service.producer;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-import org.apache.http.client.methods.HttpPut;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-class PublishRedirectStrategyTest {
-
-    private PublishRedirectStrategy redirectStrategy;
-
-    @BeforeEach
-    void setUp() {
-        redirectStrategy = new PublishRedirectStrategy();
-    }
-
-    @Test
-    void isRedirectable_shouldReturnTrue() {
-        assertTrue(redirectStrategy.isRedirectable(HttpPut.METHOD_NAME));
-    }
-}
\ No newline at end of file