2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.dcaegen2.collectors.datafile.tasks;
23 import com.google.gson.JsonElement;
24 import com.google.gson.JsonParser;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.MalformedURLException;
30 import java.nio.file.Path;
31 import java.time.Duration;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.entity.ByteArrayEntity;
37 import org.onap.dcaegen2.collectors.datafile.configuration.AppConfig;
38 import org.onap.dcaegen2.collectors.datafile.configuration.PublisherConfiguration;
39 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
40 import org.onap.dcaegen2.collectors.datafile.model.FilePublishInformation;
41 import org.onap.dcaegen2.collectors.datafile.model.JsonSerializer;
42 import org.onap.dcaegen2.collectors.datafile.model.logging.MappedDiagnosticContext;
43 import org.onap.dcaegen2.collectors.datafile.service.HttpUtils;
44 import org.onap.dcaegen2.collectors.datafile.service.producer.DmaapProducerHttpClient;
45 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import org.springframework.core.io.FileSystemResource;
50 import org.springframework.http.HttpHeaders;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.web.util.DefaultUriBuilderFactory;
54 import reactor.core.publisher.Mono;
57 * Publishes a file to the DataRouter.
59 * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 4/13/18
60 * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
62 public class DataRouterPublisher {
63 private static final String X_DMAAP_DR_META = "X-DMAAP-DR-META";
64 private static final String CONTENT_TYPE = "application/octet-stream";
66 private static final Logger logger = LoggerFactory.getLogger(DataRouterPublisher.class);
67 private final AppConfig datafileAppConfig;
69 public DataRouterPublisher(AppConfig datafileAppConfig) {
70 this.datafileAppConfig = datafileAppConfig;
76 * @param publishInfo information about the file to publish
77 * @param numRetries the maximal number of retries if the publishing fails
78 * @param firstBackoff the time to delay the first retry
79 * @return the (same) filePublishInformation
81 public Mono<FilePublishInformation> publishFile(FilePublishInformation publishInfo, long numRetries,
82 Duration firstBackoff) {
83 MDC.setContextMap(publishInfo.getContext());
84 return Mono.just(publishInfo) //
86 .flatMap(this::publishFile) //
87 .flatMap(httpStatus -> handleHttpResponse(httpStatus, publishInfo)) //
88 .retryBackoff(numRetries, firstBackoff);
91 private Mono<HttpStatus> publishFile(FilePublishInformation publishInfo) {
92 MDC.setContextMap(publishInfo.getContext());
93 logger.trace("Entering publishFile with {}", publishInfo);
95 DmaapProducerHttpClient dmaapProducerHttpClient = resolveClient(publishInfo.getChangeIdentifier());
96 HttpPut put = new HttpPut();
97 prepareHead(publishInfo, put);
98 prepareBody(publishInfo, put);
99 dmaapProducerHttpClient.addUserCredentialsToHead(put);
101 HttpResponse response =
102 dmaapProducerHttpClient.getDmaapProducerResponseWithRedirect(put, publishInfo.getContext());
103 logger.trace("{}", response);
104 return Mono.just(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));
105 } catch (Exception e) {
106 logger.warn("Unable to send file to DataRouter. Data: {}", publishInfo.getInternalLocation(), e);
107 return Mono.error(e);
111 private void prepareHead(FilePublishInformation publishInfo, HttpPut put) throws DatafileTaskException {
113 put.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE);
114 JsonElement metaData = new JsonParser().parse(JsonSerializer.createJsonBodyForDataRouter(publishInfo));
115 put.addHeader(X_DMAAP_DR_META, metaData.toString());
116 URI uri = new DefaultUriBuilderFactory(
117 datafileAppConfig.getPublisherConfiguration(publishInfo.getChangeIdentifier()).publishUrl()) //
119 .pathSegment(publishInfo.getName()) //
123 MappedDiagnosticContext.appendTraceInfo(put);
126 private void prepareBody(FilePublishInformation publishInfo, HttpPut put) throws IOException {
127 Path fileLocation = publishInfo.getInternalLocation();
128 try (InputStream fileInputStream = createInputStream(fileLocation)) {
129 put.setEntity(new ByteArrayEntity(IOUtils.toByteArray(fileInputStream)));
133 private static Mono<FilePublishInformation> handleHttpResponse(HttpStatus response, FilePublishInformation publishInfo) {
134 MDC.setContextMap(publishInfo.getContext());
135 if (HttpUtils.isSuccessfulResponseCode(response.value())) {
136 logger.trace("Publish to DR successful!");
137 return Mono.just(publishInfo);
139 logger.warn("Publish to DR unsuccessful, response code: {}", response);
140 return Mono.error(new Exception("Publish to DR unsuccessful, response code: " + response));
144 InputStream createInputStream(Path filePath) throws IOException {
145 FileSystemResource realResource = new FileSystemResource(filePath);
146 return realResource.getInputStream();
149 PublisherConfiguration resolveConfiguration(String changeIdentifer) throws DatafileTaskException {
150 return datafileAppConfig.getPublisherConfiguration(changeIdentifer);
153 DmaapProducerHttpClient resolveClient(String changeIdentifier) throws DatafileTaskException {
155 DmaapPublisherConfiguration cfg = resolveConfiguration(changeIdentifier).toDmaap();
156 return new DmaapProducerHttpClient(cfg);
157 } catch (MalformedURLException e) {
158 throw new DatafileTaskException("Cannot resolve producer client", e);