diff options
author | Alexis de Talhouët <adetalhouet89@gmail.com> | 2019-02-28 14:59:03 -0500 |
---|---|---|
committer | Alexis de Talhouët <adetalhouet89@gmail.com> | 2019-02-28 15:59:25 -0500 |
commit | 09460aff611767884905680d504b4fc3c8bb1476 (patch) | |
tree | 797cbb8b5590875391c4d4893b6af5d35d472c0e /grpc-resource/provider/src/main | |
parent | e73462e38b5a282e7308a8d92a155e47f79d1b0e (diff) |
Integration test on gRPC client
Change-Id: I5a7c4103a9139a5d1cc324cd23f644ba63e254c7
Issue-ID: CCSDK-947 -
Signed-off-by: Alexis de Talhouët <adetalhouet89@gmail.com>
Diffstat (limited to 'grpc-resource/provider/src/main')
4 files changed, 77 insertions, 854 deletions
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 a656d662..d169f14c 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/BlueprintProcessingClient.java b/grpc-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/grpc/cds/BlueprintProcessingClient.java index fdbe6f4e..a5ccff87 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,18 @@ 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()) .usePlaintext() .build(); + this.handler = new BlueprintProcessingHandler(); + } + + public BlueprintProcessingClient(ManagedChannel channel, BlueprintProcessingHandler handler) { + this.channel = channel; this.handler = handler; } @@ -69,11 +74,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 c142da91..211db3c9 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/org/opendaylight/blueprint/grpc-client.xml b/grpc-resource/provider/src/main/resources/org/opendaylight/blueprint/grpc-client.xml index 2c428da3..9febe484 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> |