diff options
7 files changed, 607 insertions, 409 deletions
diff --git a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaRestClient.java b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaRestClient.java index a4e453395d..5de2203b2f 100644 --- a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaRestClient.java +++ b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/AriaRestClient.java @@ -1,336 +1,377 @@ -/*
- * ============LICENSE_START===================================================
- * Copyright (c) 2017 Cloudify.co. 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 com.gigaspaces.aria.rest.client;
-
-import com.gigaspaces.aria.rest.client.exceptions.StorageException;
-import com.gigaspaces.aria.rest.client.exceptions.ValidationException;
-import org.codehaus.jackson.JsonFactory;
-import org.codehaus.jackson.JsonNode;
-import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
-import org.codehaus.jackson.map.ObjectMapper;
-import sun.reflect.generics.reflectiveObjects.NotImplementedException;
-
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.WebTarget;
-import javax.ws.rs.core.GenericType;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-
-import static javax.ws.rs.client.Entity.entity;
-
-/**
- * Created by DeWayne on 7/12/2017.
- */
-public class AriaRestClient implements AriaClient {
- private Client client=null;
- private WebTarget base_target=null;
-
- /**
- * Construct an Aria REST client
- *
- * @param protocol either http or https
- * @param address the IP address or host name
- * @param port the port of the service
- * @param version the api version
- */
- public AriaRestClient(String protocol, String address, int port, String version){
- this.client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build();
- base_target = client.target(protocol+"://"+address+":"+port+"/api/"+version);
- }
-
- /**
- * Installs a service template
- *
- * @param template the template object
- * @throws ValidationException
- * @throws StorageException
- */
- public void install_service_template(ServiceTemplate template) throws ValidationException, StorageException, Exception {
-
- Response response = base_target.path("templates/"+template.getName()).request(MediaType.APPLICATION_JSON).put(Entity.entity(
- "{\"service-template-path\":\""+template.getURI().toString()+"\""+
- ",\"service-template-filename\":\""+template.getFilename()+"\"", MediaType.APPLICATION_JSON));
-
- if(response.getStatus() == 500){
- throw new StorageException(response.readEntity(String.class));
- }
- else if(response.getStatus() == 400){
- throw new ValidationException(response.readEntity(String.class));
- }
- else if(response.getStatus()>199 && response.getStatus() <300){
- return;
- }
- else{
- throw new Exception("Error installing template: "+response.getStatus()+" "+ response.readEntity(String.class));
- }
- }
-
- public ValidationResult validate_service_template(ServiceTemplate template)throws Exception{
- Response response = base_target.path("templates").request(MediaType.APPLICATION_JSON).post(Entity.entity(
- "{\"service-template-path\":\""+template.getURI().toString()+"\""+
- ",\"service-template-filename\":\""+template.getFilename()+"\"}", MediaType.APPLICATION_JSON));
-
- ValidationResultImpl result = new ValidationResultImpl();
- if(response.getStatus() >= 200 && response.getStatus() < 300){
- result.setFailed(false);
- }
- else if(response.getStatus()==400){
- result.setFailed(true);
- }
- else{
- throw new Exception("received error response '"+ response.getStatus()+"':"+response.readEntity(String.class));
- }
- return result;
-
- }
-
- /**
- *
- * @return a list of service templates
- */
- public List<? extends ServiceTemplate> list_service_templates(){
- List<? extends ServiceTemplate> templates = base_target.path("templates").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ServiceTemplateImpl>>(){});
-
- return templates;
- }
-
-
- /**
- * Deletes the specified template.
- *
- * TODO: Error handling is a little blunt. Need to describe failures better
- *
- * @param template_id the template id to delete
- * @throws IllegalArgumentException thrown when the template can't be deleted
- * @throws Exception other server side errors
- */
- public void delete_service_template(int template_id) throws IllegalArgumentException, Exception{
- Response response = base_target.path("templates/"+template_id).request(MediaType.APPLICATION_JSON).delete();
-
- if(response.getStatus()>=200 && response.getStatus()<300){
- return;
- }
- else if(response.getStatus()==400){
- throw new IllegalArgumentException("Error deleting template '"+template_id+"'");
- }
- else{
- throw new Exception("Error processing request. Return code = "+response.getStatus());
- }
- }
-
- /**
- * List the node templates for a given template id
- *
- * @param template_id
- * @return
- */
- public List<? extends NodeTemplate> list_nodes(int template_id) {
- List<? extends NodeTemplate> nodes = base_target.path("templates/"+template_id+"/nodes").request(MediaType.APPLICATION_JSON).get(new GenericType<List<NodeTemplateImpl>>(){});
- return nodes;
- }
-
- /**
- * Get a specific node by id
- *
- * @param node_id the node id
- * @return
- * @throws IllegalArgumentException
- */
- public NodeTemplate get_node(int node_id) throws IllegalArgumentException {
- NodeTemplate node = base_target.path("nodes/"+node_id).request(MediaType.APPLICATION_JSON).get(NodeTemplateImpl.class);
- return node;
- }
-
- public List<? extends Service> list_services() {
- List<? extends Service> services = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ServiceImpl>>(){});
- return services;
- }
-
- public Service get_service(int service_id) throws IllegalArgumentException {
- throw new NotImplementedException();
- }
-
- public List<? extends Output> list_service_outputs(int service_id) throws IllegalArgumentException {
- List<? extends Output> outputs = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<OutputImpl>>(){});
- return outputs;
- }
-
- public List<? extends Input> list_service_inputs(int service_id) throws IllegalArgumentException {
- List<? extends Input> inputs = base_target.path("services").request(MediaType.APPLICATION_JSON).get(new GenericType<List<InputImpl>>(){});
- return inputs;
- }
-
- /**
- * Create a service based on the supplied template
- *
- * @param template_id the template to create the service for
- * @param service_name a name for the service
- * @param inputs an optional list of inputs for the service (can be null)
- * @throws Exception
- */
- public void create_service(int template_id, String service_name, List<Input> inputs) throws Exception {
-
- String json="{"+inputsToJson(inputs)+"}";
-
- Response response = base_target.path("templates/"+template_id+"/services/"+service_name).
- request(MediaType.APPLICATION_JSON).post(
- Entity.entity(json, MediaType.APPLICATION_JSON)
- );
-
- if( response.getStatus()< 200 || response.getStatus()>299){
- throw new Exception("create service failed:"+response.getStatus()+" "+ response.readEntity(String.class));
- }
- }
-
- public void delete_service(int service_id) throws Exception {
- Response response = base_target.path("services/"+service_id).request(MediaType.APPLICATION_JSON).delete();
- if(!responseOK(response)){
- throw new Exception("delete service failed: "+response.getStatus()+" "+ response.readEntity(String.class));
- }
- }
-
- /**
- * List user workflows for supplied service
- *
- * @param service_id
- * @return
- * @throws IllegalArgumentException
- */
- public List<? extends Workflow> list_workflows(int service_id) throws IllegalArgumentException {
- List<? extends Workflow> workflows = base_target.path("services/"+service_id+"/workflows").request(MediaType.APPLICATION_JSON).get(new GenericType<List<WorkflowImpl>>(){});
- return workflows;
- }
-
- public Workflow get_workflow(int workflow_id) throws IllegalArgumentException {
- throw new NotImplementedException();
- }
-
- /**
- * List all executions
- *
- * @return
- * @throws Exception
- */
- public List<? extends Execution> list_executions() throws Exception {
- List<? extends Execution> executions = base_target.path("executions").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>(){});
- return executions;
- }
-
- /**
- * List executions for specified service
- *
- * @param service_id
- * @return
- * @throws Exception
- */
- public List<? extends Execution> list_executions(int service_id) throws Exception {
- List<? extends Execution> executions = base_target.path("services/"+service_id+"/executions").request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>(){});
- return executions;
- }
-
- /**
- * Get details about a specified execution
- *
- * @param execution_id
- * @return
- * @throws IllegalArgumentException
- */
- public Execution get_execution(int execution_id) throws IllegalArgumentException {
- Execution execution = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).get(ExecutionImpl.class);
- return execution;
- }
-
- /**
- * Start an execution for the specified service
- *
- * @param service_id the service to run the execution for
- * @param workflow_name the name of the workflow to execute
- * @param details details controlling execution operation
- * @return the execution id
- * @throws Exception
- */
- public int start_execution(int service_id, String workflow_name, ExecutionDetails details) throws Exception {
- StringBuilder json=new StringBuilder("{");
- if(details.getExecutor().length()>0){
- json.append("\"executor\":\"").append(details.getExecutor()).append("\",");
- }
- if(details.getInputs()!=null){
- json.append(inputsToJson(details.getInputs()));
- }
- json.append("\"task_max_attempts\":").append(details.getTaskMaxAttempts()).append(",");
- json.append("\"task_retry_interval\":").append(details.getTaskRetryInterval()).append("}");
-
- System.out.println("JSON="+json.toString());
-
- Response response = base_target.path("services/"+service_id+"/executions/"+workflow_name).request(MediaType.APPLICATION_JSON).
- post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));
-
- if(!responseOK(response)){
- throw new Exception("start execution failed: "+response.getStatus()+" "+response.readEntity(String.class));
- }
-
- ObjectMapper mapper = new ObjectMapper(new JsonFactory());
- JsonNode rootNode = mapper.readTree(response.readEntity(String.class));
- int id=rootNode.get("id").asInt(-1);
- return id;
- }
-
- public void resume_execution(int execution_id, ExecutionDetails details) throws IllegalArgumentException {
- StringBuilder json=new StringBuilder("{");
- if(details.getExecutor().length()>0){
- json.append("\"executor\":\"").append(details.getExecutor()).append("\",");
- }
- json.append("\"retry_failed_tasks\":").append(details.isRetry_failed_tasks()).append("}");
- Response response = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).
- post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON));
- }
-
- public void cancel_execution(int execution_id) throws Exception {
- Response response = base_target.path("executions/"+execution_id).request(MediaType.APPLICATION_JSON).delete();
- if(!responseOK(response)){
- throw new Exception("delete service failed: "+response.getStatus()+" "+ response.readEntity(String.class));
- }
- }
-
- /**
- * -----
- * ----- PRIVATE METHODS
- * -----
- */
-
- private boolean responseOK(Response response){
- return response.getStatus()>199 && response.getStatus()<300;
- }
-
- private String inputsToJson(List<Input> inputs){
- if(inputs==null)return null;
-
- StringBuilder sb=new StringBuilder("\"inputs\":{");
- for(Input input:inputs){
- sb.append("\"").append(input.getName()).append("\":\"").append(input.getValue()).append("\",");
- }
- if(inputs.size()>0)sb.deleteCharAt(sb.length()-1); //trim comma
-
- return sb.toString();
- }
-}
+/* + * ============LICENSE_START=================================================== + * Copyright (c) 2017 Cloudify.co. 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 com.gigaspaces.aria.rest.client; + +import java.util.List; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.codehaus.jackson.JsonFactory; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.jaxrs.JacksonJsonProvider; +import org.codehaus.jackson.map.ObjectMapper; +import com.gigaspaces.aria.rest.client.exceptions.StorageException; +import com.gigaspaces.aria.rest.client.exceptions.ValidationException; + +import sun.reflect.generics.reflectiveObjects.NotImplementedException; + +/** + * Created by DeWayne on 7/12/2017. + */ +public class AriaRestClient implements AriaClient { + private Client client = null; + private WebTarget base_target = null; + + /** + * Construct an Aria REST client + * + * @param protocol + * either http or https + * @param address + * the IP address or host name + * @param port + * the port of the service + * @param version + * the api version + */ + public AriaRestClient(String protocol, String address, int port, String version) { + this.client = ClientBuilder.newBuilder().register(JacksonJsonProvider.class).build(); + base_target = client.target(protocol + "://" + address + ":" + port + "/api/" + version); + } + + /** + * Installs a service template + * + * @param template + * the template object + * @throws ValidationException + * @throws StorageException + */ + public void install_service_template(ServiceTemplate template) + throws ValidationException, StorageException, Exception { + + byte[] csarBytes = template.getCSARBytes(); + Response response = null; + if (csarBytes == null) { + response = base_target.path("templates/" + template.getName()).request(MediaType.APPLICATION_JSON) + .put(Entity.entity( + "{\"service-template-path\":\"" + template.getURI().toString() + "\"" + + ",\"service-template-filename\":\"" + template.getFilename() + "\"", + MediaType.APPLICATION_JSON)); + } + else { + + response = base_target.path("templates/" + template.getName()).request("application/zip") + .put(Entity.entity(csarBytes, "application/zip")); + } + + if (response.getStatus() == 500) { + throw new StorageException(response.readEntity(String.class)); + } else if (response.getStatus() == 400) { + throw new ValidationException(response.readEntity(String.class)); + } else if (response.getStatus() > 199 && response.getStatus() < 300) { + return; + } else { + throw new Exception( + "Error installing template: " + response.getStatus() + " " + response.readEntity(String.class)); + } + } + + public ValidationResult validate_service_template(ServiceTemplate template) throws Exception { + Response response = base_target.path("templates").request(MediaType.APPLICATION_JSON) + .post(Entity.entity( + "{\"service-template-path\":\"" + template.getURI().toString() + "\"" + + ",\"service-template-filename\":\"" + template.getFilename() + "\"}", + MediaType.APPLICATION_JSON)); + + ValidationResultImpl result = new ValidationResultImpl(); + if (response.getStatus() >= 200 && response.getStatus() < 300) { + result.setFailed(false); + } else if (response.getStatus() == 400) { + result.setFailed(true); + } else { + throw new Exception( + "received error response '" + response.getStatus() + "':" + response.readEntity(String.class)); + } + return result; + + } + + /** + * + * @return a list of service templates + */ + public List<? extends ServiceTemplate> list_service_templates() { + List<? extends ServiceTemplate> templates = base_target.path("templates").request(MediaType.APPLICATION_JSON) + .get(new GenericType<List<ServiceTemplateImpl>>() { + }); + + return templates; + } + + /** + * Deletes the specified template. + * + * TODO: Error handling is a little blunt. Need to describe failures better + * + * @param template_id + * the template id to delete + * @throws IllegalArgumentException + * thrown when the template can't be deleted + * @throws Exception + * other server side errors + */ + public void delete_service_template(int template_id) throws IllegalArgumentException, Exception { + Response response = base_target.path("templates/" + template_id).request(MediaType.APPLICATION_JSON).delete(); + + if (response.getStatus() >= 200 && response.getStatus() < 300) { + return; + } else if (response.getStatus() == 400) { + throw new IllegalArgumentException("Error deleting template '" + template_id + "'"); + } else { + throw new Exception("Error processing request. Return code = " + response.getStatus()); + } + } + + /** + * List the node templates for a given template id + * + * @param template_id + * @return + */ + public List<? extends NodeTemplate> list_nodes(int template_id) { + List<? extends NodeTemplate> nodes = base_target.path("templates/" + template_id + "/nodes") + .request(MediaType.APPLICATION_JSON).get(new GenericType<List<NodeTemplateImpl>>() { + }); + return nodes; + } + + /** + * Get a specific node by id + * + * @param node_id + * the node id + * @return + * @throws IllegalArgumentException + */ + public NodeTemplate get_node(int node_id) throws IllegalArgumentException { + NodeTemplate node = base_target.path("nodes/" + node_id).request(MediaType.APPLICATION_JSON) + .get(NodeTemplateImpl.class); + return node; + } + + public List<? extends Service> list_services() { + List<? extends Service> services = base_target.path("services").request(MediaType.APPLICATION_JSON) + .get(new GenericType<List<ServiceImpl>>() { + }); + return services; + } + + public Service get_service(int service_id) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + public List<? extends Output> list_service_outputs(int service_id) throws IllegalArgumentException { + List<? extends Output> outputs = base_target.path("services").request(MediaType.APPLICATION_JSON) + .get(new GenericType<List<OutputImpl>>() { + }); + return outputs; + } + + public List<? extends Input> list_service_inputs(int service_id) throws IllegalArgumentException { + List<? extends Input> inputs = base_target.path("services").request(MediaType.APPLICATION_JSON) + .get(new GenericType<List<InputImpl>>() { + }); + return inputs; + } + + /** + * Create a service based on the supplied template + * + * @param template_id + * the template to create the service for + * @param service_name + * a name for the service + * @param inputs + * an optional list of inputs for the service (can be null) + * @throws Exception + */ + public void create_service(int template_id, String service_name, List<Input> inputs) throws Exception { + + String json = "{" + inputsToJson(inputs) + "}"; + + Response response = base_target.path("templates/" + template_id + "/services/" + service_name) + .request(MediaType.APPLICATION_JSON).post(Entity.entity(json, MediaType.APPLICATION_JSON)); + + if (response.getStatus() < 200 || response.getStatus() > 299) { + throw new Exception( + "create service failed:" + response.getStatus() + " " + response.readEntity(String.class)); + } + } + + public void delete_service(int service_id) throws Exception { + Response response = base_target.path("services/" + service_id).request(MediaType.APPLICATION_JSON).delete(); + if (!responseOK(response)) { + throw new Exception( + "delete service failed: " + response.getStatus() + " " + response.readEntity(String.class)); + } + } + + /** + * List user workflows for supplied service + * + * @param service_id + * @return + * @throws IllegalArgumentException + */ + public List<? extends Workflow> list_workflows(int service_id) throws IllegalArgumentException { + List<? extends Workflow> workflows = base_target.path("services/" + service_id + "/workflows") + .request(MediaType.APPLICATION_JSON).get(new GenericType<List<WorkflowImpl>>() { + }); + return workflows; + } + + public Workflow get_workflow(int workflow_id) throws IllegalArgumentException { + throw new NotImplementedException(); + } + + /** + * List all executions + * + * @return + * @throws Exception + */ + public List<? extends Execution> list_executions() throws Exception { + List<? extends Execution> executions = base_target.path("executions").request(MediaType.APPLICATION_JSON) + .get(new GenericType<List<ExecutionImpl>>() { + }); + return executions; + } + + /** + * List executions for specified service + * + * @param service_id + * @return + * @throws Exception + */ + public List<? extends Execution> list_executions(int service_id) throws Exception { + List<? extends Execution> executions = base_target.path("services/" + service_id + "/executions") + .request(MediaType.APPLICATION_JSON).get(new GenericType<List<ExecutionImpl>>() { + }); + return executions; + } + + /** + * Get details about a specified execution + * + * @param execution_id + * @return + * @throws IllegalArgumentException + */ + public Execution get_execution(int execution_id) throws IllegalArgumentException { + Execution execution = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON) + .get(ExecutionImpl.class); + return execution; + } + + /** + * Start an execution for the specified service + * + * @param service_id + * the service to run the execution for + * @param workflow_name + * the name of the workflow to execute + * @param details + * details controlling execution operation + * @return the execution id + * @throws Exception + */ + public int start_execution(int service_id, String workflow_name, ExecutionDetails details) throws Exception { + StringBuilder json = new StringBuilder("{"); + if (details.getExecutor().length() > 0) { + json.append("\"executor\":\"").append(details.getExecutor()).append("\","); + } + if (details.getInputs() != null) { + json.append(inputsToJson(details.getInputs())); + } + json.append("\"task_max_attempts\":").append(details.getTaskMaxAttempts()).append(","); + json.append("\"task_retry_interval\":").append(details.getTaskRetryInterval()).append("}"); + + System.out.println("JSON=" + json.toString()); + + Response response = base_target.path("services/" + service_id + "/executions/" + workflow_name) + .request(MediaType.APPLICATION_JSON).post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON)); + + if (!responseOK(response)) { + throw new Exception( + "start execution failed: " + response.getStatus() + " " + response.readEntity(String.class)); + } + + ObjectMapper mapper = new ObjectMapper(new JsonFactory()); + JsonNode rootNode = mapper.readTree(response.readEntity(String.class)); + int id = rootNode.get("id").asInt(-1); + return id; + } + + public void resume_execution(int execution_id, ExecutionDetails details) throws IllegalArgumentException { + StringBuilder json = new StringBuilder("{"); + if (details.getExecutor().length() > 0) { + json.append("\"executor\":\"").append(details.getExecutor()).append("\","); + } + json.append("\"retry_failed_tasks\":").append(details.isRetry_failed_tasks()).append("}"); + Response response = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON) + .post(Entity.entity(json.toString(), MediaType.APPLICATION_JSON)); + } + + public void cancel_execution(int execution_id) throws Exception { + Response response = base_target.path("executions/" + execution_id).request(MediaType.APPLICATION_JSON).delete(); + if (!responseOK(response)) { + throw new Exception( + "delete service failed: " + response.getStatus() + " " + response.readEntity(String.class)); + } + } + + /** + * ----- ----- PRIVATE METHODS ----- + */ + + private boolean responseOK(Response response) { + return response.getStatus() > 199 && response.getStatus() < 300; + } + + private String inputsToJson(List<Input> inputs) { + if (inputs == null) + return null; + + StringBuilder sb = new StringBuilder("\"inputs\":{"); + for (Input input : inputs) { + sb.append("\"").append(input.getName()).append("\":\"").append(input.getValue()).append("\","); + } + if (inputs.size() > 0) + sb.deleteCharAt(sb.length() - 1); // trim comma + + return sb.toString(); + } +} diff --git a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplate.java b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplate.java index 0df6d60905..a2ca8cf662 100644 --- a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplate.java +++ b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplate.java @@ -1,31 +1,32 @@ -/*
- * ============LICENSE_START===================================================
- * Copyright (c) 2017 Cloudify.co. 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 com.gigaspaces.aria.rest.client;
-
-import java.net.URI;
-
-/**
- * Created by DeWayne on 7/12/2017.
- */
-public interface ServiceTemplate {
- String getName();
- URI getURI();
- int getId();
- String getFilename();
- String getDescription();
-}
+/* + * ============LICENSE_START=================================================== + * Copyright (c) 2017 Cloudify.co. 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 com.gigaspaces.aria.rest.client; + +import java.net.URI; + +/** + * Created by DeWayne on 7/12/2017. + */ +public interface ServiceTemplate { + String getName(); + URI getURI(); + int getId(); + String getFilename(); + String getDescription(); + byte[] getCSARBytes(); +} diff --git a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplateImpl.java b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplateImpl.java index 9e158a27fd..a41d5b7236 100644 --- a/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplateImpl.java +++ b/aria/aria-rest-java-client/src/main/java/com/gigaspaces/aria/rest/client/ServiceTemplateImpl.java @@ -31,6 +31,7 @@ public class ServiceTemplateImpl implements ServiceTemplate { private URI uri; private String filename = DEFAULT_TEMPLATE_NAME; private String description; + private byte[] csar_blob; // for opaque binary public ServiceTemplateImpl(){} @@ -40,7 +41,7 @@ public class ServiceTemplateImpl implements ServiceTemplate { } /** - * Construct an instance + * Construct an instance based on CSAR * @param name a textual name for the template * @param uri a URI to a CSAR * @param filename the filename in the CSAR representing main yaml template @@ -51,6 +52,13 @@ public class ServiceTemplateImpl implements ServiceTemplate { this.filename=filename; this.description=description; } + + /** + * Construct an instance based on CSAR array + */ + public ServiceTemplateImpl(byte[] csar_bytes) { + this.csar_blob = csar_bytes; + } public int getId(){ return id; @@ -76,6 +84,9 @@ public class ServiceTemplateImpl implements ServiceTemplate { public void setFilename(String filename){ this.filename=filename; } + public byte[] getCSARBytes() { + return csar_blob; + } public String getDescription(){ return description;} } diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index 4a7cb5900a..523ee403d0 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -501,5 +501,16 @@ <artifactId>guava</artifactId> <version>22.0</version> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>3.9.0</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>pl.pragmatists</groupId> + <artifactId>JUnitParams</artifactId> + <version>1.1.1</version> + </dependency> </dependencies> </project> diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcessTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcessTest.groovy index ab7ee7a689..5949c3af53 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcessTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/openecomp/mso/bpmn/common/scripts/CompleteMsoProcessTest.groovy @@ -16,23 +16,24 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */ + */ package org.openecomp.mso.bpmn.common.scripts -import org.junit.runner.RunWith; -import static org.junit.Assert.* -import static org.mockito.Mockito.* - import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner import org.openecomp.mso.bpmn.core.WorkflowException +import static org.assertj.core.api.Assertions.assertThat +import static org.assertj.core.api.Assertions.assertThatThrownBy +import static org.mockito.Matchers.eq +import static org.mockito.Mockito.* @RunWith(MockitoJUnitRunner.class) class CompleteMsoProcessTest { @@ -128,7 +129,7 @@ class CompleteMsoProcessTest { when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("BPEL") when(mockExecution.getVariable("URN_mso_adapters_db_auth")).thenReturn("757A94191D685FD2092AC1490730A4FC"); when(mockExecution.getVariable("URN_mso_msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7"); - + CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess() completeMsoProcess.setUpdateDBstatustoSuccessPayload(mockExecution) @@ -145,29 +146,25 @@ class CompleteMsoProcessTest { </sdncadapterworkflow:MsoCompletionResponse>""" */ @Test - public void testbuildDataError(){ - - boolean thrown = false; - String msg = "Some-Message"; - - ExecutionEntity mockExecution = mock(ExecutionEntity.class) - when(mockExecution.getVariable("CMSO_mso-bpel-name")).thenReturn("BPEL-NAME") - when(mockExecution.getVariable("testProcessKey")).thenReturn("CompleteMsoProcess") - - WorkflowException exception = new WorkflowException("CompleteMsoProcess", 500, msg); - - try{ - CompleteMsoProcess completeMsoProcess = new CompleteMsoProcess() - completeMsoProcess.buildDataError(mockExecution, msg) - } - catch (BpmnError e){ - thrown = true; - } - - - verify(mockExecution).setVariable("CompleteMsoProcessResponse",msoCompletionResponse) - // Can't seem to figure out how to verify the exception and have spent way too much time on fixing this test case! - //verify(mockExecution).setVariable("WorkflowException",exception) - assertTrue(thrown); - } + void testBuildDataError() { + // given + def message = "Some-Message" + + def mockExecution = mock ExecutionEntity.class + when mockExecution.getVariable("CMSO_mso-bpel-name") thenReturn "BPEL-NAME" + when mockExecution.getVariable("testProcessKey") thenReturn "CompleteMsoProcess" + + def completeMsoProcess = new CompleteMsoProcess() + // when + assertThatThrownBy { completeMsoProcess.buildDataError(mockExecution, message) } isInstanceOf BpmnError + // then + verify mockExecution setVariable("CompleteMsoProcessResponse", msoCompletionResponse) + def argumentCaptor = ArgumentCaptor.forClass WorkflowException.class + verify mockExecution setVariable(eq("WorkflowException"), argumentCaptor.capture()) + def capturedException = argumentCaptor.value + + assertThat capturedException.processKey isEqualTo "CompleteMsoProcess" + assertThat capturedException.errorCode isEqualTo 500 + assertThat capturedException.errorMessage isEqualTo message + } }
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java new file mode 100644 index 0000000000..8943014ad0 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/client/ResponseExceptionMapperImplTest.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.google.common.base.Charsets; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.ForbiddenException; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotAcceptableException; +import javax.ws.rs.NotAllowedException; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.NotSupportedException; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.core.Response.Status; +import junitparams.JUnitParamsRunner; +import junitparams.Parameters; +import org.apache.commons.io.IOUtils; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(JUnitParamsRunner.class) +public class ResponseExceptionMapperImplTest { + + private static final ResponseExceptionMapperImpl mapper = new ResponseExceptionMapperImpl(); + + public static Object[][] statusesAndCorrespondingExceptions() { + return new Object[][]{ + {Status.BAD_REQUEST, BadRequestException.class}, + {Status.UNAUTHORIZED, NotAuthorizedException.class}, + {Status.FORBIDDEN, ForbiddenException.class}, + {Status.NOT_FOUND, NotFoundException.class}, + {Status.METHOD_NOT_ALLOWED, NotAllowedException.class}, + {Status.NOT_ACCEPTABLE, NotAcceptableException.class}, + {Status.PRECONDITION_FAILED, PreconditionFailedException.class}, + {Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class}, + {Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class}, + {Status.SERVICE_UNAVAILABLE, WebApplicationException.class}, + {Status.BAD_GATEWAY, WebApplicationException.class}, + }; + } + + @Test + @Parameters(method = "statusesAndCorrespondingExceptions") + public void shouldThrowExceptionWhenStatusIsNotOk(Status status, Class<Exception> expectedException) { + // given + ClientResponseContext responseContext = createMockResponseContext(status); + // when, then + assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(expectedException); + } + + @Test + public void shouldNotThrowExceptionWhenStatusIsOk() { + // given + ClientResponseContext responseContext = createMockResponseContext(Status.OK); + // when, then + assertThatCode(() -> mapper.filter(null, responseContext)).doesNotThrowAnyException(); + } + + @Test + public void shouldThrowExceptionWithCustomMessageWhenResponseHasEntity() { + // given + ClientResponseContext responseContext = createMockResponseContext(Status.BAD_REQUEST); + when(responseContext.hasEntity()).thenReturn(true); + when(responseContext.getEntityStream()).thenReturn(IOUtils.toInputStream("test message", Charsets.UTF_8)); + // when, then + assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(BadRequestException.class) + .hasMessage("test message"); + } + + @Test + public void shouldThrowExceptionWithDefaultMessageWhenResponseHasNoEntity() { + // given + ClientResponseContext responseContext = createMockResponseContext(Status.BAD_REQUEST); + when(responseContext.hasEntity()).thenReturn(false); + // when, then + assertThatThrownBy(() -> mapper.filter(null, responseContext)).isInstanceOf(BadRequestException.class) + .hasMessage("empty message"); + } + + private static ClientResponseContext createMockResponseContext(Status status) { + ClientResponseContext responseContext = mock(ClientResponseContext.class); + when(responseContext.getStatusInfo()).thenReturn(status); + when(responseContext.getStatus()).thenReturn(status.getStatusCode()); + return responseContext; + } +}
\ No newline at end of file diff --git a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java index 86aedc1a43..b8c4aed8fa 100644 --- a/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java +++ b/common/src/main/java/org/openecomp/mso/logger/MsoLogger.java @@ -144,15 +144,16 @@ public class MsoLogger { // For internal logging of the initialization of MSO logs private static final Logger LOGGER = Logger.getLogger(MsoLogger.class.getName()); - private MsoLogger(MsoLogger.Catalog cat) { - this.logger = EELFManager.getInstance().getErrorLogger(); - this.auditLogger = EELFManager.getInstance().getAuditLogger(); - this.metricsLogger = EELFManager.getInstance().getMetricsLogger(); - MsoLogger.initialization(); - setDefaultLogCatalog(cat); - } - private static synchronized void initialization() { + // Since four adaptors are using the instance of MsoLogger which will be referenced everywhere + // hence limiting the number of MsoLogger instances to five. + private static final MsoLogger generalMsoLogger = new MsoLogger(Catalog.GENERAL); + private static final MsoLogger apihLogger = new MsoLogger(Catalog.APIH); + private static final MsoLogger asdcLogger = new MsoLogger(Catalog.ASDC); + private static final MsoLogger raLogger = new MsoLogger(Catalog.RA); + private static final MsoLogger bpelLogger = new MsoLogger(Catalog.BPEL); + + static { if (instanceUUID == null || ("").equals(instanceUUID)) { instanceUUID = getInstanceUUID(); } @@ -170,15 +171,40 @@ public class MsoLogger { } } + // Singleton instances of the EELFLogger of all types are referenced by MsoLogger + private MsoLogger(Catalog cat) { + this.logger = EELFManager.getInstance().getErrorLogger(); + this.auditLogger = EELFManager.getInstance().getAuditLogger(); + this.metricsLogger = EELFManager.getInstance().getMetricsLogger(); + this.setDefaultLogCatalog(cat); + } + + + /** * Get the MsoLogger based on the catalog - * + * This method is fixed now to resolve the total number of objects that are getting created + * everytime this function gets called. Its supposed to have fixed number of instance per java process. + * * @param cat * Catalog of the logger * @return the MsoLogger */ public static synchronized MsoLogger getMsoLogger(MsoLogger.Catalog cat) { - return new MsoLogger(cat); + switch (cat) { + case GENERAL: + return generalMsoLogger; + case APIH: + return apihLogger; + case RA: + return raLogger; + case BPEL: + return bpelLogger; + case ASDC: + return asdcLogger; + default: + return generalMsoLogger; + } } /** |