private void writePolicy(Policy policy, JsonWriter generator)
        {
            generator.WriteObjectStart();

            writePropertyValue(generator, JsonDocumentFields.VERSION, policy.Version);

            if (policy.Id != null)
            {
                writePropertyValue(generator, JsonDocumentFields.POLICY_ID, policy.Id);
            }

            generator.WritePropertyName(JsonDocumentFields.STATEMENT);
            generator.WriteArrayStart();
            foreach (Statement statement in policy.Statements)
            {
                generator.WriteObjectStart();
                if (statement.Id != null)
                {
                    writePropertyValue(generator, JsonDocumentFields.STATEMENT_ID, statement.Id);
                }
                writePropertyValue(generator, JsonDocumentFields.STATEMENT_EFFECT, statement.Effect.ToString());

                writePrincipals(statement, generator);
                writeActions(statement, generator);
                writeResources(statement, generator);
                writeConditions(statement, generator);

                generator.WriteObjectEnd();
            }
            generator.WriteArrayEnd();

            generator.WriteObjectEnd();
        }
        private void WriteStructure(JsonWriter writer, Shape structure)
        {

            if (structure.Payload != null)
            {
                this.WriteStructure(writer, structure.Members[0].Shape);
                return;
            }

            writer.WriteObjectStart();

            foreach (var member in structure.Members)
            {
                writer.WritePropertyName(member.MarshallName);

                if (member.OverrideDataType != null && string.Equals(member.OverrideDataType.Unmarshaller, "DateTimeEpochLongMillisecondsUnmarshaller"))
                {
                    var ticks = Constants.DEFAULT_DATE.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
                    writer.Write((long)TimeSpan.FromTicks(ticks).TotalMilliseconds);
                }
                else if (member.OverrideDataType != null && string.Equals(member.OverrideDataType.Unmarshaller, "Amazon.Runtime.Internal.Transform.DateTimeUnmarshaller"))
                {
                    writer.Write(Constants.DEFAULT_DATE.ToString(AWSSDKUtils.ISO8601DateFormat, CultureInfo.InvariantCulture));
                }
                else
                {
                    this.Write(writer, member.Shape);
                }
            }

            writer.WriteObjectEnd();
        }
 private void Write(JsonWriter writer, Shape shape)
 {
     if (shape.IsStructure)
         WriteStructure(writer, shape);
     else if (shape.IsList)
         WriteArray(writer, shape);
     else if (shape.IsMap)
         WriteMap(writer, shape);
     else if (shape.IsEnum)
     {
         var enumerationWrapper = this._model.Enumerations.First(x => x.Name == shape.Name);
         writer.Write(enumerationWrapper.EnumerationValues.ElementAt(0).MarshallName);
     }
     else if (shape.IsString)
         writer.Write(shape.Name + "_Value");
     else if (shape.IsInt)
         writer.Write(int.MaxValue);
     else if (shape.IsLong)
         writer.Write(long.MaxValue);
     else if (shape.IsDouble)
         writer.Write(double.MaxValue);
     else if (shape.IsFloat)
         writer.Write(float.MaxValue);
     else if (shape.IsDateTime)
         writer.Write(Constants.DEFAULT_DATE);
     else if (shape.IsBoolean)
         writer.Write(true);
     else if (shape.IsBlob)
         writer.Write(Constants.DEFAULT_BLOB_ENCODED);
     else
         throw new Exception("Unknown Type for shape " + shape.Name);
 }
        public string Execute()
        {
            JsonWriter writer = new JsonWriter();
            writer.PrettyPrint = true;

            WriteStructure(writer, this._rootStructure);

            var json = writer.ToString();
            return json;
        }
 /// <summary>
 /// Creates a Json string from the Event. Expects Event and Session Timestamps to be in UTC.
 /// </summary>
 public string MarshallToJson()
 {
     using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
     {
         JsonWriter writer = new JsonWriter(stringWriter);
         writer.WriteObjectStart();
         EventMarshaller.Instance.Marshall(this, new Runtime.Internal.Transform.JsonMarshallerContext(null, writer));
         writer.WriteObjectEnd();
         return stringWriter.ToString();
     }
 }
        public string Execute()
        {
            this._tcr = new TypeCircularReference<string>();
            JsonWriter writer = new JsonWriter();
            writer.PrettyPrint = true;

            WriteStructure(writer, this._rootStructure);

            var json = writer.ToString();
            return json;
        }
Beispiel #7
0
        /// <summary>
        /// Creates JSON text for a given Document
        /// </summary>
        /// <param name="document"></param>
        /// <param name="prettyPrint"></param>
        /// <returns></returns>
        public static string ToJson(Document document, bool prettyPrint)
        {
            var sb = new StringBuilder();
            var writer = new JsonWriter(sb);
            writer.PrettyPrint = prettyPrint;

            WriteJson(document, writer, DynamoDBEntryConversion.V2);

            // Trim everything before the first '{' character
            var jsonIndex = FirstIndex(sb, '{');
            if (jsonIndex > 0)
                sb.Remove(0, jsonIndex);

            var jsonText = sb.ToString();
            return jsonText;
        }
        /**
         * Converts the specified AWS policy object to a JSON string, suitable for
         * passing to an AWS service.
         *
         * @param policy
         *            The AWS policy object to convert to a JSON string.
         *
         * @return The JSON string representation of the specified policy object.
         *
         * @throws IllegalArgumentException
         *             If the specified policy is null or invalid and cannot be
         *             serialized to a JSON string.
         */
        public string WritePolicyToString(Policy policy)
        {
            if (policy == null)
            {
                throw new ArgumentNullException("Policy cannot be null");
            }

            StringWriter writer = new StringWriter();
            try
            {
                JsonWriter generator = new JsonWriter(writer);
                generator.PrettyPrint = true;
                generator.IndentValue = 4;
                writePolicy(policy, generator);
                return writer.ToString().Trim();
            }
            catch (Exception e)
            {
                string message = "Unable to serialize policy to JSON string: " + e.Message;
                throw new ArgumentException(message, e);
            }
        }
        /**
         * Converts the specified AWS policy object to a JSON string, suitable for
         * passing to an AWS service.
         *
         * @param policy
         *            The AWS policy object to convert to a JSON string.
         *
         * @return The JSON string representation of the specified policy object.
         *
         * @throws IllegalArgumentException
         *             If the specified policy is null or invalid and cannot be
         *             serialized to a JSON string.
         */
        public static string WritePolicyToString(bool prettyPrint, Policy policy)
        {
            if (policy == null)
            {
                throw new ArgumentNullException("policy");
            }

            StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
            try
            {
                JsonWriter generator = new JsonWriter(writer);

                generator.IndentValue = 4;
                generator.PrettyPrint = prettyPrint;

                writePolicy(policy, generator);
                return writer.ToString().Trim();
            }
            catch (Exception e)
            {
                string message = "Unable to serialize policy to JSON string: " + e.Message;
                throw new ArgumentException(message, e);
            }
        }
Beispiel #10
0
        // Writes a JSON representation of the given DynamoDBEntry
        private static void WriteJson(DynamoDBEntry entry, JsonWriter writer, DynamoDBEntryConversion conversion)
        {
            entry = entry.ToConvertedEntry(conversion);

            var document = entry as Document;
            if (document != null)
            {
                writer.WriteObjectStart();

                // Both item attributes and entries in M type are unordered, so sorting by key
                // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes
                foreach (var kvp in document)
                {
                    var name = kvp.Key;
                    var value = kvp.Value;

                    writer.WritePropertyName(name);
                    WriteJson(value, writer, conversion);
                }
                writer.WriteObjectEnd();
                return;
            }

            var primitive = entry as Primitive;
            if (primitive != null)
            {
                var type = primitive.Type;
                var value = primitive.Value;
                WritePrimitive(writer, type, value);
                return;
            }

            var primitiveList = entry as PrimitiveList;
            if (primitiveList != null)
            {
                var itemType = primitiveList.Type;

                writer.WriteArrayStart();
                foreach (var item in primitiveList.Entries)
                {
                    var itemValue = item.Value;
                    WritePrimitive(writer, itemType, itemValue);
                }
                writer.WriteArrayEnd();
                return;
            }

            var ddbList = entry as DynamoDBList;
            if (ddbList != null)
            {
                writer.WriteArrayStart();
                foreach(var item in ddbList.Entries)
                {
                    WriteJson(item, writer, conversion);
                }
                writer.WriteArrayEnd();
                return;
            }

            var ddbBool = entry as DynamoDBBool;
            if (ddbBool != null)
            {
                writer.Write(ddbBool.Value);
                return;
            }

            var ddbNull = entry as DynamoDBNull;
            if (ddbNull != null)
            {
                writer.Write(null);
                return;
            }

            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                "Unable to convert entry of type {0} to JSON", entry.GetType().FullName));
        }
        private void writeActions(Statement statement, JsonWriter generator)
        {
            IList<ActionIdentifier> actions = statement.Actions;
            if (actions == null || actions.Count == 0)
            {
                return;
            }

            generator.WritePropertyName(JsonDocumentFields.ACTION);
            if (actions.Count > 1)
            {
                generator.WriteArrayStart();
            }

            foreach (ActionIdentifier action in actions)
            {
                generator.Write(action.ActionName);
            }

            if (actions.Count > 1)
            {
                generator.WriteArrayEnd();
            }
        }
        private void WriteArray(JsonWriter writer, Shape array)
        {

            writer.WriteArrayStart();

            var listShape = array.ListShape;
            if (!listShape.IsStructure || !this._tcr.Contains(listShape.Name))
            {
                for (int i = 0; i < array.Name.Length % 5 + 2; i++)
                {
                    Write(writer, listShape);
                }
            }

            writer.WriteArrayEnd();
        }
        private void WriteMap(JsonWriter writer, Shape map)
        {

            writer.WriteObjectStart();

            var mapShape = map.ValueShape;
            if (!mapShape.IsStructure || !this._tcr.Contains(mapShape.Name))
            {
                for (int i = 0; i < map.Name.Length % 5 + 2; i++)
                {
                    writer.WritePropertyName("key" + i);
                    Write(writer, map.ValueShape);
                }
            }

            writer.WriteObjectEnd();
        }
        private void writeResources(Statement statement, JsonWriter generator)
        {
            IList<Resource> resources = statement.Resources;
            if (resources == null || resources.Count == 0)
            {
                return;
            }

            generator.WritePropertyName(JsonDocumentFields.RESOURCE);
            if (resources.Count > 1)
            {
                generator.WriteArrayStart();
            }

            foreach (Resource resource in resources)
            {
                generator.Write(resource.Id);
            }

            if (resources.Count > 1)
            {
                generator.WriteArrayEnd();
            }
        }
Beispiel #15
0
        /// <summary>
        /// Return a JSON represenation of the current metrics
        /// </summary>
        /// <returns></returns>
        public string ToJSON()
        {
            if (!this.IsEnabled)
                return "{ }";

            var sb = new StringBuilder();
            var jw = new JsonWriter(sb);

            jw.WriteObjectStart();
            jw.WritePropertyName("properties");
            jw.WriteObjectStart();
            foreach (var kvp in this.Properties)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                var properties = kvp.Value;
                if (properties.Count > 1)
                    jw.WriteArrayStart();
                foreach (var obj in properties)
                {
                    if (obj == null)
                        jw.Write(null);
                    else
                        jw.Write(obj.ToString());
                }
                if (properties.Count > 1)
                    jw.WriteArrayEnd();
            }
            jw.WriteObjectEnd();
            jw.WritePropertyName("timings");
            jw.WriteObjectStart();
            foreach (var kvp in this.Timings)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                var timings = kvp.Value;
                if (timings.Count > 1)
                    jw.WriteArrayStart();
                foreach (var timing in kvp.Value)
                {
                    if (timing.IsFinished)
                        jw.Write(timing.ElapsedTime.TotalMilliseconds);
                }
                if (timings.Count > 1)
                    jw.WriteArrayEnd();
            }
            jw.WriteObjectEnd();
            jw.WritePropertyName("counters");
            jw.WriteObjectStart();
            foreach (var kvp in this.Counters)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                jw.Write(kvp.Value);
            }
            jw.WriteObjectEnd();
            jw.WriteObjectEnd();
            return sb.ToString();
        }
        /// <summary>
        /// Uses the specified generator to write the JSON data for the principals in
        /// the specified policy statement.
        /// </summary>
        private void writePrincipals(Statement statement, JsonWriter generator)
        {
            IList<Principal> principals = statement.Principals;
            if (principals == null || principals.Count == 0) return;

            generator.WritePropertyName(JsonDocumentFields.PRINCIPAL);
            generator.WriteObjectStart();
            Dictionary<string, List<string>> principalIdsByScheme = new Dictionary<string, List<string>>();
            foreach (Principal p in principals)
            {
                List<string> principalIds;
                if (!principalIdsByScheme.TryGetValue(p.Provider, out principalIds))
                {
                    principalIds = new List<string>();
                    principalIdsByScheme[p.Provider] = principalIds;
                }

                principalIds.Add(p.Id);
            }
            foreach (string scheme in principalIdsByScheme.Keys)
            {
                generator.WritePropertyName(scheme);

                if (principalIdsByScheme[scheme].Count > 1)
                {
                    generator.WriteArrayStart();
                }
                foreach (string principalId in principalIdsByScheme[scheme])
                {
                    generator.Write(principalId);
                }
                if (principalIdsByScheme[scheme].Count > 1)
                {
                    generator.WriteArrayEnd();
                }
            }
            generator.WriteObjectEnd();
        }
 private void writePropertyValue(JsonWriter generator, string propertyName, string value)
 {
     generator.WritePropertyName(propertyName);
     generator.Write(value);
 }
        private void writeConditions(Statement statement, JsonWriter generator)
        {
            IList<Condition> conditions = statement.Conditions;
            if (conditions == null || conditions.Count == 0)
            {
                return;
            }

            /*
             * The condition values must be grouped by all the unique condition types and keys because
             * the values are written out as an array per type and key.
             */
            Dictionary<string, Dictionary<string, List<string>>> conditionsByTypeAndKeys = sortConditionsByTypeAndKey(conditions);

            generator.WritePropertyName(JsonDocumentFields.CONDITION);
            generator.WriteObjectStart();
            foreach (KeyValuePair<string, Dictionary<string, List<string>>> typeEntry in conditionsByTypeAndKeys)
            {
                generator.WritePropertyName(typeEntry.Key);
                generator.WriteObjectStart();
                foreach (KeyValuePair<string, List<string>> keyEntry in typeEntry.Value)
                {
                    IList<string> conditionValues = keyEntry.Value;
                    if (conditionValues.Count == 0)
                        continue;

                    generator.WritePropertyName(keyEntry.Key);

                    if (conditionValues.Count > 1)
                    {
                        generator.WriteArrayStart();
                    }

                    if (conditionValues != null && conditionValues.Count != 0)
                    {
                        foreach (string conditionValue in conditionValues)
                        {
                            generator.Write(conditionValue);
                        }
                    }

                    if (conditionValues.Count > 1)
                    {
                        generator.WriteArrayEnd();
                    }
                }
                generator.WriteObjectEnd();
            }
            generator.WriteObjectEnd();
        }
Beispiel #19
0
        // Write the contents of a Primitive object as JSON data
        private static void WritePrimitive(JsonWriter writer, DynamoDBEntryType type, object value)
        {
            var stringValue = value as string;

            switch (type)
            {
                case DynamoDBEntryType.Numeric:
                    writer.WriteRaw(stringValue);
                    break;
                case DynamoDBEntryType.String:
                    writer.Write(stringValue);
                    break;
                case DynamoDBEntryType.Binary:
                    var bytes = value as byte[];
                    var base64 = Convert.ToBase64String(bytes);
                    writer.Write(base64);
                    break;
                default:
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                        "Unsupport DynamoDBEntryType: {0}", type));
            }
        }
        public void MapAndCompareTest()
    
        {
            var sb = new StringBuilder();
            var writer = new JsonWriter(sb) { PrettyPrint = true };
            string jsonDocument =
@"{
    ""Zero""   : 0,
    ""PInt""   : 2147483647,
    ""NInt""   : -2147483648,
    ""UInt""   : 4294967295,
    ""Long""   : 4294967296,
    ""PLong""  : 9223372036854775807,
    ""NLong""  : -9223372036854775808, 
    ""ULong""  : 18446744073709551615,
    ""Double"" : 0.0,
    ""PDouble"": 1.7976931348623157E+308,
    ""NDouble"": -1.7976931348623157E+308
}";
            JsonData jsonOriginal = JsonMapper.ToObject(jsonDocument);
            JsonMapper.ToJson(jsonOriginal, writer);
            string jsonDcoumentGenerated  = sb.ToString();

            JsonData jsonNew = JsonMapper.ToObject(jsonDcoumentGenerated);

            foreach (string property in jsonOriginal.PropertyNames)
            {
                jsonOriginal[property].Equals(jsonNew[property]);
                Assert.AreEqual(jsonOriginal[property].ToString(), jsonNew[property].ToString());
            }
        }
        private void WriteArray(JsonWriter writer, Shape array)
        {
            writer.WriteArrayStart();

            for (int i = 0; i < array.Name.Length % 5 + 2; i++)
            {
                Write(writer, array.ListShape);
            }

            writer.WriteArrayEnd();
        }
        private void WriteMap(JsonWriter writer, Shape map)
        {
            writer.WriteObjectStart();

            for (int i = 0; i < map.Name.Length % 5 + 2; i++)
            {
                writer.WritePropertyName("key" + i);
                Write(writer, map.ValueShape);
            }

            writer.WriteObjectEnd();
        }