Code refactoring for bpa operator
[icn.git] / cmd / bpa-operator / vendor / k8s.io / client-go / rest / watch / encoder.go
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8     http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package versioned
18
19 import (
20         "encoding/json"
21
22         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23         "k8s.io/apimachinery/pkg/runtime"
24         "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
25         "k8s.io/apimachinery/pkg/watch"
26 )
27
28 // Encoder serializes watch.Events into io.Writer. The internal objects
29 // are encoded using embedded encoder, and the outer Event is serialized
30 // using encoder.
31 // TODO: this type is only used by tests
32 type Encoder struct {
33         encoder         streaming.Encoder
34         embeddedEncoder runtime.Encoder
35 }
36
37 func NewEncoder(encoder streaming.Encoder, embeddedEncoder runtime.Encoder) *Encoder {
38         return &Encoder{
39                 encoder:         encoder,
40                 embeddedEncoder: embeddedEncoder,
41         }
42 }
43
44 // Encode writes an event to the writer. Returns an error
45 // if the writer is closed or an object can't be encoded.
46 func (e *Encoder) Encode(event *watch.Event) error {
47         data, err := runtime.Encode(e.embeddedEncoder, event.Object)
48         if err != nil {
49                 return err
50         }
51         // FIXME: get rid of json.RawMessage.
52         return e.encoder.Encode(&metav1.WatchEvent{
53                 Type:   string(event.Type),
54                 Object: runtime.RawExtension{Raw: json.RawMessage(data)},
55         })
56 }