diff options
author | Bharat saraswal <bharat.saraswal@huawei.com> | 2017-09-20 11:38:37 +0530 |
---|---|---|
committer | Bharat saraswal <bharat.saraswal@huawei.com> | 2017-09-20 11:38:37 +0530 |
commit | 81082e4e3cca0fd92ae6fec17b53e3a9acb25b0b (patch) | |
tree | 0105c8608a8f01e7a02003bf1bd7ea7fc9d695a1 /src | |
parent | 556189113c7e115e939589dbf031168dbdc9ab90 (diff) |
Fix Sonar Issue
code refactoring and exception handling and redundant code removal
Issue-Id: CCSDK-87
Change-Id: I764ff5c990baaf7f03907a4f83815f0417036cc0
Signed-off-by: Bharat saraswal <bharat.saraswal@huawei.com>
Diffstat (limited to 'src')
-rw-r--r-- | src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java | 572 | ||||
-rw-r--r-- | src/main/org/onap/ecomp/main/cloudify/CloudifyService.java | 1004 |
2 files changed, 777 insertions, 799 deletions
diff --git a/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java b/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java index 78f4008..0a4a4fa 100644 --- a/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java +++ b/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java @@ -21,6 +21,8 @@ *******************************************************************************/ package org.onap.ecomp.main.cloudify; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; @@ -29,315 +31,275 @@ import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; - +import org.apache.commons.codec.binary.Base64; import org.json.JSONException; import org.json.JSONObject; import org.onap.ecomp.main.APIHConfig; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.apache.commons.codec.binary.Base64; - public class CloudifyClient { - private static CloudifyClient client = null; - final static EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyClient.class); - HttpURLConnection connection = null; - - public static CloudifyClient getInstance() { - if (client == null) - return new CloudifyClient(); - else - return client; - } - - public JSONObject doGET(String urlString) { - - URL url; - JSONObject returnObj = null; - try { - urlString = getManagerID() + urlString; - url = new URL(urlString); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("GET"); - connection.setDoOutput(true); - connection.setConnectTimeout(10000); - connection.setReadTimeout(10000); - connection.setRequestProperty("Authorization", getAuthString()); - - BufferedReader in = new BufferedReader(new InputStreamReader( - connection.getInputStream())); - StringBuilder check = new StringBuilder(); - String inputLine; - - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - - // get the Response code from the HTTP - int responseCode = connection.getResponseCode(); - - returnObj = new JSONObject(); - returnObj.put("responseMsg",check.toString()); - returnObj.put("responseCode", responseCode); - returnObj.put("timestamp", getCurrentDataAndTime()); - return returnObj; - - } catch (Exception e) { - logger.error("Exception found : " + e.getLocalizedMessage()); - returnObj = new JSONObject(); - String responseMsg = ""; - int responseCode; - try { - responseMsg = connection.getResponseMessage(); - JSONObject errorSteam = getErrorSteam(); - if (errorSteam != null) - responseMsg = errorSteam.optString("message"); - responseCode = connection.getResponseCode(); - returnObj.put("responseMsg", responseMsg); - returnObj.put("responseCode", responseCode); - } catch (Exception e1) { - responseMsg = "Some Exception while retreiving the response"; - responseCode = 500; - } - return returnObj; - }finally{ - connection.disconnect(); - } - } - - public JSONObject doPOST(String urlString, JSONObject outputJSON) { - URL url; - JSONObject returnObj = null; - try { - urlString = getManagerID() + urlString; - url = new URL(urlString); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setDoOutput(true); - connection.setConnectTimeout(10000); - connection.setReadTimeout(10000); - connection.setRequestProperty("Authorization", getAuthString()); - - connection.setRequestProperty("Content-Type", "application/json"); - OutputStreamWriter out = new OutputStreamWriter( - connection.getOutputStream()); - out.write(outputJSON.toString()); - out.close(); - - BufferedReader in = new BufferedReader(new InputStreamReader( - connection.getInputStream())); - StringBuilder check = new StringBuilder(); - String inputLine; - - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - - // get the Response code from the HTTP - int responseCode = connection.getResponseCode(); - - returnObj = new JSONObject(); - returnObj.put("responseMsg",check.toString()); - returnObj.put("responseCode", responseCode); - returnObj.put("timestamp", getCurrentDataAndTime()); - - return returnObj; - - } catch (Exception e) { - logger.error("Exception found : " + e.getLocalizedMessage()); - returnObj = new JSONObject(); - String responseMsg = ""; - int responseCode; - try { - responseMsg = connection.getResponseMessage(); - JSONObject errorSteam = getErrorSteam(); - if (errorSteam != null) - responseMsg = errorSteam.optString("message"); - responseCode = connection.getResponseCode(); - returnObj.put("responseMsg", responseMsg); - returnObj.put("responseCode", responseCode); - } catch (Exception e1) { - responseMsg = "Some Exception while retreiving the response"; - responseCode = 500; - } - return returnObj; - } finally{ - connection.disconnect(); - } - - } - - public JSONObject doPUT(String urlString, JSONObject outputJson) { - - URL url; - JSONObject returnObj = null; - try { - urlString = getManagerID() + urlString; - url = new URL(urlString); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("PUT"); - connection.setDoOutput(true); - connection.setConnectTimeout(10000); - connection.setReadTimeout(10000); - connection.setRequestProperty("Authorization", getAuthString()); - - if (outputJson != null) { - connection.setRequestProperty("Content-Type", - "application/json"); - OutputStreamWriter out = new OutputStreamWriter( - connection.getOutputStream()); - out.write(outputJson.toString()); - out.close(); - } - - System.out.println(connection.getResponseMessage()); - BufferedReader in = new BufferedReader(new InputStreamReader( - connection.getInputStream())); - StringBuilder check = new StringBuilder(); - String inputLine; - - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - - // get the Response code from the HTTP - int responseCode = connection.getResponseCode(); - - returnObj = new JSONObject(); - returnObj.put("responseMsg",check.toString()); - returnObj.put("responseCode", responseCode); - returnObj.put("timestamp", getCurrentDataAndTime()); - - return returnObj; - - } catch (Exception e) { - logger.error("Exception found : " + e.getLocalizedMessage()); - returnObj = new JSONObject(); - String responseMsg = ""; - int responseCode; - try { - responseMsg = connection.getResponseMessage(); - JSONObject errorSteam = getErrorSteam(); - if (errorSteam != null) - responseMsg = errorSteam.optString("message"); - responseCode = connection.getResponseCode(); - returnObj.put("responseMsg", responseMsg); - returnObj.put("responseCode", responseCode); - } catch (Exception e1) { - responseMsg = "Some Exception while retreiving the response"; - responseCode = 500; - } - return returnObj; - }finally{ - connection.disconnect(); - } - } - - public JSONObject doDELETE(String urlString) { - URL url; - JSONObject returnObj = null; - try { - urlString = getManagerID() + urlString; - url = new URL(urlString); - connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("DELETE"); - connection.setDoOutput(true); - connection.setConnectTimeout(10000); - connection.setReadTimeout(10000); - connection.setRequestProperty("Authorization", getAuthString()); - - BufferedReader in = new BufferedReader(new InputStreamReader( - connection.getInputStream())); - StringBuilder check = new StringBuilder(); - String inputLine; - - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - - // get the Response code from the HTTP - int responseCode = connection.getResponseCode(); - - returnObj = new JSONObject(); - returnObj.put("responseMsg",check.toString()); - returnObj.put("responseCode", responseCode); - returnObj.put("timestamp", getCurrentDataAndTime()); - - return returnObj; - - } catch (Exception e) { - logger.error("Exception found : " + e.getLocalizedMessage()); - returnObj = new JSONObject(); - String responseMsg = ""; - int responseCode; - try { - responseMsg = connection.getResponseMessage(); - JSONObject errorSteam = getErrorSteam(); - if (errorSteam != null) - responseMsg = errorSteam.optString("message"); - responseCode = connection.getResponseCode(); - returnObj.put("responseMsg", responseMsg); - returnObj.put("responseCode", responseCode); - } catch (Exception e1) { - responseMsg = "Some Exception while retreiving the response"; - responseCode = 500; - } - return returnObj; - }finally{ - connection.disconnect(); - } - } - - private String getCurrentDataAndTime() { - DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - Date date = new Date(); - return dateFormat.format(date); - } - - private String getManagerID() { - String manager_ip = ""; - String api_version = ""; - manager_ip = APIHConfig.getInstance().getConfigObject().optString("manager_ip"); - api_version = APIHConfig.getInstance().getConfigObject().optString("api_version"); - return "http://" + manager_ip + "/api/" + api_version; - } - - private String getManagerUsername() { - String manager_username = ""; - manager_username = APIHConfig.getInstance().getConfigObject().optString("manager_username"); - return manager_username; - } - - private String getManagerPassword() { - String manager_password = ""; - manager_password = APIHConfig.getInstance().getConfigObject().optString("manager_password"); - return manager_password; - } - - private String getAuthString(){ - String username = getManagerUsername(); - String password = getManagerPassword(); - String authString = username + ":" + password; - byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); - String authStringEnc = new String(authEncBytes); - return "Basic " + authStringEnc; - } - private JSONObject getErrorSteam() { - BufferedReader in = new BufferedReader(new InputStreamReader( - connection.getErrorStream())); - StringBuilder check = new StringBuilder(); - try { - - String inputLine; - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - } catch (Exception ex) { - - } - - try { - return new JSONObject(check.toString()); - } catch (JSONException e) { - return null; - } - } - + private static final String MESSAGE = "message"; + private static final String AUTHORIZATION = "Authorization"; + private static final String RESPONSE_MSG = "responseMsg"; + private static final String RESPONSE_CODE = "responseCode"; + private static final String TIME_STAMP = "timestamp"; + private static final String EXCEPTION_FOUND = "Exception found : "; + private static final String ERROR_RESPONSE_MSG = "Some Exception while retrieving the response "; + private static final int ERROR_RESPONSE_CODE = 500; + + private static CloudifyClient client = null; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyClient.class); + private HttpURLConnection connection = null; + + public static CloudifyClient getInstance() { + if (client == null) { + return new CloudifyClient(); + } else { + return client; + } + } + + public JSONObject doGET(String urlString) { + + URL url; + JSONObject returnObj; + try { + url = new URL(getManagerID() + urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty(AUTHORIZATION, getAuthString()); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + returnObj = new JSONObject(); + returnObj.put(RESPONSE_MSG, check.toString()); + returnObj.put(RESPONSE_CODE, responseCode); + returnObj.put(TIME_STAMP, getCurrentDataAndTime()); + in.close(); + return returnObj; + } catch (Exception e) { + logger.error(EXCEPTION_FOUND + e.getLocalizedMessage(), e); + return buildReturnObjectWhenExceptionOccurred(); + } finally { + connection.disconnect(); + } + } + + public JSONObject doPOST(String urlString, JSONObject outputJSON) { + URL url; + JSONObject returnObj; + try { + url = new URL(getManagerID() + urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty(AUTHORIZATION, getAuthString()); + + connection.setRequestProperty("Content-Type", "application/json"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(outputJSON.toString()); + out.close(); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + returnObj = new JSONObject(); + returnObj.put(RESPONSE_MSG, check.toString()); + returnObj.put(RESPONSE_CODE, responseCode); + returnObj.put(TIME_STAMP, getCurrentDataAndTime()); + in.close(); + + return returnObj; + } catch (Exception e) { + logger.error(EXCEPTION_FOUND + e.getLocalizedMessage()); + return buildReturnObjectWhenExceptionOccurred(); + } finally { + connection.disconnect(); + } + } + + public JSONObject doPUT(String urlString, JSONObject outputJson) { + + URL url; + JSONObject returnObj; + try { + url = new URL(getManagerID() + urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty(AUTHORIZATION, getAuthString()); + + if (outputJson != null) { + connection.setRequestProperty("Content-Type", + "application/json"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(outputJson.toString()); + out.close(); + } + + logger.info(connection.getResponseMessage()); + BufferedReader in = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + returnObj = new JSONObject(); + returnObj.put(RESPONSE_MSG, check.toString()); + returnObj.put(RESPONSE_CODE, responseCode); + returnObj.put(TIME_STAMP, getCurrentDataAndTime()); + in.close(); + + return returnObj; + } catch (Exception e) { + logger.error(EXCEPTION_FOUND + e.getLocalizedMessage()); + return buildReturnObjectWhenExceptionOccurred(); + } finally { + connection.disconnect(); + } + } + + public JSONObject doDELETE(String urlString) { + URL url; + JSONObject returnObj; + try { + url = new URL(getManagerID() + urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("DELETE"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty(AUTHORIZATION, getAuthString()); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + returnObj = new JSONObject(); + returnObj.put(RESPONSE_MSG, check.toString()); + returnObj.put(RESPONSE_CODE, responseCode); + returnObj.put(TIME_STAMP, getCurrentDataAndTime()); + + in.close(); + return returnObj; + } catch (Exception e) { + logger.error(EXCEPTION_FOUND + e.getLocalizedMessage()); + return buildReturnObjectWhenExceptionOccurred(); + } finally { + connection.disconnect(); + } + } + + private JSONObject buildReturnObjectWhenExceptionOccurred() { + JSONObject returnObj = new JSONObject(); + String responseMsg; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) { + responseMsg = errorSteam.optString(MESSAGE); + } + responseCode = connection.getResponseCode(); + returnObj.put(RESPONSE_MSG, responseMsg); + returnObj.put(RESPONSE_CODE, responseCode); + } catch (Exception e1) { + responseMsg = ERROR_RESPONSE_MSG; + responseCode = ERROR_RESPONSE_CODE; + logger.error(responseMsg + responseCode, e1); + } + return returnObj; + } + + private String getCurrentDataAndTime() { + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private String getManagerID() { + String managerIp; + String apiVersion; + managerIp = APIHConfig.getInstance().getConfigObject().optString("manager_ip"); + apiVersion = APIHConfig.getInstance().getConfigObject().optString("api_version"); + return "http://" + managerIp + "/api/" + apiVersion; + } + + private String getManagerUsername() { + String managerUsername; + managerUsername = APIHConfig.getInstance().getConfigObject().optString("manager_username"); + return managerUsername; + } + + private String getManagerPassword() { + String managerPassword; + managerPassword = APIHConfig.getInstance().getConfigObject().optString("manager_password"); + return managerPassword; + } + + private String getAuthString() { + String username = getManagerUsername(); + String password = getManagerPassword(); + String authString = username + ":" + password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + return "Basic " + authStringEnc; + } + + private JSONObject getErrorSteam() { + StringBuilder check = new StringBuilder(); + try (BufferedReader in = new BufferedReader(new InputStreamReader( + connection.getErrorStream()))) { + + String inputLine; + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + } catch (Exception ex) { + logger.error(ex.getLocalizedMessage(), ex); + } + + try { + return new JSONObject(check.toString()); + } catch (JSONException e) { + return null; + } + } }
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java b/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java index 9b39345..2818e76 100644 --- a/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java +++ b/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java @@ -21,13 +21,13 @@ *******************************************************************************/ package org.onap.ecomp.main.cloudify; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import java.io.BufferedReader; -import java.io.BufferedWriter; import java.io.File; -import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; - +import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -42,507 +42,523 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; - import org.json.JSONArray; import org.json.JSONObject; import org.onap.ecomp.main.APIHConfig; import org.onap.ecomp.persistence.EcompBlueprintPersistence; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - @Path("/") public class CloudifyService { - EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyService.class); - - CloudifyHelp cloudifyHelp; - - String errorLine = "Bad Request"; - - public CloudifyService() throws Exception { - cloudifyHelp = new CloudifyHelp(); - } - - /** - * Return the help for all the available API - * - * @param authString - * @param userid - * @return JSONObject - */ - - @GET - @Path("") - @Produces(MediaType.APPLICATION_JSON) - public Response getdefaultHelp(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - return Response.status(200).entity(" API server is Alive!!") - .build(); - } - /** - * Return the help for all the available API - * - * @param authString - * @param userid - * @return JSONObject - */ - - @GET - @Path("/help") - @Produces(MediaType.APPLICATION_JSON) - public Response getHelp(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + private static final String UNAUTHORIZED = "Unauthorized"; + private static final String RESPONSE_CODE = "responseCode"; + private static final String BLUEPRINT_ID = "blueprint_id"; + private static final String RESPONSE_ERROR_MSG = "Error parsing the incoming DATA"; + private static final String DEPLOYMENTS = "/deployments/"; + private static final String DEPLOYMENT_ID = "deployment_id"; + private static final String PARAMETERS = "parameters"; + private static final String EXECUTIONS = "/executions/"; + private EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyService.class); + + private CloudifyHelp cloudifyHelp; + + String errorLine = "Bad Request"; + + public CloudifyService() throws Exception { + cloudifyHelp = new CloudifyHelp(); + } + + /** + * Return the help for all the available API + * + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @GET + @Path("") + @Produces(MediaType.APPLICATION_JSON) + public Response getdefaultHelp(@HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + return Response.status(200).entity(" API server is Alive!!").build(); + } + + /** + * Return the help for all the available API + * + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @GET + @Path("/help") + @Produces(MediaType.APPLICATION_JSON) + public Response getHelp(@HeaderParam("authorization") String authString, @HeaderParam("userid") String userid) { /*if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ - return Response.status(401).entity("Unauthorized").build(); + return Response.status(401).entity(UNAUTHORIZED).build(); }*/ - - String result = cloudifyHelp.getHelp(); - logger.info("Handled get help API Request"); - return Response.status(200).entity(result) - .build(); - - } - - - /** - * Get the list or a specific blueprint which are already uploaded - * @param id - * @param authString - * @param userid - * @param request - * @return Response - */ - - @GET - @Path("/blueprints") - @Produces(MediaType.APPLICATION_JSON) - public Response getBlueprints(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@Context HttpServletRequest request) { - - String url = ""; - //validate the user and the application for GET request - - if (request.getQueryString() == null) { - logger.info("Received request for all blueprints"); - url = "/blueprints"; - } else { - logger.info("Received request for blueprint with query parameters = " + request.getQueryString()); - url = "/blueprints?"+ request.getQueryString(); - } - - if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ - return Response.status(401).entity("Unauthorized").build(); - } - - JSONObject result = CloudifyClient.getInstance().doGET(url); - logger.info("Handled get blueprints API Request"); - return handleResponse(result); - - } - - /** - * DELETE a blueprint - * - * @param id - * @param authString - * @param userid - * @return JSONObject - */ - - @DELETE - @Path("/blueprints/{id}") - @Produces(MediaType.APPLICATION_JSON) - public Response deleteBlueprints(@PathParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - String url = ""; - logger.info("Received request for deleting blueprint with ID = " + id); - //validate the user and application for DELETE operation - if(!APIHConfig.getInstance().validateUser(authString,userid,"DELETE")){ - return Response.status(401).entity("Unauthorized").build(); - } - - url = "/blueprints/" + id; - - JSONObject result = CloudifyClient.getInstance().doDELETE(url); - int responseCode = result.optInt("responseCode"); - if(responseCode == 200 ){ - logger.info("Deleting the blueprint from Inventory"); - if(new EcompBlueprintPersistence().deleteBlueprint(id)) - logger.info("Deleted the blueprint from Inventory"); - } - logger.info("Handled delete blueprint API Request"); - return handleResponse(result); - - } - - /** - * Upload a new Blueprint - * @param id - * @param blueprintfileName - * @param zipFileURL - * @param authString - * @param userid - * @return JSONObject - */ - - @POST - @Path("/blueprints") - @Produces(MediaType.APPLICATION_JSON) - public Response uploadBlueprints(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - String url = ""; - logger.info("Received request for uploading blueprint"); - - //validate the user and application for PUT operation - if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ - return Response.status(401).entity("Unauthorized").build(); - } - - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); - StringBuilder check = new StringBuilder(); - String inputLine; - - - try { - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - - JSONObject incomingJSON = new JSONObject(check.toString()); - if(incomingJSON.optString("blueprint_id","").equals("")) - return Response.status(400).entity("blueprint_id is mandatory in payload").build(); - - url = "/blueprints/" + incomingJSON.optString("blueprint_id","") + "?application_file_name=" - + incomingJSON.optString("blueprint_filename","") + "&blueprint_archive_url=" - + incomingJSON.optString("zip_url",""); - - JSONObject result = CloudifyClient.getInstance().doPUT(url,null); - logger.info("Handled uploading blueprint API Request"); - int responseCode = result.optInt("responseCode"); - if(responseCode == 201){ - logger.info("Pushing the blueprint in DB"); - new EcompBlueprintPersistence().saveBlueprint(incomingJSON.optString("blueprint_id",""),incomingJSON.optString("blueprint_filename",""),incomingJSON.optString("zip_url","")); - } - return handleResponse(result); - }catch(Exception e){ - e.printStackTrace(); - return Response.status(400).entity("Error parsing the incoming DATA").build(); - } - - } - - @GET - @Path("/viewblueprints") - public Response fetchBlueprintByID(@QueryParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - // validate the user and application for PUT operation - if (!APIHConfig.getInstance().validateUser(authString, userid, "PUT")) { - return Response.status(401).entity("Unauthorized").build(); - } - - if(id == "") - return Response.status(400).entity("id parameter is must for fetching the blueprint").build(); - logger.info("Fetching the blueprint with id = " + id); - EcompBlueprintPersistence blueprintPersistence = new EcompBlueprintPersistence(); - try { - File returnFile = blueprintPersistence.fetchBlueprint(id); - if (returnFile == null) { - ResponseBuilder rbuilder = Response.status(Status.OK); - String logMessage = "No such blueprint found in the inventory."; - logger.info(logMessage); - return rbuilder - .type(MediaType.TEXT_PLAIN) - .entity("") - .build(); - } else { - ResponseBuilder rbuilder = Response.status(Status.OK); - logger.info("Blueprint found. Returing the yaml file"); - return rbuilder.type(MediaType.APPLICATION_OCTET_STREAM) - .entity(returnFile).build(); - } - } catch (Exception E) { - logger.info("Exception in handling the fetch command =" + E.getMessage()); - return Response.status(500) - .entity("Error fetching the blueprint resource").build(); - } - } - - - /** - * Get the deployment list or specific deployment - * @param id - * @param authString - * @param userid - * @return JSONObject - */ - - @GET - @Path("/deployments") - @Produces(MediaType.APPLICATION_JSON) - public Response getDeployments(@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - String url = ""; - if (request.getQueryString() == null) { - logger.info("Received request for all deployments"); - url = "/deployments"; - } else { - logger.info("Received request for deployment with query = " + request.getQueryString()); - url = "/deployments?"+request.getQueryString(); - } - - if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ - return Response.status(401).entity("Unauthorized").build(); - } - - JSONObject result = CloudifyClient.getInstance().doGET(url); - logger.info("Handled get deployment API Request"); - return handleResponse(result); - } - - /** - * DELETE a deployment - * @param id - * @param authString - * @param userid - * @return JSONObject - */ - - @DELETE - @Path("/deployments/{id}") - @Produces(MediaType.APPLICATION_JSON) - public Response deleteDeployments(@Context HttpServletRequest request,@PathParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - logger.info("Received request for deleting deployment with ID = " + id); - - if(!APIHConfig.getInstance().validateUser(authString,userid,"DELETE")){ - return Response.status(401).entity("Unauthorized").build(); - } - - String url = ""; - url = "/deployments/" + id; - if(request.getQueryString() != null) - url = "/deployments/" + id + "?" + request.getQueryString(); - - JSONObject result = CloudifyClient.getInstance().doDELETE(url); - logger.info("Handled delete deployment API Request"); - return handleResponse(result); - } - - /** - * Create a new deployment - * @param inputStream - * @param deploymentID - * @param authString - * @param userid - * @return JSONObject - */ - @POST - @Path("/deployments") - @Produces(MediaType.APPLICATION_JSON) - public Response createDeployment(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - logger.info("Received request for creating deployment"); - - if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ - return Response.status(401).entity("Unauthorized").build(); - } - - String url = ""; - JSONObject inputJSon; - JSONObject outputJSON; - - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); - StringBuilder check = new StringBuilder(); - String inputLine; - - try { - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - inputJSon = new JSONObject(check.toString()); - - if(inputJSon.optString("deployment_id", "").equals("")) - return Response.status(400).entity("deployment_id is mandatory in payload").build(); - String blueprintID = inputJSon.optString("blueprint_id", ""); - JSONObject parameters = inputJSon.optJSONObject("parameters"); - - outputJSON = new JSONObject(); - outputJSON.put("blueprint_id", blueprintID); - outputJSON.put("inputs", parameters); - url = "/deployments/" + inputJSon.optString("deployment_id", ""); - JSONObject result = CloudifyClient.getInstance().doPUT(url,outputJSON); - logger.info("Handled create deployment API Request"); - return handleResponse(result); - } catch (Exception e) { - return Response.status(400).entity("Error parsing the incoming DATA").build(); - } - } - - /** - * Get the list of execution for a specific deployment - * @param deployment_id - * @param authString - * @param userid - * @return - */ - @GET - @Path("/executions") - @Produces(MediaType.APPLICATION_JSON) - public Response getExecutionForDeployment( - @Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - String url = ""; - - if (request.getQueryString() == null) { - logger.info("Received request for list execution"); - url = "/executions"; - } else { - logger.info("Received request for list execution with query paramters = " + request.getQueryString()); - url = "/executions?"+request.getQueryString(); - } - - if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ - return Response.status(401).entity("Unauthorized").build(); - } - - JSONObject result = CloudifyClient.getInstance().doGET(url); - logger.info("Handled get Execution API Request"); - return handleResponse(result); - } - - @GET - @Path("/executions/{id}") - @Produces(MediaType.APPLICATION_JSON) - public Response getExecutionWithID( - @Context HttpServletRequest request,@PathParam("id") String execution_id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - String url = ""; - if(request.getQueryString() == null){ - logger.info("Received request for list execution for Execution id as :" + execution_id); - url = "/executions/"+ execution_id; - } - else{ - url = "/executions/"+ execution_id + "?" + request.getQueryString(); - logger.info("Received request for list execution for query paramters = " + request.getQueryString() + " and Execution id as :" + execution_id); - } - - if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ - return Response.status(401).entity("Unauthorized").build(); - } - - JSONObject result = CloudifyClient.getInstance().doGET(url); - logger.info("Handled get specific execution API Request"); - return handleResponse(result); - } - - /** - * Start an execution - * @param inputStream - * @param authString - * @param userid - * @return - */ - - @POST - @Path("/executions") - @Produces(MediaType.APPLICATION_JSON) - public Response startExecution(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - logger.info("Received request for starting an execution"); - if(!APIHConfig.getInstance().validateUser(authString,userid,"POST")){ - return Response.status(401).entity("Unauthorized").build(); - } - - String url = ""; - JSONObject outputJson = new JSONObject(); - - - url = "/executions"; - - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); - StringBuilder check = new StringBuilder(); - String inputLine; - - try { - while ((inputLine = in.readLine()) != null) - check.append(inputLine); - JSONObject inputJSon = new JSONObject(check.toString()); - String deploymentID = inputJSon.optString("deployment_id",""); - String workflow = inputJSon.optString("workflow_name",""); - String customParameter = inputJSon.optString("allow_custom_parameter","false"); - String force = inputJSon.optString("force","false"); - JSONArray parameters = inputJSon.optJSONArray("parameters"); - - outputJson.put("deployment_id", deploymentID); - outputJson.put("workflow_id", workflow); - outputJson.put("allow_custom_parameters", customParameter); - outputJson.put("force", force); - outputJson.put("parameters", parameters); - - logger.info("output JSON is " + outputJson.toString()); - JSONObject result = CloudifyClient.getInstance().doPOST(url,outputJson); - logger.info("Handled start execution API Request"); - return handleResponse(result); - } catch (Exception e) { - return Response.status(400).entity("Error parsing the incoming DATA").build(); - } - - } - - /** - * - * @param execution_id - * @param inputStream - * @param authString - * @param userid - * @return - */ - - @DELETE - @Path("/executions/{execution-id}") - @Produces(MediaType.APPLICATION_JSON) - public Response cancelExecution(@PathParam("execution-id") String execution_id,@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { - - logger.info("Received request for cancel execution for Execution id as :" + execution_id); - - if(!APIHConfig.getInstance().validateUser(authString,userid,"POST")){ - return Response.status(401).entity("Unauthorized").build(); - } - - String url = ""; - JSONObject outputJson = new JSONObject(); - - url = "/executions/"+ execution_id; - - try { - String[] query = request.getQueryString().split("&"); - String deployment_id = query[0].split("=")[1]; - String action = "cancel"; - if(query.length>1) - action = query[1].split("=")[1]; - outputJson.put("deployment_id", deployment_id); - outputJson.put("action", action); - JSONObject result = CloudifyClient.getInstance().doPOST(url,outputJson); - logger.info("Handled cancel execution API Request"); - return handleResponse(result); - } catch (Exception e) { - return Response.status(400).entity("Error parsing the incoming DATA").build(); - } - } - - private Response handleResponse(JSONObject result) { - - if(result == null){ - return Response.status(500).entity("Internal Server Error – We had a problem with our server. Try again later.").build(); - } - int responseCode = result.optInt("responseCode"); - String responseMsg = result.optString("responseMsg", ""); - - if(responseCode >= 300) - { - logger.info("Response code is: " + responseCode + " and Error msg is :" + responseMsg); - } - - return Response.status(responseCode).entity(responseMsg).build(); - } - + + String result = cloudifyHelp.getHelp(); + logger.info("Handled get help API Request"); + return Response.status(200).entity(result) + .build(); + } + + + /** + * Get the list or a specific blueprint which are already uploaded + * + * @param authString authorization + * @param userid user id + * @param request http request + * @return Response + */ + + @GET + @Path("/blueprints") + @Produces(MediaType.APPLICATION_JSON) + public Response getBlueprints(@HeaderParam("authorization") String authString, @HeaderParam("userid") String userid, + @Context HttpServletRequest request) { + + String url; + //validate the user and the application for GET request + + if (request.getQueryString() == null) { + logger.info("Received request for all blueprints"); + url = "/blueprints"; + } else { + logger.info("Received request for blueprint with query parameters = " + request.getQueryString()); + url = "/blueprints?" + request.getQueryString(); + } + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get blueprints API Request"); + return handleResponse(result); + } + + /** + * DELETE a blueprint + * + * @param id id + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @DELETE + @Path("/blueprints/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteBlueprints(@PathParam("id") String id, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + String url; + logger.info("Received request for deleting blueprint with ID = " + id); + //validate the user and application for DELETE operation + if (!APIHConfig.getInstance().validateUser(authString, userid, "DELETE")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + url = "/blueprints/" + id; + + JSONObject result = CloudifyClient.getInstance().doDELETE(url); + int responseCode = result.optInt(RESPONSE_CODE); + if (responseCode == 200) { + logger.info("Deleting the blueprint from Inventory"); + if (new EcompBlueprintPersistence().deleteBlueprint(id)) { + logger.info("Deleted the blueprint from Inventory"); + } + } + logger.info("Handled delete blueprint API Request"); + return handleResponse(result); + } + + /** + * Upload a new Blueprint + * + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @POST + @Path("/blueprints") + @Produces(MediaType.APPLICATION_JSON) + public Response uploadBlueprints(InputStream inputStream, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + String url; + logger.info("Received request for uploading blueprint"); + + //validate the user and application for PUT operation + if (!APIHConfig.getInstance().validateUser(authString, userid, "PUT")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + StringBuilder check = new StringBuilder(); + String inputLine; + + try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) { + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + + JSONObject incomingJSON = new JSONObject(check.toString()); + if (incomingJSON.optString(BLUEPRINT_ID, "").equals("")) { + return Response.status(400).entity("blueprint_id is mandatory in payload").build(); + } + + url = "/blueprints/" + incomingJSON.optString(BLUEPRINT_ID, "") + "?application_file_name=" + + incomingJSON.optString("blueprint_filename", "") + "&blueprint_archive_url=" + + incomingJSON.optString("zip_url", ""); + + JSONObject result = CloudifyClient.getInstance().doPUT(url, null); + logger.info("Handled uploading blueprint API Request"); + int responseCode = result.optInt(RESPONSE_CODE); + if (responseCode == 201) { + logger.info("Pushing the blueprint in DB"); + new EcompBlueprintPersistence().saveBlueprint(incomingJSON.optString(BLUEPRINT_ID, ""), + incomingJSON.optString("blueprint_filename", ""), incomingJSON.optString("zip_url", "")); + } + return handleResponse(result); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + return Response.status(400).entity(RESPONSE_ERROR_MSG).build(); + } + } + + @GET + @Path("/viewblueprints") + public Response fetchBlueprintByID(@QueryParam("id") String id, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + // validate the user and application for PUT operation + if (!APIHConfig.getInstance().validateUser(authString, userid, "PUT")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + if (Objects.equals("", id)) { + return Response.status(400).entity("id parameter is must for fetching the blueprint").build(); + } + logger.info("Fetching the blueprint with id = " + id); + EcompBlueprintPersistence blueprintPersistence = new EcompBlueprintPersistence(); + try { + File returnFile = blueprintPersistence.fetchBlueprint(id); + if (returnFile == null) { + ResponseBuilder rbuilder = Response.status(Status.OK); + String logMessage = "No such blueprint found in the inventory."; + logger.info(logMessage); + return rbuilder + .type(MediaType.TEXT_PLAIN) + .entity("") + .build(); + } else { + ResponseBuilder rbuilder = Response.status(Status.OK); + logger.info("Blueprint found. Returing the yaml file"); + return rbuilder.type(MediaType.APPLICATION_OCTET_STREAM) + .entity(returnFile).build(); + } + } catch (Exception e) { + logger.info("Exception in handling the fetch command =" + e.getMessage()); + return Response.status(500) + .entity("Error fetching the blueprint resource").build(); + } + } + + + /** + * Get the deployment list or specific deployment + * + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @GET + @Path("/deployments") + @Produces(MediaType.APPLICATION_JSON) + public Response getDeployments(@Context HttpServletRequest request, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + String url = ""; + if (request.getQueryString() == null) { + logger.info("Received request for all deployments"); + url = "/deployments"; + } else { + logger.info("Received request for deployment with query = " + request.getQueryString()); + url = "/deployments?" + request.getQueryString(); + } + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get deployment API Request"); + return handleResponse(result); + } + + /** + * DELETE a deployment + * + * @param id id + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + + @DELETE + @Path("/deployments/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteDeployments(@Context HttpServletRequest request, @PathParam("id") String id, + @HeaderParam("authorization") String authString, @HeaderParam("userid") String userid) { + + logger.info("Received request for deleting deployment with ID = " + id); + + if (!APIHConfig.getInstance().validateUser(authString, userid, "DELETE")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + String url; + url = DEPLOYMENTS + id; + if (request.getQueryString() != null) { + url = DEPLOYMENTS + id + "?" + request.getQueryString(); + } + + JSONObject result = CloudifyClient.getInstance().doDELETE(url); + logger.info("Handled delete deployment API Request"); + return handleResponse(result); + } + + /** + * Create a new deployment + * + * @param inputStream input stream + * @param authString authorization + * @param userid user id + * @return JSONObject + */ + @POST + @Path("/deployments") + @Produces(MediaType.APPLICATION_JSON) + public Response createDeployment(InputStream inputStream, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + logger.info("Received request for creating deployment"); + + if (!APIHConfig.getInstance().validateUser(authString, userid, "PUT")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + String url; + JSONObject inputJSon; + JSONObject outputJSON; + + StringBuilder check = new StringBuilder(); + String inputLine; + + try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) { + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + inputJSon = new JSONObject(check.toString()); + + if (inputJSon.optString(DEPLOYMENT_ID, "").equals("")) { + return Response.status(400).entity("deployment_id is mandatory in payload").build(); + } + String blueprintID = inputJSon.optString(BLUEPRINT_ID, ""); + JSONObject parameters = inputJSon.optJSONObject(PARAMETERS); + + outputJSON = new JSONObject(); + outputJSON.put(BLUEPRINT_ID, blueprintID); + outputJSON.put("inputs", parameters); + url = DEPLOYMENTS + inputJSon.optString(DEPLOYMENT_ID, ""); + JSONObject result = CloudifyClient.getInstance().doPUT(url, outputJSON); + logger.info("Handled create deployment API Request"); + return handleResponse(result); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + return Response.status(400).entity(RESPONSE_ERROR_MSG).build(); + } + } + + /** + * Get the list of execution for a specific deployment + * + * @param authString authorization + * @param userid user id + * @return + */ + @GET + @Path("/executions") + @Produces(MediaType.APPLICATION_JSON) + public Response getExecutionForDeployment( + @Context HttpServletRequest request, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + String url; + + if (request.getQueryString() == null) { + logger.info("Received request for list execution"); + url = "/executions"; + } else { + logger.info("Received request for list execution with query paramters = " + request.getQueryString()); + url = "/executions?" + request.getQueryString(); + } + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get Execution API Request"); + return handleResponse(result); + } + + @GET + @Path("/executions/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getExecutionWithID( + @Context HttpServletRequest request, @PathParam("id") String executionId, + @HeaderParam("authorization") String authString, @HeaderParam("userid") String userid) { + + String url; + if (request.getQueryString() == null) { + logger.info("Received request for list execution for Execution id as :" + executionId); + url = EXECUTIONS + executionId; + } else { + url = EXECUTIONS + executionId + "?" + request.getQueryString(); + logger.info("Received request for list execution for query paramters = " + request.getQueryString() + + " and Execution id as :" + executionId); + } + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get specific execution API Request"); + return handleResponse(result); + } + + /** + * Start an execution + * + * @param inputStream input stream + * @param authString authorization + * @param userid user id + * @return response + */ + + @POST + @Path("/executions") + @Produces(MediaType.APPLICATION_JSON) + public Response startExecution(InputStream inputStream, @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + logger.info("Received request for starting an execution"); + if (!APIHConfig.getInstance().validateUser(authString, userid, "POST")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + String url; + JSONObject outputJson = new JSONObject(); + + url = "/executions"; + + StringBuilder check = new StringBuilder(); + String inputLine; + + try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) { + while ((inputLine = in.readLine()) != null) { + check.append(inputLine); + } + JSONObject inputJSon = new JSONObject(check.toString()); + String deploymentID = inputJSon.optString(DEPLOYMENT_ID, ""); + String workflow = inputJSon.optString("workflow_name", ""); + String customParameter = inputJSon.optString("allow_custom_parameter", "false"); + String force = inputJSon.optString("force", "false"); + JSONArray parameters = inputJSon.optJSONArray(PARAMETERS); + + outputJson.put(DEPLOYMENT_ID, deploymentID); + outputJson.put("workflow_id", workflow); + outputJson.put("allow_custom_parameters", customParameter); + outputJson.put("force", force); + outputJson.put(PARAMETERS, parameters); + + logger.info("output JSON is " + outputJson.toString()); + JSONObject result = CloudifyClient.getInstance().doPOST(url, outputJson); + logger.info("Handled start execution API Request"); + return handleResponse(result); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + return Response.status(400).entity(RESPONSE_ERROR_MSG).build(); + } + } + + /** + * + * @param executionId execution id + * @param authString authorization + * @param userid user id + * @return response + */ + + @DELETE + @Path("/executions/{execution-id}") + @Produces(MediaType.APPLICATION_JSON) + public Response cancelExecution(@PathParam("execution-id") String executionId, @Context HttpServletRequest request, + @HeaderParam("authorization") String authString, @HeaderParam("userid") String userid) { + + logger.info("Received request for cancel execution for Execution id as :" + executionId); + + if (!APIHConfig.getInstance().validateUser(authString, userid, "POST")) { + return Response.status(401).entity(UNAUTHORIZED).build(); + } + + String url; + JSONObject outputJson = new JSONObject(); + + url = EXECUTIONS + executionId; + + try { + String[] query = request.getQueryString().split("&"); + String deploymentId = query[0].split("=")[1]; + String action = "cancel"; + if (query.length > 1) { + action = query[1].split("=")[1]; + } + outputJson.put(DEPLOYMENT_ID, deploymentId); + outputJson.put("action", action); + JSONObject result = CloudifyClient.getInstance().doPOST(url, outputJson); + logger.info("Handled cancel execution API Request"); + return handleResponse(result); + } catch (Exception e) { + logger.error(e.getLocalizedMessage(), e); + return Response.status(400).entity(RESPONSE_ERROR_MSG).build(); + } + } + + private Response handleResponse(JSONObject result) { + + if (result == null) { + return Response.status(500) + .entity("Internal Server Error � We had a problem with our server. Try again later.").build(); + } + int responseCode = result.optInt(RESPONSE_CODE); + String responseMsg = result.optString("responseMsg", ""); + + if (responseCode >= 300) { + logger.info("Response code is: " + responseCode + " and Error msg is :" + responseMsg); + } + + return Response.status(responseCode).entity(responseMsg).build(); + } } |