1 #region Copyright notice and license
2 // Protocol Buffers - Google's data interchange format
3 // Copyright 2016 Google Inc.  All rights reserved.
4 // https://developers.google.com/protocol-buffers/
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 //     * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 //     * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 //     * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #endregion
32 
33 using System;
34 using System.Collections;
35 using System.Collections.Generic;
36 using System.IO;
37 using System.Linq;
38 using System.Text;
39 
40 namespace Google.Protobuf.WellKnownTypes
41 {
42     // Manually-written partial class for the FieldMask well-known type.
43     public partial class FieldMask : ICustomDiagnosticMessage
44     {
45         /// <summary>
46         /// Converts a timestamp  specified in seconds/nanoseconds to a string.
47         /// </summary>
48         /// <remarks>
49         /// If the value is a normalized duration in the range described in <c>field_mask.proto</c>,
50         /// <paramref name="diagnosticOnly"/> is ignored. Otherwise, if the parameter is <c>true</c>,
51         /// a JSON object with a warning is returned; if it is <c>false</c>, an <see cref="InvalidOperationException"/> is thrown.
52         /// </remarks>
53         /// <param name="paths">Paths in the field mask</param>
54         /// <param name="diagnosticOnly">Determines the handling of non-normalized values</param>
55         /// <exception cref="InvalidOperationException">The represented duration is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception>
ToJson(IList<string> paths, bool diagnosticOnly)56         internal static string ToJson(IList<string> paths, bool diagnosticOnly)
57         {
58             var firstInvalid = paths.FirstOrDefault(p => !ValidatePath(p));
59             if (firstInvalid == null)
60             {
61                 var writer = new StringWriter();
62 #if DOTNET35
63                 var query = paths.Select(JsonFormatter.ToCamelCase);
64                 JsonFormatter.WriteString(writer, string.Join(",", query.ToArray()));
65 #else
66                 JsonFormatter.WriteString(writer, string.Join(",", paths.Select(JsonFormatter.ToCamelCase)));
67 #endif
68                 return writer.ToString();
69             }
70             else
71             {
72                 if (diagnosticOnly)
73                 {
74                     var writer = new StringWriter();
75                     writer.Write("{ \"@warning\": \"Invalid FieldMask\", \"paths\": ");
76                     JsonFormatter.Default.WriteList(writer, (IList)paths);
77                     writer.Write(" }");
78                     return writer.ToString();
79                 }
80                 else
81                 {
82                     throw new InvalidOperationException($"Invalid field mask to be converted to JSON: {firstInvalid}");
83                 }
84             }
85         }
86 
87         /// <summary>
88         /// Camel-case converter with added strictness for field mask formatting.
89         /// </summary>
90         /// <exception cref="InvalidOperationException">The field mask is invalid for JSON representation</exception>
ValidatePath(string input)91         private static bool ValidatePath(string input)
92         {
93             for (int i = 0; i < input.Length; i++)
94             {
95                 char c = input[i];
96                 if (c >= 'A' && c <= 'Z')
97                 {
98                     return false;
99                 }
100                 if (c == '_' && i < input.Length - 1)
101                 {
102                     char next = input[i + 1];
103                     if (next < 'a' || next > 'z')
104                     {
105                         return false;
106                     }
107                 }
108             }
109             return true;
110         }
111 
112         /// <summary>
113         /// Returns a string representation of this <see cref="FieldMask"/> for diagnostic purposes.
114         /// </summary>
115         /// <remarks>
116         /// Normally the returned value will be a JSON string value (including leading and trailing quotes) but
117         /// when the value is non-normalized or out of range, a JSON object representation will be returned
118         /// instead, including a warning. This is to avoid exceptions being thrown when trying to
119         /// diagnose problems - the regular JSON formatter will still throw an exception for non-normalized
120         /// values.
121         /// </remarks>
122         /// <returns>A string representation of this value.</returns>
ToDiagnosticString()123         public string ToDiagnosticString()
124         {
125             return ToJson(Paths, true);
126         }
127     }
128 }
129