2 * ============LICENSE_START======================================================================
3 * Copyright (C) 2018 NOKIA Intellectual Property, 2018 Nordix Foundation. All rights reserved.
4 * ===============================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6 * in compliance with the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software distributed under the License
11 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12 * or implied. See the License for the specific language governing permissions and limitations under
14 * ============LICENSE_END========================================================================
17 package org.onap.dcaegen2.collectors.datafile.service.producer;
19 import com.google.gson.JsonElement;
20 import com.google.gson.JsonParser;
22 import java.io.IOException;
23 import java.io.InputStream;
25 import java.nio.charset.StandardCharsets;
26 import java.security.KeyManagementException;
27 import java.security.KeyStoreException;
28 import java.security.NoSuchAlgorithmException;
30 import org.apache.commons.codec.binary.Base64;
31 import org.apache.commons.io.IOUtils;
32 import org.onap.dcaegen2.collectors.datafile.config.DmaapPublisherConfiguration;
33 import org.onap.dcaegen2.collectors.datafile.model.CommonFunctions;
34 import org.onap.dcaegen2.collectors.datafile.model.ConsumerDmaapModel;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.http.HttpEntity;
38 import org.springframework.http.HttpHeaders;
39 import org.springframework.http.HttpMethod;
40 import org.springframework.http.MediaType;
41 import org.springframework.http.ResponseEntity;
42 import org.springframework.web.util.DefaultUriBuilderFactory;
44 import reactor.core.publisher.Flux;
47 * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
48 * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
50 public class DmaapProducerReactiveHttpClient {
52 private static final String X_ATT_DR_META = "X-ATT-DR-META";
53 private static final String NAME_JSON_TAG = "name";
54 private static final String LOCATION_JSON_TAG = "location";
55 private static final String URI_SEPARATOR = "/";
56 private static final String DEFAULT_FEED_ID = "1";
58 private final Logger logger = LoggerFactory.getLogger(this.getClass());
60 private final String dmaapHostName;
61 private final Integer dmaapPortNumber;
62 private final String dmaapTopicName;
63 private final String dmaapProtocol;
64 private final String dmaapContentType;
65 private final String user;
66 private final String pwd;
68 private IFileSystemResource fileResource;
69 private IRestTemplate restTemplate;
72 * Constructor DmaapProducerReactiveHttpClient.
74 * @param dmaapPublisherConfiguration - DMaaP producer configuration object
76 public DmaapProducerReactiveHttpClient(DmaapPublisherConfiguration dmaapPublisherConfiguration) {
78 this.dmaapHostName = dmaapPublisherConfiguration.dmaapHostName();
79 this.dmaapPortNumber = dmaapPublisherConfiguration.dmaapPortNumber();
80 this.dmaapTopicName = dmaapPublisherConfiguration.dmaapTopicName();
81 this.dmaapProtocol = dmaapPublisherConfiguration.dmaapProtocol();
82 this.dmaapContentType = dmaapPublisherConfiguration.dmaapContentType();
83 this.user = dmaapPublisherConfiguration.dmaapUserName();
84 this.pwd = dmaapPublisherConfiguration.dmaapUserPassword();
88 * Function for calling DMaaP HTTP producer - post request to DMaaP DataRouter.
90 * @param consumerDmaapModel - object which will be sent to DMaaP DataRouter
91 * @return status code of operation
93 public Flux<String> getDmaapProducerResponse(ConsumerDmaapModel consumerDmaapModel) {
94 logger.trace("Entering getDmaapProducerResponse with {}", consumerDmaapModel);
96 HttpHeaders headers = new HttpHeaders();
97 headers.setContentType(MediaType.parseMediaType(dmaapContentType));
98 addMetaDataToHead(consumerDmaapModel, headers);
100 addUserCredentialsToHead(headers);
102 HttpEntity<byte[]> request = addFileToRequest(consumerDmaapModel, headers);
105 logger.trace("Starting to publish to DR");
106 ResponseEntity<String> responseEntity = getRestTemplate().exchange(getUri(consumerDmaapModel.getName()),
107 HttpMethod.PUT, request, String.class);
109 return Flux.just(responseEntity.getStatusCode().toString());
110 } catch (Exception e) {
111 logger.error("Unable to send file to DataRouter. Data: {}", consumerDmaapModel, e);
116 private void addUserCredentialsToHead(HttpHeaders headers) {
117 String plainCreds = user + ":" + pwd;
118 byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
119 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
120 String base64Creds = new String(base64CredsBytes);
121 logger.trace("base64Creds...: {}", base64Creds);
122 headers.add("Authorization", "Basic " + base64Creds);
125 private void addMetaDataToHead(ConsumerDmaapModel consumerDmaapModel, HttpHeaders headers) {
126 JsonElement metaData = new JsonParser().parse(CommonFunctions.createJsonBody(consumerDmaapModel));
127 metaData.getAsJsonObject().remove(NAME_JSON_TAG).getAsString();
128 metaData.getAsJsonObject().remove(LOCATION_JSON_TAG);
129 headers.set(X_ATT_DR_META, metaData.toString());
132 private HttpEntity<byte[]> addFileToRequest(ConsumerDmaapModel consumerDmaapModel, HttpHeaders headers)
134 InputStream in = getInputStream(consumerDmaapModel.getLocation());
135 return new HttpEntity<>(IOUtils.toByteArray(in), headers);
138 private InputStream getInputStream(String filePath) throws IOException {
139 if (fileResource == null) {
140 fileResource = new FileSystemResourceWrapper(filePath);
142 return fileResource.getInputStream();
145 private IRestTemplate getRestTemplate() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
146 if (restTemplate == null) {
147 restTemplate = new RestTemplateWrapper();
152 private URI getUri(String fileName) {
153 String path = dmaapTopicName + URI_SEPARATOR + DEFAULT_FEED_ID + URI_SEPARATOR + fileName;
154 return new DefaultUriBuilderFactory().builder().scheme(dmaapProtocol).host(dmaapHostName).port(dmaapPortNumber)
158 protected void setFileSystemResource(IFileSystemResource fileSystemResource) {
159 fileResource = fileSystemResource;
162 protected void setRestTemplate(IRestTemplate restTemplate) {
163 this.restTemplate = restTemplate;