diff options
author | Stone, Avi (as206k) <as206k@att.com> | 2018-05-23 11:21:11 +0300 |
---|---|---|
committer | Stone, Avi (as206k) <as206k@att.com> | 2018-05-23 11:30:13 +0300 |
commit | 3e4c18770957b55e2f80da32c3a32caa908f1386 (patch) | |
tree | 8a94c656300e75e38febfe9826ad36fc54fe14f5 /dcaedt_catalog | |
parent | da9db1b89e8c9199da4791a2ccd26d1628120a08 (diff) |
Upgrade dt-be-main
Update sources for dcae-dt-be-main to latest version
Change-Id: I3d58a2dc32611c0ca90f1c97e1294a17d5748623
Issue-ID: SDC-1359
Signed-off-by: Stone, Avi (as206k) <as206k@att.com>
Diffstat (limited to 'dcaedt_catalog')
26 files changed, 1273 insertions, 2128 deletions
diff --git a/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/Catalog.java b/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/Catalog.java index b73bb09..c9813e4 100644 --- a/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/Catalog.java +++ b/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/Catalog.java @@ -2,14 +2,8 @@ package org.onap.sdc.dcae.catalog; import java.net.URI; -import java.util.Arrays; -import java.util.Collection; import java.util.Iterator; -import java.util.List; -import java.util.Map; import java.util.LinkedList; -import java.util.HashMap; -import java.util.EnumSet; import org.json.JSONObject; import org.onap.sdc.dcae.catalog.commons.Action; @@ -20,421 +14,258 @@ import org.onap.sdc.dcae.catalog.commons.Proxies; import org.json.JSONArray; -/* - * - */ public interface Catalog { - public abstract URI getUri(); - - public abstract String namespace(); - - public abstract boolean same(Catalog theCatalog); - - public abstract <T> T proxy(JSONObject theData, Class<T> theType); - - - /* Base class for all Catalog objects. - */ - public static interface Element<T extends Element<T>> { - - /** - * provide a typed 'self' reference - */ - public default T self() { return (T)this; } - - /** - */ - public default Class<T> selfClass() { - return (Class<T>)getClass().getInterfaces()[0]; - } - - /* */ - public Catalog catalog(); - - /** - */ - public String id(); - - /** - * Direct access to the underlying JSON object. - * Warning: Modifications to the JSON object are reflected in the Element. - */ - public JSONObject data(); - - /** - * Provides the labels of the artifacts (we use labels to type/classify the - * neo4j artifacts, nodes and edges. - * Currently not all queries retrieve the labels. - */ - public String[] labels(); - - /* Allows for typed deep exploration of the backing JSON data structure - * <pre> - * {@code - * element("type", Type.class); - * } - * </pre> - * - * @arg theName name of a JSON entry ; It must map another JSONObject. - * @arg theType the expected wrapping catalog artifact type - * @return the JSON entry wrapped in the specified type - */ - public default <E extends Element<E>> E element(String theName, Class<E> theType) { - JSONObject elemData = data().optJSONObject(theName); - if (elemData == null) - return null; - else - return catalog().proxy(elemData, theType); - } - - /* Similar to {@link #element(String,Class)} but for collection wrapping. - * Example: - * <pre> - * {@code - * element("nodes", Nodes.class); - * } - * </pre> - */ - public default <E extends Elements> E elements(String theName, Class<E> theType) { - //throws ReflectiveOperationException { - JSONArray elemsData = data().optJSONArray(theName); - if (elemsData == null) { - return null; - } - else { - Class etype = Proxies.typeArgument(theType); - Elements elems = null; - try { - elems = theType.newInstance(); - } - catch (ReflectiveOperationException rox) { - throw new RuntimeException("Failed to instantiate " + theType, rox); - } - - try{ - for (Iterator i = elemsData.iterator(); i.hasNext();) { - JSONObject elemData = (JSONObject)i.next(); - elems.add(catalog().proxy(elemData, etype)); - } - } - catch(Exception e){ - throw new RuntimeException("Failed to fetch json data ", e); - } - return (E)elems; - } - } - - /* - */ - public default boolean same(Element theElem) { - return this.catalog().same(theElem.catalog()) && - this.id().equals(theElem.id()); - } - } - - /* - * Base class for all collections of elements. - */ - public static class Elements<T extends Element> - extends LinkedList<T> { - - public String toString() { - StringBuilder sb = new StringBuilder("["); - for (Element el: this) { - sb.append(el.selfClass().getSimpleName()) - .append("(") - .append(el.data()) - .append("),"); - } - sb.append("]"); - return sb.toString(); - } - } - - /* - * We need this contraption in order to store a mix of Folders and CatalogItem - * instances (Elements in self is not good because it is defined around a - * type variable so we cannot use reflection to determine the type at runtime - * - generics are resolved compile time) - */ - public static class Mixels extends Elements<Element> { - } - - /* - */ - public static interface Item<T extends Item<T>> extends Element<T> { - - public String name(); - - public String description(); - - /* catalog item native identifier */ - public String itemId(); - - /* similar to @ItemAction#withModels - */ - default public Future<Templates> models() { - Templates t = elements("models", Templates.class); - if (t != null) - return Futures.succeededFuture(t); - else - return Futures.advance(catalog().item(itemId()) - .withModels() - .execute(), - item -> (Templates)item.elements("models", Templates.class)); - } - - /* similar to @ItemAction#withAnnotations - */ - default public Future<Annotations> annotations() { - Annotations a = elements("annotations", Annotations.class); - if (a != null) - return Futures.succeededFuture(a); - else - return Futures.advance(catalog().item(itemId()) - .withAnnotations() - .execute(), - item -> (Annotations)item.elements("annotations", Annotations.class)); - } - } - - /* - * Collection of catalog items. - */ - public static class Items extends Elements<Item> { - } - - /* - */ - public static interface Folder extends Element<Folder> { - - public String name(); - - public String description(); - - public String itemId(); - - /* the namespace is immutable */ - public default String namespace() { - return catalog().namespace(); - } - - /* - */ - default public Future<Items> items() { - Items i = elements("items", Items.class); - if (i != null) - return Futures.succeededFuture(i); - else - return Futures.advance(catalog().folder(itemId()) - .withItems() - .execute(), - folder -> (Items)folder.elements("items", Items.class)); - } - - /* - */ - default public Future<Folders> parts() { - Folders f = elements("parts", Folders.class); - if (f != null) - return Futures.succeededFuture(f); - else - return Futures.advance(catalog().folder(itemId()) - .withParts() - .execute(), - folder -> (Folders)folder.elements("parts", Folders.class)); - } - - /* - */ - public Future<Folders> partof(); - - } - - - public static class Folders extends Elements<Folder> { - } - - //no predefined properties here - public static interface Annotation extends Element<Annotation> { - - public default String namespace() { - return catalog().namespace(); + URI getUri(); + + <T> T proxy(JSONObject theData, Class<T> theType); + + + /* Base class for all Catalog objects. */ + interface Element<T extends Element<T>> { + + default Class<T> selfClass() { + return (Class<T>)getClass().getInterfaces()[0]; + } + + Catalog catalog(); + + String id(); + + /** + * Direct access to the underlying JSON object. + * Warning: Modifications to the JSON object are reflected in the Element. + */ + JSONObject data(); + + /* Allows for typed deep exploration of the backing JSON data structure + * @arg theName name of a JSON entry ; It must map another JSONObject. + * @arg theType the expected wrapping catalog artifact type + * @return the JSON entry wrapped in the specified type + */ + default <E extends Element<E>> E element(String theName, Class<E> theType) { + JSONObject elemData = data().optJSONObject(theName); + if (elemData == null) { + return null; + } + else { + return catalog().proxy(elemData, theType); + } + } + + /* Similar to {@link #element(String,Class)} but for collection wrapping. */ + default <E extends Elements> E elements(String theName, Class<E> theType) { + JSONArray elemsData = data().optJSONArray(theName); + if (elemsData == null) { + return null; + } + else { + Class etype = Proxies.typeArgument(theType); + Elements elems; + try { + elems = theType.newInstance(); + } + catch (ReflectiveOperationException rox) { + throw new RuntimeException("Failed to instantiate " + theType, rox); + } + + try{ + for (Iterator i = elemsData.iterator(); i.hasNext();) { + JSONObject elemData = (JSONObject)i.next(); + elems.add(catalog().proxy(elemData, etype)); + } + } + catch(Exception e){ + throw new RuntimeException("Failed to fetch json data ", e); + } + return (E)elems; + } + } + } + + /* Base class for all collections of elements. */ + class Elements<T extends Element> + extends LinkedList<T> { + @Override + public String toString() { + StringBuilder sb = new StringBuilder("["); + for (Element el: this) { + sb.append(el.selfClass().getSimpleName()) + .append("(") + .append(el.data()) + .append("),"); + } + sb.append("]"); + return sb.toString(); + } + } + + /* + * We need this contraption in order to store a mix of Folders and CatalogItem + * instances (Elements in self is not good because it is defined around a + * type variable so we cannot use reflection to determine the type at runtime + * - generics are resolved compile time) + */ + class Mixels extends Elements<Element> {} + + interface Item<T extends Item<T>> extends Element<T> { + String name(); + String description(); + } + + /* + * Collection of catalog items. + */ + class Items extends Elements<Item> {} + + interface Folder extends Element<Folder> { + + String name(); + + String description(); + + String itemId(); + + default Future<Items> items() { + Items i = elements("items", Items.class); + if (i != null) { + return Futures.succeededFuture(i); + } + else { + return Futures.advance(catalog().folder(itemId()) + .withItems() + .execute(), + folder -> folder.elements("items", Items.class)); + } + } } - } - public static class Annotations extends Elements<Annotation> { + class Folders extends Elements<Folder> {} + + //no predefined properties here + interface Annotation extends Element<Annotation> {} + + class Annotations extends Elements<Annotation> { } - /** - * A TOSCA teamplate. - * When a deep loading method is used to obtain a Template its collection - * of inputs and nodes will be immediately available (and 'cached' within - * the backing JSON object). It can be retrieved through a call to - * {@link Element#elements(String,Class)} as in: - * elements("inputs", Inputs.class) - * or - * elements("nodes", Nodes.class) - * - * The same result will be obtained through one of the methods of the - * navigation interface, {@link #inputs()} or {@link #nodes()}; in this case - * the result does not become part of the backing JSONObject. - */ - public static interface Template extends Element<Template> { - - public String name(); - - public String version(); - - public String description(); - - } - - /** - * Collection of {@link Catalog.Template template} instances. - */ - public static class Templates extends Elements<Template> { - } - - - /** - * A TOSCA type declaration. - */ - public interface Type extends Element<Type> { - - public String name(); - - /** - * Allows navigation to the parent {@link Catalog.Type type}, if any. - */ - public Future<Type> derivedfrom(); - - } - - /** - * Collection of {@link Catalog.Type type} instances. - */ - public static class Types extends Elements<Type> { - } - - - public static interface TemplateAction extends Action<Template> { - - public TemplateAction withInputs(); - - public TemplateAction withOutputs(); - - public TemplateAction withNodes(); - - public TemplateAction withNodeProperties(); - - public TemplateAction withNodeRequirements(); - - public TemplateAction withNodePropertiesAssignments(); - - public TemplateAction withNodeCapabilities(); - - public TemplateAction withNodeCapabilityProperties(); - - public TemplateAction withNodeCapabilityPropertyAssignments(); - - public TemplateAction withPolicies(); - - public TemplateAction withPolicyProperties(); - - public TemplateAction withPolicyPropertiesAssignments(); - - @Override - public Future<Template> execute(); - - } - - /* - */ - public static interface TypeAction extends Action<Type> { - - public TypeAction withHierarchy(); - - public TypeAction withRequirements(); - - public TypeAction withCapabilities(); - - @Override - public Future<Type> execute(); - - } - - /* - */ - public static interface FolderAction extends Action<Folder> { - - public FolderAction withAnnotations(); - - public FolderAction withAnnotations(String theSelector); - - public FolderAction withItems(); - - public FolderAction withItemAnnotations(); - - public FolderAction withItemAnnotations(String theSelector); + /** + * A TOSCA teamplate. + * When a deep loading method is used to obtain a Template its collection + * of inputs and nodes will be immediately available (and 'cached' within + * the backing JSON object). It can be retrieved through a call to + * {@link Element#elements(String,Class)} as in: + * elements("inputs", Inputs.class) + * or + * elements("nodes", Nodes.class) + * + * The same result will be obtained through one of the methods of the + * navigation interface. in this case + * the result does not become part of the backing JSONObject. + */ + interface Template extends Element<Template> { + String name(); + + String version(); + + String description(); + } + + /** + * Collection of {@link Catalog.Template template} instances. + */ + class Templates extends Elements<Template> { + } + + + /** + * A TOSCA type declaration. + */ + interface Type extends Element<Type> { + String name(); + } + + /** + * Collection of {@link Catalog.Type type} instances. + */ + class Types extends Elements<Type> { + } + - public FolderAction withItemModels(); + interface TemplateAction extends Action<Template> { - public FolderAction withParts(); - - public FolderAction withPartAnnotations(); + TemplateAction withInputs(); - public FolderAction withPartAnnotations(String theSelector); + TemplateAction withOutputs(); - @Override - public Future<Folder> execute(); - } - - /* - */ - public static interface ItemAction<T extends Item> extends Action<T> { + TemplateAction withNodes(); - public ItemAction<T> withModels(); + TemplateAction withNodeProperties(); - public ItemAction<T> withAnnotations(); - - @Override - public Future<T> execute(); + TemplateAction withNodeRequirements(); - } + TemplateAction withNodePropertiesAssignments(); - /** - */ - public abstract Future<Folders> roots(); + TemplateAction withNodeCapabilities(); - /** - */ - public abstract Future<Folders> rootsByLabel(String theLabel); + TemplateAction withNodeCapabilityProperties(); - /** - */ - public abstract Future<Mixels> lookup(JSONObject theSelector); - - public abstract Future<Mixels> lookup(String theAnnotation, JSONObject theSelector); - - /** - */ - public abstract FolderAction folder(String theFolderId); + TemplateAction withNodeCapabilityPropertyAssignments(); - /** - */ - public abstract <T extends Item> ItemAction<T> item(String theItemId); + TemplateAction withPolicies(); + + TemplateAction withPolicyProperties(); + + TemplateAction withPolicyPropertiesAssignments(); + + @Override + Future<Template> execute(); + } + + interface TypeAction extends Action<Type> { + + TypeAction withHierarchy(); + + TypeAction withRequirements(); + + TypeAction withCapabilities(); + + @Override + Future<Type> execute(); + } + + interface FolderAction extends Action<Folder> { + + FolderAction withItems(); + + FolderAction withItemAnnotations(); + + FolderAction withItemModels(); + + FolderAction withParts(); + + FolderAction withPartAnnotations(); + + @Override + Future<Folder> execute(); + } + + interface ItemAction<T extends Item> extends Action<T> { + + ItemAction<T> withModels(); + + @Override + Future<T> execute(); + + } - /** - */ - public abstract TemplateAction template(String theTemplateId); + Future<Folders> rootsByLabel(String theLabel); - /** - */ - public abstract TypeAction type(String theNamespace, String theTypeName); + FolderAction folder(String theFolderId); + <T extends Item> ItemAction<T> item(String theItemId); + TemplateAction template(String theTemplateId); + TypeAction type(String theNamespace, String theTypeName); } diff --git a/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCCatalog.java b/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCCatalog.java index e08f3a6..dfbaeaa 100644 --- a/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCCatalog.java +++ b/dcaedt_catalog/api/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCCatalog.java @@ -22,6 +22,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; +@SuppressWarnings("ALL") public class ASDCCatalog implements Catalog { private @@ -87,10 +88,10 @@ public class ASDCCatalog implements Catalog { private String[] folderFields = new String[] {ID, ITEM_ID, NAME}; private ProxyBuilder proxies; - private Map<Target, JXPathContext> contexts = new HashMap<Target, JXPathContext>(); + private Map<Target, JXPathContext> contexts = new HashMap<>(); // resource and its catalog - private Map<UUID, org.onap.sdc.dcae.checker.Catalog> catalogs = new HashMap<UUID, org.onap.sdc.dcae.checker.Catalog>(); + private Map<UUID, org.onap.sdc.dcae.checker.Catalog> catalogs = new HashMap<>(); public ASDCCatalog(URI theURI) { @@ -171,7 +172,6 @@ public class ASDCCatalog implements Catalog { return Futures.succeededFuture(roots); } - /** */ public Future<Mixels> lookup(JSONObject theSelector) { return Futures.succeededFuture(new Mixels()); } @@ -180,66 +180,48 @@ public class ASDCCatalog implements Catalog { return Futures.succeededFuture(new Mixels()); } - /** */ public ItemAction item(String theItemId) { return new ResourceAction(UUID.fromString(theItemId)); } - /** */ - public FolderAction folder(String theFolderId) { - return new FolderAction(theFolderId); - } - - public TemplateAction template(String theId) { - return new TemplateAction(theId); + public CatalogFolderAction folder(String theFolderId) { + return new CatalogFolderAction(theFolderId); } - public TypeAction type(String theItemId, String theName) { - return new TypeAction(UUID.fromString(theItemId), theName); + public CatalogTemplateAction template(String theId) { + return new CatalogTemplateAction(theId); } - protected static String resolveTargetName(Target theTarget) { - return (String) ((Map) ((Map) theTarget.getTarget()).get("metadata")).get("template_name"); + public CatalogTypeAction type(String theItemId, String theName) { + return new CatalogTypeAction(UUID.fromString(theItemId), theName); } - protected Object resolve(Target theTarget, String thePath) { + private Object resolve(Target theTarget, String thePath) { try { return contexts.get(theTarget).getValue(thePath); } catch (JXPathNotFoundException pnfx) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "JXPathNotFoundException {}", pnfx); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), JXPATH_NOT_FOUND_EXCEPTION, pnfx); return null; } } // covers common TOSCA pattern of single entry maps - public Map.Entry<String, Map> toEntry(Object theValue) { + private Map.Entry<String, Map> toEntry(Object theValue) { return (Map.Entry<String, Map>) ((Map) theValue).entrySet().iterator().next(); } - protected Map selectEntries(Map theOriginal, String... theKeys) { + private Map selectEntries(Map theOriginal, String... theKeys) { Arrays.sort(theKeys); - Map selection = ((Set<Map.Entry>) theOriginal.entrySet()).stream() + return ((Set<Map.Entry>) theOriginal.entrySet()).stream() .filter(e -> Arrays.binarySearch(theKeys, e.getKey().toString()) >= 0) .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - return selection; } - protected Map evictEntries(Map theOriginal, String... theKeys) { + private Map evictEntries(Map theOriginal, String... theKeys) { Arrays.sort(theKeys); - Map selection = ((Set<Map.Entry>) theOriginal.entrySet()).stream() + return ((Set<Map.Entry>) theOriginal.entrySet()).stream() .filter(e -> Arrays.binarySearch(theKeys, e.getKey().toString()) < 0) .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); - return selection; - } - - protected MapBuilder renderEntry(Map.Entry theEntry, String... theKeys) { - MapBuilder out = new MapBuilder(); - out.put(NAME, theEntry.getKey()); - - for (String key : theKeys) { - out.put(key, ((Map) theEntry.getValue()).get(key)); - } - return out; } protected <T> Stream<T> stream(Iterator<T> theSource) { @@ -277,18 +259,17 @@ public class ASDCCatalog implements Catalog { } private static void dumpTargets(String theDirName, Collection<Target> theTargets) { - try { - File targetDir = new File(theDirName); - if (!targetDir.exists() && !targetDir.mkdirs()) { - throw new IllegalStateException("Couldn't create dir: " + theDirName); - } - for (Target t : theTargets) { - FileWriter dump = new FileWriter(new File(theDirName, t.getName())); + File targetDir = new File(theDirName); + if (!targetDir.exists() && !targetDir.mkdirs()) { + throw new IllegalStateException("Couldn't create dir: " + theDirName); + } + for (Target t : theTargets) { + try (FileWriter dump = new FileWriter(new File(theDirName, t.getName()))) { IOUtils.copy(t.open(), dump); dump.close(); + } catch (IOException e) { + debugLogger.log(LogLevel.DEBUG, "ASDCCatalog", "IOException {}", e); } - } catch (IOException iox) { - debugLogger.log(LogLevel.DEBUG,"ASDCCatalog", "IOException {}", iox); } } @@ -365,50 +346,50 @@ public class ASDCCatalog implements Catalog { } } - public class FolderAction implements Catalog.FolderAction { + public class CatalogFolderAction implements Catalog.FolderAction { private boolean doItemModels; private String folderName; // use the id/UUID of the folder ?? - private FolderAction(String theFolderName) { + private CatalogFolderAction(String theFolderName) { this.folderName = theFolderName; } - public FolderAction withAnnotations() { + public CatalogFolderAction withAnnotations() { return this; } - public FolderAction withAnnotations(String theSelector) { + public CatalogFolderAction withAnnotations(String theSelector) { return this; } - public FolderAction withItems() { + public CatalogFolderAction withItems() { return this; } - public FolderAction withItemAnnotations() { + public CatalogFolderAction withItemAnnotations() { return this; } - public FolderAction withItemAnnotations(String theSelector) { + public CatalogFolderAction withItemAnnotations(String theSelector) { return this; } - public FolderAction withItemModels() { + public CatalogFolderAction withItemModels() { doItemModels = true; return this; } - public FolderAction withParts() { + public CatalogFolderAction withParts() { return this; } - public FolderAction withPartAnnotations() { + public CatalogFolderAction withPartAnnotations() { return this; } - public FolderAction withPartAnnotations(String theSelector) { + public CatalogFolderAction withPartAnnotations(String theSelector) { return this; } @@ -425,7 +406,7 @@ public class ASDCCatalog implements Catalog { return Futures.advance(asdc.getResources(JSONArray.class, "DCAE Component", this.folderName), resourcesData -> { - Actions.CompoundAction<Resource> itemsAction = new Actions.BasicCompoundAction<Resource>(); + Actions.CompoundAction<Resource> itemsAction = new Actions.BasicCompoundAction<>(); for (int i = 0; i < resourcesData.length(); i++) { JSONObject resource = resourcesData.getJSONObject(i); @@ -453,7 +434,7 @@ public class ASDCCatalog implements Catalog { }, resourcesError -> new RuntimeException("Failed to retrieve resources", resourcesError)); } - public Collection<Resource> filterLatestVersion(Collection<Resource> items) throws IllegalArgumentException { + public Collection<Resource> filterLatestVersion(Collection<Resource> items) { if (items == null) { throw new IllegalArgumentException("null is not acceptable as a list of items"); } @@ -475,7 +456,7 @@ public class ASDCCatalog implements Catalog { } /** */ - public class TemplateAction implements Catalog.TemplateAction { + public class CatalogTemplateAction implements Catalog.TemplateAction { private String artifactId; private Target target; @@ -485,32 +466,28 @@ public class ASDCCatalog implements Catalog { private boolean doNodes, doNodeProperties, doNodePropertiesAssignments, doNodeRequirements, doNodeCapabilities, doNodeCapabilityProperties, doNodeCapabilityPropertyAssignments; - protected TemplateAction(Target theTarget) { - this.target = theTarget; - } - /* * expected to be the relative url provided by asdc for the template * artifact */ - protected TemplateAction(String theArtifactId) { + CatalogTemplateAction(String theArtifactId) { this.artifactId = theArtifactId; } - public TemplateAction withInputs() { + public CatalogTemplateAction withInputs() { return this; } - public TemplateAction withOutputs() { + public CatalogTemplateAction withOutputs() { return this; } - public TemplateAction withNodes() { + public CatalogTemplateAction withNodes() { this.doNodes = true; return this; } - protected TemplateAction doNodes() { + CatalogTemplateAction doNodes() { if (!this.doNodes) { return this; } @@ -531,12 +508,12 @@ public class ASDCCatalog implements Catalog { } // pre-requisite: a call to 'withNodes' - public TemplateAction withNodeProperties() { + public CatalogTemplateAction withNodeProperties() { this.doNodeProperties = true; return this; } - protected TemplateAction doNodeProperties() { + protected CatalogTemplateAction doNodeProperties() { if (!this.doNodeProperties) { return this; } @@ -558,12 +535,12 @@ public class ASDCCatalog implements Catalog { } // pre-requisite: a call to 'withNodesProperties' - public TemplateAction withNodePropertiesAssignments() { + public CatalogTemplateAction withNodePropertiesAssignments() { this.doNodePropertiesAssignments = true; return this; } - protected TemplateAction doNodePropertiesAssignments() { + CatalogTemplateAction doNodePropertiesAssignments() { if (!this.doNodePropertiesAssignments) { return this; } @@ -573,8 +550,8 @@ public class ASDCCatalog implements Catalog { return this; } - nodes.entrySet().stream().forEach(node -> { - List nodeProps = null; + nodes.entrySet().forEach(node -> { + List nodeProps; try { nodeProps = (List) ctx.getValue(NODES_NAME + ((Map.Entry) node).getKey() + PROPERTIES); } catch (JXPathNotFoundException pnfx) { @@ -582,7 +559,7 @@ public class ASDCCatalog implements Catalog { return; } - nodeProps.stream().forEach(prop -> { + nodeProps.forEach(prop -> { // pick from String propPath = TOPOLOGY_TEMPLATE_NODE_TEMPLATES1 + ((Map.Entry) node).getKey() + "/properties/" + ((Map) prop).get(NAME); @@ -602,7 +579,7 @@ public class ASDCCatalog implements Catalog { return this; } - protected Map renderRequirementDefinition(Map.Entry theReq) { + Map renderRequirementDefinition(Map.Entry theReq) { Map def = (Map) theReq.getValue(); return new MapBuilder().put(NAME, theReq.getKey()) // capability must be present @@ -613,7 +590,7 @@ public class ASDCCatalog implements Catalog { } // TODO: see how this comes out of neo and match it - protected Map renderRequirementAssignment(Map.Entry theReq) { + Map renderRequirementAssignment(Map.Entry theReq) { Map def = (Map) theReq.getValue(); return new MapBuilder().put(NAME, theReq.getKey()) // capability must be present @@ -628,12 +605,12 @@ public class ASDCCatalog implements Catalog { .putAll(evictEntries(def, CAPABILITY)).build(); } - public TemplateAction withNodeRequirements() { + public CatalogTemplateAction withNodeRequirements() { this.doNodeRequirements = true; return this; } - TemplateAction doNodeRequirements() { + CatalogTemplateAction doNodeRequirements() { if (!this.doNodeRequirements) { return this; } @@ -647,7 +624,7 @@ public class ASDCCatalog implements Catalog { } // type - nodes.entrySet().stream() + nodes.entrySet() .forEach( node -> ctx .setValue( @@ -666,13 +643,13 @@ public class ASDCCatalog implements Catalog { .collect(Collectors.toList()))); // merge assignments on top of definitions - nodes.entrySet().stream().forEach(node -> { + nodes.entrySet().forEach(node -> { List nodeReqsAssigns = (List) resolve(this.target, TOPOLOGY_TEMPLATE_NODE_TEMPLATES1 + ((Map.Entry) node).getKey() + "/requirements"); if (nodeReqsAssigns == null) { return; } - nodeReqsAssigns.stream().forEach(req -> { + nodeReqsAssigns.forEach(req -> { Map.Entry reqAssign = toEntry(req); catalog.mergeDefinitions((Map) ctx.getValue(NODES_NAME + ((Map.Entry) node).getKey() + "']/requirements[name='" + reqAssign.getKey() + "']"), @@ -683,12 +660,12 @@ public class ASDCCatalog implements Catalog { return this; } - public TemplateAction withNodeCapabilities() { + public CatalogTemplateAction withNodeCapabilities() { this.doNodeCapabilities = true; return this; } - protected Map renderCapabilityDefinition(Map.Entry theCap) { + Map renderCapabilityDefinition(Map.Entry theCap) { Map def = (Map) theCap.getValue(); return new MapBuilder().put(NAME, theCap.getKey()) .put("type", @@ -697,7 +674,7 @@ public class ASDCCatalog implements Catalog { .putAll(evictEntries(def, "properties", "type")).build(); } - TemplateAction doNodeCapabilities() { + CatalogTemplateAction doNodeCapabilities() { if (!this.doNodeCapabilities) { return this; } @@ -718,18 +695,18 @@ public class ASDCCatalog implements Catalog { stream(catalog.facets(Construct.Node, Facet.capabilities, ((Map) ((Map.Entry) node).getValue()).get("type").toString())) - .map((Map.Entry capEntry) -> renderCapabilityDefinition(capEntry)) + .map(this::renderCapabilityDefinition) .collect(Collectors.toList()))); return this; } - public TemplateAction withNodeCapabilityProperties() { + public CatalogTemplateAction withNodeCapabilityProperties() { this.doNodeCapabilityProperties = true; return this; } - TemplateAction doNodeCapabilityProperties() { + CatalogTemplateAction doNodeCapabilityProperties() { if (!this.doNodeCapabilityProperties) { return this; @@ -742,7 +719,7 @@ public class ASDCCatalog implements Catalog { // pick up all the properties from the capability type hierarchy // definition - nodes.entrySet().stream().forEach(node -> { + nodes.entrySet().forEach(node -> { List nodeCapabilities = (List) ctx .getValue(NODES_NAME + ((Map.Entry) node).getKey() + CAPABILITIES); if (nodeCapabilities == null) { @@ -750,7 +727,7 @@ public class ASDCCatalog implements Catalog { } // collect properties from the capability type hierarchy - nodeCapabilities.stream().forEach(capability -> { + nodeCapabilities.forEach(capability -> { List capabilityProperties = StreamSupport .stream(Spliterators.spliteratorUnknownSize( catalog.facets(Construct.Capability, Facet.properties, @@ -781,7 +758,7 @@ public class ASDCCatalog implements Catalog { return; } - properties.entrySet().stream().forEach(property -> { + properties.entrySet().forEach(property -> { String propertyLoc = NODES_NAME + ((Map.Entry) node).getKey() + CAPABILITIES_NAME + ((Map) capability).get(NAME) + PROPERTIES_NAME + ((Map.Entry) property).getKey() + "']"; @@ -794,12 +771,12 @@ public class ASDCCatalog implements Catalog { return this; } - public TemplateAction withNodeCapabilityPropertyAssignments() { + public CatalogTemplateAction withNodeCapabilityPropertyAssignments() { this.doNodeCapabilityPropertyAssignments = true; return this; } - TemplateAction doNodeCapabilityPropertyAssignments() { + CatalogTemplateAction doNodeCapabilityPropertyAssignments() { if (!this.doNodeCapabilityPropertyAssignments) { return this; } @@ -818,14 +795,14 @@ public class ASDCCatalog implements Catalog { return this; } - nodes.stream().forEach(node -> { + nodes.forEach(node -> { List capabilities = (List) ctx.getValue(NODES_NAME + ((Map) node).get(NAME) + CAPABILITIES); if (capabilities == null) { return; } - capabilities.stream().forEach(capability -> { - List properties = null; + capabilities.forEach(capability -> { + List properties; try { properties = (List) ctx.getValue(NODES_NAME + ((Map) node).get(NAME) + CAPABILITIES_NAME + ((Map) capability).get(NAME) + PROPERTIES); @@ -834,7 +811,7 @@ public class ASDCCatalog implements Catalog { return; } - properties.stream().forEach(property -> { + properties.forEach(property -> { String location = NODES_NAME + ((Map) node).get(NAME) + CAPABILITIES_NAME + ((Map) capability).get(NAME) + PROPERTIES_NAME + ((Map) property).get(NAME) + "']/assignment"; @@ -859,15 +836,15 @@ public class ASDCCatalog implements Catalog { return this; } - public TemplateAction withPolicies() { + public CatalogTemplateAction withPolicies() { return this; } - public TemplateAction withPolicyProperties() { + public CatalogTemplateAction withPolicyProperties() { return this; } - public TemplateAction withPolicyPropertiesAssignments() { + public CatalogTemplateAction withPolicyPropertiesAssignments() { return this; } @@ -913,7 +890,7 @@ public class ASDCCatalog implements Catalog { this.catalog = checker.catalog(); ASDCCatalog.this.catalogs.put(resourceId, this.catalog); // we should only be doing this if we discovered an update - // (by checking timestampts). Actually, we should + // (by checking timestamps). Actually, we should // only do the artifact fetching if we detect an update ASDCCatalog.this.contexts.put(template, JXPathContext.newContext(template.getTarget())); } catch (Exception x) { @@ -924,7 +901,7 @@ public class ASDCCatalog implements Catalog { this.doNodes().doNodeProperties().doNodePropertiesAssignments().doNodeRequirements().doNodeCapabilities() .doNodeCapabilityProperties().doNodeCapabilityPropertyAssignments(); - JSONObject pack = new JSONObject((Map) ctx.getContextBean()).put(NAME, this.target.getName().toString()) + JSONObject pack = new JSONObject((Map) ctx.getContextBean()).put(NAME, this.target.getName()) .put(ID, this.target.getLocation().toString()) .put(ITEM_ID, this.target.getLocation().toString()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), pack.toString(2)); @@ -933,7 +910,7 @@ public class ASDCCatalog implements Catalog { } } - public class TypeAction implements Catalog.TypeAction { + public class CatalogTypeAction implements Catalog.TypeAction { private String name; private UUID resourceId; @@ -941,17 +918,17 @@ public class ASDCCatalog implements Catalog { private boolean doHierarchy = false, doRequirements = false, doCapabilities = false; - private TypeAction(UUID theResourceId, /* Construct theConstruct, */ String theName) { + private CatalogTypeAction(UUID theResourceId, /* Construct theConstruct, */ String theName) { this.resourceId = theResourceId; this.name = theName; } - public TypeAction withHierarchy() { + public CatalogTypeAction withHierarchy() { this.doHierarchy = true; return this; } - TypeAction doHierarchy(org.onap.sdc.dcae.checker.Catalog theCatalog) { + CatalogTypeAction doHierarchy(org.onap.sdc.dcae.checker.Catalog theCatalog) { if (!this.doHierarchy) { return this; } @@ -968,12 +945,12 @@ public class ASDCCatalog implements Catalog { return this; } - public TypeAction withRequirements() { + public CatalogTypeAction withRequirements() { this.doRequirements = true; return this; } - TypeAction doRequirements(org.onap.sdc.dcae.checker.Catalog theCatalog) { + CatalogTypeAction doRequirements(org.onap.sdc.dcae.checker.Catalog theCatalog) { if (!this.doRequirements) { return this; } @@ -991,7 +968,7 @@ public class ASDCCatalog implements Catalog { // (within a node type) .put(ID, getCatalog(resourceId).hasType(Construct.Capability, capability) - ? (resourceId + "/" + capability) : capability.toString()) + ? (resourceId + "/" + capability) : capability) .build()) .put("node", new MapBuilder().putOpt(NAME, node).putOpt(ID, node == null ? null : (resourceId + "/" + node)).buildOpt()) @@ -1004,12 +981,12 @@ public class ASDCCatalog implements Catalog { return this; } - public TypeAction withCapabilities() { + public CatalogTypeAction withCapabilities() { this.doCapabilities = true; return this; } - TypeAction doCapabilities(org.onap.sdc.dcae.checker.Catalog theCatalog) { + CatalogTypeAction doCapabilities(org.onap.sdc.dcae.checker.Catalog theCatalog) { if (!this.doCapabilities) { return this; } @@ -1065,7 +1042,7 @@ public class ASDCCatalog implements Catalog { } } - public static interface Resource extends Catalog.Item<Resource> { + public interface Resource extends Catalog.Item<Resource> { @Override @Proxy.DataMap(map = "uuid") @@ -1091,22 +1068,22 @@ public class ASDCCatalog implements Catalog { public static class Resources extends Elements<Resource> { } - public static interface Artifact extends Catalog.Element<Artifact> { + public interface Artifact extends Catalog.Element<Artifact> { @Proxy.DataMap(map = ARTIFACT_NAME) - public String name(); + String name(); @Proxy.DataMap(map = "artifactType") - public String type(); + String type(); @Proxy.DataMap(map = "artifactDescription") - public String description(); + String description(); @Proxy.DataMap(map = "artifactUUID") - public UUID uuid(); + UUID uuid(); @Proxy.DataMap(map = "artifactVersion") - public int version(); + int version(); } @@ -1150,7 +1127,7 @@ public class ASDCCatalog implements Catalog { return null; } - ASDCTarget target = null; + ASDCTarget target; if (this.catalog != null) { // this is the caching!! target = (ASDCTarget) this.catalog.getTarget(ASDCCatalog.this.getArtifactURI(targetArtifact)); @@ -1210,16 +1187,20 @@ public class ASDCCatalog implements Catalog { Resources items = f.elements(ITEMS, Resources.class); if (items != null) { for (Resource item : items) { - debugLogger.log(LogLevel.DEBUG, ASDCCatalog.class.getName(), "\titem: {} : {}",item.name(), item.data()); - Templates templates = item.elements(MODELS, Templates.class); - if (templates != null) { - for (Template t : templates) { - Template ft = catalog.template(t.id()).withNodes().withNodeProperties() - .withNodePropertiesAssignments().execute().waitForResult(); - - debugLogger.log(LogLevel.DEBUG, ASDCCatalog.class.getName(), "template data: {}", ft.data()); - } - } + executeItemsNodePropertiesAssignments(catalog, item); + } + } + } + + private static void executeItemsNodePropertiesAssignments(ASDCCatalog catalog, Resource item) throws Exception { + debugLogger.log(LogLevel.DEBUG, ASDCCatalog.class.getName(), "\titem: {} : {}",item.name(), item.data()); + Templates templates = item.elements(MODELS, Templates.class); + if (templates != null) { + for (Template t : templates) { + Template ft = catalog.template(t.id()).withNodes().withNodeProperties() + .withNodePropertiesAssignments().execute().waitForResult(); + + debugLogger.log(LogLevel.DEBUG, ASDCCatalog.class.getName(), "template data: {}", ft.data()); } } } diff --git a/dcaedt_catalog/api/src/test/java/org/onap/sdc/dcae/catalog/ASDCCatalogTest.java b/dcaedt_catalog/api/src/test/java/org/onap/sdc/dcae/catalog/ASDCCatalogTest.java index fcd92f0..360b76d 100644 --- a/dcaedt_catalog/api/src/test/java/org/onap/sdc/dcae/catalog/ASDCCatalogTest.java +++ b/dcaedt_catalog/api/src/test/java/org/onap/sdc/dcae/catalog/ASDCCatalogTest.java @@ -12,7 +12,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog; -import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog.FolderAction; +import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog.CatalogFolderAction; import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog.Resource; import static org.mockito.Mockito.*; @@ -23,17 +23,17 @@ public class ASDCCatalogTest { @Rule public ExpectedException thrown = ExpectedException.none(); - private static FolderAction getTarget() { + private static CatalogFolderAction getTarget() { ASDCCatalog catalog = mock(ASDCCatalog.class); when(catalog.folder("test")).thenCallRealMethod(); - FolderAction target = catalog.folder("test"); + CatalogFolderAction target = catalog.folder("test"); return target; } @Test public void filterLatestVersion_null_throwIllegalArgumentException() { // arrange - FolderAction target = getTarget(); + CatalogFolderAction target = getTarget(); // assert thrown.expect(IllegalArgumentException.class); // act @@ -43,7 +43,7 @@ public class ASDCCatalogTest { @Test public void filterLatestVersion_emptyItemsList_emptyItemsList() throws URISyntaxException { // arrange - FolderAction target = getTarget(); + CatalogFolderAction target = getTarget(); // act Collection<Resource> result = target.filterLatestVersion(new ArrayList<>()); // assert @@ -53,7 +53,7 @@ public class ASDCCatalogTest { @Test public void filterLatestVersion_itemWithTwoVersions_itemWithLatestVersion() { // arrange - FolderAction target = getTarget(); + CatalogFolderAction target = getTarget(); UUID invariantUUID = UUID.randomUUID(); Resource r1v1 = mock(Resource.class); @@ -72,7 +72,7 @@ public class ASDCCatalogTest { @Test public void filterLatestVersion_2distinctItems_2distinctItems() { // arrange - FolderAction target = getTarget(); + CatalogFolderAction target = getTarget(); Resource r1 = mock(Resource.class); Resource r2 = mock(Resource.class); diff --git a/dcaedt_catalog/asdc/pom.xml b/dcaedt_catalog/asdc/pom.xml index abaff6a..635868e 100644 --- a/dcaedt_catalog/asdc/pom.xml +++ b/dcaedt_catalog/asdc/pom.xml @@ -125,5 +125,10 @@ <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-core</artifactId> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java index 66afab1..08383ea 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java @@ -38,13 +38,11 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.Base64Utils; -//import org.springframework.util.DigestUtils; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.stereotype.Component; import org.springframework.context.annotation.Scope; import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; @@ -57,8 +55,6 @@ import org.onap.sdc.dcae.catalog.commons.Action; import org.onap.sdc.dcae.catalog.commons.Future; import org.onap.sdc.dcae.catalog.commons.Futures; import org.onap.sdc.dcae.catalog.commons.JSONHttpMessageConverter; -import org.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.composition.util.SystemProperties; import org.json.JSONArray; import org.apache.commons.cli.BasicParser; @@ -69,82 +65,68 @@ import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; - @Component("asdc") @Scope("singleton") -//@ConfigurationProperties(prefix="asdc") public class ASDC { - public static enum AssetType { + private static final String TARGET = "target"; + private static final String ACTION = "action"; + private static final String ASSET_TYPE = "assetType"; + private static final String USER_ID = "USER_ID"; + public static final String ASSET_ID = "assetId"; + public static final String ARTIFACT_ID = "artifactId"; + public static final String LIST_FILTER = "listFilter"; + + public enum AssetType { resource, service, product } -// public static enum ArtifactType { -// DCAE_TOSCA, -// DCAE_JSON, -// DCAE_POLICY, -// DCAE_DOC, -// DCAE_EVENT, -// DCAE_INVENTORY_TOSCA, -// DCAE_INVENTORY_JSON, -// DCAE_INVENTORY_POLICY, -// DCAE_INVENTORY_DOC, -// DCAE_INVENTORY_BLUEPRINT, -// DCAE_INVENTORY_EVENT, -// HEAT, -// HEAT_VOL, -// HEAT_NET, -// HEAT_NESTED, -// HEAT_ARTIFACT, -// HEAT_ENV, -// OTHER -// } - -// public static enum ArtifactGroupType { -// DEPLOYMENT, -// INFORMATIONAL -// } - - public static enum LifecycleState { + public enum LifecycleState { Checkin, Checkout, Certify, undocheckout } - -// @Retention(RetentionPolicy.RUNTIME) -// @Target(ElementType.METHOD) -// public @interface Mandatory { -// } protected static OnapLoggerError errLogger = OnapLoggerError.getInstance(); protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - @Autowired - private SystemProperties systemProperties; - private URI rootUri; - private String rootPath = "/sdc/v1/catalog/"; - private String user, - passwd; - private String instanceId; + private static final String ARTIFACT_TYPE = "artifactType"; + private static final String ARTIFACT_GROUP_TYPE = "artifactGroupType"; + private static final String ARTIFACT_LABEL = "artifactLabel"; + private static final String ARTIFACT_NAME = "artifactName"; + private static final String DESCRIPTION = "description"; + private static final String PAYLOAD_DATA = "payloadData"; + + private static final String[] artifactMandatoryEntries = new String[] {}; + + private static final String[] updateMandatoryEntries = new String[] {ARTIFACT_NAME, + ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA}; + + private static final String[] uploadMandatoryEntries = new String[] {ARTIFACT_NAME, + ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA}; + private URI rootUri; + private String rootPath = "/sdc/v1/catalog/"; + private String user, passwd; + private String instanceId; public void setUri(URI theUri) { - //theUri = URI.create(systemProperties.getProperties().getProperty(SystemProperties.ASDC_CATALOG_URL)); String userInfo = theUri.getUserInfo(); if (userInfo != null) { String[] userInfoParts = userInfo.split(":"); setUser(userInfoParts[0]); - if (userInfoParts.length > 1) + if (userInfoParts.length > 1) { setPassword(userInfoParts[1]); + } } String fragment = theUri.getFragment(); - if (fragment == null) + if (fragment == null) { throw new IllegalArgumentException("The URI must contain a fragment specification, to be used as ASDC instance id"); + } setInstanceId(fragment); try { @@ -179,24 +161,14 @@ public class ASDC { this.instanceId = theId; } - public String getInstanceId() { - return this.instanceId; - } - - public void setRootPath(String thePath) { - this.rootPath = systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_ROOTPATH); - } - - public String getRootPath() { - return systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_ROOTPATH); - } - @Scheduled(fixedRateString = "${beans.context.scripts.updateCheckFrequency?:60000}") - public void checkForUpdates() { + public void checkForUpdates() { + // ffu } @PostConstruct public void initASDC() { + // ffu } public <T> Future<T> getResources(Class<T> theType) { @@ -236,7 +208,7 @@ public class ASDC { } public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType) { - return (() -> fetch(refAssets(theAssetType), theType)); + return () -> fetch(refAssets(theAssetType), theType); } public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType, @@ -251,7 +223,7 @@ public class ASDC { public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType, String theCategory, String theSubCategory, String theResourceType) { - return (() -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType)); + return () -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType); } protected String refAssets(AssetType theAssetType) { @@ -306,7 +278,7 @@ public class ASDC { } public <T> Action<T> getAssetAction(AssetType theAssetType, UUID theId, Class<T> theType) { - return (() -> fetch(refAsset(theAssetType, theId) + "/metadata", theType)); + return () -> fetch(refAsset(theAssetType, theId) + "/metadata", theType); } public Future<byte[]> getResourceArchive(UUID theId) { @@ -322,7 +294,7 @@ public class ASDC { } public Action<byte[]> getAssetArchiveAction(AssetType theAssetType, UUID theId) { - return (() -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class)); + return () -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class); } public Future<JSONObject> checkinResource(UUID theId, String theUser, String theMessage) { @@ -354,9 +326,7 @@ public class ASDC { public Future<JSONObject> cycleAsset(AssetType theAssetType, UUID theId, LifecycleState theState, String theUser, String theMessage) { return post(refAsset(theAssetType, theId) + "/lifecycleState/" + theState, - (headers) -> prepareHeaders(headers) - .header("USER_ID", theUser), - new JSONObject().putOpt("userRemarks", theMessage)); + headers -> prepareHeaders(headers).header(USER_ID, theUser), new JSONObject().putOpt("userRemarks", theMessage)); } protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance, UUID theArtifactId) { @@ -388,7 +358,7 @@ public class ASDC { } public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) { - return (() -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType)); + return () -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType); } public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) { @@ -396,7 +366,7 @@ public class ASDC { } public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) { - return (() -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType)); + return () -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType); } public ArtifactUploadAction createResourceArtifact(UUID theAssetId) { @@ -518,8 +488,9 @@ public class ASDC { protected void checkMandatoryInfo() { for (String field: mandatoryInfoEntries()) { - if (!info.has(field)) + if (!info.has(field)) { throw new IllegalStateException("No '" + field + "' was provided"); + } } } @@ -529,10 +500,9 @@ public class ASDC { } } - protected static final String[] artifactMandatoryEntries = new String[] {}; /** - * We use teh same API to operate on artifacts attached to assets or to their instances + * We use teh same API to operate on artifacts attached to assets or to their instances */ public abstract class ASDCArtifactAction<A extends ASDCArtifactAction<A>> extends ASDCAction<A, JSONObject> { @@ -570,17 +540,12 @@ public class ASDC { refAssetArtifact(this.assetType, this.assetId, theArtifactId) : refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance), theArtifactId); } - } - - protected static final String[] uploadMandatoryEntries = new String[] { "artifactName", - "artifactType", - "artifactGroupType", - "artifactLabel", - "description", - "payloadData" }; + } public class ArtifactUploadAction extends ASDCArtifactAction<ArtifactUploadAction> { - + + public static final String PAYLOAD_DATA = ASDC.PAYLOAD_DATA; + protected ArtifactUploadAction() { super(new JSONObject()); } @@ -590,7 +555,7 @@ public class ASDC { } public ArtifactUploadAction withContent(byte[] theContent) { - return with("payloadData", Base64Utils.encodeToString(theContent)); + return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent)); } public ArtifactUploadAction withContent(File theFile) throws IOException { @@ -598,11 +563,11 @@ public class ASDC { } public ArtifactUploadAction withLabel(String theLabel) { - return with("artifactLabel", theLabel); + return with(ARTIFACT_LABEL, theLabel); } public ArtifactUploadAction withName(String theName) { - return with("artifactName", theName); + return with(ARTIFACT_NAME, theName); } public ArtifactUploadAction withDisplayName(String theName) { @@ -610,17 +575,18 @@ public class ASDC { } public ArtifactUploadAction withType(ArtifactType theType) { - return with("artifactType", theType.toString()); + return with(ARTIFACT_TYPE, theType.toString()); } public ArtifactUploadAction withGroupType(ArtifactGroupType theGroupType) { - return with("artifactGroupType", theGroupType.toString()); + return with(ARTIFACT_GROUP_TYPE, theGroupType.toString()); } public ArtifactUploadAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } - + + @Override protected String[] mandatoryInfoEntries() { return ASDC.this.uploadMandatoryEntries; } @@ -628,18 +594,11 @@ public class ASDC { public Future<JSONObject> execute() { checkMandatory(); return ASDC.this.post(ref(null), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId), - this.info); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info); } } - protected static final String[] updateMandatoryEntries = new String[] { "artifactName", - "artifactType", - "artifactGroupType", - "artifactLabel", - "description", - "payloadData" }; + /** * In its current form the update relies on a previous artifact retrieval. One cannot build an update from scratch. @@ -657,7 +616,7 @@ public class ASDC { } public ArtifactUpdateAction withContent(byte[] theContent) { - return with("payloadData", Base64Utils.encodeToString(theContent)); + return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent)); } public ArtifactUpdateAction withContent(File theFile) throws IOException { @@ -665,13 +624,14 @@ public class ASDC { } public ArtifactUpdateAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } public ArtifactUpdateAction withName(String theName) { - return with("artifactName", theName); + return with(ARTIFACT_NAME, theName); } - + + @Override protected String[] mandatoryInfoEntries() { return ASDC.this.updateMandatoryEntries; } @@ -690,9 +650,7 @@ public class ASDC { checkMandatory(); cleanupInfoEntries(); return ASDC.this.post(ref(artifactUUID), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId), - this.info); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId),this.info); } } @@ -712,26 +670,25 @@ public class ASDC { public Future<JSONObject> execute() { checkMandatory(); return ASDC.this.delete(ref(this.artifactId), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId)); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId)); } } - public VFCMTCreateAction createVFCMT() { + private VFCMTCreateAction createVFCMT() { return new VFCMTCreateAction(); } - - protected static final String[] vfcmtMandatoryEntries = new String[] { "name", - "vendorName", - "vendorRelease", - "contactId" }; + + public class VFCMTCreateAction extends ASDCAction<VFCMTCreateAction, JSONObject> { + private static final String CONTACT_ID = "contactId"; + private final String[] vfcmtMandatoryEntries = new String[] { "name", "vendorName", "vendorRelease", CONTACT_ID}; + protected VFCMTCreateAction() { super(new JSONObject()); @@ -751,7 +708,7 @@ public class ASDC { } public VFCMTCreateAction withDescription(String theDescription) { - return with("description", theDescription); + return with(DESCRIPTION, theDescription); } public VFCMTCreateAction withVendorName(String theVendorName) { @@ -763,8 +720,9 @@ public class ASDC { } public VFCMTCreateAction withTags(String... theTags) { - for (String tag: theTags) + for (String tag: theTags) { this.info.append("tags", tag); + } return this; } @@ -773,30 +731,29 @@ public class ASDC { } protected String[] mandatoryInfoEntries() { - return ASDC.this.vfcmtMandatoryEntries; + return vfcmtMandatoryEntries; } public VFCMTCreateAction withContact(String theContact) { - return with("contactId", theContact); + return with(CONTACT_ID, theContact); } public Future<JSONObject> execute() { - this.info.putOnce("contactId", this.operatorId); + this.info.putOnce(CONTACT_ID, this.operatorId); this.info.append("tags", info.optString("name")); checkMandatory(); return ASDC.this.post(refAssets(AssetType.resource), - (headers) -> prepareHeaders(headers) - .header("USER_ID", this.operatorId), - this.info); + headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info); } } public static JSONObject merge(JSONObject theOriginal, JSONObject thePatch) { for (String key: (Set<String>)thePatch.keySet()) { - if (!theOriginal.has(key)) + if (!theOriginal.has(key)) { theOriginal.put(key, thePatch.get(key)); + } } return theOriginal; } @@ -883,18 +840,7 @@ public class ASDC { - public class ASDCFuture<T> - extends Futures.BasicFuture<T> { - - private boolean http404toEmpty = false; - - ASDCFuture() { - } - - public ASDCFuture setHttp404ToEmpty(boolean doEmpty) { - this.http404toEmpty = doEmpty; - return this; - } + public class ASDCFuture<T> extends Futures.BasicFuture<T> { ListenableFutureCallback<ResponseEntity<T>> callback = new ListenableFutureCallback<ResponseEntity<T>>() { @@ -904,9 +850,6 @@ public class ASDC { public void onFailure(Throwable theError) { if (theError instanceof HttpClientErrorException) { - // if (theError.getRawStatusCode() == 404 && this.http404toEmpty) - // ASDCFuture.this.result(); //th eresult is of type T ... - // else ASDCFuture.this.cause(new ASDCException((HttpClientErrorException)theError)); } else { @@ -918,70 +861,66 @@ public class ASDC { } public class ContentMD5Interceptor implements AsyncClientHttpRequestInterceptor { - - @Override - public ListenableFuture<ClientHttpResponse> intercept( - HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution) - throws IOException { - if (HttpMethod.POST == theRequest.getMethod()) { - HttpHeaders headers = theRequest.getHeaders(); - headers.add("Content-MD5", Base64Utils.encodeToString( - //DigestUtils.md5Digest(theBody))); - DigestUtils.md5Hex(theBody).getBytes())); - - } - return theExecution.executeAsync(theRequest, theBody); - } + @Override + public ListenableFuture<ClientHttpResponse> intercept( + HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution) + throws IOException { + if (HttpMethod.POST == theRequest.getMethod()) { + HttpHeaders headers = theRequest.getHeaders(); + headers.add("Content-MD5", Base64Utils.encodeToString(DigestUtils.md5Hex(theBody).getBytes())); + } + return theExecution.executeAsync(theRequest, theBody); + } } public static void main(String[] theArgs) throws Exception { CommandLineParser parser = new BasicParser(); - String user_id = "jh0003"; + String userId = "jh0003"; Options options = new Options(); options.addOption(OptionBuilder - .withArgName("target") - .withLongOpt("target") + .withArgName(TARGET) + .withLongOpt(TARGET) .withDescription("target asdc system") .hasArg() .isRequired() .create('t') ); options.addOption(OptionBuilder - .withArgName("action") - .withLongOpt("action") + .withArgName(ACTION) + .withLongOpt(ACTION) .withDescription("one of: list, get, getartifact, checkin, checkout") .hasArg() .isRequired() .create('a') ); options.addOption(OptionBuilder - .withArgName("assetType") - .withLongOpt("assetType") + .withArgName(ASSET_TYPE) + .withLongOpt(ASSET_TYPE) .withDescription("one of resource, service, product") .hasArg() .isRequired() .create('k') ); //k for 'kind' .. options.addOption(OptionBuilder - .withArgName("assetId") - .withLongOpt("assetId") + .withArgName(ASSET_ID) + .withLongOpt(ASSET_ID) .withDescription("asset uuid") .hasArg() .create('u') ); //u for 'uuid' options.addOption(OptionBuilder - .withArgName("artifactId") - .withLongOpt("artifactId") + .withArgName(ARTIFACT_ID) + .withLongOpt(ARTIFACT_ID) .withDescription("artifact uuid") .hasArg() .create('s') ); //s for 'stuff' options.addOption(OptionBuilder - .withArgName("listFilter") - .withLongOpt("listFilter") + .withArgName(LIST_FILTER) + .withLongOpt(LIST_FILTER) .withDescription("filter for list operations") .hasArg() .create('f') ); //u for 'uuid' @@ -997,86 +936,67 @@ public class ASDC { } ASDC asdc = new ASDC(); - asdc.setUri(new URI(line.getOptionValue("target"))); + asdc.setUri(new URI(line.getOptionValue(TARGET))); - String action = line.getOptionValue("action"); - if (action.equals("list")) { + String action = line.getOptionValue(ACTION); + if ("list".equals(action)) { JSONObject filterInfo = new JSONObject( - line.hasOption("listFilter") ? - line.getOptionValue("listFilter") : "{}"); + line.hasOption(LIST_FILTER) ? + line.getOptionValue(LIST_FILTER) : "{}"); JSONArray assets = - asdc.getAssets(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), JSONArray.class, + asdc.getAssets(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), JSONArray.class, filterInfo.optString("category", null), filterInfo.optString("subCategory", null)) .waitForResult(); for (int i = 0; i < assets.length(); i++) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"> {}", assets.getJSONObject(i).toString(2)); } } - else if (action.equals("get")) { + else if ("get".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), JSONObject.class) .waitForResult() .toString(2) ); } - else if (action.equals("getartifact")) { + else if ("getartifact".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.getAssetArtifact(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), - UUID.fromString(line.getOptionValue("artifactId")), + asdc.getAssetArtifact(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), + UUID.fromString(line.getOptionValue(ARTIFACT_ID)), String.class) .waitForResult() ); } - else if (action.equals("checkin")) { + else if ("checkin".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), ASDC.LifecycleState.Checkin, - user_id, + userId, "cli op") .waitForResult() .toString() ); } - else if (action.equals("checkout")) { + else if ("checkout".equals(action)) { debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(), - asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue("assetType")), - UUID.fromString(line.getOptionValue("assetId")), + asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), + UUID.fromString(line.getOptionValue(ASSET_ID)), ASDC.LifecycleState.Checkout, - user_id, + userId, "cli op") .waitForResult() .toString() ); } - else if (action.equals("cleanup")) { + else if ("cleanup".equals(action)) { JSONArray resources = asdc.getResources() .waitForResult(); debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Got {} resources", resources.length()); - // vfcmt cleanup - for (int i = 0; i < resources.length(); i++) { - - JSONObject resource = resources.getJSONObject(i); - - if (resource.getString("resourceType").equals("VFCMT") && - resource.getString("name").contains("test")) { - - debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"undocheckout for {}", resource.getString("uuid")); - - try { - asdc.cycleAsset(AssetType.resource, UUID.fromString(resource.getString("uuid")), LifecycleState.undocheckout, user_id, null) - .waitForResult(); - } - catch (Exception x) { - debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"** {}", x); - } - } - } - + vfcmtCleanup(userId, asdc, resources); } else { try { @@ -1087,7 +1007,7 @@ public class ASDC { .withVendorName("CloneInc") .withVendorRelease("1.0") .withTags("clone") - .withOperator(user_id) + .withOperator(userId) .execute() .waitForResult() .toString() @@ -1098,4 +1018,25 @@ public class ASDC { } } } + + private static void vfcmtCleanup(String userId, ASDC asdc, JSONArray resources) { + for (int i = 0; i < resources.length(); i++) { + + JSONObject resource = resources.getJSONObject(i); + + if ("VFCMT".equals(resource.getString("resourceType")) && + resource.getString("name").contains("test")) { + + debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"undocheckout for {}", resource.getString("uuid")); + + try { + asdc.cycleAsset(AssetType.resource, UUID.fromString(resource.getString("uuid")), LifecycleState.undocheckout, userId, null) + .waitForResult(); + } + catch (Exception x) { + debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"** {}", x); + } + } + } + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java index 1d70627..d6a175f 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtils.java @@ -35,414 +35,422 @@ import java.util.zip.ZipInputStream; @ConfigurationProperties(prefix="asdcutils") public class ASDCUtils { - private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); - private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - @Autowired - private ASDC asdc; - - @Autowired - private Blueprinter blueprint; - - public ASDCUtils() { - // Making sonar happy - } - - public ASDCUtils(URI theASDCURI) { - this(theASDCURI, null); - } - - public ASDCUtils(URI theASDCURI, URI theBlueprinterURI) { - this.asdc = new ASDC(); - this.asdc.setUri(theASDCURI); - if (theBlueprinterURI != null) { - this.blueprint = new Blueprinter(); - this.blueprint.setUri(theBlueprinterURI); - } - } - - public ASDCUtils(ASDC theASDC) { - this(theASDC, null); - } - - public ASDCUtils(ASDC theASDC, Blueprinter theBlueprinter) { - this.asdc = theASDC; - this.blueprint = theBlueprinter; - } - - public CloneAssetArtifactsAction cloneAssetArtifacts(ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) { - return new CloneAssetArtifactsAction(this.asdc, theAssetType, theSourceId, theTargetId); - } - - public static class CloneAssetArtifactsAction extends ASDC.ASDCAction<CloneAssetArtifactsAction, List<JSONObject>> { - - private ASDC.AssetType assetType; - private UUID sourceId, targetId; - - protected CloneAssetArtifactsAction(ASDC theASDC, ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) { - theASDC.super(new JSONObject()); - this.assetType = theAssetType; - this.sourceId = theSourceId; - this.targetId = theTargetId; - } - - protected CloneAssetArtifactsAction self() { - return this; - } - - public CloneAssetArtifactsAction withLabel(String theLabel) { - return with("artifactLabel", theLabel); - } - - protected String[] mandatoryInfoEntries() { - return new String[] {}; - } - - public Future<List<JSONObject>> execute() { - checkMandatory(); - - final Actions.Sequence<JSONObject> sequencer = new Actions.Sequence<JSONObject>(); - - new Actions.Sequence().add(super.asdc().getAssetArchiveAction(this.assetType, this.sourceId)).add(super.asdc().getAssetAction(this.assetType, this.sourceId, JSONObject.class)).execute().setHandler(assetFuture -> { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*** {}", assetFuture.result()); - processArtifacts((List) assetFuture.result(), (JSONObject theInfo, byte[] theData) -> { - theInfo.remove("artifactChecksum"); - theInfo.remove("artifactUUID"); - theInfo.remove("artifactVersion"); - theInfo.remove("artifactURL"); - theInfo.put("description", theInfo.remove("artifactDescription")); - theInfo.put("payloadData", Base64Utils.encodeToString(theData)); - return theInfo; - }, null).forEach(artifactInfo -> sequencer.add(super.asdc().createAssetArtifact(this.assetType, this.targetId).withInfo(ASDC.merge(artifactInfo, this.info)).withOperator(this.operatorId))); - sequencer.execute(); - }); - - return sequencer.future(); - } - } //the Action class - - /* */ - private static JSONObject lookupArtifactInfo(JSONArray theArtifacts, String theName) { - - for (int i = 0; theArtifacts != null && i < theArtifacts.length(); i++) { - JSONObject artifactInfo = theArtifacts.getJSONObject(i); - if (theName.equals(artifactInfo.getString("artifactName"))) { - debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Found artifact info {}", artifactInfo); - return artifactInfo; - } - } - - return null; - } - - private static byte[] extractArtifactData(InputStream theEntryStream) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - byte[] buff = new byte[4096]; - int cnt = 0; - while ((cnt = theEntryStream.read(buff)) != -1) { - baos.write(buff, 0, cnt); - } - } finally { - baos.close(); - } - return baos.toByteArray(); - } - - /** - * Recycle a cdump, fetch all relevant ASDC artifacts, interact with Shu's toscalib service in order to generate - * a blueprint. No 'Action' object here as there is nothig to set up. - */ - public Future<Future<String>> buildBlueprint(Reader theCdump) { - - final Recycler recycler = new Recycler(); - Object template = null; - - try { - template = recycler.recycle(theCdump); - - } catch (Exception x) { - return Futures.failedFuture(x); - } - - JXPathContext jxroot = JXPathContext.newContext(template); - jxroot.setLenient(true); - - //based on the output of ASDCCatalog the node description will contain the UUID of the resource declaring it - List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) - //the desc contains the full URI and the resource uuid is the 5th path element - .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); - - //prepare fetching all archives/resource details - final Futures.Accumulator accumulator = new Futures.Accumulator(); - uuids.stream().forEach(uuid -> { - UUID rid = UUID.fromString((String) uuid); - accumulator.add(this.asdc.getAssetArchive(ASDC.AssetType.resource, rid)); - accumulator.add(this.asdc.getAsset(ASDC.AssetType.resource, rid, JSONObject.class)); - }); - - final byte[] templateData = recycler.toString(template).getBytes(/*"UTF-8"*/); - //retrieve all resource archive+details, prepare blueprint service request and send its request - return Futures.advance(accumulator.accumulate(), (List theArchives) -> { - Blueprinter.BlueprintAction action = blueprint.generateBlueprint(); - processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString("artifactName").split("\\.")[0], Base64Utils.encodeToString(theData)), - (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo)); - - return action.withTemplateData(templateData).execute(); - }); - } - - public Future<Future<String>> buildBlueprintViaToscaLab(Reader theCdump) { - return processCdump(theCdump, (theTemplate, theArchives) -> { - Blueprinter.BlueprintAction action = blueprint.generateBlueprint(); - processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString("artifactName").split("\\.")[0], Base64Utils.encodeToString(theData)), - (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo)); - - return action.withTemplateData(Recycler.toString(theTemplate).getBytes()).execute(); - - }); - } - - private static class Tracker implements TargetLocator { - - private static enum Position { - SCHEMA, TEMPLATE, TRANSLATE; - } - - private static final int Positions = Position.values().length; - - private List<Target> tgts = new ArrayList<Target>(3); - - public Tracker() { - clear(); - } - - public boolean addSearchPath(URI theURI) { - return false; - } - - public boolean addSearchPath(String thePath) { - return false; - } - - public Iterable<URI> searchPaths() { - return Collections.emptyList(); - } - - protected int position(String... theKeys) { - for (String key : theKeys) { - if ("schema".equals(key)) { - return Position.SCHEMA.ordinal(); - } - if ("template".equals(key)) { - return Position.TEMPLATE.ordinal(); - } - if ("translate".equals(key)) { - return Position.TRANSLATE.ordinal(); - } - } - return -1; - } - - public Target resolve(String theName) { - for (Target tgt : tgts) { - if (tgt != null && tgt.getName().equals(theName)) { - return tgt; - } - } - return null; - } - - public void track(JSONObject theInfo, final byte[] theData) { - String uri = theInfo.getString("artifactURL").split("/")[5]; - String name = theInfo.getString("artifactName"), desc = theInfo.getString("artifactDescription"), label = theInfo.getString("artifactLabel"); - int pos = position(desc, label); - - debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Tracking {} at {}, {}", name, pos, theInfo.optString("artifactURL")); - - if (pos > -1) { - tgts.set(pos, new Target(name, URI.create("asdc:" + uri + "/" + name)) { - @Override - public Reader open(){ - return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(theData))); - } - }); - } - } - - public boolean hasSchema() { - return tgts.get(Position.SCHEMA.ordinal()) != null; - } - - public Target schema() { - return tgts.get(Position.SCHEMA.ordinal()); - } - - public boolean hasTemplate() { - return tgts.get(Position.TEMPLATE.ordinal()) != null; - } - - public Target template() { - return tgts.get(Position.TEMPLATE.ordinal()); - } - - public boolean hasTranslation() { - return tgts.get(Position.TRANSLATE.ordinal()) != null; - } - - public Target translation() { - return tgts.get(Position.TRANSLATE.ordinal()); - } - - public void clear() { - if (tgts.isEmpty()) { - for (int i = 0; i < Positions; i++) { - tgts.add(null); - } - } else { - Collections.fill(tgts, null); - } - } - } - - private Checker buildChecker() { - try { - return new Checker(); - } catch (CheckerException cx) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "CheckerException while creating Checker {}", cx); - return null; - } - } - - public Future<Catalog> buildCatalog(Reader theCdump) { - - // - //the purpose of the tracking is to be able to resolve import references within the 'space' of an - //asset's artifacts - //processing order is important too so we 'order the targets: schema, template, translation - // - final Tracker tracker = new Tracker(); - final Catalog catalog = Checker.buildCatalog(); - - return processCdump(theCdump, (theTemplate, theArchives) -> { - - final Checker checker = buildChecker(); - if (checker == null) { - return null; - } - checker.setTargetLocator(tracker); - - processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> { - tracker.track(theInfo, theData); - return (Catalog) null; - }, - // aggregation: this is where the actual processing takes place now that - // we have all the targets - (Stream<Catalog> theAssetArtifacts) -> { - //the stream is full of nulls, ignore it, work with the tracker - - try { - if (tracker.hasSchema()) { - checker.check(tracker.schema(), catalog); - } - if (tracker.hasTemplate()) { - checker.check(tracker.template(), catalog); - } - if (tracker.hasTranslation()) { - checker.check(tracker.translation(), catalog); - } - } catch (CheckerException cx) { - //got to do better than this - errLogger.log(LogLevel.ERROR, ASDC.class.getName(),"CheckerException while checking catalog:{}", cx); - } finally { - tracker.clear(); - } - return checker.catalog(); - }); - - Target cdump = new Target("cdump", URI.create("asdc:cdump")); - cdump.setTarget(theTemplate); - - validateCatalog(catalog, checker, cdump); - - return catalog; - }); - } - - private void validateCatalog(Catalog catalog, Checker checker, Target cdump) { - try { + private static final String ARTIFACT_URL = "artifactURL"; + private static final String ARTIFACT_NAME = "artifactName"; + private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); + private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + + @Autowired + private ASDC asdc; + + @Autowired + private Blueprinter blueprint; + + public ASDCUtils() { + // Making sonar happy + } + + public ASDCUtils(URI theASDCURI) { + this(theASDCURI, null); + } + + public ASDCUtils(URI theASDCURI, URI theBlueprinterURI) { + this.asdc = new ASDC(); + this.asdc.setUri(theASDCURI); + if (theBlueprinterURI != null) { + this.blueprint = new Blueprinter(); + this.blueprint.setUri(theBlueprinterURI); + } + } + + public ASDCUtils(ASDC theASDC) { + this(theASDC, null); + } + + public ASDCUtils(ASDC theASDC, Blueprinter theBlueprinter) { + this.asdc = theASDC; + this.blueprint = theBlueprinter; + } + + public CloneAssetArtifactsAction cloneAssetArtifacts(ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) { + return new CloneAssetArtifactsAction(this.asdc, theAssetType, theSourceId, theTargetId); + } + + public static class CloneAssetArtifactsAction extends ASDC.ASDCAction<CloneAssetArtifactsAction, List<JSONObject>> { + + private ASDC.AssetType assetType; + private UUID sourceId, targetId; + + CloneAssetArtifactsAction(ASDC theASDC, ASDC.AssetType theAssetType, UUID theSourceId, UUID theTargetId) { + theASDC.super(new JSONObject()); + this.assetType = theAssetType; + this.sourceId = theSourceId; + this.targetId = theTargetId; + } + + protected CloneAssetArtifactsAction self() { + return this; + } + + public CloneAssetArtifactsAction withLabel(String theLabel) { + return with("artifactLabel", theLabel); + } + + protected String[] mandatoryInfoEntries() { + return new String[] {}; + } + + public Future<List<JSONObject>> execute() { + checkMandatory(); + + final Actions.Sequence<JSONObject> sequencer = new Actions.Sequence<JSONObject>(); + + new Actions.Sequence().add(super.asdc().getAssetArchiveAction(this.assetType, this.sourceId)).add(super.asdc().getAssetAction(this.assetType, this.sourceId, JSONObject.class)).execute().setHandler(assetFuture -> { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*** {}", assetFuture.result()); + processArtifacts((List) assetFuture.result(), (JSONObject theInfo, byte[] theData) -> { + theInfo.remove("artifactChecksum"); + theInfo.remove("artifactUUID"); + theInfo.remove("artifactVersion"); + theInfo.remove(ARTIFACT_URL); + theInfo.put("description", theInfo.remove("artifactDescription")); + theInfo.put("payloadData", Base64Utils.encodeToString(theData)); + return theInfo; + }, null).forEach(artifactInfo -> sequencer.add(super.asdc().createAssetArtifact(this.assetType, this.targetId).withInfo(ASDC.merge(artifactInfo, this.info)).withOperator(this.operatorId))); + sequencer.execute(); + }); + + return sequencer.future(); + } + } //the Action class + + /* */ + private static JSONObject lookupArtifactInfo(JSONArray theArtifacts, String theName) { + + for (int i = 0; theArtifacts != null && i < theArtifacts.length(); i++) { + JSONObject artifactInfo = theArtifacts.getJSONObject(i); + if (theName.equals(artifactInfo.getString(ARTIFACT_NAME))) { + debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Found artifact info {}", artifactInfo); + return artifactInfo; + } + } + + return null; + } + + private static byte[] extractArtifactData(InputStream theEntryStream) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + byte[] buff = new byte[4096]; + int cnt = 0; + while ((cnt = theEntryStream.read(buff)) != -1) { + baos.write(buff, 0, cnt); + } + } finally { + baos.close(); + } + return baos.toByteArray(); + } + + /** + * Recycle a cdump, fetch all relevant ASDC artifacts, interact with Shu's toscalib service in order to generate + * a blueprint. No 'Action' object here as there is nothig to set up. + */ + public Future<Future<String>> buildBlueprint(Reader theCdump) { + + final Recycler recycler = new Recycler(); + Object template = null; + + try { + template = recycler.recycle(theCdump); + + } catch (Exception x) { + return Futures.failedFuture(x); + } + + JXPathContext jxroot = JXPathContext.newContext(template); + jxroot.setLenient(true); + + //based on the output of ASDCCatalog the node description will contain the UUID of the resource declaring it + List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) + //the desc contains the full URI and the resource uuid is the 5th path element + .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); + + //prepare fetching all archives/resource details + final Futures.Accumulator accumulator = new Futures.Accumulator(); + uuids.forEach(uuid -> { + UUID rid = UUID.fromString((String) uuid); + accumulator.add(this.asdc.getAssetArchive(ASDC.AssetType.resource, rid)); + accumulator.add(this.asdc.getAsset(ASDC.AssetType.resource, rid, JSONObject.class)); + }); + + final byte[] templateData = recycler.toString(template).getBytes(/*"UTF-8"*/); + //retrieve all resource archive+details, prepare blueprint service request and send its request + return Futures.advance(accumulator.accumulate(), (List theArchives) -> { + Blueprinter.BlueprintAction action = blueprint.generateBlueprint(); + processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString(ARTIFACT_NAME).split("\\.")[0], Base64Utils.encodeToString(theData)), + (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo)); + + return action.withTemplateData(templateData).execute(); + }); + } + + public Future<Future<String>> buildBlueprintViaToscaLab(Reader theCdump) { + return processCdump(theCdump, (theTemplate, theArchives) -> { + Blueprinter.BlueprintAction action = blueprint.generateBlueprint(); + processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> new JSONObject().put(theInfo.getString(ARTIFACT_NAME).split("\\.")[0], Base64Utils.encodeToString(theData)), + (Stream<JSONObject> theAssetArtifacts) -> theAssetArtifacts.reduce(new JSONObject(), ASDC::merge)).forEach(artifactInfo -> action.withModelInfo(artifactInfo)); + + return action.withTemplateData(Recycler.toString(theTemplate).getBytes()).execute(); + + }); + } + + private static class Tracker implements TargetLocator { + + private enum Position { + SCHEMA, TEMPLATE, TRANSLATE; + } + + private static final int POSITIONS = Position.values().length; + + private List<Target> tgts = new ArrayList<Target>(3); + + Tracker() { + clear(); + } + + public boolean addSearchPath(URI theURI) { + return false; + } + + public boolean addSearchPath(String thePath) { + return false; + } + + public Iterable<URI> searchPaths() { + return Collections.emptyList(); + } + + int position(String... theKeys) { + for (String key : theKeys) { + if ("schema".equals(key)) { + return Position.SCHEMA.ordinal(); + } + if ("template".equals(key)) { + return Position.TEMPLATE.ordinal(); + } + if ("translate".equals(key)) { + return Position.TRANSLATE.ordinal(); + } + } + return -1; + } + + public Target resolve(String theName) { + for (Target tgt : tgts) { + if (tgt != null && tgt.getName().equals(theName)) { + return tgt; + } + } + return null; + } + + void track(JSONObject theInfo, final byte[] theData) { + String uri = theInfo.getString(ARTIFACT_URL).split("/")[5]; + String name = theInfo.getString(ARTIFACT_NAME), desc = theInfo.getString("artifactDescription"), label = theInfo.getString("artifactLabel"); + int pos = position(desc, label); + + debugLogger.log(LogLevel.DEBUG, ASDCUtils.class.getName(), "Tracking {} at {}, {}", name, pos, theInfo.optString(ARTIFACT_URL)); + + if (pos > -1) { + tgts.set(pos, new Target(name, URI.create("asdc:" + uri + "/" + name)) { + @Override + public Reader open(){ + return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(theData))); + } + }); + } + } + + boolean hasSchema() { + return tgts.get(Position.SCHEMA.ordinal()) != null; + } + + public Target schema() { + return tgts.get(Position.SCHEMA.ordinal()); + } + + boolean hasTemplate() { + return tgts.get(Position.TEMPLATE.ordinal()) != null; + } + + public Target template() { + return tgts.get(Position.TEMPLATE.ordinal()); + } + + boolean hasTranslation() { + return tgts.get(Position.TRANSLATE.ordinal()) != null; + } + + public Target translation() { + return tgts.get(Position.TRANSLATE.ordinal()); + } + + public void clear() { + if (tgts.isEmpty()) { + for (int i = 0; i < POSITIONS; i++) { + tgts.add(null); + } + } else { + Collections.fill(tgts, null); + } + } + } + + private Checker buildChecker() { + try { + return new Checker(); + } catch (CheckerException cx) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "CheckerException while creating Checker {}", cx); + return null; + } + } + + public Future<Catalog> buildCatalog(Reader theCdump) { + + // + //the purpose of the tracking is to be able to resolve import references within the 'space' of an + //asset's artifacts + //processing order is important too so we 'order the targets: schema, template, translation + // + final Tracker tracker = new Tracker(); + final Catalog catalog = Checker.buildCatalog(); + + return processCdump(theCdump, (theTemplate, theArchives) -> { + + final Checker checker = buildChecker(); + if (checker == null) { + return null; + } + checker.setTargetLocator(tracker); + + processArtifacts(theArchives, (JSONObject theInfo, byte[] theData) -> { + tracker.track(theInfo, theData); + return (Catalog) null; + }, + // aggregation: this is where the actual processing takes place now that + // we have all the targets + (Stream<Catalog> theAssetArtifacts) -> checkAndGetCatalog(tracker, catalog, checker)); + + Target cdump = new Target("cdump", URI.create("asdc:cdump")); + cdump.setTarget(theTemplate); + + validateCatalog(catalog, checker, cdump); + + return catalog; + }); + } + + private Catalog checkAndGetCatalog(Tracker tracker, Catalog catalog, Checker checker) { + //the stream is full of nulls, ignore it, work with the tracker + + try { + if (tracker.hasSchema()) { + checker.check(tracker.schema(), catalog); + } + if (tracker.hasTemplate()) { + checker.check(tracker.template(), catalog); + } + if (tracker.hasTranslation()) { + checker.check(tracker.translation(), catalog); + } + } catch (CheckerException cx) { + //got to do better than this + errLogger.log(LogLevel.ERROR, ASDC.class.getName(),"CheckerException while checking catalog:{}", cx); + } finally { + tracker.clear(); + } + return checker.catalog(); + } + + private void validateCatalog(Catalog catalog, Checker checker, Target cdump) { + try { checker.validate(cdump, catalog); } catch (CheckerException cx) { errLogger.log(LogLevel.ERROR, ASDC.class.getName(),"CheckerException while building catalog:{}", cx); } - } - - /* The common process of recycling, retrieving all related artifacts and then doing 'something' */ - private <T> Future<T> processCdump(Reader theCdump, BiFunction<Object, List, T> theProcessor) { - - final Recycler recycler = new Recycler(); - Object template = null; - try { - template = recycler.recycle(theCdump); - - } catch (Exception x) { - return Futures.failedFuture(x); - } - - JXPathContext jxroot = JXPathContext.newContext(template); - jxroot.setLenient(true); - - //based on the output of ASDCCatalog the node description will contain the UUID of the resource declaring it - //the desc contains the full URI and the resource uuid is the 5th path element - List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) - .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); - - //serialized fetch version - final Actions.Sequence sequencer = new Actions.Sequence(); - uuids.stream().forEach(uuid -> { - UUID rid = UUID.fromString((String) uuid); - sequencer.add(this.asdc.getAssetArchiveAction(ASDC.AssetType.resource, rid)); - sequencer.add(this.asdc.getAssetAction(ASDC.AssetType.resource, rid, JSONObject.class)); - }); - - final Object tmpl = template; - return Futures.advance(sequencer.execute(), (List theArchives) -> theProcessor.apply(tmpl, theArchives)); - } - - private static <T> Stream<T> processArtifacts(List theArtifactData, BiFunction<JSONObject, byte[], T> theProcessor, Function<Stream<T>, T> theAggregator) { - - Stream.Builder<T> assetBuilder = Stream.builder(); - - for (int i = 0; i < theArtifactData.size(); i = i + 2) { //cute old style loop - - JSONObject assetInfo = (JSONObject) theArtifactData.get(i + 1); - byte[] assetData = (byte[]) theArtifactData.get(i + 0); - - JSONArray artifacts = assetInfo.optJSONArray("artifacts"); - - Stream.Builder<T> artifactBuilder = Stream.builder(); - - try (ZipInputStream zipper = new ZipInputStream(new ByteArrayInputStream(assetData))){ - //we process the artifacts in the order they are stored in the archive .. fugly - for (ZipEntry zipped = zipper.getNextEntry(); zipped != null; zipped = zipper.getNextEntry()) { - JSONObject artifactInfo = lookupArtifactInfo(artifacts, StringUtils.substringAfterLast(zipped.getName(), "/")); - if (artifactInfo != null) { - artifactBuilder.add(theProcessor.apply(artifactInfo, extractArtifactData(zipper))); - } - zipper.closeEntry(); - } - } catch (IOException iox) { - errLogger.log(LogLevel.ERROR, ASDC.class.getName(), "IOException: {}", iox); - return null; - } - - if (theAggregator != null) { - assetBuilder.add(theAggregator.apply(artifactBuilder.build())); - } else { - artifactBuilder.build().forEach(entry -> assetBuilder.add(entry)); - } - } - - return assetBuilder.build(); - } + } + + /* The common process of recycling, retrieving all related artifacts and then doing 'something' */ + private <T> Future<T> processCdump(Reader theCdump, BiFunction<Object, List, T> theProcessor) { + + final Recycler recycler = new Recycler(); + Object template = null; + try { + template = recycler.recycle(theCdump); + + } catch (Exception x) { + return Futures.failedFuture(x); + } + + JXPathContext jxroot = JXPathContext.newContext(template); + jxroot.setLenient(true); + + //based on the output of ASDCCatalog the node description will contain the UUID of the resource declaring it + //the desc contains the full URI and the resource uuid is the 5th path element + List uuids = (List) StreamSupport.stream(Spliterators.spliteratorUnknownSize(jxroot.iterate("topology_template/node_templates/*/description"), 16), false).distinct().filter(desc -> desc != null) + .map(desc -> desc.toString().split("/")[5]).collect(Collectors.toList()); + + //serialized fetch version + final Actions.Sequence sequencer = new Actions.Sequence(); + uuids.stream().forEach(uuid -> { + UUID rid = UUID.fromString((String) uuid); + sequencer.add(this.asdc.getAssetArchiveAction(ASDC.AssetType.resource, rid)); + sequencer.add(this.asdc.getAssetAction(ASDC.AssetType.resource, rid, JSONObject.class)); + }); + + final Object tmpl = template; + return Futures.advance(sequencer.execute(), (List theArchives) -> theProcessor.apply(tmpl, theArchives)); + } + + private static <T> Stream<T> processArtifacts(List theArtifactData, BiFunction<JSONObject, byte[], T> theProcessor, Function<Stream<T>, T> theAggregator) { + + Stream.Builder<T> assetBuilder = Stream.builder(); + + for (int i = 0; i < theArtifactData.size(); i = i + 2) { //cute old style loop + + JSONObject assetInfo = (JSONObject) theArtifactData.get(i + 1); + byte[] assetData = (byte[]) theArtifactData.get(i + 0); + + JSONArray artifacts = assetInfo.optJSONArray("artifacts"); + + Stream.Builder<T> artifactBuilder = Stream.builder(); + + try (ZipInputStream zipper = new ZipInputStream(new ByteArrayInputStream(assetData))){ + //we process the artifacts in the order they are stored in the archive .. fugly + processZipArtifacts(theProcessor, artifacts, artifactBuilder, zipper); + } catch (IOException iox) { + errLogger.log(LogLevel.ERROR, ASDC.class.getName(), "IOException: {}", iox); + return null; + } + + if (theAggregator != null) { + assetBuilder.add(theAggregator.apply(artifactBuilder.build())); + } else { + artifactBuilder.build().forEach(entry -> assetBuilder.add(entry)); + } + } + + return assetBuilder.build(); + } + + private static <T> void processZipArtifacts(BiFunction<JSONObject, byte[], T> theProcessor, JSONArray artifacts, Stream.Builder<T> artifactBuilder, ZipInputStream zipper) throws IOException { + for (ZipEntry zipped = zipper.getNextEntry(); zipped != null; zipped = zipper.getNextEntry()) { + JSONObject artifactInfo = lookupArtifactInfo(artifacts, StringUtils.substringAfterLast(zipped.getName(), "/")); + if (artifactInfo != null) { + artifactBuilder.add(theProcessor.apply(artifactInfo, extractArtifactData(zipper))); + } + zipper.closeEntry(); + } + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java index 4432712..377e71b 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDCUtilsController.java @@ -1,70 +1,30 @@ package org.onap.sdc.dcae.catalog.asdc; -import java.io.StringReader; - -import java.util.UUID; -import java.util.Map; -import java.util.List; -import java.util.concurrent.Callable; - -import java.net.URI; -import java.net.URISyntaxException; - -import javax.servlet.http.HttpServletRequest; - -import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.springframework.beans.BeansException; - -import org.springframework.web.bind.annotation.RestController; - -import org.onap.sdc.dcae.catalog.asdc.ASDC; -import org.onap.sdc.dcae.catalog.asdc.ASDCUtils; -import org.onap.sdc.dcae.catalog.asdc.ASDCUtilsController; - -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.http.HttpStatus; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; - +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; - -import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; -import org.json.JSONObject; - @RestController @ConfigurationProperties(prefix="asdcUtilsController") public class ASDCUtilsController implements ApplicationContextAware { - private ApplicationContext appCtx; private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - //Constants// - private static String NOT_CERTIFIED_CHECKOUT = "NOT_CERTIFIED_CHECKOUT"; - private static String NOT_CERTIFIED_CHECKIN = "NOT_CERTIFIED_CHECKIN"; - private static String CERTIFICATION_IN_PROGRESS = "CERTIFICATION_IN_PROGRESS"; - private static String CERTIFIED = "CERTIFIED"; - public void setApplicationContext(ApplicationContext theCtx) throws BeansException { - this.appCtx = theCtx; + // no use for app context } @PostConstruct public void initController() { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"initASDCUtilsController"); - - //Done debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"ASDCUtilsController started"); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java index 3e78d38..4e5349f 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Blueprinter.java @@ -10,7 +10,6 @@ import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.catalog.commons.Action; import org.onap.sdc.dcae.catalog.commons.Future; import org.onap.sdc.dcae.catalog.commons.Http; -import org.json.JSONArray; import org.springframework.util.Base64Utils; @@ -26,51 +25,41 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @Scope("singleton") @ConfigurationProperties(prefix="blueprinter") public class Blueprinter { + private URI serviceUri; + private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + public void setUri(URI theUri) { + this.serviceUri = theUri; + } - private URI serviceUri; - private OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); + public BlueprintAction generateBlueprint() { + return new BlueprintAction(); + } + public class BlueprintAction implements Action<String> { - public Blueprinter() { - } + private JSONObject body = new JSONObject(); - public void setUri(URI theUri) { - this.serviceUri = theUri; - } + protected BlueprintAction() { + } - public BlueprintAction generateBlueprint() { - return new BlueprintAction(); - } + public BlueprintAction withModelInfo(JSONObject theModelInfo) { + body.append("models", theModelInfo); + return this; + } - public class BlueprintAction implements Action<String> { + public BlueprintAction withTemplateData(byte[] theData) { + body.put("template", Base64Utils.encodeToString(theData)); + return this; + } - private JSONObject body = new JSONObject(); + public Future<String> execute() { - - protected BlueprintAction() { - } - - public BlueprintAction withModelData(byte[] theSchema, byte[] theTemplate, byte[] theTranslation) { - return this; - } - - public BlueprintAction withModelInfo(JSONObject theModelInfo) { - body.append("models", theModelInfo); - return this; - } - - public BlueprintAction withTemplateData(byte[] theData) { - body.put("template", Base64Utils.encodeToString(theData)); - return this; - } - - public Future<String> execute() { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Blueprinter::execute() | PAYLOAD to TOSCA_LAB={}", body.toString()); - HttpHeaders headers = new HttpHeaders(); - headers.setContentType(MediaType.APPLICATION_JSON); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); - return Http.exchange(serviceUri.toString(), HttpMethod.POST, new HttpEntity<String>(body.toString(), headers), String.class); - } - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Blueprinter::execute() | PAYLOAD to TOSCA_LAB={}", body.toString()); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + return Http.exchange(serviceUri.toString(), HttpMethod.POST, new HttpEntity<>(body.toString(), headers), String.class); + } + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java deleted file mode 100644 index 3208bd2..0000000 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/Cloudify.java +++ /dev/null @@ -1,249 +0,0 @@ -package org.onap.sdc.dcae.catalog.asdc; - -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.stream.Stream; - -import org.apache.commons.jxpath.JXPathContext; -import org.apache.commons.jxpath.Pointer; -import org.onap.sdc.common.onaplog.OnapLoggerDebug; -import org.onap.sdc.common.onaplog.OnapLoggerError; -import org.onap.sdc.common.onaplog.Enums.LogLevel; -import org.onap.sdc.dcae.catalog.commons.ListBuilder; -import org.onap.sdc.dcae.catalog.commons.MapBuilder; -import org.onap.sdc.dcae.checker.Catalog; -import org.onap.sdc.dcae.checker.Construct; -import org.onap.sdc.dcae.checker.Target; - -import com.google.common.collect.Lists; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.Yaml; - - -public class Cloudify { - - private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); - private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - - Catalog catalog; - - public Cloudify(Catalog c) - { - catalog = c; - } - public class ModelTemplate { - public Map<String, Map> template; - public JXPathContext jx; - public String node; - public ModelTemplate(Map<String, Map> t, JXPathContext j, String node_name) - { - template = t; - jx = j; - node = node_name; - } - - public Object getPropValue(JXPathContext jx_src, String name) - { - try{ - Object ret = jx_src.getValue("properties/"+name+"/get_input"); - if (ret==null) - return jx_src.getValue("properties/"+name); - return getDefaultPropValue((String)ret); - } - catch (RuntimeException e) { - - } - try{ - return jx_src.getValue("properties/"+name+""); - } - catch (RuntimeException e) { - return null; - } - } - - public Object getDefaultPropValue(String name) { - try { - return jx.getValue("//"+name+"/default"); - } - catch (RuntimeException e) { - return null; - } - - } - } - - public class ModelTranslate { - public Map<String, Map> template; - public JXPathContext jx; - public String node; - - public ModelTranslate(Map<String, Map> t, JXPathContext j, String node_name) - { - template = t; - jx = j; - node = node_name; - } - - public String getTranslateName() - { - Map<String, Object> node_temp = (Map<String, Object>)jx.getValue("//node_templates"); - Iterator it = node_temp.keySet().iterator(); - if (it.hasNext()) - return node + "_"+ it.next(); - else - return null; - } - - public Map<String, Object> translate(JXPathContext jx_src, Map<String, Map> model_lib, String node_name) - { - for (Iterator prop_iter = jx.iteratePointers("//*[@get_input]"); prop_iter.hasNext();) { - - Pointer p = (Pointer)prop_iter.next(); - JXPathContext prop_path = jx.getRelativeContext(p); - - ModelTemplate src_model =(ModelTemplate) model_lib.get(node_name).get("model"); - - Object temp_o = src_model.getPropValue(jx_src, (String) prop_path.getValue("get_input")); - //prop_path.setValue(".", temp_o); - jx.setValue(p.asPath(), temp_o); - } - -// JXPathContext jx_src = JXPathContext.newContext(src); - for (Iterator req_iter = jx_src.iteratePointers("//*/node"); req_iter.hasNext();) { - Pointer p = (Pointer)req_iter.next(); - String req_node_name = (String)jx_src.getValue(p.asPath()); - - for (Iterator it = model_lib.keySet().iterator(); it.hasNext();) { - String key = (String) it.next(); - if (key.indexOf(req_node_name) <0 ) - continue; - ModelTranslate tt = (ModelTranslate) model_lib.get(key).get("translate"); - if (tt == null) - req_node_name = null; - else - { - req_node_name = tt.getTranslateName(); - } - break; - } - - } - - String tn_name = getTranslateName(); - - if (tn_name == null) - return (Map<String, Object>)jx.getValue("//node_templates"); - else - return (new MapBuilder<String, Object>().put(tn_name, jx.getValue("//node_templates/*")).build()); - } - - } - - public ModelTranslate findTranslateTemplate(String ty, String node) { - for (Target t: catalog.targets()) { - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "findTranslateTemplate: target {}", t.getName()); - if (t.getName().startsWith("translat") == false) { - continue; - } - - Map<String, Map>temp = (Map<String, Map>)t.getTarget(); - - JXPathContext jxroot = JXPathContext.newContext(temp); - try{ - String sub_type = (String)jxroot.getValue("topology_template/substitution_mappings/node_type"); - if (sub_type != null && sub_type.equals(ty)) { - return new ModelTranslate(temp, jxroot, node); - } - } - catch (RuntimeException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "translate template {} does not have substitution mapping section", t.getName()); - } - } - return null; - } - - public ModelTemplate findModelTemplate(String ty, String node) { - for (Target t: catalog.targets()) { - - if (t.getName().startsWith("templat") == false) - continue; - Map<String, Map>temp = (Map<String, Map>)t.getTarget(); - - JXPathContext jxroot = JXPathContext.newContext(temp); - for (Iterator it = jxroot.iterate("topology_template/node_templates/*/type"); it.hasNext();) { - String node_type = (String)it.next(); - if (node_type != null && node_type.equals(ty)) { - return new ModelTemplate(temp, jxroot, node); - } - } - } - return null; - } - - public Map<String, Object> createBlueprint() { - - Map<String, Map> target_temp = null; - for (Target t: catalog.targets()) { - - if (t.getName().equals("cdump")) { - target_temp = catalog.getTargetTemplates(t, Construct.Node); - } - } - - JXPathContext jxroot = JXPathContext.newContext(target_temp); - - Map<String, Object> output_temp = new HashMap<String, Object>(); - Map<String, Map> model_lib = new HashMap<String, Map>(); - - for (Iterator iter = target_temp.keySet().iterator(); iter.hasNext();) - { - String node_key = (String)iter.next(); - //jxroot.getVariables().declareVariable("name", target_temp.get(node_key)); - //String node_type = (String)jxroot.getValue("$name/type"); - String node_type = (String)jxroot.getValue(node_key+"/type"); - - ModelTranslate t_temp = findTranslateTemplate(node_type, node_key); - ModelTemplate t_model = findModelTemplate(node_type, node_key); - - model_lib.put(node_key, new MapBuilder() - .put("model", t_model) - .put("translate", t_temp) - .build()); - } - - for (Iterator iter = model_lib.keySet().iterator(); iter.hasNext();) { - String node_key = (String) iter.next(); - ModelTranslate t = (ModelTranslate) model_lib.get(node_key).get("translate"); - JXPathContext jxnode = jxroot.getRelativeContext(jxroot.getPointer(node_key)); - if (t != null) { - Map<String, Object> t_output =t.translate(jxnode, model_lib, node_key); - if (t_output != null) - output_temp.putAll(t_output); - } - - } - - return new MapBuilder<String, Object>() - .put("tosca_definitions_version", new String("cloudify_dsl_1_3")) - .put("imports", new ListBuilder() - .add(new MapBuilder() - .put("cloudify", - "http://www.getcloudify.org/spec/cloudify/3.4/types.yaml") - .build()) - .build()) - .put("node_templates", output_temp) - .build(); - - } - - public String createBlueprintDocument() { - DumperOptions options = new DumperOptions(); - options.setWidth(1000000); - Yaml yaml = new Yaml(options); - return yaml.dump(createBlueprint()); - } -} diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java index 554991a..c389d75 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/ISdcClient.java @@ -1,47 +1,48 @@ package org.onap.sdc.dcae.client; +import com.fasterxml.jackson.core.JsonProcessingException; import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; -import org.onap.sdc.dcae.composition.restmodels.sdc.*; import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; -import org.onap.sdc.dcae.enums.AssetType; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; import java.util.List; public interface ISdcClient { - ResourceDetailed getResource(String uuid, String requestId) throws Exception; + ResourceDetailed getResource(String uuid, String requestId); + + ServiceDetailed getService(String uuid, String requestId); - ServiceDetailed getService(String uuid, String requestId) throws Exception; + ServiceDetailed getAssetMetadata(String contextType, String uuid, String requestId); - List<Resource> getResources(String resourceType, String category, String subcategory, String requestId) throws Exception; + List<Resource> getResources(String resourceType, String category, String subcategory, String requestId); - List<Service> getServices(String requestId) throws Exception; + List<Service> getServices(String requestId); - String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfiUuid, String requestId); + String addExternalMonitoringReference(String userId, String contextType, String serviceUuid, String vfiName, ReferenceUUID vfcmtUuid, String requestId); - void deleteExternalMonitoringReference(String userId, String context, String uuid, String vfiName, String vfcmtUuid, String requestId); + String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId); - ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId) throws Exception; + void deleteExternalMonitoringReference(String userId, String contextType, String uuid, String vfiName, String vfcmtUuid, String requestId); - ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) throws Exception; + ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId); - ServiceDetailed changeServiceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) throws Exception; + ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId); - Asset changeAssetLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, AssetType assetType, String requestId) throws Exception; + String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId); - String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId) throws Exception; + Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception; + Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception; + void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId); - void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId) throws Exception; + Artifact createInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact createVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception; + Artifact updateInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException; - Artifact updateVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception; + ExternalReferencesMap getMonitoringReferences(String contextType, String uuid, String version, String requestId); - ExternalReferencesMap getMonitoringReferences(String context, String uuid, String version, String requestId); + void deleteInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId); - void deleteInstanceResourceArtifact(String userId, String context, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java index 058d9c7..b07126e 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/client/SdcRestClient.java @@ -1,9 +1,12 @@ package org.onap.sdc.dcae.client; +import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.codec.digest.DigestUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; import org.onap.sdc.dcae.composition.restmodels.sdc.*; @@ -14,18 +17,22 @@ import org.onap.sdc.dcae.enums.SdcConsumerInfo; import org.onap.sdc.dcae.utils.Normalizers; import org.onap.sdc.dcae.utils.SDCResponseErrorHandler; import org.onap.sdc.dcae.utils.SdcRestClientUtils; -import org.onap.sdc.common.onaplog.OnapLoggerDebug; -import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; -import org.springframework.web.client.*; +import org.springframework.web.client.RestTemplate; import javax.annotation.PostConstruct; import java.net.URI; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -39,8 +46,6 @@ public class SdcRestClient implements ISdcClient { private static final String ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID"; private static final String ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; private static final String USER_ID_HEADER = "USER_ID"; - private static final String RESOURCES_PATH = "resources"; - private static final String SERVICES_PATH = "services"; private static final String ARTIFACTS_PATH = "artifacts"; private static final String CONTENT_MD5_HEADER = "Content-MD5"; private static final String RESOURCE_INSTANCES_PATH = "resourceInstances"; @@ -76,117 +81,110 @@ public class SdcRestClient implements ISdcClient { return headers; } + public ServiceDetailed getAssetMetadata(String contextType, String uuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), uuid, METADATA_PATH); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get asset metadata from SDC. URL={}", url); + return getObject(url, requestId, ServiceDetailed.class); + } + public ResourceDetailed getResource(String uuid, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, uuid, METADATA_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), uuid, METADATA_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resource from SDC. URL={}", url); return getObject(url, requestId, ResourceDetailed.class); } public ServiceDetailed getService(String uuid, String requestId) { - String url = buildRequestPath(SERVICES_PATH, uuid, METADATA_PATH); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get service from SDC. URL={}", url); - return getObject(url, requestId, ServiceDetailed.class); + return getAssetMetadata(AssetType.SERVICE.name(), uuid, requestId); } public List<Resource> getResources(String resourceType, String category, String subcategory, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, SdcRestClientUtils.buildResourceFilterQuery(resourceType, category, subcategory)); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), SdcRestClientUtils.buildResourceFilterQuery(resourceType, category, subcategory)); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resources from SDC. URL={}", url); return Arrays.asList(getObject(url, requestId, Resource[].class)); } public List<Service> getServices(String requestId) { - String url = buildRequestPath(SERVICES_PATH); + String url = buildRequestPath(AssetType.SERVICE.getSdcContextPath()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get services from SDC. URL={}", url); return Arrays.asList(getObject(url, requestId, Service[].class)); } - public String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId) { - String url = buildRequestPath(resource.getContextType(), resource.getServiceUuid(), RESOURCE_INSTANCES_PATH, - Normalizers.normalizeComponentInstanceName(resource.getVfiName()), MONITORING_REFERENCES_PATH); - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Connecting service id {} name {} to vfcmt {} URL={}", - resource.getServiceUuid(), resource.getVfiName(), vfcmtUuid.getReferenceUUID(), url); + public String addExternalMonitoringReference(String userId, String contextType, String serviceUuid, String vfiName, ReferenceUUID vfcmtUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, Normalizers.normalizeComponentInstanceName(vfiName), MONITORING_REFERENCES_PATH); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Creating external monitoring reference from service id {} vfi name {} to vfcmt {} URL={}", serviceUuid, vfiName, vfcmtUuid.getReferenceUUID(), url); + return client.postForObject(url, new HttpEntity<>(vfcmtUuid, postResourceHeaders(userId, requestId)), String.class); + } - return client.postForObject(url, new HttpEntity<>(vfcmtUuid, postResourceHeaders(userId, requestId)), - String.class); + public String addExternalMonitoringReference(String userId, CreateVFCMTRequest resource, ReferenceUUID vfcmtUuid, String requestId) { + return addExternalMonitoringReference(userId, resource.getContextType(), resource.getServiceUuid(), resource.getVfiName(), vfcmtUuid, requestId); } - public void deleteExternalMonitoringReference(String userId, String context, String uuid, String normalizeVfiName, String vfcmtUuid, String requestId) { - String url = buildRequestPath(context, uuid, RESOURCE_INSTANCES_PATH, - normalizeVfiName, MONITORING_REFERENCES_PATH, vfcmtUuid); + public void deleteExternalMonitoringReference(String userId, String contextType, String serviceUuid, String normalizeVfiName, String vfcmtUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizeVfiName, MONITORING_REFERENCES_PATH, vfcmtUuid); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete external monitoring reference from SDC asset. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), String.class); } public ResourceDetailed createResource(String userId, CreateVFCMTRequest resource, String requestId) { - String url = buildRequestPath(RESOURCES_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource with name {} URL={}", resource.getName(), url); return client.postForObject(url, new HttpEntity<>(resource, postResourceHeaders(userId, requestId)), ResourceDetailed.class); } public ResourceDetailed changeResourceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, uuid, LIFECYCLE_STATE_PATH); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), uuid, LIFECYCLE_STATE_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Change SDC resource lifecycle state ({}). URL={}", lifecycleOperation, url); return client.postForObject(url, new HttpEntity<>(SdcRestClientUtils.buildUserRemarksObject(userRemarks), postResourceHeaders(userId, requestId)), ResourceDetailed.class, lifecycleOperation); } - public ServiceDetailed changeServiceLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, String requestId) { - String url = buildRequestPath(SERVICES_PATH, uuid, LIFECYCLE_STATE_PATH); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Change SDC service lifecycle state ({}). URL={}", lifecycleOperation, url); - return client.postForObject(url, new HttpEntity<>(SdcRestClientUtils.buildUserRemarksObject(userRemarks), postResourceHeaders(userId, requestId)), ServiceDetailed.class, lifecycleOperation); - } - - public Asset changeAssetLifecycleState(String userId, String uuid, String lifecycleOperation, String userRemarks, AssetType assetType, String requestId) { - return AssetType.RESOURCE == assetType ? changeResourceLifecycleState(userId, uuid, lifecycleOperation, userRemarks, requestId) : changeServiceLifecycleState(userId, uuid, lifecycleOperation, userRemarks, requestId); - } - public String getResourceArtifact(String resourceUuid, String artifactUuid, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifactUuid); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifactUuid); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get resource artifact from SDC. URL={}", url); return getObject(url, requestId, String.class); } - public Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH); + public Artifact createResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifact.getArtifactUUID()); + public Artifact updateResourceArtifact(String userId, String resourceUuid, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifact.getArtifactUUID()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Update SDC resource artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } public void deleteResourceArtifact(String userId, String resourceUuid, String artifactId, String requestId) { - String url = buildRequestPath(RESOURCES_PATH, resourceUuid, ARTIFACTS_PATH, artifactId); + String url = buildRequestPath(AssetType.RESOURCE.getSdcContextPath(), resourceUuid, ARTIFACTS_PATH, artifactId); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete SDC resource artifact. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), Artifact.class); } - public Artifact createVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(SERVICES_PATH, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH); + public Artifact createInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Create SDC resource instance artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public Artifact updateVfInstanceArtifact(String userId, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws Exception { - String url = buildRequestPath(SERVICES_PATH, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH, artifact.getArtifactUUID()); + public Artifact updateInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedInstanceName, Artifact artifact, String requestId) throws JsonProcessingException { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedInstanceName, ARTIFACTS_PATH, artifact.getArtifactUUID()); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Update SDC resource instance artifact. URL={}", url); String artifactData = SdcRestClientUtils.artifactToString(artifact); return client.postForObject(url, new HttpEntity<>(artifactData, postArtifactHeaders(userId, artifactData, requestId)), Artifact.class); } - public ExternalReferencesMap getMonitoringReferences(String context, String uuid, String version, String requestId) { - String url = buildRequestPath(context, uuid, VERSION_PATH, version, MONITORING_REFERENCES_PATH); + public ExternalReferencesMap getMonitoringReferences(String contextType, String uuid, String version, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), uuid, VERSION_PATH, version, MONITORING_REFERENCES_PATH); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Get SDC service monitoring references. URL={}", url); return getObject(url, requestId, ExternalReferencesMap.class); } - public void deleteInstanceResourceArtifact(String userId, String context, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId) { - String url = buildRequestPath(context, serviceUuid, RESOURCE_INSTANCES_PATH, normalizedVfiName, ARTIFACTS_PATH, artifactUuid); + public void deleteInstanceArtifact(String userId, String contextType, String serviceUuid, String normalizedVfiName, String artifactUuid, String requestId) { + String url = buildRequestPath(AssetType.getSdcContextPath(contextType), serviceUuid, RESOURCE_INSTANCES_PATH, normalizedVfiName, ARTIFACTS_PATH, artifactUuid); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Delete SDC instance resource artifact. URL={}", url); client.exchange(url, HttpMethod.DELETE, new HttpEntity(postResourceHeaders(userId, requestId)), Artifact.class); } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java index 576643f..647349f 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/enums/AssetType.java @@ -1,5 +1,32 @@ package org.onap.sdc.dcae.enums; public enum AssetType { - RESOURCE, SERVICE + + RESOURCE(SdcContextPath.RESOURCES), + SERVICE(SdcContextPath.SERVICES), + VFCMT(SdcContextPath.RESOURCES), + VF(SdcContextPath.RESOURCES); + + private String sdcContextPath; + + AssetType(SdcContextPath sdcContextPath) { + this.sdcContextPath = sdcContextPath.name().toLowerCase(); + } + + public String getSdcContextPath() { + return sdcContextPath; + } + + // passing an invalid type will result in an IllegalArgumentException, which is fine as the 'type' value is an SDC enum value passed from SDC pluggable UI + public static AssetType getAssetTypeByName(String type) { + return AssetType.valueOf(type.toUpperCase()); + } + + public static String getSdcContextPath(String type) { + return getAssetTypeByName(type).getSdcContextPath(); + } + + private enum SdcContextPath { + RESOURCES, SERVICES + } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java index b559634..17c25b2 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/BaseException.java @@ -7,55 +7,53 @@ import org.springframework.web.client.HttpClientErrorException; public class BaseException extends HttpClientErrorException { - private static Gson gson = new Gson(); - - protected RequestError requestError; - - public RequestError getRequestError() { - return requestError; - } - - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - public BaseException(HttpClientErrorException theError) { - super(theError.getStatusCode()); - String body = theError.getResponseBodyAsString(); - if (body != null) { - requestError = extractRequestError(body); - } - } - - public BaseException(HttpStatus status, RequestError re){ - super(status); - requestError = re; - } - - private RequestError extractRequestError(String error) { - ResponseFormat responseFormat = gson.fromJson(error, ResponseFormat.class); - return responseFormat.getRequestError(); - } - - @JsonIgnore - public String getMessageId() { - return requestError.getMessageId(); - } - - @JsonIgnore - public String[] getVariables() { - return requestError.getVariables(); - } - - @JsonIgnore - public String getText(){ - return requestError.getText(); - } - - @Override - @JsonIgnore - public String getMessage() { - return requestError.getFormattedMessage(); - } + private static final Gson gson = new Gson(); + + protected final transient RequestError requestError; + + public BaseException(HttpClientErrorException theError) { + super(theError.getStatusCode()); + String body = theError.getResponseBodyAsString(); + if (body != null) { + requestError = extractRequestError(body); + } else { + requestError = null; + } + } + + public BaseException(HttpStatus status, RequestError re){ + super(status); + requestError = re; + } + + public RequestError getRequestError() { + return requestError; + } + + private RequestError extractRequestError(String error) { + ResponseFormat responseFormat = gson.fromJson(error, ResponseFormat.class); + return responseFormat.getRequestError(); + } + + @JsonIgnore + public String getMessageId() { + return requestError.getMessageId(); + } + + @JsonIgnore + public String[] getVariables() { + return requestError.getVariables(); + } + + @JsonIgnore + public String getText(){ + return requestError.getText(); + } + + @Override + @JsonIgnore + public String getMessage() { + return requestError.getFormattedMessage(); + } }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java index 53bdf3e..f2a7f9a 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/OkResponseInfo.java @@ -2,7 +2,7 @@ package org.onap.sdc.dcae.errormng; public class OkResponseInfo extends AbstractSdncException { - public OkResponseInfo(String messageId, String text, String[] variables) { + OkResponseInfo(String messageId, String text, String[] variables) { super(messageId, text, variables); } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java index 3fc2d71..8a4aec9 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/PolicyException.java @@ -5,7 +5,4 @@ public class PolicyException extends AbstractSdncException { public PolicyException(String messageId, String text, String[] variables) { super(messageId, text, variables); } - - public PolicyException() { - } } diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java index 00fe3f2..7207916 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/RequestError.java @@ -9,25 +9,16 @@ public class RequestError { private PolicyException policyException; private ServiceException serviceException; private OkResponseInfo okResponseInfo; - private List<ServiceException> serviceExceptions; - - public PolicyException getPolicyException() { - return policyException; - } public ServiceException getServiceException() { return serviceException; } - public OkResponseInfo getOkResponseInfo() { - return okResponseInfo; - } - public void setPolicyException(PolicyException policyException) { this.policyException = policyException; } - void setServiceException(ServiceException serviceException) { + public void setServiceException(ServiceException serviceException) { this.serviceException = serviceException; } @@ -35,12 +26,8 @@ public class RequestError { this.okResponseInfo = okResponseInfo; } - public List<ServiceException> getServiceExceptions() { - return serviceExceptions; - } - void setServiceExceptions(List<ServiceException> serviceExceptions) { - this.serviceExceptions = serviceExceptions; + // no one asks for these exception ever } String getFormattedMessage() { @@ -60,6 +47,11 @@ public class RequestError { } AbstractSdncException getError() { - return null != serviceException ? serviceException : null != policyException ? policyException : okResponseInfo; + if (null != policyException) { + return (null != serviceException) ? serviceException : policyException; + } + else { + return (null != serviceException) ? serviceException : okResponseInfo; + } } }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java index 163a07f..68e646c 100644 --- a/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java +++ b/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/errormng/ServiceException.java @@ -1,12 +1,7 @@ package org.onap.sdc.dcae.errormng; public class ServiceException extends AbstractSdncException { - public ServiceException(String messageId, String text, String[] variables) { super(messageId, text, variables); } - - public ServiceException() { - } - }
\ No newline at end of file diff --git a/dcaedt_catalog/asdc/src/test/org/onap/sdc/dcae/utils/NormalizersTest.java b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/NormalizersTest.java index bf06e22..5a9b5f5 100644 --- a/dcaedt_catalog/asdc/src/test/org/onap/sdc/dcae/utils/NormalizersTest.java +++ b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/NormalizersTest.java @@ -1,11 +1,7 @@ package org.onap.sdc.dcae.utils; -import static org.assertj.core.api.Assertions.*; - import org.assertj.core.api.Assertions; import org.junit.Test; -import org.onap.sdc.dcae.utils.Normalizers; - public class NormalizersTest { diff --git a/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java new file mode 100644 index 0000000..f17e18f --- /dev/null +++ b/dcaedt_catalog/asdc/src/test/java/org/onap/sdc/dcae/utils/SDCResponseErrorHandlerTest.java @@ -0,0 +1,93 @@ +package org.onap.sdc.dcae.utils; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; + +import java.io.IOException; +import java.io.InputStream; + +@RunWith(MockitoJUnitRunner.class) +public class SDCResponseErrorHandlerTest { + @InjectMocks + private SDCResponseErrorHandler classUnderTest; + private ClientHttpResponse clientHttpResponse; + private HttpStatus httpStatus; + + @Before + public void setup() { + clientHttpResponse = new ClientHttpResponse() { + @Override + public HttpStatus getStatusCode() throws IOException { + return httpStatus; + } + + @Override + public int getRawStatusCode() throws IOException { + return 0; + } + + @Override + public String getStatusText() throws IOException { + return null; + } + + @Override + public void close() { + + } + + @Override + public InputStream getBody() throws IOException { + return null; + } + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + }; + } + + @Test(expected = HttpClientErrorException.class) + public void handleError_haveError_throwsClientException() throws IOException { + httpStatus = HttpStatus.EXPECTATION_FAILED; + classUnderTest.handleError(clientHttpResponse); + } + + @Test(expected = HttpServerErrorException.class) + public void handleError_haveError_throwsServerException() throws IOException { + httpStatus = HttpStatus.BAD_GATEWAY; + classUnderTest.handleError(clientHttpResponse); + } + + @Test + public void hasError_haveClientError_returnTrue() throws IOException { + httpStatus = HttpStatus.EXPECTATION_FAILED; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertTrue(result); + } + + @Test + public void hasError_haveServerError_returnTrue() throws IOException { + httpStatus = HttpStatus.BAD_GATEWAY; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertTrue(result); + } + + @Test + public void hasError_200OK_returnFalse() throws IOException { + httpStatus = HttpStatus.OK; + boolean result = classUnderTest.hasError(clientHttpResponse); + Assert.assertFalse(result); + } + +}
\ No newline at end of file diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java index ffaf42b..a405932 100644 --- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java +++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Futures.java @@ -8,9 +8,6 @@ import java.util.concurrent.CountDownLatch; import java.util.function.Function; import org.onap.sdc.common.onaplog.OnapLoggerDebug; -import org.onap.sdc.common.onaplog.OnapLoggerError; -import org.onap.sdc.dcae.catalog.commons.Future; -import org.onap.sdc.dcae.catalog.commons.FutureHandler; import org.onap.sdc.common.onaplog.Enums.LogLevel; @@ -196,16 +193,13 @@ public class Futures<T> { return this; } } - - /** */ + public static class Accumulator<T> extends BasicFuture<List<T>> implements Future<List<T>> { - protected List<Future<T>> futures = new LinkedList<Future<T>>(); - //protected List<T> results = new LinkedList<T>(); - protected BasicHandler<T> handler = null; + protected List<Future<T>> futures = new LinkedList<Future<T>>(); + protected BasicHandler<T> accumulatorHandler = null; - private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); private static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); public Accumulator() { @@ -228,7 +222,7 @@ public class Futures<T> { public Future<List<T>> accumulate() { this.futures = Collections.unmodifiableList(this.futures); - this.handler = new BasicHandler<T>(new CountDownLatch(this.futures.size())) { + this.accumulatorHandler = new BasicHandler<T>(new CountDownLatch(this.futures.size())) { protected void process(Future<T> theResult) { if (theResult.failed()) { Accumulator.this.cause = theResult.cause(); @@ -246,7 +240,7 @@ public class Futures<T> { } }; futures.stream() - .forEach(f -> f.setHandler(this.handler)); + .forEach(f -> f.setHandler(this.accumulatorHandler)); return this; } diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxies.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxies.java index 8983599..0b13def 100644 --- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxies.java +++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxies.java @@ -19,10 +19,6 @@ public class Proxies { public static <T> T build(Map theData, Class<T> theType) { return builder.build(new JSONObject(theData), theType); } - - public static <T> T build(Map theData, Map theContextData, Class<T> theType) { - return builder.build(new JSONObject(theData), theContextData, theType); - } public static <T> T build(JSONObject theData, Class<T> theType) { return builder.build(theData, theType); diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxy.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxy.java index d368886..bdce9c3 100644 --- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxy.java +++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Proxy.java @@ -1,30 +1,14 @@ package org.onap.sdc.dcae.catalog.commons; import java.util.List; -import java.util.LinkedList; -import java.util.Map; -import java.util.Collections; - -import java.util.stream.Collectors; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - -import java.lang.reflect.Type; import java.lang.reflect.Method; -import java.lang.reflect.Array; import java.lang.reflect.Constructor; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; - import java.lang.invoke.MethodHandles; -import com.google.common.reflect.Invokable; -import org.onap.sdc.dcae.catalog.commons.Proxy; -import org.onap.sdc.dcae.catalog.commons.ProxyBuilder; import com.google.common.reflect.AbstractInvocationHandler; import org.apache.commons.beanutils.ConvertUtils; @@ -37,13 +21,13 @@ public class Proxy extends AbstractInvocationHandler { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) - public static @interface DataMap { + public @interface DataMap { - public String map() default ""; + String map() default ""; - public boolean proxy() default false; + boolean proxy() default false; - public Class elementType() default Void.class; + Class elementType() default Void.class; } @@ -51,12 +35,10 @@ public class Proxy extends AbstractInvocationHandler { static { try { - lookupHandleConstructor = - MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, - int.class); + lookupHandleConstructor = MethodHandles.Lookup.class.getDeclaredConstructor(Class.class, int.class); if (!lookupHandleConstructor.isAccessible()) { - lookupHandleConstructor.setAccessible(true); + lookupHandleConstructor.setAccessible(true); } } catch (Exception x) { @@ -64,7 +46,6 @@ public class Proxy extends AbstractInvocationHandler { } } - private JSONObject data; private ProxyBuilder builder; @@ -81,11 +62,9 @@ public class Proxy extends AbstractInvocationHandler { return this.builder; } - protected Object handleInvocation( - Object theProxy,Method theMethod,Object[] theArgs) - throws Throwable { + protected Object handleInvocation(Object theProxy,Method theMethod,Object[] theArgs) throws Throwable { if (theMethod.isDefault()) { - final Class<?> declaringClass = theMethod.getDeclaringClass(); + final Class<?> declaringClass = theMethod.getDeclaringClass(); return lookupHandleConstructor .newInstance(declaringClass, MethodHandles.Lookup.PRIVATE) @@ -96,28 +75,35 @@ public class Proxy extends AbstractInvocationHandler { String key = theMethod.getName(); - Proxy.DataMap dataMap = (Proxy.DataMap)theMethod.getAnnotation(Proxy.DataMap.class); + Proxy.DataMap dataMap = theMethod.getAnnotation(Proxy.DataMap.class); if (dataMap != null) { String dataKey = dataMap.map(); - if (dataKey != null && !"".equals(dataKey)) + if (!"".equals(dataKey)) { key = dataKey; + } } //this is ugly, can this be done through an extension mechanism such as plugging in functions? - if ( builder.hasExtension(key) ) + if ( builder.hasExtension(key) ) { return this.builder.extension(key).apply(this, theArgs); + } //we give priority to the context (because of the 'catalog' property issue in catalog service) but //how natural is this? Object val = this.builder.context(key); - if (val == null) + if (val == null) { val = this.data.opt(key); + } - if (val == null) + if (val == null) { return null; + } + return getProxies(theMethod, dataMap, val); + } -//as we create proxies here we should store them back in the 'data' so that we do not do it again -//can we always 'recognize' them? + private Object getProxies(Method theMethod, DataMap dataMap, Object val) throws InstantiationException, IllegalAccessException { + //as we create proxies here we should store them back in the 'data' so that we do not do it again + //can we always 'recognize' them? if (val instanceof String && String.class != theMethod.getReturnType()) { //??This will yield a POJO .. @@ -128,7 +114,7 @@ public class Proxy extends AbstractInvocationHandler { return builder.build((JSONObject)val, theMethod.getReturnType()); } } - else if (val instanceof JSONArray&& dataMap != null && + else if (val instanceof JSONArray && dataMap != null && dataMap.proxy() && List.class.isAssignableFrom(theMethod.getReturnType())) { diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/ProxyBuilder.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/ProxyBuilder.java index e3a422a..8b6e6d1 100644 --- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/ProxyBuilder.java +++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/ProxyBuilder.java @@ -21,40 +21,18 @@ public class ProxyBuilder { public ProxyBuilder() { } -/* - public <T> T build(Map theData, Class<T> theType) { - return build(theData, this.context, theType); - } - - public <T> T build(Map theData, Map theContextData, Class<T> theType) { - return (T)java.lang.reflect.Proxy.newProxyInstance( - ProxyBuilder.class.getClassLoader(), - new Class[] { theType }, - new Proxy(theData, this)); - } -*/ + public <T> T build(Map theData, Class<T> theType) { return build(new JSONObject(theData), theType); } - - public <T> T build(Map theData, Map theContextData, Class<T> theType) { - return build(new JSONObject(theData), theContextData, theType); - } public <T> T build(JSONObject theData, Class<T> theType) { - return build(theData, this.context, theType); - } - - public <T> T build(JSONObject theData, Map theContextData, Class<T> theType) { return (T)java.lang.reflect.Proxy.newProxyInstance( - ProxyBuilder.class.getClassLoader(), - new Class[] { theType }, - new Proxy(theData, this)); + ProxyBuilder.class.getClassLoader(), + new Class[] { theType }, + new Proxy(theData, this)); } - - - public ProxyBuilder withConverter(final Function<Object, ?> theConverter, Class theType) { ConvertUtils.register(new Converter() { public Object convert(Class theToType, Object theValue) { diff --git a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Recycler.java b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Recycler.java index 3493cb1..f6ea6ad 100644 --- a/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Recycler.java +++ b/dcaedt_catalog/commons/src/main/java/org/onap/sdc/dcae/catalog/commons/Recycler.java @@ -138,26 +138,26 @@ public class Recycler { } } String type = (String)theSpec.get("type"); - if (value != null && type != null) { + if (value != null && type != null && !"string".equals(type)) { value = getValueByType(value, type); } return value; } private Object getValueByType(Object value, String type) { - Object returnValue = null; + try { if ("map".equals(type) && !(value instanceof Map)) { - returnValue = new ObjectMapper().readValue(value.toString(), new TypeReference<Map>(){}); + return new ObjectMapper().readValue(value.toString(), new TypeReference<Map>(){}); } - else if ("list".equals(type) && !(value instanceof List)) { - returnValue = new ObjectMapper().readValue(value.toString(), new TypeReference<List>(){}); + if ("list".equals(type) && !(value instanceof List)) { + return new ObjectMapper().readValue(value.toString(), new TypeReference<List>(){}); } - else if ("integer".equals(type) && (value instanceof String)) { - returnValue = Integer.valueOf((String)value); + if ("integer".equals(type) && (value instanceof String)) { + return Integer.valueOf((String)value); } - else if ("float".equals(type) && (value instanceof String)) { - returnValue = Double.valueOf((String)value); //double because that's how the yaml parser would encode it + if ("float".equals(type) && (value instanceof String)) { + return Double.valueOf((String)value); //double because that's how the yaml parser would encode it } } catch (NumberFormatException nfx) { @@ -166,7 +166,7 @@ public class Recycler { catch (IOException iox) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Failed to process {} representation of a collection: {}", value.getClass().getName(), iox); } - return returnValue; + return value; } /* */ diff --git a/dcaedt_catalog/service/Dockerfile b/dcaedt_catalog/service/Dockerfile new file mode 100644 index 0000000..c99dc32 --- /dev/null +++ b/dcaedt_catalog/service/Dockerfile @@ -0,0 +1,19 @@ +FROM java:8u40-jre +MAINTAINER Arthur Martella <am153x@att.com> +ENV insdir /opt/app/catalog +RUN \ + mkdir -p ${insdir}/lib \ + && mkdir -p ${insdir}/etc \ + && mkdir -p ${insdir}/log \ + && useradd -d ${insdir} catalog \ + && chown -R catalog:catalog ${insdir} +WORKDIR ${insdir} +USER catalog +COPY target/ASC-Catalog*.jar ${insdir}/lib/ASC-Catalog.jar +#COPY target/deps/*.jar ${insdir}/lib/ +COPY src/main/resources/log4j.properties ${insdir}/etc/log4j.properties +#COPY src/main/resources/config.json ${insdir}/etc/config.json +#COPY src/main/resources/cluster.xml ${insdir}/etc/cluster.xml +VOLUME ${insdir}/log +EXPOSE 7575 +CMD ["/usr/bin/java","-jar","lib/ASC-Catalog.jar","--spring.profiles.active=default"] diff --git a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java index 3e71c88..90994f6 100644 --- a/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java +++ b/dcaedt_catalog/service/src/main/java/org/onap/sdc/dcae/catalog/engine/CatalogController.java @@ -18,41 +18,27 @@ under the License. */ package org.onap.sdc.dcae.catalog.engine; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import static org.onap.sdc.dcae.catalog.Catalog.*; - -import java.net.URI; -import java.net.URISyntaxException; - import org.json.JSONObject; +import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.common.onaplog.OnapLoggerError; -import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.catalog.Catalog; import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog; import org.onap.sdc.dcae.catalog.commons.Future; import org.onap.sdc.dcae.catalog.commons.FutureHandler; import org.onap.sdc.dcae.composition.util.DcaeBeConstants; import org.onap.sdc.dcae.composition.util.SystemProperties; -import org.json.JSONArray; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RestController; - import org.springframework.web.context.request.async.DeferredResult; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.web.bind.annotation.CrossOrigin; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; /** * All requests body: @@ -69,23 +55,23 @@ import org.springframework.web.bind.annotation.CrossOrigin; * } * * If a non-2xx reponse is provided and error occured at catalog engine processing level. - * If error has occured in data retrieval then the response error object is not empty. + * If error has occured in data retrieval then the response error object is not empty. * * Available uris * /catalog * /elements : roots of the catalog; request body is optional but can specify a label under 'startingLabel' * response contains items under 'data/elements' - * /{itemId}/elements : catalog descendants of the given item, possibly a mix of folders and items + * /{itemId}/elements : catalog descendants of the given item, possibly a mix of folders and items * response contains items under 'data/elements' * /lookup.by.name : lookup catalog entries by name. The request body must contain a 'selector' entry with a 'name' criteria * response contains items under 'data/elements' * Example: '{"id":"5d0c1cf4-11aa-11e6-a148-3e1d05defe78","selector":{"name":"Firewall"}}' * /lookup.by.annotation - The request body must contain a 'annotation' entry and it can have a 'selector' entry + The request body must contain a 'annotation' entry and it can have a 'selector' entry * with a multiple annotation property criteria * response contains items under 'data/elements' - * /lookup.by.model.property.value : + * /lookup.by.model.property.value : * The request must contain a "selector" entry as a JSONObject containing the selection criteria * (property name with values) and desired output properties (null values). Example: * "selector":{"att-part-number":"L-CSR-50M-APP-3Y", @@ -104,9 +90,7 @@ import org.springframework.web.bind.annotation.CrossOrigin; @RestController -//@RequestMapping(value="/catalog",method=RequestMethod.POST) @CrossOrigin(origins="*") -//@ConfigurationProperties(prefix="catalogController") public class CatalogController { private static OnapLoggerError errLogger = OnapLoggerError.getInstance(); @@ -116,9 +100,7 @@ public class CatalogController { @Autowired private SystemProperties systemProperties; - - private boolean enableCORS = false; - private URI defaultCatalog; + private URI defaultCatalog; private static Map<URI, Catalog> catalogs = new HashMap<URI, Catalog>(); @@ -127,375 +109,11 @@ public class CatalogController { this.defaultCatalog = theUri; } - public void setEnableCORS(boolean doEnable) { - this.enableCORS = doEnable; - } - -// @RequestMapping(value="/elements",method={RequestMethod.POST, RequestMethod.GET}, produces = "application/json") -// public DeferredResult<CatalogResponse> items(@RequestBody(required=false) ItemsRequest theRequest) { -// -// final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; -// -// Catalog catalog = getCatalog(request.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); -// -// catalog.rootsByLabel(request.getStartingLabel()) -// //catalog.roots() -// .setHandler( -// new CatalogHandler<Folders>(request, result) { -// public CatalogResponse handleData(Folders theFolders) { -// JSONArray ja = new JSONArray(); -// if (theFolders != null) { -// for (Folder folder : theFolders) { -// ja.put(patchData(catalog, folder.data())); -// } -// } -// CatalogResponse response = new CatalogResponse(this.request); -// response.data() -// .put("elements", ja); -// return response; -// } -// }); -// return result; -// } -// -// @RequestMapping(value="/{theItemId}/elements",method={RequestMethod.POST,RequestMethod.GET}, produces = "application/json") -// public DeferredResult<CatalogResponse> items(@RequestBody(required=false) ItemsRequest theRequest, @PathVariable String theItemId) { -// -// final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; -// -// Catalog catalog = getCatalog(request.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); -// -// catalog -//// .fetchFolderByItemId(theItemId) -// .folder(theItemId) -// .withParts() -// .withPartAnnotations() -// .withItems() -// .withItemAnnotations() -// .withItemModels() -// .execute() -// .setHandler( -// new CatalogHandler<Folder>(request, result) { -// public CatalogResponse handleData(Folder theFolder) { -// CatalogResponse response = new CatalogResponse(this.request); -// if (theFolder == null) { -// return response; -// } -// -// try { -// Elements folders = theFolder.elements("parts",Folders.class); -// if (folders != null) { -// for (Object folder: folders) { -// patchData(catalog, ((Element)folder).data()); -// //lots of ephemere proxies created here .. -// Elements annotations = -// ((Element)folder).elements("annotations", Annotations.class); -// if (annotations != null) { -// for (Object a: annotations) { -// patchData(catalog, ((Annotation)a).data()); -// } -// } -// } -// } -// Elements items = theFolder.elements("items",Items.class); -// if (items != null) { -// for (Object i: items) { -// patchData(catalog, ((Element)i).data()); -// //lots of ephemere proxies created here .. -// Elements annotations = -// ((Element)i).elements("annotations", Annotations.class); -// if (annotations != null) { -// for (Object a: annotations){ -// patchData(catalog, ((Annotation)a).data()); -// } -// } -// } -// } -// } -// catch(Exception x) { -//x.printStackTrace(); -// return new CatalogError(this.request, "", x); -// } -// -// response.data() -// .put("element", theFolder.data()); -// return response; -// } -// }); -// -// return result; -// } -// -// @RequestMapping(value="/lookup.by.name",method=RequestMethod.POST, produces = "application/json") -// public DeferredResult<CatalogResponse> elementsByName(@RequestBody ElementsLookup theRequest) { -// -// Catalog catalog = getCatalog(theRequest.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(theRequest.getTimeout()); -// -// catalog -// .lookup(new JSONObject(theRequest.getSelector())) -// .setHandler( -// new CatalogHandler<Mixels>(theRequest, result) { -// public CatalogResponse handleData(Mixels theElems) { -// JSONArray ja = new JSONArray(); -// if (theElems != null) { -// for (Object elem : theElems) { -// ja.put(patchData(catalog, ((Element)elem).data())); -// } -// } -// CatalogResponse response = new CatalogResponse(theRequest); -// response.data() -// .put("elements", ja); -// return response; -// } -// }); -// -// return result; -// } -// -// @RequestMapping(value="/lookup.by.annotation",method=RequestMethod.POST, produces = "application/json") -// public DeferredResult<CatalogResponse> elementsByAnnotation(@RequestBody ElementsLookup theRequest) { -// -// Catalog catalog = getCatalog(theRequest.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(theRequest.getTimeout()); -// -// catalog -// .lookup(theRequest.getAnnotation(), -// new JSONObject(theRequest.getSelector())) -// .setHandler( -// new CatalogHandler<Mixels>(theRequest, result) { -// public CatalogResponse handleData(Mixels theElems) { -// JSONArray ja = new JSONArray(); -// if (theElems != null) { -// for (Object elem : theElems) { -// ja.put(patchData(catalog, ((Element)elem).data())); -// } -// } -// CatalogResponse response = new CatalogResponse(this.request); -// response.data() -// .put("elements", ja); -// return response; -// } -// }); -// -// return result; -// } - - /** - * NeoCatalog specific - *//* - @RequestMapping(value="/lookup.by.model.property.value",method=RequestMethod.POST, produces = "application/json") - public DeferredResult<CatalogResponse> elementsByModelPropertyValue(@RequestBody ElementsLookup theRequest) { - - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(theRequest.getTimeout()); - - NeoCatalog catalog = asNeo(getCatalog(theRequest.getCatalog())); - if (catalog == null) { - result.setErrorResult( - new CatalogError( - theRequest,"The selected catalog is not capable of handling this request (lookup.by.model.property.value)")); - return result; - } - - catalog - .lookupItemsByToscaNodePropertyValue(theRequest.getJSONSelector()) - .setHandler( - new CatalogHandler<Items>(theRequest, result) { - public CatalogResponse handleData(Items theItems) { - JSONArray ja = new JSONArray(); - if (theItems != null) { - for (Item item : theItems) { - ja.put(patchData(catalog, item.data())); - } - } - CatalogResponse response = new CatalogResponse(this.request); - response.data() - .put("elements", ja); - return response; - } - }); - - return result; - } -*/ - /** - * This follows the current convention that each item will have a single model - 2 stage - */ -// @RequestMapping(value="/{theItemId}/model",method={RequestMethod.POST,RequestMethod.GET}, produces = "application/json") -// //public DeferredResult<CatalogResponse> model(@RequestBody ElementRequest theRequest) { -// public DeferredResult<CatalogResponse> model(@RequestBody(required=false) ElementRequest theRequest, @PathVariable String theItemId) { -// final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; -// -// Catalog catalog = getCatalog(request.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); -// -// catalog -//// .fetchItemByItemId(/*theRequest.getProductId()*/theItemId) -// .item(theItemId) -// .withModels() -// .execute() -// .setHandler( -// new CatalogHandler<Item>(request, result) { -// public CatalogResponse handleData(Item theItem) { -// if (theItem == null) { -// return new CatalogError(this.request, "No such item"); -// } -// Templates models = null; -// try { -// models = (Templates)theItem.elements("models", Templates.class); -// } -// catch (Exception x) { -// return new CatalogError(this.request, "Failed to decode templates from result", x); -// } -// -// if (models == null || models.size() == 0) { -// return new CatalogError(this.request, "Item has no models"); -// } -// if (models.size() > 1) { -// return new CatalogError(this.request, "Item has more than one model !?"); -// } -// try{ -// catalog.template(models.get(0).id()) -// .withInputs() -// .withOutputs() -// .withNodes() -// .withNodeProperties() -// .withNodePropertiesAssignments() -// .withNodeRequirements() -// .withNodeCapabilities() -// .withNodeCapabilityProperties() -// .withNodeCapabilityPropertyAssignments() -// .withPolicies() -// .withPolicyProperties() -// .withPolicyPropertiesAssignments() -// .execute() -// .setHandler( -// new CatalogHandler<Template>(this.request, this.result) { -// public CatalogResponse handleData(Template theTemplate) { -// CatalogResponse response = new CatalogResponse(this.request); -// if (theTemplate != null) { -// response.data() -// .put("model", patchData(catalog, theTemplate.data())); -// } -// return response; -// } -// }); -// } -// catch (Exception x) { -// x.printStackTrace(); -// } -// return null; -// } -// }); -// -// return result; -// } - -// @RequestMapping(value="/{theItemId}/type/{theTypeName}",method={RequestMethod.POST,RequestMethod.GET}, produces = "application/json") -// public DeferredResult<CatalogResponse> model(@RequestBody(required=false) ElementRequest theRequest, @PathVariable String theItemId, @PathVariable String theTypeName) { -// final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; -// -// Catalog catalog = getCatalog(request.getCatalog()); -// DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); -// -// catalog.type(theItemId, theTypeName) -// .withHierarchy() -// .withCapabilities() -// .withRequirements() -// .execute() -// .setHandler( -// new CatalogHandler<Type>(request, result) { -// public CatalogResponse handleData(Type theType) { -// CatalogResponse response = new CatalogResponse(this.request); -// if (theType != null) { -// response.data() -// .put("type", patchData(catalog, theType.data())); -// } -// return response; -// } -// }); -// -// return result; -// } - -/* - @RequestMapping(value="/referents",method=RequestMethod.POST, produces = "application/json") - public DeferredResult<CatalogResponse> referents(@RequestBody(required=false) ElementRequest theRequest) { - final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); - - NeoCatalog catalog = asNeo(getCatalog(theRequest.getCatalog())); - if (catalog == null) { - result.setErrorResult( - new CatalogError( - theRequest,"The selected catalog is not capable of handling this request (referents)")); - return result; - } - - catalog - .defaultRecommendations() - .setHandler( - new CatalogHandler<Mixels>(request, result) { - public CatalogResponse handleData(Mixels theElems) { - JSONArray ja = new JSONArray(); - if (theElems != null) { - for (Element elem : theElems) { - ja.put(patchData(catalog, elem.data())); - } - } - CatalogResponse response = new CatalogResponse(this.request); - response.data() - .put("elements", ja); - return response; - } - }); - - return result; - } -*/ - -/* @RequestMapping(value="/{theItemId}/referents",method=RequestMethod.POST, produces = "application/json") - public DeferredResult<CatalogResponse> referents(@RequestBody(required=false) ElementRequest theRequest, @PathVariable String theItemId) { - final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); - - NeoCatalog catalog = asNeo(getCatalog(theRequest.getCatalog())); - if (catalog == null) { - result.setErrorResult( - new CatalogError( - theRequest,"The selected catalog is not capable of handling this request (item referents)")); - return result; - } - - catalog - .recommendationsForItemId(theItemId) - .setHandler( - new CatalogHandler<Mixels>(request, result) { - public CatalogResponse handleData(Mixels theElems) { - JSONArray ja = new JSONArray(); - if (theElems != null) { - for (Element elem : theElems) { - ja.put(patchData(catalog, elem.data())); - } - } - CatalogResponse response = new CatalogResponse(this.request); - response.data() - .put("elements", ja); - return response; - } - }); - - return result; - } -*/ @PostConstruct public void initCatalog() { // Dump some info and construct our configuration objects debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "initCatalog"); - + this.defaultCatalog = URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_CATALOG_URL)); // Initialize default catalog connection debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "default catalog at {}", this.defaultCatalog); @@ -518,7 +136,7 @@ public class CatalogController { Catalog cat = catalogs.get(theCatalogUri); if (cat == null && theCatalogUri != null) { String scheme = theCatalogUri.getScheme(); - URI catalogUri = null; + URI catalogUri; try { catalogUri = new URI(theCatalogUri.getSchemeSpecificPart() + "#" + theCatalogUri.getFragment()); } @@ -539,15 +157,6 @@ public class CatalogController { return cat; } -/* private NeoCatalog asNeo(Catalog theCatalog) { - try { - return (NeoCatalog)theCatalog; - } - catch (ClassCastException ccx) { - return null; - } - }*/ - public JSONObject patchData(Catalog theCat, JSONObject theData) { theData.put("catalog", theCat.getUri()); theData.put("catalogId", theData.optLong("id")); @@ -582,7 +191,7 @@ public class CatalogController { else { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "handle, got: {}", theEvent.result()); CatalogResponse response = handleData(theEvent.result()); - //a null result allows the handler to pass the processing onto some other async processing stage + //a null result allows the accumulatorHandler to pass the processing onto some other async processing stage if (response != null) { if (!this.result.setResult(response)) { this.result.setErrorResult(new CatalogError(this.request, "Catalog API call succesful but late")); @@ -591,4 +200,4 @@ public class CatalogController { } } } -} +} |