Added new feeds/sync API
[dmaap/dbcapi.git] / src / main / java / org / onap / dmaap / dbcapi / client / DrProvConnection.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dmaap
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  *
7  * Modifications Copyright (C) 2019 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.dmaap.dbcapi.client;
24
25 import org.onap.dmaap.dbcapi.logging.BaseLoggingClass;
26 import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum;
27 import org.onap.dmaap.dbcapi.model.ApiError;
28 import org.onap.dmaap.dbcapi.model.DR_Sub;
29 import org.onap.dmaap.dbcapi.model.Feed;
30 import org.onap.dmaap.dbcapi.service.DmaapService;
31 import org.onap.dmaap.dbcapi.util.DmaapConfig;
32
33 import javax.net.ssl.HttpsURLConnection;
34 import java.io.*;
35 import java.net.ConnectException;
36 import java.net.ProtocolException;
37 import java.net.SocketException;
38 import java.net.URL;
39 import java.util.Arrays;
40
41
42
43 public class DrProvConnection extends BaseLoggingClass {
44            
45    
46         private String provURL;
47         private String provApi;
48         private String  behalfHeader;
49         private String  feedContentType;
50         private String  subContentType;
51         private String unit_test;
52         private String  provURI;
53         
54         private HttpsURLConnection uc;
55
56
57         public DrProvConnection() {
58                 provURL = new DmaapService().getDmaap().getDrProvUrl();
59                 if ( provURL.length() < 1 ) {
60                         errorLogger.error( DmaapbcLogMessageEnum.PREREQ_DMAAP_OBJECT, "getDrProvUrl");
61                 }
62                 DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
63                 provApi = p.getProperty( "DR.provApi", "ONAP" );
64                 behalfHeader = p.getProperty( "DR.onBehalfHeader", "X-DMAAP-DR-ON-BEHALF-OF");
65                 feedContentType = p.getProperty( "DR.feedContentType", "application/vnd.dmaap-dr.feed");
66                 subContentType = p.getProperty( "DR.subContentType", "application/vnd.dmaap-dr.subscription");
67                 provURI = p.getProperty( "DR.ProvisioningURI", "/internal/prov");
68                 logger.info( "provURL=" + provURL + " provApi=" + provApi + " behalfHeader=" + behalfHeader
69                                 + " feedContentType=" + feedContentType + " subContentType=" + subContentType );
70                 unit_test = p.getProperty( "UnitTest", "No" );
71                         
72         }
73         
74         public boolean makeFeedConnection() {
75                 return makeConnection( provURL );
76         }
77         public boolean makeFeedConnection(String feedId) {
78                 return makeConnection( provURL + "/feed/" + feedId );   
79         }
80         public boolean makeSubPostConnection( String subURL ) {
81                 String[] parts = subURL.split("/");
82                 String revisedURL = provURL + "/" + parts[3] + "/" + parts[4];
83                 logger.info( "mapping " + subURL + " to " + revisedURL );
84                 return makeConnection( revisedURL );
85         }
86         public boolean makeSubPutConnection( String subId ) {
87                 String revisedURL = provURL + "/subs/" + subId;
88                 logger.info( "mapping " + subId + " to " + revisedURL );
89                 return makeConnection( revisedURL );
90         }
91
92         public boolean makeIngressConnection( String feed, String user, String subnet, String nodep ) {
93                 String uri = String.format("/internal/route/ingress/?feed=%s&user=%s&subnet=%s&nodepatt=%s", 
94                                         feed, user, subnet, nodep );
95                 return makeConnection( provURL + uri );
96         }
97         public boolean makeEgressConnection( String sub, String nodep ) {
98                 String uri = String.format("/internal/route/egress/?sub=%s&node=%s", 
99                                         sub,  nodep );
100                 return makeConnection( provURL + uri );
101         }
102         public boolean makeDumpConnection() {
103                 String url = provURL + provURI;
104                 return makeConnection( url );
105         }
106         public boolean makeNodesConnection( String varName ) {
107                 
108                 String uri = String.format("/internal/api/%s", varName);
109                 return makeConnection( provURL + uri );
110         }
111         
112         public boolean makeNodesConnection( String varName, String val ) {
113
114                 if ( val == null ) {
115                         return false;
116                 } 
117                 String cv = val.replaceAll("\\|", "%7C");
118                 String uri = String.format( "/internal/api/%s?val=%s", varName, cv );
119
120                 return makeConnection( provURL + uri );
121         }
122         
123         private boolean makeConnection( String pURL ) {
124         
125                 try {
126                         URL u = new URL( pURL );
127                         uc = (HttpsURLConnection) u.openConnection();
128                         uc.setInstanceFollowRedirects(false);
129                         logger.info( "successful connect to " + pURL );
130                         return(true);
131                 } catch (Exception e) {
132                         errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR,  pURL, e.getMessage() );
133             return(false);
134         }
135
136         }
137         
138         public String bodyToString( InputStream is ) {
139                 logger.info( "is=" + is );
140                 StringBuilder sb = new StringBuilder();
141                 BufferedReader br = new BufferedReader( new InputStreamReader(is));
142                 String line;
143                 try {
144                         while ((line = br.readLine()) != null ) {
145                                 sb.append( line );
146                         }
147                 } catch (IOException ex ) {
148                         errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION, ex.getMessage());
149                 }
150                         
151                 return sb.toString();
152         }
153         
154
155         public  String doPostFeed( Feed postFeed, ApiError err ) {
156
157                 byte[] postData = postFeed.getBytes();
158                 logger.info( "post fields=" + Arrays.toString(postData) );
159                 String responsemessage = null;
160                 String responseBody = null;
161
162                 try {
163                         logger.info( "uc=" + uc );
164                         uc.setRequestMethod("POST");
165                         uc.setRequestProperty("Content-Type", feedContentType);
166                         uc.setRequestProperty( "charset", "utf-8");
167                         uc.setRequestProperty( behalfHeader, postFeed.getOwner() );
168                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
169                         uc.setUseCaches(false);
170                         uc.setDoOutput(true);
171                         OutputStream os = null;
172                         int rc = -1;
173                         
174                         try {
175                  uc.connect();
176                  os = uc.getOutputStream();
177                  os.write( postData );
178
179             } catch (ProtocolException pe) {
180                  // Rcvd error instead of 100-Continue
181                  try {
182                      // work around glitch in Java 1.7.0.21 and likely others
183                      // without this, Java will connect multiple times to the server to run the same request
184                      uc.setDoOutput(false);
185                  } catch (Exception e) {
186                  }
187             }
188                         rc = uc.getResponseCode();
189                         logger.info( "http response code:" + rc );
190             responsemessage = uc.getResponseMessage();
191             logger.info( "responsemessage=" + responsemessage );
192
193
194             if (responsemessage == null) {
195                  // work around for glitch in Java 1.7.0.21 and likely others
196                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
197                  String h0 = uc.getHeaderField(0);
198                  if (h0 != null) {
199                      int i = h0.indexOf(' ');
200                      int j = h0.indexOf(' ', i + 1);
201                      if (i != -1 && j != -1) {
202                          responsemessage = h0.substring(j + 1);
203                      }
204                  }
205             }
206             if (rc == 201 ) {
207                         responseBody = bodyToString( uc.getInputStream() );
208                         logger.info( "responseBody=" + responseBody );
209
210             } else {
211                 err.setCode( rc );
212                 err.setMessage(responsemessage);
213             }
214             
215                 } catch (ConnectException ce) {
216                         errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
217             err.setCode( 500 );
218                 err.setMessage("Backend connection refused");
219                 } catch (SocketException se) {
220                         errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from prov server" );
221                         err.setCode( 500 );
222                         err.setMessage( "Unable to read response from DR");
223         } catch (Exception e) {
224                 if ( unit_test.equals( "Yes" ) ) {
225                                 err.setCode(200);
226                                 err.setMessage( "simulated response");
227                                 logger.info( "artificial 200 response from doPostFeed because unit_test =" + unit_test );
228                 } else {
229                     logger.warn("Unable to read response  " );
230                     errorLogger.error("Unable to read response  ", e.getMessage());
231                     try {
232                             err.setCode( uc.getResponseCode());
233                             err.setMessage(uc.getResponseMessage());
234                     } catch (Exception e2) {
235                         err.setCode( 500 );
236                         err.setMessage("Unable to determine response message");
237                     }
238                 }
239         } 
240                 finally {
241                         try {
242                                 uc.disconnect();
243                         } catch ( Exception e ) {
244                                 logger.error(e.getMessage(), e);
245                         }
246                 }
247                 return responseBody;
248
249         }
250
251         
252         // the POST for /internal/route/ingress doesn't return any data, so needs a different function
253         // the POST for /internal/route/egress doesn't return any data, so needs a different function   
254         public int doXgressPost( ApiError err ) {
255                 
256                 String responsemessage = null;
257                 int rc = -1;
258
259                 try {
260                         uc.setRequestMethod("POST");
261
262
263                         try {
264                  uc.connect();
265
266             } catch (ProtocolException pe) {
267                  // Rcvd error instead of 100-Continue
268                  try {
269                      // work around glitch in Java 1.7.0.21 and likely others
270                      // without this, Java will connect multiple times to the server to run the same request
271                      uc.setDoOutput(false);
272                  } catch (Exception e) {
273                         logger.error(e.getMessage(), e);
274                  }
275             }
276                         rc = uc.getResponseCode();
277                         logger.info( "http response code:" + rc );
278             responsemessage = uc.getResponseMessage();
279             logger.info( "responsemessage=" + responsemessage );
280
281
282
283             if (rc < 200 || rc >= 300 ) {
284                 err.setCode( rc );
285                 err.setMessage(responsemessage);
286             }
287                 } catch (Exception e) {
288                 if ( unit_test.equals( "Yes" ) ) {
289                                 err.setCode(200);
290                                 err.setMessage( "simulated response");
291                                 logger.info( "artificial 200 response from doXgressPost because unit_test =" + unit_test );
292                 } else {
293                     logger.error("Unable to read response  " );
294                     logger.error(e.getMessage(), e);
295                 }
296         }               
297         finally {
298                         try {
299                                 uc.disconnect();
300                         } catch ( Exception e ) {
301                                 logger.error(e.getMessage(), e);
302                         }
303                 }
304         
305                 return rc;
306
307         }
308         
309         public String doPostDr_Sub( DR_Sub postSub, ApiError err ) {
310                 logger.info( "entry: doPostDr_Sub() "  );
311                 byte[] postData = postSub.getBytes(provApi );
312                 logger.info( "post fields=" + postData );
313                 String responsemessage = null;
314                 String responseBody = null;
315
316                 try {
317         
318                         uc.setRequestMethod("POST");
319                 
320                         uc.setRequestProperty("Content-Type", subContentType );
321                         uc.setRequestProperty( "charset", "utf-8");
322                         uc.setRequestProperty( behalfHeader, "DGL" );
323                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
324                         uc.setUseCaches(false);
325                         uc.setDoOutput(true);
326                         OutputStream os = null;
327                         int rc = -1;
328                         
329                         try {
330                  uc.connect();
331                  os = uc.getOutputStream();
332                  os.write( postData );
333
334             } catch (ProtocolException pe) {
335                  // Rcvd error instead of 100-Continue
336                  try {
337                      // work around glitch in Java 1.7.0.21 and likely others
338                      // without this, Java will connect multiple times to the server to run the same request
339                      uc.setDoOutput(false);
340                  } catch (Exception e) {
341                          logger.error(e.getMessage(), e);
342                  }
343             }
344                         rc = uc.getResponseCode();
345                         logger.info( "http response code:" + rc );
346             responsemessage = uc.getResponseMessage();
347             logger.info( "responsemessage=" + responsemessage );
348
349
350             if (responsemessage == null) {
351                  // work around for glitch in Java 1.7.0.21 and likely others
352                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
353                  String h0 = uc.getHeaderField(0);
354                  if (h0 != null) {
355                      int i = h0.indexOf(' ');
356                      int j = h0.indexOf(' ', i + 1);
357                      if (i != -1 && j != -1) {
358                          responsemessage = h0.substring(j + 1);
359                      }
360                  }
361             }
362             if (rc == 201 ) {
363                         responseBody = bodyToString( uc.getInputStream() );
364                         logger.info( "responseBody=" + responseBody );
365
366             } else {
367                 err.setCode(rc);
368                 err.setMessage(responsemessage);
369             }
370             
371                 } catch (Exception e) {
372                 if ( unit_test.equals( "Yes" ) ) {
373                                 err.setCode(200);
374                                 err.setMessage( "simulated response");
375                                 logger.info( "artificial 200 response from doPostDr_Sub because unit_test =" + unit_test );
376                 } else {
377                     logger.error("Unable to read response  ", e.getMessage());
378                 }
379         }               
380                 finally {
381                         try {
382                                 uc.disconnect();
383                         } catch ( Exception e ) {
384                                 logger.error(e.getMessage(), e);
385                         }
386                 }
387                 return responseBody;
388
389         }
390         
391
392         public String doPutFeed(Feed putFeed, ApiError err) {
393                 byte[] postData = putFeed.getBytes();
394                 logger.info( "post fields=" + Arrays.toString(postData) );
395                 String responsemessage = null;
396                 String responseBody = null;
397
398                 try {
399                         logger.info( "uc=" + uc );
400                         uc.setRequestMethod("PUT");
401                         uc.setRequestProperty("Content-Type", feedContentType );
402                         uc.setRequestProperty( "charset", "utf-8");
403                         uc.setRequestProperty( behalfHeader, putFeed.getOwner() );
404                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
405                         uc.setUseCaches(false);
406                         uc.setDoOutput(true);
407                         OutputStream os = null;
408                         int rc = -1;
409                         
410                         try {
411                  uc.connect();
412                  os = uc.getOutputStream();
413                  os.write( postData );
414
415             } catch (ProtocolException pe) {
416                  // Rcvd error instead of 100-Continue
417                  try {
418                      // work around glitch in Java 1.7.0.21 and likely others
419                      // without this, Java will connect multiple times to the server to run the same request
420                      uc.setDoOutput(false);
421                  } catch (Exception e) {
422                          logger.error(e.getMessage(), e);
423                  }
424             }
425                         rc = uc.getResponseCode();
426                         logger.info( "http response code:" + rc );
427             responsemessage = uc.getResponseMessage();
428             logger.info( "responsemessage=" + responsemessage );
429
430
431             if (responsemessage == null) {
432                  // work around for glitch in Java 1.7.0.21 and likely others
433                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
434                  String h0 = uc.getHeaderField(0);
435                  if (h0 != null) {
436                      int i = h0.indexOf(' ');
437                      int j = h0.indexOf(' ', i + 1);
438                      if (i != -1 && j != -1) {
439                          responsemessage = h0.substring(j + 1);
440                      }
441                  }
442             }
443             if (rc >= 200 && rc < 300 ) {
444                         responseBody = bodyToString( uc.getInputStream() );
445                         logger.info( "responseBody=" + responseBody );
446                         err.setCode( rc );
447             } else if ( rc == 404 ) {
448                 err.setCode( rc );
449                 err.setFields( "feedid");
450                 String message =  "FeedId " + putFeed.getFeedId() + " not found on DR to update.  Out-of-sync condition?";
451                 err.setMessage( message );
452                 errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() );
453                 
454             } else {
455                 err.setCode( rc );
456                 err.setMessage(responsemessage);
457             }
458             
459                 } catch (ConnectException ce) {
460                         errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
461             err.setCode( 500 );
462                 err.setMessage("Backend connection refused");
463                 } catch (SocketException se) {
464                         errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" );
465                         err.setCode( 500 );
466                         err.setMessage( "Unable to read response from DR");
467         } catch (Exception e) {
468                 if ( unit_test.equals( "Yes" ) ) {
469                                 err.setCode(200);
470                                 err.setMessage( "simulated response");
471                                 logger.info( "artificial 200 response from doPutFeed because unit_test =" + unit_test );
472                 } else {
473                     logger.warn("Unable to read response  " );
474                     logger.error(e.getMessage(), e);
475                 }
476             try {
477                     err.setCode( uc.getResponseCode());
478                     err.setMessage(uc.getResponseMessage());
479             } catch (Exception e2) {
480                 err.setCode( 500 );
481                 err.setMessage("Unable to determine response message");
482                 logger.error(e2.getMessage(), e2);
483             }
484         }               finally {
485                         try {
486                                 uc.disconnect();
487                         } catch ( Exception e ) {
488                                 logger.error(e.getMessage(), e);
489                         }
490                 }
491                 return responseBody;
492         }
493         public String doPutDr_Sub(DR_Sub postSub, ApiError err) {
494                 logger.info( "entry: doPutDr_Sub() "  );
495                 byte[] postData = postSub.getBytes(provApi);
496                 logger.info( "post fields=" + postData );
497                 String responsemessage = null;
498                 String responseBody = null;
499
500                 try {
501         
502                         uc.setRequestMethod("PUT");
503                 
504                         uc.setRequestProperty("Content-Type", subContentType );
505                         uc.setRequestProperty( "charset", "utf-8");
506                         uc.setRequestProperty( behalfHeader, "DGL" );
507                         uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
508                         uc.setUseCaches(false);
509                         uc.setDoOutput(true);
510                         OutputStream os = null;
511                         int rc = -1;
512                         
513                         try {
514                  uc.connect();
515                  os = uc.getOutputStream();
516                  os.write( postData );
517
518             } catch (ProtocolException pe) {
519                  // Rcvd error instead of 100-Continue
520                  try {
521                      // work around glitch in Java 1.7.0.21 and likely others
522                      // without this, Java will connect multiple times to the server to run the same request
523                      uc.setDoOutput(false);
524                  } catch (Exception e) {
525                          logger.error(e.getMessage(), e);
526                  }
527             }
528                         rc = uc.getResponseCode();
529                         logger.info( "http response code:" + rc );
530             responsemessage = uc.getResponseMessage();
531             logger.info( "responsemessage=" + responsemessage );
532
533
534             if (responsemessage == null) {
535                  // work around for glitch in Java 1.7.0.21 and likely others
536                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
537                  String h0 = uc.getHeaderField(0);
538                  if (h0 != null) {
539                      int i = h0.indexOf(' ');
540                      int j = h0.indexOf(' ', i + 1);
541                      if (i != -1 && j != -1) {
542                          responsemessage = h0.substring(j + 1);
543                      }
544                  }
545             }
546             if (rc == 200 ) {
547                         responseBody = bodyToString( uc.getInputStream() );
548                         logger.info( "responseBody=" + responseBody );
549
550             } else {
551                 err.setCode(rc);
552                 err.setMessage(responsemessage);
553             }
554             
555                 } catch (ConnectException ce) {
556             errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
557             err.setCode( 500 );
558                 err.setMessage("Backend connection refused");
559                 logger.error(ce.getMessage(), ce);
560                 } catch (Exception e) {
561                 if ( unit_test.equals( "Yes" ) ) {
562                                 err.setCode(200);
563                                 err.setMessage( "simulated response");
564                                 logger.info( "artificial 200 response from doPutDr_Sub because unit_test =" + unit_test );
565                 } else {
566                     logger.error("Unable to read response  " );
567                     logger.error(e.getMessage(), e);
568                 }
569         } finally {
570                 if(null != uc){
571                     uc.disconnect();
572                 }
573         }
574                 return responseBody;
575
576         }
577         
578         public String doGetNodes( ApiError err ) {
579                 logger.info( "entry: doGetNodes() "  );
580                 //byte[] postData = postSub.getBytes();
581                 //logger.info( "get fields=" + postData );
582                 String responsemessage = null;
583                 String responseBody = null;
584
585                 try {
586         
587                         uc.setRequestMethod("GET");
588                         int rc = -1;
589                         
590
591                         try {
592                 uc.connect();
593         
594
595             } catch (ProtocolException pe) {
596
597                  // Rcvd error instead of 100-Continue
598                  try {
599                      // work around glitch in Java 1.7.0.21 and likely others
600                      // without this, Java will connect multiple times to the server to run the same request
601                      uc.setDoOutput(false);
602                  } catch (Exception e) {
603                          logger.error(e.getMessage(), e);
604                  }
605             } 
606         
607                         rc = uc.getResponseCode();
608                         logger.info( "http response code:" + rc );
609             responsemessage = uc.getResponseMessage();
610             logger.info( "responsemessage=" + responsemessage );
611         
612
613
614             if (responsemessage == null) {
615
616                  // work around for glitch in Java 1.7.0.21 and likely others
617                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
618                  String h0 = uc.getHeaderField(0);
619                  if (h0 != null) {
620                      int i = h0.indexOf(' ');
621                      int j = h0.indexOf(' ', i + 1);
622                      if (i != -1 && j != -1) {
623                          responsemessage = h0.substring(j + 1);
624                      }
625                  }
626             }
627         
628                 err.setCode(rc);  // may not really be an error, but we save rc
629             if (rc == 200 ) {
630                         responseBody = bodyToString( uc.getInputStream() );
631                         logger.info( "responseBody=" + responseBody );
632             } else {
633                 err.setMessage(responsemessage);
634             }
635             
636
637                 } catch (ConnectException ce) {
638         
639             errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
640             err.setCode( 500 );
641                 err.setMessage("Backend connection refused");
642                 logger.error(ce.getMessage(), ce);
643                 } catch (Exception e) {
644                 if ( unit_test.equals( "Yes" ) ) {
645                                 err.setCode(200);
646                                 err.setMessage( "simulated response");
647                                 logger.info( "artificial 200 response from doGetNodes because unit_test =" + unit_test );
648                 } else {
649                     logger.error("Unable to read response  ", e.getMessage());
650                 }
651         } finally {
652
653                         if ( uc != null ) uc.disconnect();
654         }
655
656                 return responseBody;
657
658         }
659         public String doPutNodes( ApiError err ) {
660                 logger.info( "entry: doPutNodes() "  );
661                 //byte[] postData = nodeList.getBytes();
662                 //logger.info( "get fields=" + postData );
663                 String responsemessage = null;
664                 String responseBody = null;
665
666                 try {
667         
668                         uc.setRequestMethod("PUT");
669                 
670                         //uc.setRequestProperty("Content-Type", subContentType );
671                         //uc.setRequestProperty( "charset", "utf-8");
672                         //uc.setRequestProperty( behalfHeader, "DGL" );
673                         //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
674                         uc.setUseCaches(false);
675                         //uc.setDoOutput(true);
676                         OutputStream os = null;
677                         int rc = -1;
678                         
679                         try {
680                  uc.connect();
681                  //os = uc.getOutputStream();
682                  //os.write( postData );
683
684             } catch (ProtocolException pe) {
685                  // Rcvd error instead of 100-Continue
686                  try {
687                      // work around glitch in Java 1.7.0.21 and likely others
688                      // without this, Java will connect multiple times to the server to run the same request
689                      uc.setDoOutput(false);
690                  } catch (Exception e) {
691                  }
692             }
693                         rc = uc.getResponseCode();
694                         logger.info( "http response code:" + rc );
695             responsemessage = uc.getResponseMessage();
696             logger.info( "responsemessage=" + responsemessage );
697
698
699             if (responsemessage == null) {
700                  // work around for glitch in Java 1.7.0.21 and likely others
701                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
702                  String h0 = uc.getHeaderField(0);
703                  if (h0 != null) {
704                      int i = h0.indexOf(' ');
705                      int j = h0.indexOf(' ', i + 1);
706                      if (i != -1 && j != -1) {
707                          responsemessage = h0.substring(j + 1);
708                      }
709                  }
710             }
711                 err.setCode(rc);
712             if (rc == 200 ) {
713                         responseBody = bodyToString( uc.getInputStream() );
714                         logger.info( "responseBody=" + responseBody );
715
716             } else {
717   
718                 err.setMessage(responsemessage);
719             }
720             
721                 } catch (Exception e) {
722                 if ( unit_test.equals( "Yes" ) ) {
723                                 err.setCode(200);
724                                 err.setMessage( "simulated response");
725                                 logger.info( "artificial 200 response from doPutNodes because unit_test =" + unit_test );
726                 } else {
727                     logger.error("Unable to read response  ", e.getMessage());
728                 }
729         } finally {
730                         if ( uc != null ) {
731                         uc.disconnect();
732                         }
733         }
734                 return responseBody;
735
736         }
737         
738         public String doDeleteFeed(Feed putFeed, ApiError err) {
739                 //byte[] postData = putFeed.getBytes();
740                 //logger.info( "post fields=" + postData.toString() );
741                 String responsemessage = null;
742                 String responseBody = null;
743
744                 try {
745                         logger.info( "uc=" + uc );
746                         uc.setRequestMethod("DELETE");
747                         uc.setRequestProperty("Content-Type", feedContentType );
748                         uc.setRequestProperty( "charset", "utf-8");
749                         uc.setRequestProperty( behalfHeader, putFeed.getOwner() );
750                         //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
751                         uc.setUseCaches(false);
752                         uc.setDoOutput(true);
753                         OutputStream os = null;
754                         int rc = -1;
755                         
756                         try {
757                  uc.connect();
758                  os = uc.getOutputStream();
759                  //os.write( postData );
760
761             } catch (ProtocolException pe) {
762                  // Rcvd error instead of 100-Continue
763                  try {
764                      // work around glitch in Java 1.7.0.21 and likely others
765                      // without this, Java will connect multiple times to the server to run the same request
766                      uc.setDoOutput(false);
767                  } catch (Exception e) {
768                          logger.error(e.getMessage(), e);
769                  }
770             }
771                         rc = uc.getResponseCode();
772                         logger.info( "http response code:" + rc );
773             responsemessage = uc.getResponseMessage();
774             logger.info( "responsemessage=" + responsemessage );
775
776
777             if (responsemessage == null) {
778                  // work around for glitch in Java 1.7.0.21 and likely others
779                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
780                  String h0 = uc.getHeaderField(0);
781                  if (h0 != null) {
782                      int i = h0.indexOf(' ');
783                      int j = h0.indexOf(' ', i + 1);
784                      if (i != -1 && j != -1) {
785                          responsemessage = h0.substring(j + 1);
786                      }
787                  }
788             }
789             if (rc >= 200 && rc < 300 ) {
790                         responseBody = bodyToString( uc.getInputStream() );
791                         logger.info( "responseBody=" + responseBody );
792
793             } else if ( rc == 404 ) {
794                 err.setCode( rc );
795                 err.setFields( "feedid");
796                 String message =  "FeedId " + putFeed.getFeedId() + " not found on DR to update.  Out-of-sync condition?";
797                 err.setMessage( message );
798                 errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() );
799                 
800             } else {
801                 err.setCode( rc );
802                 err.setMessage(responsemessage);
803             }
804             
805                 } catch (ConnectException ce) {
806                         errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
807             err.setCode( 500 );
808                 err.setMessage("Backend connection refused");
809                 logger.error(ce.getMessage(), ce);
810                 } catch (SocketException se) {
811                         errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" );
812                         err.setCode( 500 );
813                         err.setMessage( "Unable to read response from DR");
814                         logger.error(se.getMessage(), se);
815         } catch (Exception e) {
816                 if ( unit_test.equals( "Yes" ) ) {
817                                 err.setCode(200);
818                                 err.setMessage( "simulated response");
819                                 logger.info( "artificial 200 response from doDeleteFeed because unit_test =" + unit_test );
820                 } else {
821                     logger.warn("Unable to read response  " );
822                     logger.error(e.getMessage(), e);
823                     try {
824                             err.setCode( uc.getResponseCode());
825                             err.setMessage(uc.getResponseMessage());
826                     } catch (Exception e2) {
827                         err.setCode( 500 );
828                         err.setMessage("Unable to determine response message");
829                         logger.error(e2.getMessage(), e2);
830                     }
831                 }
832         }               finally {
833                         try {
834                                 if(uc != null) {
835                                     uc.disconnect();
836                                 }
837                         } catch ( Exception e ) {
838                                 logger.error(e.getMessage(), e);
839                         }
840                 }
841                 return responseBody;
842         }
843         
844         public String doDeleteDr_Sub(DR_Sub delSub, ApiError err) {
845                 logger.info( "entry: doDeleteDr_Sub() "  );
846                 byte[] postData = delSub.getBytes(provApi);
847                 logger.info( "post fields=" + postData );
848                 String responsemessage = null;
849                 String responseBody = null;
850
851                 try {
852         
853                         uc.setRequestMethod("DELETE");
854                 
855                         uc.setRequestProperty("Content-Type", subContentType);
856                         uc.setRequestProperty( "charset", "utf-8");
857                         uc.setRequestProperty( behalfHeader, "DGL" );
858                         //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
859                         uc.setUseCaches(false);
860                         uc.setDoOutput(true);
861                         OutputStream os = null;
862                         int rc = -1;
863                         
864                         try {
865                  uc.connect();
866                  os = uc.getOutputStream();
867                  //os.write( postData );
868
869             } catch (ProtocolException pe) {
870                  // Rcvd error instead of 100-Continue
871                  try {
872                      // work around glitch in Java 1.7.0.21 and likely others
873                      // without this, Java will connect multiple times to the server to run the same request
874                      uc.setDoOutput(false);
875                  } catch (Exception e) {
876                          logger.error(e.getMessage(), e);
877                  }
878             }
879                         rc = uc.getResponseCode();
880                         logger.info( "http response code:" + rc );
881             responsemessage = uc.getResponseMessage();
882             logger.info( "responsemessage=" + responsemessage );
883
884
885             if (responsemessage == null) {
886                  // work around for glitch in Java 1.7.0.21 and likely others
887                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
888                  String h0 = uc.getHeaderField(0);
889                  if (h0 != null) {
890                      int i = h0.indexOf(' ');
891                      int j = h0.indexOf(' ', i + 1);
892                      if (i != -1 && j != -1) {
893                          responsemessage = h0.substring(j + 1);
894                      }
895                  }
896             }
897                 err.setCode(rc);
898             if (rc == 204 ) {
899                         responseBody = bodyToString( uc.getInputStream() );
900                         logger.info( "responseBody=" + responseBody );
901             } else {
902                 err.setMessage(responsemessage);
903             }
904             
905                 } catch (ConnectException ce) {
906                 if ( unit_test.equals( "Yes" ) ) {
907                                 err.setCode(200);
908                                 err.setMessage( "simulated response");
909                                 logger.info( "artificial 200 response from doDeleteDr_Sub because unit_test =" + unit_test );
910                 } else {
911                     errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
912                     err.setCode( 500 );
913                         err.setMessage("Backend connection refused");
914                 }
915                 } catch (Exception e) {
916                 if ( unit_test.equals( "Yes" ) ) {
917                                 err.setCode(200);
918                                 err.setMessage( "simulated response");
919                                 logger.info( "artificial 200 response from doDeleteDr_Sub because unit_test =" + unit_test );
920                 } else {
921                     logger.error("Unable to read response  ", e.getMessage());
922                 }
923         } finally {
924                 if(uc != null){
925                     uc.disconnect();
926                 }
927         }
928                 return responseBody;
929
930         }
931         
932         // add double-quotes around a value
933         // hope his is easier to read than in-line escaping...
934         private String dq( String v ) {
935                 return ( "\"" + v + "\"");
936         }
937         private String dq( String k, String v) {
938                 return( dq(k) + ":" + dq(v));
939         }
940         private String dqc( String k, String v) {
941                 return( dq(k) + ":" + dq(v) + ",");
942         }
943         
944         private String dumpSimulation() {
945                 logger.info( "enter dumpSimulation()");
946                 String                                  responseBody = 
947                                 "{"
948                                 + dq("feeds") + ":["
949                                 + "{" + dq( "suspend") + ":false,"
950                                           + dq( "groupid") + ":0,"
951                                           + dqc( "description", "Some description" )
952                                           + dqc( "version", "m1.1") 
953                                           + dq( "authorization") + ":"
954                                           + "{" + dq( "endpoint_addrs" ) + ":[],"
955                                                         + dq( "classification", "unclassified")
956                                                         + dq( "endpoint_ids") + ":[{"
957                                                                 + dqc( "password", "dradmin" )
958                                                                 + dq( "id", "dradmin")
959                                                                 + "}]}"
960                                                 + dq( "last_mod") + ":1553738110000,"
961                                                 + dq( "deleted") + ":false,"
962                                                 + dq( "feedid") + ":1,"
963                                                 + dqc( "name", "Default PM Feed")
964                                                 + dq( "business_description") + ":\"\","
965                                                 + dqc( "publisher", "onap")
966                                                 + dq( "links") + ":{"
967                                                         + dqc( "subscribe", "https://dmaap-dr-prov/subscribe/1")
968                                                         + dqc( "log", "https://dmaap-dr-prov/feedlog/1")
969                                                         + dqc( "publish", "https://dmaap-dr-prov/publish/1")
970                                                         + dq( "self", "https:/dmaap-dr-prov/feed/1")
971                                                         + "}"
972                                                 + dq( "created_date") + ":1553738110000 }"
973                                 + "],"
974                                 + dq( "groups") + ":["
975                                 + "],"
976                                 + dq( "subscriptions") + ":["
977                                 + "],"
978                                 + dq( "ingress") + ":["
979                                 + "],"
980                                 + dq( "egress") + ":{"
981                                 + "},"
982                                 + dq( "routing") + ":["
983                                 + "],"
984                           + "}";
985                 return responseBody;
986         }
987         
988         public String doGetDump( ApiError err ) {
989                 logger.info( "entry: doGetDump() "  );
990
991                 String responsemessage = null;
992                 String responseBody = null;
993
994                 try {
995         
996                         uc.setRequestMethod("GET");
997                         int rc = -1;
998                         
999
1000                         try {
1001                 uc.connect();
1002         
1003
1004             } catch (ProtocolException pe) {
1005
1006                  // Rcvd error instead of 100-Continue
1007                  try {
1008                      // work around glitch in Java 1.7.0.21 and likely others
1009                      // without this, Java will connect multiple times to the server to run the same request
1010                      uc.setDoOutput(false);
1011                  } catch (Exception e) {
1012                          logger.error(e.getMessage(), e);
1013                  }
1014             } 
1015         
1016                         rc = uc.getResponseCode();
1017                         logger.info( "http response code:" + rc );
1018             responsemessage = uc.getResponseMessage();
1019             logger.info( "responsemessage=" + responsemessage );
1020         
1021
1022
1023             if (responsemessage == null) {
1024
1025                  // work around for glitch in Java 1.7.0.21 and likely others
1026                  // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
1027                  String h0 = uc.getHeaderField(0);
1028                  if (h0 != null) {
1029                      int i = h0.indexOf(' ');
1030                      int j = h0.indexOf(' ', i + 1);
1031                      if (i != -1 && j != -1) {
1032                          responsemessage = h0.substring(j + 1);
1033                      }
1034                  }
1035             }
1036         
1037                 err.setCode(rc);  // may not really be an error, but we save rc
1038             if (rc == 200 ) {
1039                         responseBody = bodyToString( uc.getInputStream() );
1040                         logger.info( "responseBody=" + responseBody );
1041             } else {
1042                 err.setMessage(responsemessage);
1043             }
1044             
1045
1046                 } catch (ConnectException ce) {
1047                 if ( unit_test.equals( "Yes" ) ) {
1048                                 err.setCode(200);
1049                                 err.setMessage( "simulated response");
1050                                 logger.info( "artificial 200 response from doGetNodes because unit_test =" + unit_test );
1051                                 responseBody = dumpSimulation();
1052                                                           
1053                 } else {
1054                     errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
1055                     err.setCode( 500 );
1056                         err.setMessage("Backend connection refused");
1057                         logger.error(ce.getMessage(), ce);
1058                 }
1059                 } catch (Exception e) {
1060                 if ( unit_test.equals( "Yes" ) ) {
1061                                 err.setCode(200);
1062                                 err.setMessage( "simulated response");
1063                                 logger.info( "artificial 200 response from doGetNodes because unit_test =" + unit_test );
1064                                 responseBody = dumpSimulation();
1065                                                           
1066                 } else {
1067                     logger.error("Unable to read response  ", e.getMessage());
1068                 }
1069         } finally {
1070
1071                         if ( uc != null ) uc.disconnect();
1072         }
1073
1074                 return responseBody;
1075
1076         }
1077                 
1078 }