github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/watch/json/decoder.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors All rights reserved.
     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 json
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  
    24  	"k8s.io/kubernetes/pkg/runtime"
    25  	"k8s.io/kubernetes/pkg/watch"
    26  )
    27  
    28  // Decoder implements the watch.Decoder interface for io.ReadClosers that
    29  // have contents which consist of a series of watchEvent objects encoded via JSON.
    30  // It will decode any object registered in the supplied codec.
    31  type Decoder struct {
    32  	r       io.ReadCloser
    33  	decoder *json.Decoder
    34  	codec   runtime.Codec
    35  }
    36  
    37  // NewDecoder creates an Decoder for the given writer and codec.
    38  func NewDecoder(r io.ReadCloser, codec runtime.Codec) *Decoder {
    39  	return &Decoder{
    40  		r:       r,
    41  		decoder: json.NewDecoder(r),
    42  		codec:   codec,
    43  	}
    44  }
    45  
    46  // Decode blocks until it can return the next object in the writer. Returns an error
    47  // if the writer is closed or an object can't be decoded.
    48  func (d *Decoder) Decode() (watch.EventType, runtime.Object, error) {
    49  	var got WatchEvent
    50  	if err := d.decoder.Decode(&got); err != nil {
    51  		return "", nil, err
    52  	}
    53  	switch got.Type {
    54  	case watch.Added, watch.Modified, watch.Deleted, watch.Error:
    55  	default:
    56  		return "", nil, fmt.Errorf("got invalid watch event type: %v", got.Type)
    57  	}
    58  
    59  	obj, err := d.codec.Decode(got.Object.RawJSON)
    60  	if err != nil {
    61  		return "", nil, fmt.Errorf("unable to decode watch event: %v", err)
    62  	}
    63  	return got.Type, obj, nil
    64  }
    65  
    66  // Close closes the underlying r.
    67  func (d *Decoder) Close() {
    68  	d.r.Close()
    69  }