2 * ================================================================================
3 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
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.
16 * ============LICENSE_END=========================================================
20 package org.onap.dcae.analytics.model.util.function;
22 import java.io.IOException;
23 import java.net.HttpURLConnection;
25 import java.nio.charset.StandardCharsets;
26 import java.util.Optional;
27 import java.util.Scanner;
28 import java.util.function.Function;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Simple Function that calls http 'GET' on given URL and returns the response as String if successful. This function
35 * has side effects and only used for convenience in lambda expressions
37 * NOTE: Suitable for only light weight http get requests as this will be a blocking call
39 * @author Rajiv Singla
41 public class URLToHttpGetFunction implements Function<URL, Optional<String>> {
43 private static final Logger logger = LoggerFactory.getLogger(URLToHttpGetFunction.class);
46 public Optional<String> apply(final URL url) {
49 final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
50 httpConnection.setRequestMethod("GET");
52 logger.info("Sending 'GET' request to URL : {}", url);
53 final int responseCode = httpConnection.getResponseCode();
55 if (responseCode == 200) {
56 final StringBuilder responseString = new StringBuilder();
57 try (Scanner scanner = new Scanner(httpConnection.getInputStream(), StandardCharsets.UTF_8.name())) {
58 while (scanner.hasNext()) {
59 responseString.append(scanner.next());
63 logger.info("Successful Response: {}", responseString);
64 return Optional.of(responseString.toString());
67 logger.error("Unsuccessful Response Code: {} when calling URL: {}", responseCode, url);
69 } catch (IOException e) {
71 logger.error("Unable to create HTTP URL Connection to URL:" + url, e);
75 return Optional.empty();