From 161df8a94bb3b0c34ed16fd4fdba078bd1eeef9a Mon Sep 17 00:00:00 2001 From: Patrick Brady Date: Wed, 13 Dec 2017 11:14:21 -0800 Subject: Second part of onap rename This is the second commit of the rename. The folder structure is renamed for appc-adapters and appc-config in this commit. Change-Id: Iaa2b8c937ff1ca1b5d1178128961fb115ee65d9b Signed-off-by: Patrick Brady Issue-ID: APPC-13 --- .../org/onap/appc/adapter/rest/RequestFactory.java | 60 +++++ .../org/onap/appc/adapter/rest/RestActivator.java | 145 ++++++++++++ .../org/onap/appc/adapter/rest/RestAdapter.java | 208 +++++++++++++++++ .../appc/adapter/rest/impl/RequestContext.java | 254 +++++++++++++++++++++ .../adapter/rest/impl/RequestFailedException.java | 247 ++++++++++++++++++++ .../appc/adapter/rest/impl/RestAdapterImpl.java | 244 ++++++++++++++++++++ 6 files changed, 1158 insertions(+) create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java create mode 100644 appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java (limited to 'appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap') diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java new file mode 100644 index 000000000..685ae13a9 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RequestFactory.java @@ -0,0 +1,60 @@ +/* + * ============LICENSE_START============================================================================================================= + * Copyright (c) 2017 Intel Corp. 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.onap.appc.adapter.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.utils.URIBuilder; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +public class RequestFactory { + private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestFactory.class); + + final static Map> map = new HashMap<>(); + + static { + map.put("GET", HttpGet::new); + map.put("POST", HttpPost::new); + map.put("PUT", HttpPut::new); + map.put("DELETE", HttpDelete::new); + } + + public HttpRequestBase getHttpRequest(String method, String tUrl) { + Supplier httpRequestSupplier = map.get(method.toUpperCase()); + URI uri = null; + if (httpRequestSupplier != null ) { + try { + uri = new URIBuilder(tUrl).build(); + } catch (URISyntaxException ex) { + logger.error("URI Syntax Incorrect: " + tUrl, ex); + } + HttpRequestBase httpRequest = httpRequestSupplier.get(); + httpRequest.setURI(uri); + return httpRequest; + + } + throw new IllegalArgumentException("No method named: " + method.toUpperCase()); + } +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java new file mode 100644 index 000000000..3e224b923 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestActivator.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest; + +import org.onap.appc.Constants; +import org.onap.appc.adapter.rest.impl.RestAdapterImpl; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.i18n.Msg; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +/** + * This activator is used to initialize and terminate the connection pool to one or more providers. + *

+ * The CDP abstraction layer supports multiple types of providers, with each provider supporting multiple tenants. The + * "connection" to a specific tenant on a specific provider is represented by a "context" object. These context objects + * are authenticated to a specific tenant on the provider, but can be reused from one request to another. Contexts are + * slow to set up and are resource intensive, so they are cached. However, the contexts for a specific tenant on a + * specific provider must be cached separately. + *

+ *

+ * Activation of the bundle creates an empty cache which is organized first by provider type, then by tenant name, with + * the contents being an empty pool of contexts for that provider/tenant combination. The pool is created on first use, + * and retained for as long as the bundle is active. + *

+ *

+ * When the bundle is deactivated, the cache is torn down with all contexts being closed. + *

+ */ +public class RestActivator implements BundleActivator { + + /** + * The bundle registration + */ + private ServiceRegistration registration = null; + + /** + * The reference to the actual implementation object that implements the services + */ + private RestAdapter adapter; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(RestActivator.class); + + /** + * The configuration object used to configure this bundle + */ + private Configuration configuration; + + /** + * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start + * this bundle. This method can be used to register services or to allocate any resources that this bundle needs. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param context + * The execution context of the bundle being started. + * @throws java.lang.Exception + * If this method throws an exception, this bundle is marked as stopped and the Framework will remove + * this bundle's listeners, unregister all services registered by this bundle, and release all services + * used by this bundle. + * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) + */ + @Override + public void start(BundleContext context) throws Exception { + logger.info("Starting bundle " + getName()); + + configuration = ConfigurationFactory.getConfiguration(); + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_INITIALIZING, appName, "rest adapter"); + adapter = new RestAdapterImpl(); + if (registration == null) { + registration = context.registerService(RestAdapter.class, adapter, null); + } + + logger.info(Msg.COMPONENT_INITIALIZED, appName, "REST adapter"); + } + + /** + * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop + * the bundle. In general, this method should undo the work that the BundleActivator.start method started. There + * should be no active threads that were started by this bundle when this bundle returns. A stopped bundle must not + * call any Framework objects. + *

+ * This method must complete and return to its caller in a timely manner. + *

+ * + * @param context + * The execution context of the bundle being stopped. + * @throws java.lang.Exception + * If this method throws an exception, the bundle is still marked as stopped, and the Framework will + * remove the bundle's listeners, unregister all services registered by the bundle, and release all + * services used by the bundle. * + * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) + */ + @Override + public void stop(BundleContext context) throws Exception { + logger.info("Stopping bundle " + getName()); + + if (registration != null) { + String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME); + logger.info(Msg.COMPONENT_TERMINATING, appName, "REST adapter"); + logger.info(Msg.UNREGISTERING_SERVICE, appName, adapter.getAdapterName()); + registration.unregister(); + registration = null; + logger.info(Msg.COMPONENT_TERMINATED, appName, "REST adapter"); + } + } + + public String getName() { + return "APPC IaaS adapter"; + } + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java new file mode 100644 index 000000000..8542f105a --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/RestAdapter.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest; + +import java.util.Map; + +import org.onap.appc.exceptions.APPCException; +import com.att.cdp.zones.model.Server; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; + +/** + * This interface defines the operations that the provider adapter exposes. + *

+ * This interface defines static constant property values that can be used to configure the adapter. These constants are + * prefixed with the name PROPERTY_ to indicate that they are configuration properties. These properties are read from + * the configuration file for the adapter and are used to define the providers, identity service URLs, and other + * information needed by the adapter to interface with an IaaS provider. + *

+ */ +public interface RestAdapter extends SvcLogicJavaPlugin { + + /** + * The type of provider to be accessed to locate and operate on a virtual machine instance. This is used to load the + * correct provider support through the CDP IaaS abstraction layer and can be OpenStackProvider, BareMetalProvider, + * or any other supported provider type. + */ + static final String PROPERTY_PROVIDER_TYPE = "org.onap.appc.provider.type"; + + /** + * The adapter maintains a cache of providers organized by the name of the provider, not its type. This is + * equivalent to the system or installation name. All regions within the same installation are assumed to be the + * same type. + */ + static final String PROPERTY_PROVIDER_NAME = "org.onap.appc.provider.name"; + + /** + * The fully-qualified URL of the instance to be manipulated as it is known to the provider. + */ + static final String PROPERTY_INSTANCE_URL = "org.onap.appc.instance.url"; + + /** + * The fully-qualified URL of the instance to be manipulated as it is known to the provider. + */ + static final String PROPERTY_IDENTITY_URL = "org.onap.appc.identity.url"; + + /** + * This method is used to restart an existing virtual machine given the fully qualified URL of the machine. + *

+ * This method is invoked from a directed graph as an Executor node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.
+ *
org.onap.appc.instance.url
+ *
The fully qualified URL of the instance to be restarted, as it is known to the provider (i.e., the self-link + * URL of the server)
+ *
+ *

+ * + * @param properties + * A map of name-value pairs that supply the parameters needed by this method. The properties needed are + * defined above. + * @param context + * The service logic context of the graph being executed. + * @return The Server object that represents the VM being restarted. The returned server object can be + * inspected for the final state of the server once the restart has been completed. The method does not + * return until the restart has either completed or has failed. + * @throws APPCException + * If the server cannot be restarted for some reason + */ + // Server restartServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to stop the indicated server + *

+ * This method is invoked from a directed graph as an Executor node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.
+ *
org.onap.appc.instance.url
+ *
The fully qualified URL of the instance to be stopped, as it is known to the provider (i.e., the self-link + * URL of the server)
+ *
+ *

+ * + * @param properties + * A map of name-value pairs that supply the parameters needed by this method. The properties needed are + * defined above. + * @param context + * The service logic context of the graph being executed. + * @return The Server object that represents the VM being stopped. The returned server object can be + * inspected for the final state of the server once the stop has been completed. The method does not return + * until the stop has either completed or has failed. + * @throws APPCException + * If the server cannot be stopped for some reason + */ + //Server stopServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to start the indicated server + *

+ * This method is invoked from a directed graph as an Executor node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.
+ *
org.onap.appc.instance.url
+ *
The fully qualified URL of the instance to be started, as it is known to the provider (i.e., the self-link + * URL of the server)
+ *
+ *

+ * + * @param properties + * A map of name-value pairs that supply the parameters needed by this method. The properties needed are + * defined above. + * @param context + * The service logic context of the graph being executed. + * @return The Server object that represents the VM being started. The returned server object can be + * inspected for the final state of the server once the start has been completed. The method does not return + * until the start has either completed or has failed. + * @throws APPCException + * If the server cannot be started for some reason + */ + // Server startServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * This method is used to rebuild the indicated server + *

+ * This method is invoked from a directed graph as an Executor node. This means that the parameters + * passed to the method are passed as properties in a map. This method expects the following properties to be + * defined: + *

+ *
org.onap.appc.provider.type
+ *
The appropriate provider type, such as OpenStackProvider. This is used by the CDP IaaS + * abstraction layer to dynamically load and open a connection to the appropriate provider type. All CDP supported + * provider types are legal.
+ *
org.onap.appc.instance.url
+ *
The fully qualified URL of the instance to be rebuilt, as it is known to the provider (i.e., the self-link + * URL of the server)
+ *
+ *

+ * + * @param properties + * A map of name-value pairs that supply the parameters needed by this method. The properties needed are + * defined above. + * @param context + * The service logic context of the graph being executed. + * @return The Server object that represents the VM being rebuilt. The returned server object can be + * inspected for the final state of the server once the rebuild has been completed. The method does not + * return until the rebuild has either completed or has failed. + * @throws APPCException + * If the server cannot be rebuilt for some reason + */ + // Server rebuildServer(Map properties, SvcLogicContext context) throws APPCException; + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + */ + String getAdapterName(); + + // Server evacuateServer(Map params, SvcLogicContext ctx) throws APPCException; + + //Server migrateServer(Map params, SvcLogicContext ctx) throws APPCException; + + void commonGet(Map params, SvcLogicContext ctx) ; + + void commonPost(Map params, SvcLogicContext ctx) ; + + void commonPut(Map params, SvcLogicContext ctx) ; + + void commonDelete(Map params, SvcLogicContext ctx) ; + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java new file mode 100644 index 000000000..a3e6b1db4 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestContext.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.rest.impl; + +import org.onap.appc.Constants; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +/** + * This class is used to track and maintain recovery and time-to-live information for a request as it is being + * processed. + */ +public class RequestContext { + /** + * The number of seconds of wait time between successive attempts to connect to the provider. This is used to + * recover from provider outages or failures. It is not used to recover from logical errors, such as an invalid + * request, server not found, etc. + */ + private Integer retryDelay; + + /** + * The number of times we will attempt to connect to the provider. This is used to recover from provider outages or + * failures. It is not used to recover from logical errors, such as an invalid request, server not found, etc. + */ + private Integer retryLimit; + + /** + * The total time, in milliseconds, that the provider can have to process this request. If the accumulated time + * exceeds the time to live, then the request is failed with a timeout exception, regardless of the state of the + * provider. Note that the caller may supply this as a value in seconds, in which case it must be converted to + * milliseconds for the request context. + */ + private Long timeToLive; + + /** + * The accumulated time, in milliseconds, that has been used so far to process the request. This is compared to the + * time to live each time it is updated. If the accumulated time exceeds the time to live, then the request is + * failed with a timeout exception, regardless of the state of the provider. + */ + private long accumulatedTime; + + /** + * The total number of retries attempted so far + */ + private int attempt; + + /** + * The time when the stopwatch was started + */ + private long startTime = -1; + + /** + * The service logic (DG) context from the SLI + */ + private SvcLogicContext svcLogicContext; + + /** + * The configuration + */ + private Configuration configuration = ConfigurationFactory.getConfiguration(); + + /** + * Set to true whenever the retry limit has been exceeded, reset to false when reset() is called. + */ + private boolean retryFailed; + + /** + * Creates the request context + * + * @param context + * The service logic (SLI) context associated with the current DG + */ + public RequestContext(SvcLogicContext context) { + setSvcLogicContext(context); + } + + /** + * @return The retry delay, in seconds. If zero, then no retry is to be performed + */ + public int getRetryDelay() { + if (retryDelay == null) { + int value = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_DELAY); + retryDelay = Integer.valueOf(value); + } + + return retryDelay.intValue(); + } + + /** + * This method is a helper that allows the caller to delay for the retry interval time and not have to handle the + * thread interruption, timer handling, etc. + */ + public void delay() { + long time = getRetryDelay() * 1000L; + long future = System.currentTimeMillis() + time; + if (time != 0) { + while (System.currentTimeMillis() < future && time > 0) { + try { + Thread.sleep(time); + } catch (InterruptedException e) { + /* + * This is rare, but it can happen if another thread interrupts us while we are sleeping. In that + * case, the thread is resumed before the delay time has actually expired, so re-calculate the + * amount of delay time needed and reenter the sleep until we get to the future time. + */ + time = future - System.currentTimeMillis(); + } + } + } + } + + /** + * @return The number of retries that are allowed per connection + */ + public int getRetryLimit() { + if (retryLimit == null) { + int value = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_LIMIT); + retryLimit = Integer.valueOf(value); + } + + return retryLimit.intValue(); + } + + /** + * Check and count the connection attempt. + * + * @return True if the connection should be attempted. False indicates that the number of retries has been exhausted + * and it should NOT be attempted. + */ + public boolean attempt() { + if (retryFailed || attempt >= getRetryLimit()) { + retryFailed = true; + return false; + } + attempt++; + + return true; + } + + /** + * @return The number of retry attempts so far + */ + public int getAttempts() { + return attempt; + } + + /** + * @return True if the retry limit has been exceeded, false otherwise + */ + public boolean isFailed() { + return retryFailed; + } + + /** + * This method both checks the time to live to see if it has been exceeded and accumulates the total time used so + * far. + *

+ * Each time this method is called it accumulates the total duration since the last time it was called to the total + * time accumulator. It then checks the total time to the time to live and if greater, it returns false. As long as + * the total time used is less than or equal to the time to live limit, the method returns true. It is important to + * call this method at the very beginning of the process so that all parts of the process are tracked. + *

+ * + * @return True if the total time to live has not been exceeded. False indicates that the total time to live has + * been exceeded and no further processing should be performed. + */ + public boolean isAlive() { + long now = System.currentTimeMillis(); + if (startTime == -1) { + startTime = now; + return true; + } + accumulatedTime += (now - startTime); + startTime = now; + if (accumulatedTime > timeToLive) { + return false; + } + return true; + } + + /** + * @return The total amount of time used, in milliseconds. + */ + public long getTotalDuration() { + return accumulatedTime; + } + + /** + * This method is called to reset the retry counters. It has no effect on the time to live accumulator. + */ + public void reset() { + attempt = 0; + } + + /** + * Sets the time to live to the value, expressed in seconds + * + * @param time + * The time to live, in seconds + */ + public void setTimeToLiveSeconds(int time) { + setTimeToLiveMS(time * 1000L); + } + + /** + * Sets the time to live to the value, expressed in milliseconds + * + * @param time + * The time to live, in milliseconds + */ + public void setTimeToLiveMS(long time) { + this.timeToLive = time; + } + + /** + * @return The service logic context associated with this request + */ + public SvcLogicContext getSvcLogicContext() { + return svcLogicContext; + } + + /** + * @param svcLogicContext + * The service logic context to be associated with this request + */ + public void setSvcLogicContext(SvcLogicContext svcLogicContext) { + this.svcLogicContext = svcLogicContext; + } +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java new file mode 100644 index 000000000..3d3f35985 --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RequestFailedException.java @@ -0,0 +1,247 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + + +package org.onap.appc.adapter.rest.impl; + +import org.glassfish.grizzly.http.util.HttpStatus; +import com.att.cdp.zones.model.Server; + +/** + * This class is used to capture the exact cause and point of failure for the processing of a request. It is then used + * to encode the reason for the failure, status code, and anything else that needs to be captured and reported for + * diagnostic purposes. + */ +public class RequestFailedException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * The operation that was being requested or performed at the time of the failure. + */ + private String operation; + + /** + * A message that details the reason for the failure + */ + private String reason; + + /** + * The server that was being operated upon + */ + private Server server; + + /** + * The id of the server being operated upon if the server object is not available (such as the server was not found) + */ + private String serverId; + + /** + * The most appropriate Http Status code that reflects the error + */ + private HttpStatus status; + + /** + * + */ + public RequestFailedException() { + // intentionally empty + } + + /** + * @param message + * The error message + */ + public RequestFailedException(String message) { + super(message); + } + + /** + * Construct the request failed exception with the operation being performed, reason for the failure, http status + * code that is most appropriate, and the server we were processing. + * + * @param operation + * The operation being performed + * @param reason + * The reason that the operation was failed + * @param status + * The http status code that is most appropriate + * @param server + * The server that we were processing + */ + @SuppressWarnings("nls") + public RequestFailedException(String operation, String reason, HttpStatus status, Server server) { + super(operation + ":" + reason); + this.operation = operation; + this.reason = reason; + this.status = status; + this.server = server; + if (server != null) { + this.serverId = server.getId(); + } + } + + /** + * Construct the request failed exception with the operation being performed, reason for the failure, http status + * code that is most appropriate, and the server we were processing. + * + * @param ex + * The exception that we are wrapping + * @param operation + * The operation being performed + * @param reason + * The reason that the operation was failed + * @param status + * The http status code that is most appropriate + * @param server + * The server that we were processing + */ + @SuppressWarnings("nls") + public RequestFailedException(Throwable ex, String operation, String reason, HttpStatus status, Server server) { + super(operation + ":" + reason, ex); + this.operation = operation; + this.reason = reason; + this.status = status; + this.server = server; + if (server != null) { + this.serverId = server.getId(); + } + } + + /** + * @param message + * The error message + * @param cause + * A nested exception + */ + public RequestFailedException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + * The error message + * @param cause + * A nested exception + * @param enableSuppression + * whether or not suppression is enabled or disabled + * @param writableStackTrace + * whether or not the stack trace should be writable + */ + public RequestFailedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + /** + * @param cause + * the cause (which is saved for later retrieval by the {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or unknown.) + */ + public RequestFailedException(Throwable cause) { + super(cause); + } + + /** + * @return The operation being performed + */ + public String getOperation() { + return operation; + } + + /** + * @return The reason for the failure + */ + public String getReason() { + return reason; + } + + /** + * @return The server being operated upon + */ + public Server getServer() { + return server; + } + + /** + * @return The id of the server being operated upon + */ + public String getServerId() { + return serverId; + } + + /** + * @return The status code from the operation + */ + public HttpStatus getStatus() { + return status; + } + + /** + * @param operation + * The operation being performed + */ + public void setOperation(String operation) { + this.operation = operation; + } + + /** + * @param reason + * The reason for the failure + */ + public void setReason(String reason) { + this.reason = reason; + } + + /** + * @param server + * The server being operated upon + */ + public void setServer(Server server) { + this.server = server; + if (server != null) { + setServerId(server.getId()); + } + } + + /** + * @param serverId + * The id of the server being operated upon + */ + public void setServerId(String serverId) { + this.serverId = serverId; + } + + /** + * @param status + * The status of the request + */ + public void setStatus(HttpStatus status) { + this.status = status; + } + +} diff --git a/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java new file mode 100644 index 000000000..bbb37f4cf --- /dev/null +++ b/appc-adapters/appc-rest-adapter/appc-rest-adapter-bundle/src/main/java/org/onap/appc/adapter/rest/impl/RestAdapterImpl.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.adapter.rest.impl; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.json.JSONObject; +import org.onap.appc.Constants; +import org.onap.appc.adapter.rest.RestAdapter; +import org.onap.appc.adapter.rest.RequestFactory; +import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; + +import java.util.Iterator; +import java.util.Map; +import java.util.function.Supplier; + +/** + * This class implements the {@link RestAdapter} interface. This interface + * defines the behaviors that our service provides. + */ +public class RestAdapterImpl implements RestAdapter { + + /** + * The constant for the status code for a failed outcome + */ + @SuppressWarnings("nls") + private static final String OUTCOME_FAILURE = "failure"; + + /** + * The constant for the status code for a successful outcome + */ + @SuppressWarnings("nls") + private static final String OUTCOME_SUCCESS = "success"; + + /** + * The logger to be used + */ + private final EELFLogger logger = EELFManager.getInstance().getLogger(RestAdapterImpl.class); + + /** + * A reference to the adapter configuration object. + */ + private Configuration configuration; + + /** + * This default constructor is used as a work around because the activator + * wasnt getting called + */ + public RestAdapterImpl() { + initialize(); + + } + + /** + * Returns the symbolic name of the adapter + * + * @return The adapter name + * @see org.onap.appc.adapter.rest.RestAdapter#getAdapterName() + */ + @Override + public String getAdapterName() { + return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME); + } + + public void commonGet(Map params, SvcLogicContext ctx) { + logger.info("Run get method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpGet httpGet = (HttpGet) createHttpRequest("GET", params, rc); + executeHttpRequest(httpGet, rc); + } + + public void commonDelete(Map params, SvcLogicContext ctx) { + logger.info("Run Delete method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpDelete httpDelete = (HttpDelete) createHttpRequest("DELETE", params, rc); + executeHttpRequest(httpDelete, rc); + } + + public void commonPost(Map params, SvcLogicContext ctx) { + logger.info("Run post method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpPost httpPost = (HttpPost) createHttpRequest("POST", params, rc); + executeHttpRequest(httpPost, rc); + } + + public void commonPut(Map params, SvcLogicContext ctx) { + logger.info("Run put method"); + + RequestContext rc = new RequestContext(ctx); + rc.isAlive(); + + HttpPut httpPut = (HttpPut) createHttpRequest("PUT", params, rc); + executeHttpRequest(httpPut, rc); + } + + @SuppressWarnings("static-method") + private void doFailure(RequestContext rc, HttpStatus code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + String msg = (message == null) ? code.getReasonPhrase() : message; + if (msg.contains("\n")) { + msg = msg.substring(msg.indexOf("\n")); + } + + String status; + try { + status = Integer.toString(code.getStatusCode()); + } catch (Exception e) { + status = "500"; + } + svcLogic.setStatus(OUTCOME_FAILURE); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, status); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg); + svcLogic.setAttribute("org.openecomp.rest.result.code", status); + svcLogic.setAttribute("org.openecomp.rest.result.message", msg); + } + + + /** + * @param rc + * The request context that manages the state and recovery of the + * request for the life of its processing. + */ + @SuppressWarnings("static-method") + private void doSuccess(RequestContext rc, int code, String message) { + SvcLogicContext svcLogic = rc.getSvcLogicContext(); + svcLogic.setStatus(OUTCOME_SUCCESS); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_CODE, Integer.toString(HttpStatus.OK_200.getStatusCode())); + svcLogic.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, message); + svcLogic.setAttribute("org.openecomp.rest.agent.result.code",Integer.toString(code)); + svcLogic.setAttribute("org.openecomp.rest.agent.result.message",message); + svcLogic.setAttribute("org.openecomp.rest.result.code",Integer.toString(HttpStatus.OK_200.getStatusCode())); + } + + public void executeHttpRequest(HttpRequestBase httpRequest, RequestContext rc){ + try { + HttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(httpRequest); + int responseCode = response.getStatusLine().getStatusCode(); + HttpEntity entity = response.getEntity(); + String responseOutput = EntityUtils.toString(entity); + if(responseCode == 200){ + doSuccess(rc,responseCode,responseOutput); + } else { + doFailure(rc, HttpStatus.getHttpStatus(responseCode), response.getStatusLine().getReasonPhrase()); + } + } + catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + } + + public HttpRequestBase createHttpRequest(String method, Map params, RequestContext rc){ + HttpRequestBase httpRequest = null; + try { + String tUrl = params.get("org.onap.appc.instance.URI"); + String haveHeader = params.get("org.onap.appc.instance.haveHeader"); + String headers = params.get("org.onap.appc.instance.headers"); + + Supplier requestFactory = RequestFactory::new; + httpRequest = requestFactory.get().getHttpRequest(method, tUrl); + + if (haveHeader.equals("true")) { + JSONObject JsonHeaders = new JSONObject(headers); + Iterator keys = JsonHeaders.keys(); + while (keys.hasNext()) { + String String1 = (String) keys.next(); + String String2 = JsonHeaders.getString(String1); + httpRequest.addHeader(String1, String2); + } + } + if (params.containsKey("org.onap.appc.instance.requestBody")) { + String body = params.get("org.onap.appc.instance.requestBody"); + StringEntity bodyParams = new StringEntity (body,"UTF-8"); + if (method.equals("PUT")){ + HttpPut httpPut = (HttpPut) httpRequest; + httpPut.setEntity(bodyParams); + } + if (method.equals("POST")){ + HttpPost httpPost = (HttpPost) httpRequest; + httpPost.setEntity(bodyParams); + } + } + } catch (Exception ex) { + doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, ex.toString()); + } + return httpRequest; + } + + + /** + * initialize the provider adapter by building the context cache + */ + private void initialize() { + configuration = ConfigurationFactory.getConfiguration(); + + logger.info("init rest adapter!!!!!"); + } + +} -- cgit 1.2.3-korg