diff options
11 files changed, 380 insertions, 855 deletions
diff --git a/grpc-resource/features/ccsdk-grpc-client/pom.xml b/grpc-resource/features/ccsdk-grpc-client/pom.xml index cc9b9ba5e..7bc4de636 100644 --- a/grpc-resource/features/ccsdk-grpc-client/pom.xml +++ b/grpc-resource/features/ccsdk-grpc-client/pom.xml @@ -54,11 +54,11 @@ <version>${project.version}</version> </dependency> + <!--overwrite protobuf jave version--> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.6.1</version> </dependency> - </dependencies> </project> diff --git a/grpc-resource/provider/pom.xml b/grpc-resource/provider/pom.xml index 4eee611f0..72fc7f1ef 100644 --- a/grpc-resource/provider/pom.xml +++ b/grpc-resource/provider/pom.xml @@ -125,6 +125,12 @@ <version>${mockito.version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>io.grpc</groupId> + <artifactId>grpc-testing</artifactId> + <version>${grpc.version}</version> + <scope>test</scope> + </dependency> </dependencies> <build> diff --git a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/GrpcProperties.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/GrpcProperties.java index 96775f379..ff158c2e0 100644 --- a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/GrpcProperties.java +++ b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/GrpcProperties.java @@ -36,6 +36,7 @@ public class GrpcProperties { private static final String BLUEPRINT_PROCESSOR_URL_PROP = "org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.url"; private static final String BLUEPRINT_PROCESSOR_PORT_PROP = "org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.port"; + private static final String BLUEPRINT_PROCESSOR_AUTH_PROP = "org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.auth"; private Properties properties; @@ -47,6 +48,10 @@ public class GrpcProperties { return properties.getProperty(BLUEPRINT_PROCESSOR_URL_PROP); } + public String getAuth() { + return properties.getProperty(BLUEPRINT_PROCESSOR_AUTH_PROP); + } + public int getPort() { return Integer.parseInt(properties.getProperty(BLUEPRINT_PROCESSOR_PORT_PROP)); } diff --git a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/JsonFormat.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/JsonFormat.java index a656d6623..d169f14c7 100644 --- a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/JsonFormat.java +++ b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/JsonFormat.java @@ -1,28 +1,39 @@ -/* - * Copyright (C) 2019 Google - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.onap.ccsdk.sli.adaptors.grpc; -import com.google.common.base.Preconditions; -import com.google.common.io.BaseEncoding; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; -import com.google.gson.JsonIOException; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -30,19 +41,11 @@ import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import com.google.protobuf.Any; import com.google.protobuf.BoolValue; -import com.google.protobuf.ByteString; import com.google.protobuf.BytesValue; import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.EnumDescriptor; -import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; -import com.google.protobuf.Descriptors.FieldDescriptor.Type; -import com.google.protobuf.Descriptors.FileDescriptor; -import com.google.protobuf.Descriptors.FileDescriptor.Syntax; -import com.google.protobuf.Descriptors.OneofDescriptor; import com.google.protobuf.DoubleValue; -import com.google.protobuf.DynamicMessage; import com.google.protobuf.FloatValue; import com.google.protobuf.Int32Value; import com.google.protobuf.Int64Value; @@ -57,20 +60,16 @@ import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import com.google.protobuf.Value; import java.io.IOException; -import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.TreeMap; -import java.util.logging.Logger; //Fork from : // @@ -82,8 +81,6 @@ import java.util.logging.Logger; public class JsonFormat { - private static final Logger logger = Logger.getLogger(JsonFormat.class.getName()); - private JsonFormat() { } @@ -96,24 +93,6 @@ public class JsonFormat { return new JsonFormat.Parser(JsonFormat.TypeRegistry.getEmptyTypeRegistry(), false, 100); } - private static String unsignedToString(int value) { - return value >= 0 ? Integer.toString(value) : Long.toString((long) value & 4294967295L); - } - - private static String unsignedToString(long value) { - return value >= 0L ? Long.toString(value) - : BigInteger.valueOf(value & 9223372036854775807L).setBit(63).toString(); - } - - private static String getTypeName(String typeUrl) throws InvalidProtocolBufferException { - String[] parts = typeUrl.split("/"); - if (parts.length == 1) { - throw new InvalidProtocolBufferException("Invalid type url found: " + typeUrl); - } else { - return parts[parts.length - 1]; - } - } - private static class ParserImpl { private final JsonFormat.TypeRegistry registry; @@ -137,24 +116,6 @@ public class JsonFormat { this.currentDepth = 0; } - void merge(Reader json, com.google.protobuf.Message.Builder builder) throws IOException { - try { - JsonReader reader = new JsonReader(json); - reader.setLenient(false); - this.merge(this.jsonParser.parse(reader), builder); - } catch (InvalidProtocolBufferException var4) { - throw var4; - } catch (JsonIOException var5) { - if (var5.getCause() instanceof IOException) { - throw (IOException) var5.getCause(); - } else { - throw new InvalidProtocolBufferException(var5.getMessage()); - } - } catch (Exception var6) { - throw new InvalidProtocolBufferException(var6.getMessage()); - } - } - void merge(String json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { try { JsonReader reader = new JsonReader(new StringReader(json)); @@ -172,13 +133,11 @@ public class JsonFormat { parsers.put(Any.getDescriptor().getFullName(), new JsonFormat.ParserImpl.WellKnownTypeParser() { public void merge(JsonFormat.ParserImpl parser, JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { - parser.mergeAny(json, builder); } }); JsonFormat.ParserImpl.WellKnownTypeParser wrappersPrinter = new JsonFormat.ParserImpl.WellKnownTypeParser() { public void merge(JsonFormat.ParserImpl parser, JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { - parser.mergeWrapper(json, builder); } }; parsers.put(BoolValue.getDescriptor().getFullName(), wrappersPrinter); @@ -199,7 +158,6 @@ public class JsonFormat { parsers.put(ListValue.getDescriptor().getFullName(), new JsonFormat.ParserImpl.WellKnownTypeParser() { public void merge(JsonFormat.ParserImpl parser, JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { - parser.mergeListValue(json, builder); } }); parsers.put(Value.getDescriptor().getFullName(), new JsonFormat.ParserImpl.WellKnownTypeParser() { @@ -217,104 +175,6 @@ public class JsonFormat { .get(builder.getDescriptorForType().getFullName()); if (specialParser != null) { specialParser.merge(this, json, builder); - } else { - this.mergeMessage(json, builder, false); - } - } - - private Map<String, FieldDescriptor> getFieldNameMap(Descriptor descriptor) { - if (this.fieldNameMaps.containsKey(descriptor)) { - return (Map) this.fieldNameMaps.get(descriptor); - } else { - Map<String, FieldDescriptor> fieldNameMap = new HashMap(); - Iterator var3 = descriptor.getFields().iterator(); - - while (var3.hasNext()) { - FieldDescriptor field = (FieldDescriptor) var3.next(); - fieldNameMap.put(field.getName(), field); - fieldNameMap.put(field.getJsonName(), field); - } - - this.fieldNameMaps.put(descriptor, fieldNameMap); - return fieldNameMap; - } - } - - private void mergeMessage(JsonElement json, com.google.protobuf.Message.Builder builder, boolean skipTypeUrl) - throws InvalidProtocolBufferException { - if (!(json instanceof JsonObject)) { - throw new InvalidProtocolBufferException("Expect message object but got: " + json); - } else { - JsonObject object = (JsonObject) json; - Map<String, FieldDescriptor> fieldNameMap = this.getFieldNameMap(builder.getDescriptorForType()); - Iterator var6 = object.entrySet().iterator(); - - while (true) { - Entry entry; - do { - if (!var6.hasNext()) { - return; - } - - entry = (Entry) var6.next(); - } while (skipTypeUrl && ((String) entry.getKey()).equals("@type")); - - FieldDescriptor field = (FieldDescriptor) fieldNameMap.get(entry.getKey()); - if (field == null) { - if (!this.ignoringUnknownFields) { - throw new InvalidProtocolBufferException( - "Cannot find field: " + (String) entry.getKey() + " in message " + builder - .getDescriptorForType().getFullName()); - } - } else { - this.mergeField(field, (JsonElement) entry.getValue(), builder); - } - } - } - } - - private void mergeAny(JsonElement json, com.google.protobuf.Message.Builder builder) - throws InvalidProtocolBufferException { - Descriptor descriptor = builder.getDescriptorForType(); - FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url"); - FieldDescriptor valueField = descriptor.findFieldByName("value"); - if (typeUrlField != null && valueField != null && typeUrlField.getType() == Type.STRING - && valueField.getType() == Type.BYTES) { - if (!(json instanceof JsonObject)) { - throw new InvalidProtocolBufferException("Expect message object but got: " + json); - } else { - JsonObject object = (JsonObject) json; - if (!object.entrySet().isEmpty()) { - JsonElement typeUrlElement = object.get("@type"); - if (typeUrlElement == null) { - throw new InvalidProtocolBufferException("Missing type url when parsing: " + json); - } else { - String typeUrl = typeUrlElement.getAsString(); - Descriptor contentType = this.registry.find(JsonFormat.getTypeName(typeUrl)); - if (contentType == null) { - throw new InvalidProtocolBufferException("Cannot resolve type: " + typeUrl); - } else { - builder.setField(typeUrlField, typeUrl); - com.google.protobuf.Message.Builder contentBuilder = DynamicMessage - .getDefaultInstance(contentType).newBuilderForType(); - JsonFormat.ParserImpl.WellKnownTypeParser specialParser = (JsonFormat.ParserImpl.WellKnownTypeParser) wellKnownTypeParsers - .get(contentType.getFullName()); - if (specialParser != null) { - JsonElement value = object.get("value"); - if (value != null) { - specialParser.merge(this, value, contentBuilder); - } - } else { - this.mergeMessage(json, contentBuilder, true); - } - - builder.setField(valueField, contentBuilder.build().toByteString()); - } - } - } - } - } else { - throw new InvalidProtocolBufferException("Invalid Any type."); } } @@ -330,17 +190,6 @@ public class JsonFormat { } } - private void mergeListValue(JsonElement json, com.google.protobuf.Message.Builder builder) - throws InvalidProtocolBufferException { - Descriptor descriptor = builder.getDescriptorForType(); - FieldDescriptor field = descriptor.findFieldByName("values"); - if (field == null) { - throw new InvalidProtocolBufferException("Invalid ListValue type."); - } else { - this.mergeRepeatedField(field, json, builder); - } - } - private void mergeValue(JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { Descriptor type = builder.getDescriptorForType(); @@ -377,52 +226,6 @@ public class JsonFormat { } - private void mergeWrapper(JsonElement json, com.google.protobuf.Message.Builder builder) - throws InvalidProtocolBufferException { - Descriptor type = builder.getDescriptorForType(); - FieldDescriptor field = type.findFieldByName("value"); - if (field == null) { - throw new InvalidProtocolBufferException("Invalid wrapper type: " + type.getFullName()); - } else { - builder.setField(field, this.parseFieldValue(field, json, builder)); - } - } - - private void mergeField(FieldDescriptor field, JsonElement json, com.google.protobuf.Message.Builder builder) - throws InvalidProtocolBufferException { - if (field.isRepeated()) { - if (builder.getRepeatedFieldCount(field) > 0) { - throw new InvalidProtocolBufferException("Field " + field.getFullName() + " has already been set."); - } - } else { - if (builder.hasField(field)) { - throw new InvalidProtocolBufferException("Field " + field.getFullName() + " has already been set."); - } - - if (field.getContainingOneof() != null - && builder.getOneofFieldDescriptor(field.getContainingOneof()) != null) { - FieldDescriptor other = builder.getOneofFieldDescriptor(field.getContainingOneof()); - throw new InvalidProtocolBufferException( - "Cannot set field " + field.getFullName() + " because another field " + other.getFullName() - + " belonging to the same oneof has already been set "); - } - } - - if (!field.isRepeated() || !(json instanceof JsonNull)) { - if (field.isMapField()) { - this.mergeMapField(field, json, builder); - } else if (field.isRepeated()) { - this.mergeRepeatedField(field, json, builder); - } else { - Object value = this.parseFieldValue(field, json, builder); - if (value != null) { - builder.setField(field, value); - } - } - - } - } - private void mergeMapField(FieldDescriptor field, JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { if (!(json instanceof JsonObject)) { @@ -456,188 +259,10 @@ public class JsonFormat { } } - private void mergeRepeatedField(FieldDescriptor field, JsonElement json, - com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { - if (!(json instanceof JsonArray)) { - throw new InvalidProtocolBufferException("Expect an array but found: " + json); - } else { - JsonArray array = (JsonArray) json; - - for (int i = 0; i < array.size(); ++i) { - Object value = this.parseFieldValue(field, array.get(i), builder); - if (value == null) { - throw new InvalidProtocolBufferException( - "Repeated field elements cannot be null in field: " + field.getFullName()); - } - - builder.addRepeatedField(field, value); - } - - } - } - - private int parseInt32(JsonElement json) throws InvalidProtocolBufferException { - try { - return Integer.parseInt(json.getAsString()); - } catch (Exception var4) { - try { - BigDecimal value = new BigDecimal(json.getAsString()); - return value.intValueExact(); - } catch (Exception var3) { - throw new InvalidProtocolBufferException("Not an int32 value: " + json); - } - } - } - - private long parseInt64(JsonElement json) throws InvalidProtocolBufferException { - try { - return Long.parseLong(json.getAsString()); - } catch (Exception var4) { - try { - BigDecimal value = new BigDecimal(json.getAsString()); - return value.longValueExact(); - } catch (Exception var3) { - throw new InvalidProtocolBufferException("Not an int64 value: " + json); - } - } - } - - private int parseUint32(JsonElement json) throws InvalidProtocolBufferException { - try { - long result = Long.parseLong(json.getAsString()); - if (result >= 0L && result <= 4294967295L) { - return (int) result; - } else { - throw new InvalidProtocolBufferException("Out of range uint32 value: " + json); - } - } catch (InvalidProtocolBufferException var6) { - throw var6; - } catch (Exception var7) { - try { - BigDecimal decimalValue = new BigDecimal(json.getAsString()); - BigInteger value = decimalValue.toBigIntegerExact(); - if (value.signum() >= 0 && value.compareTo(new BigInteger("FFFFFFFF", 16)) <= 0) { - return value.intValue(); - } else { - throw new InvalidProtocolBufferException("Out of range uint32 value: " + json); - } - } catch (InvalidProtocolBufferException var4) { - throw var4; - } catch (Exception var5) { - throw new InvalidProtocolBufferException("Not an uint32 value: " + json); - } - } - } - - private long parseUint64(JsonElement json) throws InvalidProtocolBufferException { - try { - BigDecimal decimalValue = new BigDecimal(json.getAsString()); - BigInteger value = decimalValue.toBigIntegerExact(); - if (value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(MAX_UINT64) <= 0) { - return value.longValue(); - } else { - throw new InvalidProtocolBufferException("Out of range uint64 value: " + json); - } - } catch (InvalidProtocolBufferException var4) { - throw var4; - } catch (Exception var5) { - throw new InvalidProtocolBufferException("Not an uint64 value: " + json); - } - } - - private boolean parseBool(JsonElement json) throws InvalidProtocolBufferException { - if (json.getAsString().equals("true")) { - return true; - } else if (json.getAsString().equals("false")) { - return false; - } else { - throw new InvalidProtocolBufferException("Invalid bool value: " + json); - } - } - - private float parseFloat(JsonElement json) throws InvalidProtocolBufferException { - if (json.getAsString().equals("NaN")) { - return (float) (0.0F / 0.0); - } else if (json.getAsString().equals("Infinity")) { - return (float) (1.0F / 0.0); - } else if (json.getAsString().equals("-Infinity")) { - return (float) (-1.0F / 0.0); - } else { - try { - double value = Double.parseDouble(json.getAsString()); - if (value <= 3.402826869208755E38D && value >= -3.402826869208755E38D) { - return (float) value; - } else { - throw new InvalidProtocolBufferException("Out of range float value: " + json); - } - } catch (InvalidProtocolBufferException var4) { - throw var4; - } catch (Exception var5) { - throw new InvalidProtocolBufferException("Not a float value: " + json); - } - } - } - - private double parseDouble(JsonElement json) throws InvalidProtocolBufferException { - if (json.getAsString().equals("NaN")) { - return 0.0D / 0.0; - } else if (json.getAsString().equals("Infinity")) { - return 1.0D / 0.0; - } else if (json.getAsString().equals("-Infinity")) { - return -1.0D / 0.0; - } else { - try { - BigDecimal value = new BigDecimal(json.getAsString()); - if (value.compareTo(MAX_DOUBLE) <= 0 && value.compareTo(MIN_DOUBLE) >= 0) { - return value.doubleValue(); - } else { - throw new InvalidProtocolBufferException("Out of range double value: " + json); - } - } catch (InvalidProtocolBufferException var3) { - throw var3; - } catch (Exception var4) { - throw new InvalidProtocolBufferException("Not an double value: " + json); - } - } - } - private String parseString(JsonElement json) { return json.getAsString(); } - private ByteString parseBytes(JsonElement json) throws InvalidProtocolBufferException { - try { - return ByteString.copyFrom(BaseEncoding.base64().decode(json.getAsString())); - } catch (IllegalArgumentException var3) { - return ByteString.copyFrom(BaseEncoding.base64Url().decode(json.getAsString())); - } - } - - private EnumValueDescriptor parseEnum(EnumDescriptor enumDescriptor, JsonElement json) - throws InvalidProtocolBufferException { - String value = json.getAsString(); - EnumValueDescriptor result = enumDescriptor.findValueByName(value); - if (result == null) { - try { - int numericValue = this.parseInt32(json); - if (enumDescriptor.getFile().getSyntax() == Syntax.PROTO3) { - result = enumDescriptor.findValueByNumberCreatingIfUnknown(numericValue); - } else { - result = enumDescriptor.findValueByNumber(numericValue); - } - } catch (InvalidProtocolBufferException var6) { - ; - } - - if (result == null) { - throw new InvalidProtocolBufferException( - "Invalid enum value: " + value + " for enum type: " + enumDescriptor.getFullName()); - } - } - - return result; - } - private Object parseFieldValue(FieldDescriptor field, JsonElement json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { if (json instanceof JsonNull) { @@ -652,32 +277,8 @@ public class JsonFormat { } } else { switch (field.getType()) { - case INT32: - case SINT32: - case SFIXED32: - return this.parseInt32(json); - case INT64: - case SINT64: - case SFIXED64: - return this.parseInt64(json); - case BOOL: - return this.parseBool(json); - case FLOAT: - return this.parseFloat(json); - case DOUBLE: - return this.parseDouble(json); - case UINT32: - case FIXED32: - return this.parseUint32(json); - case UINT64: - case FIXED64: - return this.parseUint64(json); case STRING: return this.parseString(json); - case BYTES: - return this.parseBytes(json); - case ENUM: - return this.parseEnum(field.getEnumType(), json); case MESSAGE: case GROUP: if (this.currentDepth >= this.recursionLimit) { @@ -746,8 +347,6 @@ public class JsonFormat { .get(message.getDescriptorForType().getFullName()); if (specialPrinter != null) { specialPrinter.print(this, message); - } else { - this.print(message, (String) null); } } @@ -755,12 +354,10 @@ public class JsonFormat { Map<String, JsonFormat.PrinterImpl.WellKnownTypePrinter> printers = new HashMap(); printers.put(Any.getDescriptor().getFullName(), new JsonFormat.PrinterImpl.WellKnownTypePrinter() { public void print(JsonFormat.PrinterImpl printer, MessageOrBuilder message) throws IOException { - printer.printAny(message); } }); JsonFormat.PrinterImpl.WellKnownTypePrinter wrappersPrinter = new JsonFormat.PrinterImpl.WellKnownTypePrinter() { public void print(JsonFormat.PrinterImpl printer, MessageOrBuilder message) throws IOException { - printer.printWrapper(message); } }; printers.put(BoolValue.getDescriptor().getFullName(), wrappersPrinter); @@ -784,68 +381,11 @@ public class JsonFormat { }); printers.put(ListValue.getDescriptor().getFullName(), new JsonFormat.PrinterImpl.WellKnownTypePrinter() { public void print(JsonFormat.PrinterImpl printer, MessageOrBuilder message) throws IOException { - printer.printListValue(message); } }); return printers; } - private void printAny(MessageOrBuilder message) throws IOException { - if (Any.getDefaultInstance().equals(message)) { - this.generator.print("{}"); - } else { - Descriptor descriptor = message.getDescriptorForType(); - FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url"); - FieldDescriptor valueField = descriptor.findFieldByName("value"); - if (typeUrlField != null && valueField != null && typeUrlField.getType() == Type.STRING - && valueField.getType() == Type.BYTES) { - String typeUrl = (String) message.getField(typeUrlField); - String typeName = JsonFormat.getTypeName(typeUrl); - Descriptor type = this.registry.find(typeName); - if (type == null) { - throw new InvalidProtocolBufferException("Cannot find type for url: " + typeUrl); - } else { - ByteString content = (ByteString) message.getField(valueField); - Message contentMessage = (Message) DynamicMessage.getDefaultInstance(type).getParserForType() - .parseFrom(content); - JsonFormat.PrinterImpl.WellKnownTypePrinter printer = (JsonFormat.PrinterImpl.WellKnownTypePrinter) wellKnownTypePrinters - .get(typeName); - if (printer != null) { - this.generator.print("{" + this.blankOrNewLine); - this.generator.indent(); - this.generator.print("\"@type\":" + this.blankOrSpace + this.gson.toJson(typeUrl) + "," - + this.blankOrNewLine); - this.generator.print("\"value\":" + this.blankOrSpace); - printer.print(this, contentMessage); - this.generator.print(this.blankOrNewLine); - this.generator.outdent(); - this.generator.print("}"); - } else { - this.print(contentMessage, typeUrl); - } - - } - } else { - throw new InvalidProtocolBufferException("Invalid Any type."); - } - } - } - - private void printWrapper(MessageOrBuilder message) throws IOException { - Descriptor descriptor = message.getDescriptorForType(); - FieldDescriptor valueField = descriptor.findFieldByName("value"); - if (valueField == null) { - throw new InvalidProtocolBufferException("Invalid Wrapper type."); - } else { - this.printSingleFieldValue(valueField, message.getField(valueField)); - } - } - - private ByteString toByteString(MessageOrBuilder message) { - return message instanceof Message ? ((Message) message).toByteString() - : ((com.google.protobuf.Message.Builder) message).build().toByteString(); - } - private void printStruct(MessageOrBuilder message) throws IOException { Descriptor descriptor = message.getDescriptorForType(); FieldDescriptor field = descriptor.findFieldByName("fields"); @@ -873,116 +413,6 @@ public class JsonFormat { } } - private void printListValue(MessageOrBuilder message) throws IOException { - Descriptor descriptor = message.getDescriptorForType(); - FieldDescriptor field = descriptor.findFieldByName("values"); - if (field == null) { - throw new InvalidProtocolBufferException("Invalid ListValue type."); - } else { - this.printRepeatedFieldValue(field, message.getField(field)); - } - } - - private void print(MessageOrBuilder message, String typeUrl) throws IOException { - this.generator.print("{" + this.blankOrNewLine); - this.generator.indent(); - boolean printedField = false; - if (typeUrl != null) { - this.generator.print("\"@type\":" + this.blankOrSpace + this.gson.toJson(typeUrl)); - printedField = true; - } - - Map<FieldDescriptor, Object> fieldsToPrint = null; - Iterator var5; - if (!this.alwaysOutputDefaultValueFields && this.includingDefaultValueFields.isEmpty()) { - fieldsToPrint = message.getAllFields(); - } else { - fieldsToPrint = new TreeMap(message.getAllFields()); - var5 = message.getDescriptorForType().getFields().iterator(); - - label66: - while (true) { - FieldDescriptor field; - do { - do { - while (true) { - if (!var5.hasNext()) { - break label66; - } - - field = (FieldDescriptor) var5.next(); - if (!field.isOptional()) { - break; - } - - if (field.getJavaType() != JavaType.MESSAGE || message.hasField(field)) { - OneofDescriptor oneof = field.getContainingOneof(); - if (oneof == null || message.hasField(field)) { - break; - } - } - } - } while (((Map) fieldsToPrint).containsKey(field)); - } while (!this.alwaysOutputDefaultValueFields && !this.includingDefaultValueFields.contains(field)); - - ((Map) fieldsToPrint).put(field, message.getField(field)); - } - } - - Entry field; - for (var5 = ((Map) fieldsToPrint).entrySet().iterator(); var5.hasNext(); - this.printField((FieldDescriptor) field.getKey(), field.getValue())) { - field = (Entry) var5.next(); - if (printedField) { - this.generator.print("," + this.blankOrNewLine); - } else { - printedField = true; - } - } - - if (printedField) { - this.generator.print(this.blankOrNewLine); - } - - this.generator.outdent(); - this.generator.print("}"); - } - - private void printField(FieldDescriptor field, Object value) throws IOException { - if (this.preservingProtoFieldNames) { - this.generator.print("\"" + field.getName() + "\":" + this.blankOrSpace); - } else { - this.generator.print("\"" + field.getJsonName() + "\":" + this.blankOrSpace); - } - - if (field.isMapField()) { - this.printMapFieldValue(field, value); - } else if (field.isRepeated()) { - this.printRepeatedFieldValue(field, value); - } else { - this.printSingleFieldValue(field, value); - } - - } - - private void printRepeatedFieldValue(FieldDescriptor field, Object value) throws IOException { - this.generator.print("["); - boolean printedElement = false; - - Object element; - for (Iterator var4 = ((List) value).iterator(); var4.hasNext(); - this.printSingleFieldValue(field, element)) { - element = var4.next(); - if (printedElement) { - this.generator.print("," + this.blankOrSpace); - } else { - printedElement = true; - } - } - - this.generator.print("]"); - } - private void printMapFieldValue(FieldDescriptor field, Object value) throws IOException { Descriptor type = field.getMessageType(); FieldDescriptor keyField = type.findFieldByName("key"); @@ -1027,59 +457,6 @@ public class JsonFormat { private void printSingleFieldValue(FieldDescriptor field, Object value, boolean alwaysWithQuotes) throws IOException { switch (field.getType()) { - case INT32: - case SINT32: - case SFIXED32: - if (alwaysWithQuotes) { - this.generator.print("\""); - } - - this.generator.print(((Integer) value).toString()); - if (alwaysWithQuotes) { - this.generator.print("\""); - } - break; - case INT64: - case SINT64: - case SFIXED64: - this.generator.print("\"" + ((Long) value).toString() + "\""); - break; - case BOOL: - if (alwaysWithQuotes) { - this.generator.print("\""); - } - - if ((Boolean) value) { - this.generator.print("true"); - } else { - this.generator.print("false"); - } - - if (alwaysWithQuotes) { - this.generator.print("\""); - } - break; - case FLOAT: - Float floatValue = (Float) value; - if (floatValue.isNaN()) { - this.generator.print("\"NaN\""); - } else if (floatValue.isInfinite()) { - if (floatValue < 0.0F) { - this.generator.print("\"-Infinity\""); - } else { - this.generator.print("\"Infinity\""); - } - } else { - if (alwaysWithQuotes) { - this.generator.print("\""); - } - - this.generator.print(floatValue.toString()); - if (alwaysWithQuotes) { - this.generator.print("\""); - } - } - break; case DOUBLE: Double doubleValue = (Double) value; if (doubleValue.isNaN()) { @@ -1101,45 +478,9 @@ public class JsonFormat { } } break; - case UINT32: - case FIXED32: - if (alwaysWithQuotes) { - this.generator.print("\""); - } - - this.generator.print(JsonFormat.unsignedToString((Integer) value)); - if (alwaysWithQuotes) { - this.generator.print("\""); - } - break; - case UINT64: - case FIXED64: - this.generator.print("\"" + JsonFormat.unsignedToString((Long) value) + "\""); - break; case STRING: this.generator.print(this.gson.toJson(value)); break; - case BYTES: - this.generator.print("\""); - this.generator.print(BaseEncoding.base64().encode(((ByteString) value).toByteArray())); - this.generator.print("\""); - break; - case ENUM: - if (field.getEnumType().getFullName().equals("google.protobuf.NullValue")) { - if (alwaysWithQuotes) { - this.generator.print("\""); - } - - this.generator.print("null"); - if (alwaysWithQuotes) { - this.generator.print("\""); - } - } else if (!this.printingEnumsAsInts && ((EnumValueDescriptor) value).getIndex() != -1) { - this.generator.print("\"" + ((EnumValueDescriptor) value).getName() + "\""); - } else { - this.generator.print(String.valueOf(((EnumValueDescriptor) value).getNumber())); - } - break; case MESSAGE: case GROUP: this.print((Message) value); @@ -1249,10 +590,6 @@ public class JsonFormat { return JsonFormat.TypeRegistry.EmptyTypeRegistryHolder.EMPTY; } - public static JsonFormat.TypeRegistry.Builder newBuilder() { - return new JsonFormat.TypeRegistry.Builder(); - } - public Descriptor find(String name) { return (Descriptor) this.types.get(name); } @@ -1261,81 +598,6 @@ public class JsonFormat { this.types = types; } - public static class Builder { - - private final Set<String> files; - private Map<String, Descriptor> types; - - private Builder() { - this.files = new HashSet(); - this.types = new HashMap(); - } - - public JsonFormat.TypeRegistry.Builder add(Descriptor messageType) { - if (this.types == null) { - throw new IllegalStateException("A TypeRegistry.Builer can only be used once."); - } else { - this.addFile(messageType.getFile()); - return this; - } - } - - public JsonFormat.TypeRegistry.Builder add(Iterable<Descriptor> messageTypes) { - if (this.types == null) { - throw new IllegalStateException("A TypeRegistry.Builder can only be used once."); - } else { - Iterator var2 = messageTypes.iterator(); - - while (var2.hasNext()) { - Descriptor type = (Descriptor) var2.next(); - this.addFile(type.getFile()); - } - - return this; - } - } - - public JsonFormat.TypeRegistry build() { - JsonFormat.TypeRegistry result = new JsonFormat.TypeRegistry(this.types); - this.types = null; - return result; - } - - private void addFile(FileDescriptor file) { - if (this.files.add(file.getFullName())) { - Iterator var2 = file.getDependencies().iterator(); - - while (var2.hasNext()) { - FileDescriptor dependency = (FileDescriptor) var2.next(); - this.addFile(dependency); - } - - var2 = file.getMessageTypes().iterator(); - - while (var2.hasNext()) { - Descriptor message = (Descriptor) var2.next(); - this.addMessage(message); - } - - } - } - - private void addMessage(Descriptor message) { - Iterator var2 = message.getNestedTypes().iterator(); - - while (var2.hasNext()) { - Descriptor nestedType = (Descriptor) var2.next(); - this.addMessage(nestedType); - } - - if (this.types.containsKey(message.getFullName())) { - JsonFormat.logger.warning("Type " + message.getFullName() + " is added multiple times."); - } else { - this.types.put(message.getFullName(), message); - } - } - } - private static class EmptyTypeRegistryHolder { private static final JsonFormat.TypeRegistry EMPTY = new JsonFormat.TypeRegistry(Collections.emptyMap()); @@ -1358,32 +620,11 @@ public class JsonFormat { this.recursionLimit = recursionLimit; } - public JsonFormat.Parser usingTypeRegistry(JsonFormat.TypeRegistry registry) { - if (this.registry != JsonFormat.TypeRegistry.getEmptyTypeRegistry()) { - throw new IllegalArgumentException("Only one registry is allowed."); - } else { - return new JsonFormat.Parser(registry, this.ignoringUnknownFields, this.recursionLimit); - } - } - - public JsonFormat.Parser ignoringUnknownFields() { - return new JsonFormat.Parser(this.registry, true, this.recursionLimit); - } - public void merge(String json, com.google.protobuf.Message.Builder builder) throws InvalidProtocolBufferException { (new JsonFormat.ParserImpl(this.registry, this.ignoringUnknownFields, this.recursionLimit)) .merge(json, builder); } - - public void merge(Reader json, com.google.protobuf.Message.Builder builder) throws IOException { - (new JsonFormat.ParserImpl(this.registry, this.ignoringUnknownFields, this.recursionLimit)) - .merge(json, builder); - } - - JsonFormat.Parser usingRecursionLimit(int recursionLimit) { - return new JsonFormat.Parser(this.registry, this.ignoringUnknownFields, recursionLimit); - } } public static class Printer { @@ -1406,58 +647,6 @@ public class JsonFormat { this.printingEnumsAsInts = printingEnumsAsInts; } - public JsonFormat.Printer usingTypeRegistry(JsonFormat.TypeRegistry registry) { - if (this.registry != JsonFormat.TypeRegistry.getEmptyTypeRegistry()) { - throw new IllegalArgumentException("Only one registry is allowed."); - } else { - return new JsonFormat.Printer(registry, this.alwaysOutputDefaultValueFields, - this.includingDefaultValueFields, this.preservingProtoFieldNames, - this.omittingInsignificantWhitespace, this.printingEnumsAsInts); - } - } - - public JsonFormat.Printer includingDefaultValueFields() { - this.checkUnsetIncludingDefaultValueFields(); - return new JsonFormat.Printer(this.registry, true, Collections.emptySet(), this.preservingProtoFieldNames, - this.omittingInsignificantWhitespace, this.printingEnumsAsInts); - } - - public JsonFormat.Printer printingEnumsAsInts() { - this.checkUnsetPrintingEnumsAsInts(); - return new JsonFormat.Printer(this.registry, this.alwaysOutputDefaultValueFields, Collections.emptySet(), - this.preservingProtoFieldNames, this.omittingInsignificantWhitespace, true); - } - - private void checkUnsetPrintingEnumsAsInts() { - if (this.printingEnumsAsInts) { - throw new IllegalStateException("JsonFormat printingEnumsAsInts has already been set."); - } - } - - public JsonFormat.Printer includingDefaultValueFields(Set<FieldDescriptor> fieldsToAlwaysOutput) { - Preconditions.checkArgument(null != fieldsToAlwaysOutput && !fieldsToAlwaysOutput.isEmpty(), - "Non-empty Set must be supplied for includingDefaultValueFields."); - this.checkUnsetIncludingDefaultValueFields(); - return new JsonFormat.Printer(this.registry, false, fieldsToAlwaysOutput, this.preservingProtoFieldNames, - this.omittingInsignificantWhitespace, this.printingEnumsAsInts); - } - - private void checkUnsetIncludingDefaultValueFields() { - if (this.alwaysOutputDefaultValueFields || !this.includingDefaultValueFields.isEmpty()) { - throw new IllegalStateException("JsonFormat includingDefaultValueFields has already been set."); - } - } - - public JsonFormat.Printer preservingProtoFieldNames() { - return new JsonFormat.Printer(this.registry, this.alwaysOutputDefaultValueFields, - this.includingDefaultValueFields, true, this.omittingInsignificantWhitespace, this.printingEnumsAsInts); - } - - public JsonFormat.Printer omittingInsignificantWhitespace() { - return new JsonFormat.Printer(this.registry, this.alwaysOutputDefaultValueFields, - this.includingDefaultValueFields, this.preservingProtoFieldNames, true, this.printingEnumsAsInts); - } - public void appendTo(MessageOrBuilder message, Appendable output) throws IOException { (new JsonFormat.PrinterImpl(this.registry, this.alwaysOutputDefaultValueFields, this.includingDefaultValueFields, this.preservingProtoFieldNames, output, diff --git a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BasicAuthClientInterceptor.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BasicAuthClientInterceptor.java new file mode 100644 index 000000000..5d2e848cf --- /dev/null +++ b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BasicAuthClientInterceptor.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.sli.adaptors.grpc.cds; + +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingClientCall; +import io.grpc.Metadata; +import io.grpc.Metadata.Key; +import io.grpc.MethodDescriptor; +import org.apache.http.HttpHeaders; +import org.onap.ccsdk.sli.adaptors.grpc.GrpcProperties; + +public class BasicAuthClientInterceptor implements ClientInterceptor { + + private GrpcProperties props; + + public BasicAuthClientInterceptor(GrpcProperties props) { + this.props = props; + } + + @Override + public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( + MethodDescriptor<ReqT, RespT> method, + CallOptions callOptions, + Channel channel) { + + Key<String> authHeader = Key.of(HttpHeaders.AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER); + + return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>( + channel.newCall(method, callOptions)) { + @Override + public void start(Listener<RespT> responseListener, Metadata headers) { + headers.put(authHeader, props.getAuth()); + super.start(responseListener, headers); + } + }; + } +} diff --git a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClient.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClient.java index fdbe6f4e3..f922f9ec5 100644 --- a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClient.java +++ b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClient.java @@ -34,13 +34,19 @@ public class BlueprintProcessingClient implements GrpcClient { private ManagedChannel channel; private BlueprintProcessingHandler handler; - public BlueprintProcessingClient(BlueprintProcessingHandler handler, GrpcProperties props) { + public BlueprintProcessingClient(GrpcProperties props) { this.channel = NettyChannelBuilder .forAddress(props.getUrl(), props.getPort()) .nameResolverFactory(new DnsNameResolverProvider()) .loadBalancerFactory(new PickFirstLoadBalancerProvider()) + .intercept(new BasicAuthClientInterceptor(props)) .usePlaintext() .build(); + this.handler = new BlueprintProcessingHandler(); + } + + public BlueprintProcessingClient(ManagedChannel channel, BlueprintProcessingHandler handler) { + this.channel = channel; this.handler = handler; } @@ -69,11 +75,12 @@ public class BlueprintProcessingClient implements GrpcClient { * <tr><td>action</td><td>Mandatory</td><td>Action of the blueprint to process.</td></tr> * <tr><td>mode</td><td>Mandatory</td><td>Mode to operate the transaction.</td></tr> * <tr><td>payload</td><td>Mandatory</td><td>Payload.</td></tr> + * <tr><td>prefix</td><td>Mandatory</td><td>Prefix string to put response in context.</td></tr> * </tbody> * </table> */ @Override public QueryStatus sendRequest(Map<String, String> parameters, SvcLogicContext ctx) { - return handler.process(parameters, channel); + return handler.process(parameters, channel, ctx); } }
\ No newline at end of file diff --git a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingHandler.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingHandler.java index c142da91b..211db3c90 100644 --- a/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingHandler.java +++ b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingHandler.java @@ -15,6 +15,7 @@ */ package org.onap.ccsdk.sli.adaptors.grpc.cds; +import com.google.common.collect.Maps; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Struct; import com.google.protobuf.Struct.Builder; @@ -35,16 +36,18 @@ import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceI import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; import org.onap.ccsdk.sli.adaptors.grpc.JsonFormat; import org.onap.ccsdk.sli.adaptors.grpc.Utils; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class BlueprintProcessingHandler { +class BlueprintProcessingHandler { private static final Logger log = LoggerFactory.getLogger(BlueprintProcessingHandler.class); + private static final int DEFAULT_TTL = 180; private static final String CCSDK_ORIGINATOR = "CCSDK"; private static final String IS_FORCE_PROP = "is_force"; private static final String TTL_PROP = "ttl"; @@ -53,22 +56,27 @@ public class BlueprintProcessingHandler { private static final String ACTION_PROP = "action"; private static final String MODE_PROP = "mode"; private static final String PAYLOAD_PROP = "payload"; + private static final String PREFIX_PROP = "prefix"; - QueryStatus process(final Map<String, String> parameters, final ManagedChannel channel) { + QueryStatus process(final Map<String, String> parameters, final ManagedChannel channel, final SvcLogicContext ctx) { try { SliPluginUtils.checkParameters(parameters, - new String[]{BLUEPRINT_NAME_PROP, BLUEPRINT_VERSION_PROP, ACTION_PROP, MODE_PROP}, log); + new String[]{BLUEPRINT_NAME_PROP, BLUEPRINT_VERSION_PROP, ACTION_PROP, MODE_PROP, PREFIX_PROP}, log); } catch (SvcLogicException e) { return QueryStatus.FAILURE; } final boolean isForce = Boolean.getBoolean(parameters.get(IS_FORCE_PROP)); - final int ttl = Integer.parseInt(parameters.get(TTL_PROP)); + int ttl = Integer.parseInt(parameters.get(TTL_PROP)); + if (ttl == 0) { + ttl = DEFAULT_TTL; + } final String blueprintName = parameters.get(BLUEPRINT_NAME_PROP); final String blueprintVersion = parameters.get(BLUEPRINT_VERSION_PROP); final String action = parameters.get(ACTION_PROP); final String mode = parameters.get(MODE_PROP); final String payload = parameters.get(PAYLOAD_PROP); + final String prefix = parameters.get(PREFIX_PROP); log.info("Processing blueprint({}:{}) for action({})", blueprintVersion, blueprintName, action); @@ -81,6 +89,31 @@ public class BlueprintProcessingHandler { @Override public void onNext(ExecutionServiceOutput output) { log.info("onNext: {}", output); + + Map<String, String> jsonToCtx = Maps.newHashMap(); + String json = ""; + try { + json = JsonFormat.printer().print(output); + } catch (InvalidProtocolBufferException e) { + log.error("Failed to parse received message. blueprint({}:{}) for action({}). {}", blueprintVersion, + blueprintName, action, output, e); + responseStatus.compareAndSet(null, QueryStatus.FAILURE); + finishLatch.countDown(); + } + + ctx.setAttribute("BlueprintProcessingHandler_process", json); + jsonToCtx.put("source", "BlueprintProcessingHandler_process"); + jsonToCtx.put("outputPath", prefix); + jsonToCtx.put("isEscaped", Boolean.FALSE.toString()); + + try { + SliPluginUtils.jsonStringToCtx(jsonToCtx, ctx); + } catch (SvcLogicException e) { + log.error("Failed to put jsonStringToCtx. blueprint({}:{}) for action({}). {}", blueprintVersion, + blueprintName, action, output, e); + responseStatus.compareAndSet(null, QueryStatus.FAILURE); + finishLatch.countDown(); + } } @Override @@ -141,7 +174,7 @@ public class BlueprintProcessingHandler { requestObserver.onCompleted(); try { - finishLatch.await(1, TimeUnit.MINUTES); + finishLatch.await(ttl, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error("Failed processing blueprint({}:{}) for action({}). {}", blueprintVersion, blueprintName, action, e); diff --git a/grpc-resource/provider/src/main/resources/grpc.properties b/grpc-resource/provider/src/main/resources/grpc.properties index 650910eb9..7e1bf40ea 100644 --- a/grpc-resource/provider/src/main/resources/grpc.properties +++ b/grpc-resource/provider/src/main/resources/grpc.properties @@ -15,3 +15,4 @@ # org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.url=blueprint-processor org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.port=9111 +org.onap.ccsdk.sli.adaptors.grpc.blueprint.processor.auth=Basic Y2NzZGthcHBzOmNjc2RrYXBwcw== diff --git a/grpc-resource/provider/src/main/resources/org/opendaylight/blueprint/grpc-client.xml b/grpc-resource/provider/src/main/resources/org/opendaylight/blueprint/grpc-client.xml index 2c428da37..9febe4846 100644 --- a/grpc-resource/provider/src/main/resources/org/opendaylight/blueprint/grpc-client.xml +++ b/grpc-resource/provider/src/main/resources/org/opendaylight/blueprint/grpc-client.xml @@ -15,21 +15,16 @@ limitations under the License. --> <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0" - odl:use-default-for-reference-types="true"> - + odl:use-default-for-reference-types="true" odl:restart-dependents-on-updates="true"> <bean id="grpcProperty" class="org.onap.ccsdk.sli.adaptors.grpc.GrpcProperties"/> <!--CDS--> - - <bean id="blueprintProcessingHandler" class="org.onap.ccsdk.sli.adaptors.grpc.cds.BlueprintProcessingHandler"/> - <bean id="grpcClient" class="org.onap.ccsdk.sli.adaptors.grpc.cds.BlueprintProcessingClient" init-method="start" destroy-method="stop"> - <argument ref="blueprintProcessingHandler"/> <argument ref="grpcProperty"/> </bean> - <service ref="grpcClient" interface="org.onap.ccsdk.sli.adaptors.grpc.cds.BlueprintProcessingClient" + <service ref="grpcClient" interface="org.onap.ccsdk.sli.adaptors.grpc.GrpcClient" odl:type="default"/> </blueprint> diff --git a/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClientTest.java b/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClientTest.java new file mode 100644 index 000000000..8c0da5119 --- /dev/null +++ b/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClientTest.java @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2019 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.ccsdk.sli.adaptors.grpc.cds; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; + +import com.google.common.collect.Maps; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import io.grpc.testing.GrpcCleanupRule; +import io.grpc.util.MutableHandlerRegistry; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Mockito; +import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase; +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.ccsdk.sli.adaptors.grpc.GrpcProperties; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; + +@RunWith(JUnit4.class) +public class BlueprintProcessingClientTest { + + @Rule + public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); + + private BlueprintProcessingClient client; + + private final SvcLogicContext svcLogicContext = new SvcLogicContext(); + private final MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry(); + private final List<String> messagesDelivered = new ArrayList<>(); + private final CountDownLatch allRequestsDelivered = new CountDownLatch(1); + private final AtomicReference<StreamObserver<ExecutionServiceOutput>> responseObserverRef = new AtomicReference<>(); + + @Before + public void setUp() throws Exception { + + String serverName = InProcessServerBuilder.generateName(); + grpcCleanup.register(InProcessServerBuilder.forName(serverName) + .fallbackHandlerRegistry(serviceRegistry).directExecutor().build().start()); + + BlueprintProcessingHandler handler = new BlueprintProcessingHandler(); + + client = + new BlueprintProcessingClient(InProcessChannelBuilder.forName(serverName).directExecutor().build(), + handler); + + final BluePrintProcessingServiceImplBase routeChatImpl = + new BluePrintProcessingServiceImplBase() { + @Override + public StreamObserver<ExecutionServiceInput> process( + StreamObserver<ExecutionServiceOutput> responseObserver) { + + responseObserverRef.set(responseObserver); + + StreamObserver<ExecutionServiceInput> requestObserver = new StreamObserver<ExecutionServiceInput>() { + @Override + public void onNext(ExecutionServiceInput message) { + messagesDelivered.add(message.getActionIdentifiers().getActionName()); + } + + @Override + public void onError(Throwable t) { + + } + + @Override + public void onCompleted() { + allRequestsDelivered.countDown(); + } + }; + + return requestObserver; + } + }; + + serviceRegistry.addService(routeChatImpl); + } + + @After + public void tearDown() { + client.stop(); + } + + @Test + public void testClientCst() { + GrpcProperties props = Mockito.mock(GrpcProperties.class); + doReturn(999).when(props).getPort(); + doReturn("localhost").when(props).getUrl(); + new BlueprintProcessingClient(props).stop(); + } + + + @Test + public void testSendMessageFail() throws Exception { + Map<String, String> input = Maps.newHashMap(); + input.put("is_force", "true"); + input.put("ttl", "1"); + input.put("blueprint_name", "test"); + input.put("blueprint_version", "1.0.0"); + input.put("action", "test-action"); + input.put("mode", "sync"); + input.put("payload", ""); + input.put("prefix", "res"); + + QueryStatus status = client.sendRequest(input, svcLogicContext); + + Assert.assertEquals(QueryStatus.FAILURE, status); + + } + + @Test + public void testSendMessage() throws Exception { + ExecutionServiceOutput fakeResponse1 = ExecutionServiceOutput.newBuilder().setActionIdentifiers( + ActionIdentifiers.newBuilder().setActionName("response1").build()).build(); + + ExecutionServiceOutput fakeResponse2 = ExecutionServiceOutput.newBuilder().setActionIdentifiers( + ActionIdentifiers.newBuilder().setActionName("response2").build()).build(); + + Map<String, String> input = Maps.newHashMap(); + input.put("is_force", "true"); + input.put("ttl", "1"); + input.put("blueprint_name", "test"); + input.put("blueprint_version", "1.0.0"); + input.put("action", "test-action"); + input.put("mode", "sync"); + input.put("payload", "{}"); + input.put("prefix", "res"); + + client.sendRequest(input, svcLogicContext); + + // request message sent and delivered for one time + assertTrue(allRequestsDelivered.await(1, TimeUnit.SECONDS)); + assertEquals(Collections.singletonList("test-action"), messagesDelivered); + + // let server complete. + responseObserverRef.get().onCompleted(); + } + +}
\ No newline at end of file diff --git a/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/GrpcClientTest.java b/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/GrpcClientTest.java index 2b1a42ba9..2ad49d795 100644 --- a/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/GrpcClientTest.java +++ b/grpc-resource/provider/src/test/java/org/onap/ccsdk/sli/adaptors/grpc/cds/GrpcClientTest.java @@ -15,6 +15,70 @@ */ package org.onap.ccsdk.sli.adaptors.grpc.cds; +import com.google.common.collect.Maps; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Struct; +import com.google.protobuf.Struct.Builder; +import java.util.Map; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.grpc.JsonFormat; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.slipluginutils.SliPluginUtils; + public class GrpcClientTest { + @Test + public void testPayload() throws InvalidProtocolBufferException { + + String payload = "{\n" + + " \"commonHeader\": {\n" + + " \"timestamp\": \"2019-02-27T22:08:39.587Z\",\n" + + " \"originatorId\": \"System\",\n" + + " \"requestId\": \"1234\",\n" + + " \"subRequestId\": \"1234-12234\"\n" + + " },\n" + + " \"actionIdentifiers\": {\n" + + " \"blueprintName\": \"test\",\n" + + " \"blueprintVersion\": \"1.0.0\",\n" + + " \"actionName\": \"resource-assignment\",\n" + + " \"mode\": \"sync\"\n" + + " },\n" + + " \"status\": {\n" + + " \"code\": 200,\n" + + " \"eventType\": \"EVENT-COMPONENT-EXECUTED\",\n" + + " \"timestamp\": \"2019-02-27T22:08:39.981Z\",\n" + + " \"message\": \"success\"\n" + + " },\n" + + " \"payload\": {\n" + + " \"resource-assignment-params\": {\n" + + " \"test\": \"THIS IS A TEST: service-capability-resolved-status-test\"\n" + + " },\n" + + " \"status\": \"success\"\n" + + " }\n" + + "}"; + + Map<String, String> jsonToCtx = Maps.newHashMap(); + jsonToCtx.put("source", "blueprint_processing_result"); + jsonToCtx.put("outputPath", "t"); + jsonToCtx.put("isEscaped", Boolean.FALSE.toString()); + + SvcLogicContext svcLogicContext = new SvcLogicContext(); + svcLogicContext.setAttribute("blueprint_processing_result", payload); + + try { + SliPluginUtils.jsonStringToCtx(jsonToCtx, svcLogicContext); + } catch (SvcLogicException e) { + e.printStackTrace(); + } + + Builder t = Struct.newBuilder(); + + JsonFormat.parser().merge(payload, t); + + System.out.println(((Builder) t).build().toString()); + + System.out.println(JsonFormat.printer().print(t)); + } + }
\ No newline at end of file |