aboutsummaryrefslogtreecommitdiffstats
path: root/ajsc-aai/src/main/java/org/openecomp/aai/util/RelationshipPutDel.java
blob: 7a8af118a3e9dc1b33c49deb7b3cfa38cb1a55eb (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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*-
 * ============LICENSE_START=======================================================
 * org.openecomp.aai
 * ================================================================================
 * 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.aai.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyManagementException;
import java.util.Properties;
import java.util.UUID;

import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.logging.AAILogger;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.logging.LogLine;
import org.openecomp.aai.domain.yang.Relationship;
import com.att.eelf.configuration.Configuration;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;


public class RelationshipPutDel {
	
	private static 	final  String    COMPONENT = "aairestctrl";
	private static 	final  String    FROMAPPID = "AAI-TOOLS";
	private static 	final  String    TRANSID   = UUID.randomUUID().toString();
	private static AAILogger aaiLogger = null;
	
	private static final String USAGE_STRING = "Usage: rshipTool.sh <PUT|DELETE> <resource-path> <filename>\n" +
			"resource-path for a particular resource starting after the aai/<version>, relationship-list/relationship gets added by script\n" +
			"filename is the path to a file which contains the json input for the relationship payload" +
			"for example: relTool.sh PUT cloud-infrastructure/oam-networks/oam-network/test-100-oam /tmp/putrship.json\n";
	
	/**
	 * The main method.
	 *
	 * @param args the arguments
	 */
	public static void main(String[] args) {

		// Set the logging file properties to be used by EELFManager
		Properties props = System.getProperties();
		props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_RSHIPTOOL_LOGBACK_PROPS);
		props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES);		
		
		aaiLogger = new AAILogger(RelationshipPutDel.class.getName());
		LogLine   logline = new LogLine();
		LogLine   glogline = new LogLine();
		logline.init(COMPONENT, TRANSID, FROMAPPID, "main");
		aaiLogger.debug(logline, "Start processing...");
		String rshipURL, resURL = null;
		Relationship rship = null;
		
		try {
			if ((args.length < 3) || (!args[0].equalsIgnoreCase("PUT") && !args[0].equalsIgnoreCase("DELETE"))) {
				System.out.println("Insufficient or Invalid arguments");
				System.out.println(USAGE_STRING);
				logline.add("msg",  "Insufficient or Invalid arguments");
				aaiLogger.info(logline, true, "0");
				System.exit(1);
			} 
			
			rship = readJsonFile(args[2]);
			
			// Assume the config AAI_SERVER_URL has a last slash so remove if  
			//  resource-path has it as the first char
			resURL = args[1].replaceFirst("^/", "");
			resURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + resURL;
			rshipURL = resURL.concat("/relationship-list/relationship");

			logline.add("rshipURL", rshipURL);
			logline.add("action", args[0]);
			System.out.println("Resource URL=" + rshipURL);
			
			PutDelRelationship(aaiLogger, logline, rshipURL, rship, args[0]);
			
			logline.add("rel", rship.getRelatedTo());
			System.out.println(args[0] + " Relationship succeeded to: " + rship.getRelatedTo() + "\n");
			
			GetResource.getNode(aaiLogger, glogline, resURL);
			System.out.println("\nDone!!");
			
			aaiLogger.info(logline, true, "0");
			System.exit(0);

		} catch (AAIException e) {
			System.out.println(args[0] + " Relationship PUT/DELETE failed: " + e.getMessage());
			aaiLogger.error(e.getErrorObject(), logline, e);
			aaiLogger.info(logline, false, e.getErrorObject().getErrorCodeString());
			System.exit(1);	
		} catch (Exception e) {
			System.out.println(args[0] + " Relationship PUT/DELETE failed: " + e.toString());
			aaiLogger.error(ErrorLogHelper.getErrorObject("AAI_7402", e.getMessage()), logline, e);
			aaiLogger.info(logline, false, "AAI_7402");
			System.exit(1);
		}
	}
	
	   /**
   	 * Read json file.
   	 *
   	 * @param fName the f name
   	 * @return the relationship
   	 * @throws AAIException the AAI exception
   	 */
   	public static Relationship readJsonFile( String fName ) throws AAIException { 
		    
	    	LogLine logline = new LogLine();
	    	logline.init(COMPONENT, TRANSID, FROMAPPID, "readJsonFile");
	    	
	        String jsonData = "";
	        BufferedReader br = null;
	        Relationship rship = new Relationship();
	        
	        try {
	            String line;
	            br = new BufferedReader(new FileReader(fName));
	            while ((line = br.readLine()) != null) {
	                jsonData += line + "\n";
	            }
	        } catch (IOException e) {
                throw new AAIException("AAI_7403", e, "Error opening json file");
	        } finally {
	            try {
	                if (br != null)
	                    br.close();
	            } catch (IOException ex) {
	                ex.printStackTrace();
	                aaiLogger.info(logline, false, "AAI_7403");
	                throw new AAIException("AAI_7403", ex, "Error closing json file");
	            }
	        }

	        try {	        	
	        	rship = MapperUtil.readWithDashesAsObjectOf(Relationship.class, jsonData);
	        }
	        catch (Exception je){
	            aaiLogger.info(logline, false, "AAI_7403");
	            throw new AAIException("AAI_7403", je, "Error parsing json file"); 
	        }

	        aaiLogger.info(logline, true, "0");
	        return rship;

	    }//End readJsonFile()

	
	/**
	 * Put del relationship.
	 *
	 * @param aaiLogger the aai logger
	 * @param logline the logline
	 * @param rshipURL the rship URL
	 * @param rship the rship
	 * @param action the action
	 * @throws AAIException the AAI exception
	 */
	public static void PutDelRelationship(AAILogger aaiLogger, 
											LogLine logline, 
											String rshipURL, 
											Relationship rship, 
											String action) throws AAIException{		
		try {
			String useBasicAuth = AAIConfig.get("aai.tools.enableBasicAuth");
			Client client = null;

			if (useBasicAuth != null && useBasicAuth.equals("true")) {
				
				client = HttpsAuthClient.getBasicAuthClient();
			} else {
				client = HttpsAuthClient.getTwoWaySSLClient();
			}			
			ClientResponse cres = null;
		
			if (action.equalsIgnoreCase("PUT"))
				 cres = client.resource(rshipURL)
										.header("X-TransactionId", TRANSID)
										.header("X-FromAppId",  FROMAPPID)
										.accept("application/json")
										.entity(rship)
										.put(ClientResponse.class);
			else
				 cres = client.resource(rshipURL)
					.header("X-TransactionId", TRANSID)
					.header("X-FromAppId",  FROMAPPID)
					.accept("application/json")
					.entity(rship)
					.delete(ClientResponse.class);
			
			if (cres.getStatus() == 404) { // resource not found				
				String msg = "Resource does not exist...: " + cres.getStatus()
									+ ":\n" + cres.getEntity(String.class);
				System.out.println(msg);
				logline.add("msg", msg);
	            throw new AAIException("AAI_7404", "Resource does not exist");
			} else if ((action.equalsIgnoreCase("PUT") && cres.getStatus() == 200) ||
					   (action.equalsIgnoreCase("DELETE") && cres.getStatus() == 204)) {
				String msg = action + " Resource status: " + cres.getStatus();
				System.out.println(msg);
			} else {
				String msg = action + " Resource failed: " + cres.getStatus()
						+ ":\n" + cres.getEntity(String.class);
				System.out.println(msg);
				logline.add("msg", msg);
	            throw new AAIException("AAI_7402", "Error during PutDel");
			}
		} catch (AAIException e) {
            throw e;
		} catch (KeyManagementException e) {
            throw new AAIException("AAI_7401", "Error during PutDel");
		}  catch (Exception e) {
            throw new AAIException("AAI_7402", "Error during PutDel");
		}
	}	

}