aboutsummaryrefslogtreecommitdiffstats
path: root/ncomp-docker-adaptor/src/main/java/org/openecomp/ncomp/servers/docker/DockerHttpClient.java
blob: 42b373c0b07de1e8bf50a3f13afa3e691ee67ed0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*-
 * ============LICENSE_START==========================================
 * OPENECOMP - DCAE
 * ===================================================================
 * Copyright (c) 2017 AT&T Intellectual Property. 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.openecomp.ncomp.servers.docker;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.openecomp.ncomp.utils.CryptoUtils;
import org.openecomp.ncomp.utils.PropertyUtil;

public class DockerHttpClient extends DockerAbstractClient {
	
	public static final Logger logger = Logger.getLogger(DockerHttpClient.class);
	String authorization;
	String baseAddress;
	private boolean debug = true;
	private int responseCode;

	public int getResponseCode() {
		return this.responseCode;
	}
	
	private static void safeClose(final OutputStream out) {
    	if (out != null) {
    		try { 
    			out.close();
    		} catch(IOException e) {
    			logger.error("Failed to close stream " + e);
    		}
    	}
    }
	
	private static void safeClose(final InputStream in) {
    	if (in != null) {
    		try { 
    			in.close();
    		} catch(IOException e) {
    			logger.error("Failed to close stream " + e);
    		}
    	}
    }
	
	public DockerHttpClient(String fileName, String endpoint) {
		this.responseCode = 0;
		try {
			props = PropertyUtil.getPropertiesFromClasspath(fileName);
			setBaseAddress(props.getProperty(endpoint + ".endpoint"));
			if (getBaseAddress() == null) {
				logger.error("unable to determine baseAddress for endpoint: " + endpoint + " in " + fileName);
				throw new RuntimeException("unable to determine baseAddress for endpoint: " + endpoint + " in "
						+ fileName);
			}
			//String user = props.getProperty(endpoint + ".user");
			//String password = decryptPassword(props.getProperty(endpoint + ".password"));
			debug = Boolean.parseBoolean(props.getProperty(endpoint + ".debug", "false"));
			//authorization = "Basic " + Base64.encodeBase64String((user + ":" + password).getBytes());
			//authorization = authorization.trim();
		} catch (Exception e) {
			logger.error("creating client failed: " + e.getMessage());
		}
	}
	
	public byte[] httpBinaryTransaction(String path, String method, HashMap<String, String> headers, JSONObject body,
			Long timeout) {

		byte[] rawbody = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		if ("DELETE".equals(method) || "GET".equals(method)) {
			body = null;
		}
		if (body != null) {
			rawbody = body.toString(2).getBytes();
			if (rawbody.length == 0) {
				rawbody = null;
			}
		}
		String url = getBaseAddress() + path;
		int tout = 60000;
		if (timeout != null) {
			// units? seconds or millis?
			tout = (int) timeout.longValue();
		}
		InputStream is = null;
		OutputStream os = null;
		try {
			URL u = new URL(url);
			HttpURLConnection uc = (HttpURLConnection) u.openConnection();
			uc.setConnectTimeout(tout);
			uc.setReadTimeout(tout);
			if (headers == null)
				headers = new HashMap<String, String>();

			if (body != null) {
				headers.put("Content-type", "application/json");
			}
			// headers.put("Authorization", authorization);
			for (String n : headers.keySet()) {
				uc.setRequestProperty(n, headers.get(n));
				if (debug) {
					System.err.println("HTTP REQUEST header: " + n + " " + headers.get(n));
				}
			}
			uc.setRequestMethod(method);
			if (debug)
				System.err.println("HTTP REQUEST method: " + method + " " + uc.getRequestMethod());

			if (rawbody != null && rawbody.length > 0) {
				uc.setRequestProperty("Content-Length", Integer.toString(rawbody.length));
				uc.setFixedLengthStreamingMode(rawbody.length);
				uc.setDoOutput(true);
				os = uc.getOutputStream();
				os.write(rawbody);
			}
			int rc = uc.getResponseCode();
			this.responseCode = rc;
			if (rc < 200 || rc >= 300) {
				// do not throw an error - log the failure
				// throw new DockerHttpClientException("HTTP Request Failed:
				// URL: " + url + " code:" + rc + " msg:"
				// + uc.getResponseMessage());
				throw new RuntimeException("Docker HTTP Request Failed. URL: " + url + " code: " + rc + " msg: "
						+ uc.getResponseMessage());
			}

			// ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int i;
			is = uc.getInputStream();
			byte[] buf = new byte[65536];
			while ((i = is.read(buf)) > 0) {
				baos.write(buf, 0, i);
			}
		} catch (RuntimeException re) {
			throw re;
		} catch (Exception e) {
			logger.error("Exception <- " + e + " " + e.getMessage());
			throw new RuntimeException("http error: " + e, e);
		} finally {
			safeClose(os);
			safeClose(is);
		}
		return baos.toByteArray();
	}

	public String getBaseAddress() {
		return baseAddress;
	}

	public void setBaseAddress(String baseAddress) {
		this.baseAddress = baseAddress;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public void httpBinaryTransaction(String path, String method, HashMap<String, String> headers, InputStream i, int j) {
		// TODO Auto-generated method stub

	}

	public void httpJsonTransaction(String path, String method, HashMap<String, String> headers, InputStream i, int j) {
		// TODO Auto-generated method stub

	}
}