1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31#include <google/protobuf/util/json_util.h>
32
33#include <google/protobuf/stubs/common.h>
34#include <google/protobuf/io/coded_stream.h>
35#include <google/protobuf/io/zero_copy_stream.h>
36#include <google/protobuf/util/internal/default_value_objectwriter.h>
37#include <google/protobuf/util/internal/error_listener.h>
38#include <google/protobuf/util/internal/json_objectwriter.h>
39#include <google/protobuf/util/internal/json_stream_parser.h>
40#include <google/protobuf/util/internal/protostream_objectsource.h>
41#include <google/protobuf/util/internal/protostream_objectwriter.h>
42#include <google/protobuf/util/type_resolver.h>
43#include <google/protobuf/util/type_resolver_util.h>
44#include <google/protobuf/stubs/bytestream.h>
45#include <google/protobuf/stubs/status_macros.h>
46
47namespace google {
48namespace protobuf {
49namespace util {
50
51namespace internal {
52void ZeroCopyStreamByteSink::Append(const char* bytes, size_t len) {
53  while (len > 0) {
54    void* buffer;
55    int length;
56    if (!stream_->Next(&buffer, &length)) {
57      // There isn't a way for ByteSink to report errors.
58      return;
59    }
60    if (len < length) {
61      memcpy(buffer, bytes, len);
62      stream_->BackUp(length - len);
63      break;
64    } else {
65      memcpy(buffer, bytes, length);
66      bytes += length;
67      len -= length;
68    }
69  }
70}
71}  // namespace internal
72
73util::Status BinaryToJsonStream(TypeResolver* resolver,
74                                  const string& type_url,
75                                  io::ZeroCopyInputStream* binary_input,
76                                  io::ZeroCopyOutputStream* json_output,
77                                  const JsonOptions& options) {
78  io::CodedInputStream in_stream(binary_input);
79  google::protobuf::Type type;
80  RETURN_IF_ERROR(resolver->ResolveMessageType(type_url, &type));
81  converter::ProtoStreamObjectSource proto_source(&in_stream, resolver, type);
82  io::CodedOutputStream out_stream(json_output);
83  converter::JsonObjectWriter json_writer(options.add_whitespace ? " " : "",
84                                          &out_stream);
85  if (options.always_print_primitive_fields) {
86    converter::DefaultValueObjectWriter default_value_writer(
87        resolver, type, &json_writer);
88    return proto_source.WriteTo(&default_value_writer);
89  } else {
90    return proto_source.WriteTo(&json_writer);
91  }
92}
93
94util::Status BinaryToJsonString(TypeResolver* resolver,
95                                  const string& type_url,
96                                  const string& binary_input,
97                                  string* json_output,
98                                  const JsonOptions& options) {
99  io::ArrayInputStream input_stream(binary_input.data(), binary_input.size());
100  io::StringOutputStream output_stream(json_output);
101  return BinaryToJsonStream(resolver, type_url, &input_stream, &output_stream,
102                            options);
103}
104
105namespace {
106class StatusErrorListener : public converter::ErrorListener {
107 public:
108  StatusErrorListener() : status_(util::Status::OK) {}
109  virtual ~StatusErrorListener() {}
110
111  util::Status GetStatus() { return status_; }
112
113  virtual void InvalidName(const converter::LocationTrackerInterface& loc,
114                           StringPiece unknown_name, StringPiece message) {
115    status_ = util::Status(util::error::INVALID_ARGUMENT,
116                             loc.ToString() + ": " + message.ToString());
117  }
118
119  virtual void InvalidValue(const converter::LocationTrackerInterface& loc,
120                            StringPiece type_name, StringPiece value) {
121    status_ =
122        util::Status(util::error::INVALID_ARGUMENT,
123                       loc.ToString() + ": invalid value " + value.ToString() +
124                           " for type " + type_name.ToString());
125  }
126
127  virtual void MissingField(const converter::LocationTrackerInterface& loc,
128                            StringPiece missing_name) {
129    status_ = util::Status(
130        util::error::INVALID_ARGUMENT,
131        loc.ToString() + ": missing field " + missing_name.ToString());
132  }
133
134 private:
135  util::Status status_;
136
137  GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StatusErrorListener);
138};
139}  // namespace
140
141util::Status JsonToBinaryStream(TypeResolver* resolver,
142                                  const string& type_url,
143                                  io::ZeroCopyInputStream* json_input,
144                                  io::ZeroCopyOutputStream* binary_output) {
145  google::protobuf::Type type;
146  RETURN_IF_ERROR(resolver->ResolveMessageType(type_url, &type));
147  internal::ZeroCopyStreamByteSink sink(binary_output);
148  StatusErrorListener listener;
149  converter::ProtoStreamObjectWriter proto_writer(resolver, type, &sink,
150                                                  &listener);
151
152  converter::JsonStreamParser parser(&proto_writer);
153  const void* buffer;
154  int length;
155  while (json_input->Next(&buffer, &length)) {
156    if (length == 0) continue;
157    RETURN_IF_ERROR(
158        parser.Parse(StringPiece(static_cast<const char*>(buffer), length)));
159  }
160  RETURN_IF_ERROR(parser.FinishParse());
161
162  return listener.GetStatus();
163}
164
165util::Status JsonToBinaryString(TypeResolver* resolver,
166                                  const string& type_url,
167                                  const string& json_input,
168                                  string* binary_output) {
169  io::ArrayInputStream input_stream(json_input.data(), json_input.size());
170  io::StringOutputStream output_stream(binary_output);
171  return JsonToBinaryStream(resolver, type_url, &input_stream, &output_stream);
172}
173
174}  // namespace util
175}  // namespace protobuf
176}  // namespace google
177