94a0d83ec3259f42576d41d1654ec6d999512621
[vtn.git] /
1 /**
2  * Copyright (c) 2014 NEC Corporation
3  * All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this
7  * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.vtn.app.run.config.rest.parser;
11
12 import java.net.ConnectException;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 import org.json.JSONException;
20 import org.json.JSONObject;
21
22 import com.sun.jersey.api.client.Client;
23 import com.sun.jersey.api.client.ClientResponse;
24 import com.sun.jersey.api.client.ClientHandlerException;
25 import com.sun.jersey.api.client.WebResource;
26 import com.sun.jersey.api.client.WebResource.Builder;
27 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
28 import org.opendaylight.vtn.app.run.config.rest.client.CRUDOperation;
29 import org.opendaylight.vtn.app.run.config.rest.client.VTNClientException;
30 import org.opendaylight.vtn.app.run.config.rest.enumgroups.APPLICATION_TYPE;
31 import org.opendaylight.vtn.app.run.config.rest.enumgroups.HTTP_RESPONSE;
32
33 public class CRUDImpl implements CRUDOperation {
34
35     /**
36      * Logger instance.
37      */
38     static final Logger LOG = LoggerFactory.getLogger(CRUDImpl.class);
39
40     private Client client = null;
41
42     public static final String HTTP_STATUS_DESCR  = "response_description";
43     public static final String HTTP_STATUS  = "response_status";
44     private APPLICATION_TYPE appType = null;
45     private String userName;
46     private String password;
47
48     /**
49      * CRUDImpl - constructor with arguments.
50      * @param appType - content type of the http response.
51      * @param userName - username of the controller to connect to the server.
52      * @param password - password of the controller to connect to the server.
53      */
54     public CRUDImpl(APPLICATION_TYPE appType, String userName, String password) {
55         this.appType = appType;
56         this.client = Client.create();
57         this.userName = userName;
58         this.password = password;
59         this.client.addFilter(new HTTPBasicAuthFilter(userName, password));
60     }
61
62     /**
63      * Get the Jersey client
64      * @return
65      *         Client instance
66      */
67     private Client getClient() {
68         return this.client;
69     }
70
71     /**
72      * Create the web resource with the URL
73      * @param url
74      *         URL
75      * @param headers
76      *         Headers
77      * @return
78      *         Web resource instance
79      */
80     protected Builder getWebResource(String url, Map<String, String> queryParams, Map<String, Object> headers) {
81         WebResource webResource = getClient().resource(url);
82
83         /*
84          * Set query parameters
85          */
86         if (queryParams != null) {
87             for (Entry<String, String> entry: queryParams.entrySet()) {
88                 webResource.queryParam(entry.getKey(), entry.getValue());
89             }
90         }
91
92         /*
93          * Set request headers
94          */
95         Builder builder = null;
96         if (headers != null) {
97             for (Entry<String, Object> entry: headers.entrySet()) {
98                 if (builder == null) {
99                     builder = webResource.header(entry.getKey(), entry.getValue());
100                 } else {
101                     builder = builder.header(entry.getKey(), entry.getValue());
102                 }
103             }
104         }
105         return (builder != null ? builder : webResource.getRequestBuilder());
106     }
107
108     /**
109      * To create a JSON object for a particular HTTP response
110      * @param response
111      *         HTTP_RESPONSE
112      * @return
113      *         JSONObject
114      * @throws JSONException
115      */
116     private JSONObject getHttpResponseObject(HTTP_RESPONSE response) throws JSONException {
117         JSONObject object = new JSONObject();
118         object.put(HTTP_STATUS_DESCR, response.getDescription());
119         object.put(HTTP_STATUS, response.getStatus());
120         return object;
121     }
122
123     /**
124      * Send a GET request
125      * @param url
126      *         URL
127      * @return
128      *         Response as String
129      * @throws VTNClientException if request does not return 'success'
130      * @throws JSONException
131      * @throws ConnectException
132      */
133     public String doGET(String url, Map<String, Object> headers) throws VTNClientException, JSONException, ConnectException {
134         try {
135             ClientResponse response = getWebResource(url, null, headers).accept(appType.getType()).get(ClientResponse.class);
136             if (response.getStatus() == HTTP_RESPONSE.NO_CONTENT.getStatus()) {
137                 return getHttpResponseObject(HTTP_RESPONSE.NO_CONTENT).toString();
138             } else {
139                 if (response.getStatus() == HTTP_RESPONSE.UNAUTHORIZED.getStatus()) {
140                     LOG.error("Unauthorized access :HTTP error code : {}", response.getStatus());
141                     LOG.error(getHttpResponseObject(HTTP_RESPONSE.UNAUTHORIZED).toString());
142                     throw new VTNClientException("\n\nFailed to connect to ODL Controller due to unauthorized access..."
143                                                     + "\nPlease check Username/Password...");
144                 } else if (response.getStatus() != HTTP_RESPONSE.OPERATION_SUCCESS.getStatus()) {
145                     LOG.error("GET RequestFailed :HTTP error code : {}", response.getStatus());
146                     throw new VTNClientException("\n\nPage not found - " + response.getStatus());
147                 }
148                 return response.getEntity(String.class);
149             }
150         } catch (ClientHandlerException e) {
151             LOG.error("An exception occured - ", e);
152             throw new VTNClientException("\n\nFailed to connect to ODL Controller..."
153                                                     + "\nPlease check Controller is running or IP address/Port number is incorrect...");
154         }
155     }
156
157     /**
158      * Send a POST request
159      * @param url
160      *         URL
161      * @param obj
162      *         Object to send along POST request
163      * @param headers
164      *         Headers
165      * @return
166      *         Response as String
167      * @throws VTNClientException if request does not return 'success'
168      * @throws JSONException
169      */
170     public String doPOST(String url, Object obj, Map<String, Object> headers) throws VTNClientException, ConnectException, JSONException {
171         return "";
172     }
173
174     /**
175      * Send a PUT request
176      * @param url
177      *         URL
178      * @param obj
179      *         Object to send along PUT request
180      * @param headers
181      *         Headers
182      * @return
183      *         Response as String
184      * @throws VTNClientException if request does not return 'success'
185      * @throws JSONException
186      */
187     public String doPUT(String url, Object obj, Map<String, Object> headers) throws VTNClientException, ConnectException, JSONException {
188         return "";
189     }
190
191     /**
192      * Send a DELETE request
193      * @param url
194      *         URL
195      * @param obj
196      *         Object to send along DELETE request
197      * @param headers
198      *         Headers
199      * @return
200      *         Response as String
201      * @throws VTNClientException if request does not return 'success'
202      * @throws JSONException
203      */
204     public String doDELETE(String url, Object obj, Map<String, Object> headers) throws VTNClientException, ConnectException, JSONException {
205         return "";
206     }
207 }