<commit_before>package minify // import "github.com/tdewolff/minify"

import (
	"io"
	"io/ioutil"
	"math"
	"math/rand"
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
)

func assertDataURI(t *testing.T, m Minifier, s, e string) {
	assert.Equal(t, e, string(DataURI(m, []byte(s))), "data URIs must match")
}

func assertNumber(t *testing.T, x, e string) {
	assert.Equal(t, e, string(Number([]byte(x))), "numbers must match in "+x)
}

func assertLenInt(t *testing.T, x int64) {
	e := 1
	if x != 0 {
		e = int(math.Log10(math.Abs(float64(x)))) + 1
	}
	assert.Equal(t, e, lenInt64(int64(x)), "number lengths must match for "+strconv.FormatInt(x, 10))
}

////////////////////////////////////////////////////////////////

func TestContentType(t *testing.T) {
	assert.Equal(t, "text/html", string(ContentType([]byte("text/html"))))
	assert.Equal(t, "text/html;charset=utf-8", string(ContentType([]byte("text/html; charset=UTF-8"))))
	assert.Equal(t, "text/html;charset=utf-8;param=\" ; \"", string(ContentType([]byte("text/html; charset=UTF-8 ; param = \" ; \""))))
	assert.Equal(t, "text/html,text/css", string(ContentType([]byte("text/html, text/css"))))
}

func TestDataURI(t *testing.T) {
	m := New()
	m.AddFunc("text/x", func(m Minifier, mediatype string, w io.Writer, r io.Reader) error {
		b, _ := ioutil.ReadAll(r)
		assert.Equal(t, "<?x?>", string(b))
		w.Write(b)
		return nil
	})
	assertDataURI(t, m, "data:text/x,<?x?>", "data:text/x,%3C%3Fx%3F%3E")
	assertDataURI(t, m, "data:,text", "data:,text")
	assertDataURI(t, m, "data:;base64,dGV4dA==", "data:,text")
	assertDataURI(t, m, "data:text/svg+xml;base64,PT09PT09", "data:text/svg+xml;base64,PT09PT09")
	assertDataURI(t, m, "data:text/xml;version=2.0,content", "data:text/xml;version=2.0,content")
	assertDataURI(t, m, "data:text/xml; version = 2.0,content", "data:text/xml;version=2.0,content")
	assertDataURI(t, m, "data:,=====", "data:,%3D%3D%3D%3D%3D")
	assertDataURI(t, m, "data:,======", "data:;base64,PT09PT09")
}

func TestNumber(t *testing.T) {
	assertNumber(t, "0", "0")
	assertNumber(t, ".0", "0")
	assertNumber(t, "1.0", "1")
	assertNumber(t, "0.1", ".1")
	assertNumber(t, "+1", "1")
	assertNumber(t, "-1", "-1")
	assertNumber(t, "-0.1", "-.1")
	assertNumber(t, "100", "100")
	assertNumber(t, "1000", "1e3")
	assertNumber(t, "0.001", ".001")
	assertNumber(t, "0.0001", "1e-4")
	assertNumber(t, "100e1", "1e3")
	assertNumber(t, "1.1e+1", "11")
	assertNumber(t, "0.252", ".252")
	assertNumber(t, "1.252", "1.252")
	assertNumber(t, "-1.252", "-1.252")
	assertNumber(t, "0.075", ".075")
	assertNumber(t, "789012345678901234567890123456789e9234567890123456789", "789012345678901234567890123456789e9234567890123456789")
	assertNumber(t, ".000100009", "100009e-9")
	assertNumber(t, ".0001000009", ".0001000009")
	assertNumber(t, ".0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009", ".0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009")
	assertNumber(t, "E\x1f", "E\x1f") // fuzz
	//assertNumber(t, "96px", "1in")
}

func TestLenInt(t *testing.T) {
	assertLenInt(t, 0)
	assertLenInt(t, 1)
	assertLenInt(t, 10)
	assertLenInt(t, 99)
}

////////////////

var num []int64

func RandNumBytes() []byte {
	b := []byte{}
	n := rand.Int() % 10
	for i := 0; i < n; i++ {
		b = append(b, byte(rand.Int()%10)+'0')
	}
	if rand.Int()%2 == 0 {
		b = append(b, '.')
		n = rand.Int() % 10
		for i := 0; i < n; i++ {
			b = append(b, byte(rand.Int()%10)+'0')
		}
	}
	if rand.Int()%2 == 0 {
		b = append(b, 'e')
		if rand.Int()%2 == 0 {
			b = append(b, '-')
		}
		n = rand.Int() % 5
		for i := 0; i < n; i++ {
			b = append(b, byte(rand.Int()%10)+'0')
		}
	}
	return b
}

func TestMain(t *testing.T) {
	for j := 0; j < 1000; j++ {
		num = append(num, rand.Int63n(1000))
	}
}

func BenchmarkLenIntLog(b *testing.B) {
	n := 0
	for i := 0; i < b.N; i++ {
		for j := 0; j < 1000; j++ {
			n += int(math.Log10(math.Abs(float64(num[j])))) + 1
		}
	}
}

func BenchmarkLenIntSwitch(b *testing.B) {
	n := 0
	for i := 0; i < b.N; i++ {
		for j := 0; j < 1000; j++ {
			n += lenInt64(num[j])
		}
	}
}

func BenchmarkNumber(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Number(RandNumBytes())
	}
}
<commit_msg>Fix test<commit_after>package minify // import "github.com/tdewolff/minify"

import (
	"io"
	"io/ioutil"
	"math"
	"math/rand"
	"strconv"
	"testing"

	"github.com/stretchr/testify/assert"
)

func assertDataURI(t *testing.T, m Minifier, s, e string) {
	assert.Equal(t, e, string(DataURI(m, []byte(s))), "data URIs must match")
}

func assertNumber(t *testing.T, x, e string) {
	assert.Equal(t, e, string(Number([]byte(x))), "numbers must match in "+x)
}

func assertLenInt(t *testing.T, x int64) {
	e := 1
	if x != 0 {
		e = int(math.Log10(math.Abs(float64(x)))) + 1
	}
	assert.Equal(t, e, lenInt64(int64(x)), "number lengths must match for "+strconv.FormatInt(x, 10))
}

////////////////////////////////////////////////////////////////

func TestContentType(t *testing.T) {
	assert.Equal(t, "text/html", string(ContentType([]byte("text/html"))))
	assert.Equal(t, "text/html;charset=utf-8", string(ContentType([]byte("text/html; charset=UTF-8"))))
	assert.Equal(t, "text/html;charset=utf-8;param=\" ; \"", string(ContentType([]byte("text/html; charset=UTF-8 ; param = \" ; \""))))
	assert.Equal(t, "text/html,text/css", string(ContentType([]byte("text/html, text/css"))))
}

func TestDataURI(t *testing.T) {
	m := New()
	m.AddFunc("text/x", func(m Minifier, mediatype string, w io.Writer, r io.Reader) error {
		b, _ := ioutil.ReadAll(r)
		assert.Equal(t, "<?x?>", string(b))
		w.Write(b)
		return nil
	})
	assertDataURI(t, m, "data:text/x,<?x?>", "data:text/x,%3C%3Fx%3F%3E")
	assertDataURI(t, m, "data:,text", "data:,text")
	assertDataURI(t, m, "data:;base64,dGV4dA==", "data:,text")
	assertDataURI(t, m, "data:text/svg+xml;base64,PT09PT09", "data:text/svg+xml;base64,PT09PT09")
	assertDataURI(t, m, "data:text/xml;version=2.0,content", "data:text/xml;version=2.0,content")
	assertDataURI(t, m, "data:text/xml; version = 2.0,content", "data:text/xml;version=2.0,content")
	assertDataURI(t, m, "data:,=====", "data:,%3D%3D%3D%3D%3D")
	assertDataURI(t, m, "data:,======", "data:;base64,PT09PT09")
}

func TestNumber(t *testing.T) {
	assertNumber(t, "0", "0")
	assertNumber(t, ".0", "0")
	assertNumber(t, "1.0", "1")
	assertNumber(t, "0.1", ".1")
	assertNumber(t, "+1", "1")
	assertNumber(t, "-1", "-1")
	assertNumber(t, "-0.1", "-.1")
	assertNumber(t, "100", "100")
	assertNumber(t, "1000", "1e3")
	assertNumber(t, "0.001", ".001")
	assertNumber(t, "0.0001", "1e-4")
	assertNumber(t, "100e1", "1e3")
	assertNumber(t, "1.1e+1", "11")
	assertNumber(t, "0.252", ".252")
	assertNumber(t, "1.252", "1.252")
	assertNumber(t, "-1.252", "-1.252")
	assertNumber(t, "0.075", ".075")
	assertNumber(t, "789012345678901234567890123456789e9234567890123456789", "789012345678901234567890123456789e9234567890123456789")
	assertNumber(t, ".000100009", "100009e-9")
	assertNumber(t, ".0001000009", ".0001000009")
	assertNumber(t, ".0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009", ".0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009")
	assertNumber(t, "E\x1f", "") // fuzz
	//assertNumber(t, "96px", "1in")
}

func TestLenInt(t *testing.T) {
	assertLenInt(t, 0)
	assertLenInt(t, 1)
	assertLenInt(t, 10)
	assertLenInt(t, 99)
}

////////////////

var num []int64

func RandNumBytes() []byte {
	b := []byte{}
	n := rand.Int() % 10
	for i := 0; i < n; i++ {
		b = append(b, byte(rand.Int()%10)+'0')
	}
	if rand.Int()%2 == 0 {
		b = append(b, '.')
		n = rand.Int() % 10
		for i := 0; i < n; i++ {
			b = append(b, byte(rand.Int()%10)+'0')
		}
	}
	if rand.Int()%2 == 0 {
		b = append(b, 'e')
		if rand.Int()%2 == 0 {
			b = append(b, '-')
		}
		n = rand.Int() % 5
		for i := 0; i < n; i++ {
			b = append(b, byte(rand.Int()%10)+'0')
		}
	}
	return b
}

func TestMain(t *testing.T) {
	for j := 0; j < 1000; j++ {
		num = append(num, rand.Int63n(1000))
	}
}

func BenchmarkLenIntLog(b *testing.B) {
	n := 0
	for i := 0; i < b.N; i++ {
		for j := 0; j < 1000; j++ {
			n += int(math.Log10(math.Abs(float64(num[j])))) + 1
		}
	}
}

func BenchmarkLenIntSwitch(b *testing.B) {
	n := 0
	for i := 0; i < b.N; i++ {
		for j := 0; j < 1000; j++ {
			n += lenInt64(num[j])
		}
	}
}

func BenchmarkNumber(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Number(RandNumBytes())
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"

	"github.com/Sirupsen/logrus"
	log "github.com/cihub/seelog"
	"github.com/stampzilla/gozwave"
	"github.com/stampzilla/gozwave/events"
	"github.com/stampzilla/stampzilla-go/nodes/basenode"
	"github.com/stampzilla/stampzilla-go/pkg/notifier"
	"github.com/stampzilla/stampzilla-go/protocol"
)

var VERSION string = "dev"
var BUILD_DATE string = ""

// MAIN - This is run when the init function is done

var notify *notifier.Notify

func main() {
	log.Info("Starting ZWAVE node")

	debug := flag.Bool("v", false, "Verbose - show more debuging info")

	// Parse all commandline arguments, host and port parameters are added in the basenode init function
	flag.Parse()
	logrus.SetLevel(logrus.WarnLevel)
	if *debug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	//Get a config with the correct parameters
	config := basenode.NewConfig()

	//Activate the config
	basenode.SetConfig(config)

	z, err := gozwave.Connect("/dev/ttyACM0", "zwave-networkmap.json")
	if err != nil {
		log.Error(err)
		return
	}

	node := protocol.NewNode("zwave")
	node.Version = VERSION
	node.BuildDate = BUILD_DATE

	//Start communication with the server
	connection := basenode.Connect()
	notify = notifier.New(connection)
	notify.SetSource(node)

	// Thit worker keeps track on our connection state, if we are connected or not
	go monitorState(node, connection)

	node.AddElement(&protocol.Element{
		Type: protocol.ElementTypeButton,
		Name: "Up",
		Command: &protocol.Command{
			Cmd:  "blinds",
			Args: []string{"0"},
		},
	})
	node.AddElement(&protocol.Element{
		Type: protocol.ElementTypeButton,
		Name: "Down",
		Command: &protocol.Command{
			Cmd:  "blinds",
			Args: []string{"1"},
		},
	})

	state := NewState()
	node.SetState(state)
	state.zwave = z

	// This worker recives all incomming commands
	go serverRecv(node, connection)

	//state.Nodes, _ = z.GetNodes()
	//connection.Send(node.Node())

	for {
		select {
		case event := <-z.GetNextEvent():
			log.Infof("Event: %#v", event)
			switch e := event.(type) {
			case events.NodeDiscoverd:
				log.Infof("%#v", z.Nodes.Get(e.Address))
				state.Nodes = append(state.Nodes, z.Nodes.Get(e.Address))
			}

			connection.Send(node.Node())
		}
	}
}

// WORKER that monitors the current connection state
func monitorState(node *protocol.Node, connection basenode.Connection) {
	for s := range connection.State() {
		switch s {
		case basenode.ConnectionStateConnected:
			connection.Send(node.Node())
		case basenode.ConnectionStateDisconnected:
		}
	}
}

// WORKER that recives all incomming commands
func serverRecv(node *protocol.Node, connection basenode.Connection) {
	for d := range connection.Receive() {
		processCommand(node, connection, d)
	}
}

// THis is called on each incomming command
func processCommand(node *protocol.Node, connection basenode.Connection, cmd protocol.Command) {
	if s, ok := node.State().(*State); ok {
		log.Infof("Incoming command from server: %#v \n", cmd, s)
		if len(cmd.Args) == 0 {
			return
		}

		switch cmd.Cmd {
		case "blinds":

			//rollup := switchbinary.New().SetNode(2)

			//if cmd.Args[0] == "1" {
			//	rollup.SetValue(true)
			//}

			//<-s.zwave.Send(rollup) // Stop previous motion
			//<-time.After(time.Millisecond * 200)
			//<-s.zwave.Send(rollup) // Start up
			//connection.Send(node.Node())
		}
	}
}
<commit_msg>trying to get binary switch to work<commit_after>package main

import (
	"flag"
	"strconv"
	"time"

	"github.com/Sirupsen/logrus"
	log "github.com/cihub/seelog"
	"github.com/stampzilla/gozwave"
	"github.com/stampzilla/gozwave/commands"
	"github.com/stampzilla/gozwave/events"
	"github.com/stampzilla/stampzilla-go/nodes/basenode"
	"github.com/stampzilla/stampzilla-go/pkg/notifier"
	"github.com/stampzilla/stampzilla-go/protocol"
)

var VERSION string = "dev"
var BUILD_DATE string = ""

// MAIN - This is run when the init function is done

var notify *notifier.Notify

func main() {
	log.Info("Starting ZWAVE node")

	debug := flag.Bool("v", false, "Verbose - show more debuging info")

	// Parse all commandline arguments, host and port parameters are added in the basenode init function
	flag.Parse()
	logrus.SetLevel(logrus.WarnLevel)
	if *debug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	//Get a config with the correct parameters
	config := basenode.NewConfig()

	//Activate the config
	basenode.SetConfig(config)

	z, err := gozwave.Connect("/dev/ttyACM0", "zwave-networkmap.json")
	if err != nil {
		log.Error(err)
		return
	}

	node := protocol.NewNode("zwave")
	node.Version = VERSION
	node.BuildDate = BUILD_DATE

	//Start communication with the server
	connection := basenode.Connect()
	notify = notifier.New(connection)
	notify.SetSource(node)

	// Thit worker keeps track on our connection state, if we are connected or not
	go monitorState(node, connection)

	node.AddElement(&protocol.Element{
		Type: protocol.ElementTypeButton,
		Name: "Up",
		Command: &protocol.Command{
			Cmd:  "blinds",
			Args: []string{"0"},
		},
	})
	node.AddElement(&protocol.Element{
		Type: protocol.ElementTypeButton,
		Name: "Down",
		Command: &protocol.Command{
			Cmd:  "blinds",
			Args: []string{"1"},
		},
	})

	state := NewState()
	node.SetState(state)
	state.zwave = z

	// This worker recives all incomming commands
	go serverRecv(node, connection)

	//state.Nodes, _ = z.GetNodes()
	//connection.Send(node.Node())

	for {
		select {
		case event := <-z.GetNextEvent():
			log.Infof("Event: %#v", event)
			switch e := event.(type) {
			case events.NodeDiscoverd:
				log.Infof("%#v", z.Nodes.Get(e.Address))
				state.Nodes = append(state.Nodes, z.Nodes.Get(e.Address))
			}

			connection.Send(node.Node())
		}
	}
}

// WORKER that monitors the current connection state
func monitorState(node *protocol.Node, connection basenode.Connection) {
	for s := range connection.State() {
		switch s {
		case basenode.ConnectionStateConnected:
			connection.Send(node.Node())
		case basenode.ConnectionStateDisconnected:
		}
	}
}

// WORKER that recives all incomming commands
func serverRecv(node *protocol.Node, connection basenode.Connection) {
	for d := range connection.Receive() {
		processCommand(node, connection, d)
	}
}

// THis is called on each incomming command
func processCommand(node *protocol.Node, connection basenode.Connection, cmd protocol.Command) {
	if s, ok := node.State().(*State); ok {
		log.Infof("Incoming command from server: %#v \n", cmd, s)
		if len(cmd.Args) == 0 {
			return
		}

		id, err := strconv.Atoi(cmd.Args[0])
		if err != nil {
			log.Error(err)
			return
		}

		//device := s.zwave.Nodes.Get(byte(id))

		switch cmd.Cmd {
		case "on":
			//TODO SwitchBinary not working yet :(
			cmd := commands.NewSwitchBinary()
			cmd.SetValue(true)
			cmd.SetNode(byte(id))
			s.zwave.Connection.Send(cmd, time.Second)
		case "off":
			cmd := commands.NewSwitchBinary()
			cmd.SetValue(false)
			cmd.SetNode(byte(id))
			s.zwave.Connection.Send(cmd, time.Second)
		case "blinds":

			//rollup := switchbinary.New().SetNode(2)

			//if cmd.Args[0] == "1" {
			//	rollup.SetValue(true)
			//}

			//<-s.zwave.Send(rollup) // Stop previous motion
			//<-time.After(time.Millisecond * 200)
			//<-s.zwave.Send(rollup) // Start up
			//connection.Send(node.Node())
		}
	}
}
<|endoftext|>


<commit_before>package tmwire

import (
	"bytes"
	"github.com/stretchr/testify/assert"
	"github.com/tendermint/go-wire/nowriter/tmdecoding"
	"github.com/tendermint/go-wire/nowriter/tmencoding"
	"github.com/tendermint/go-wire/nowriter/tmlegacy"
	"testing"
)

var legacy = tmlegacy.TMEncoderLegacy{}
var pure = tmencoding.TMEncoderPure{}
var dec = tmdecoding.TMDecoderPure{}

func TestByte(t *testing.T) {
	for i := 0; i < 256; i += 1 {
		x0 := byte(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteOctet(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeOctet(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeOctet(b1)
		if b3 != x0 {
			t.Fatalf("Decoded bytes do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct")
		}
		assert.Nil(t, err3)
	}
}

func TestUint16(t *testing.T) {
	for i := 0; i < 0x10000; i += 1 {
		x0 := uint16(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint16(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint16(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint16(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint16 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestUint32(t *testing.T) {
	totry := [5]uint32{0, 1, 0x7FFFFFFE, 0x7FFFFFFF, 0xFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := uint32(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint32(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint32(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint32(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint32 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestUint64(t *testing.T) {
	totry := [5]uint64{0, 1, 0x7FFFFFFFFFFFFFFE, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := uint64(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint64(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint64(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint64(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint64 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt8(t *testing.T) {
	for i := -0x80; i < 0x80; i += 1 {
		x0 := int8(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt8(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt8(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt8(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int8 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt16(t *testing.T) {
	for i := -0x8000; i < 0x8000; i += 1 {
		x0 := int16(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt16(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt16(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt16(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int16 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt32(t *testing.T) {
	totry := [7]int32{-0x80000000, -0x7FFFFFFF, -1, 0, 1,
		0x7FFFFFFE, 0x7FFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := int32(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt32(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt32(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt32(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int32 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}
func TestInt64(t *testing.T) {
	totry := [7]int64{-0x8000000000000000, -0x7FFFFFFFFFFFFFFF, -1, 0, 1,
		0x7FFFFFFFFFFFFFFE, 0x7FFFFFFFFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := int64(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt64(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt64(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt64(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int64 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}
<commit_msg>add broken tests<commit_after>package tmwire

import (
	"bytes"
	"testing"

	"github.com/stretchr/testify/assert"

	cmn "github.com/tendermint/tmlibs/common"

	"github.com/tendermint/go-wire/nowriter/tmdecoding"
	"github.com/tendermint/go-wire/nowriter/tmencoding"
	"github.com/tendermint/go-wire/nowriter/tmlegacy"
)

var legacy = tmlegacy.TMEncoderLegacy{}
var pure = tmencoding.TMEncoderPure{}
var dec = tmdecoding.TMDecoderPure{}

func TestByte(t *testing.T) {
	for i := 0; i < 256; i += 1 {
		x0 := byte(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteOctet(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeOctet(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeOctet(b1)
		if b3 != x0 {
			t.Fatalf("Decoded bytes do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct")
		}
		assert.Nil(t, err3)
	}
}

func TestBytes(t *testing.T) {
	cases := []int{1, 40, 255, 256, 257, 65530, 65535, 65536, 65537}

	for _, l0 := range cases {
		x0 := cmn.RandBytes(l0)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteOctetSlice(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeOctets(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeOctets(b1)
		if !bytes.Equal(b3, x0) {
			t.Fatalf("Decoded bytes do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct")
		}
		assert.Nil(t, err3)
	}
}

func TestUint16(t *testing.T) {
	for i := 0; i < 0x10000; i += 1 {
		x0 := uint16(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint16(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint16(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint16(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint16 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestUint16s(t *testing.T) {
	// This should panic on 32-bit machine
	/*
		countBytes := []byte{0xff, 0xff, 0xff, 0xff}
		count := binary.BigEndian.Uint32(countBytes)
		fmt.Println(count, int32(count))
		size := int(2 * count)
		x0 := make([]byte, size+4)
		copy(x0[:4], countBytes)
		dec.DecodeUint16s(x0)
	*/
	x0 := []uint16{0xff, 0xffff, 0xabcd, 0xdabc}
	buf1 := new(bytes.Buffer)
	n1, err1 := new(int), new(error)
	legacy.WriteUint16s(x0, buf1, n1, err1)
	b1 := buf1.Bytes()
	b2 := pure.EncodeUint16s(x0)
	if !bytes.Equal(b1, b2) {
		t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
	}
	b3, n3, err3 := dec.DecodeUint16s(b1)
	for i := range b3 {
		if x0[i] != b3[i] {
			t.Fatalf("Decoded Uint16 do not match for %#v and %#v", b3, x0)
		}
	}
	if n3 != *n1 {
		t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
	}
	assert.Nil(t, err3)
}

func TestUint32(t *testing.T) {
	totry := [5]uint32{0, 1, 0x7FFFFFFE, 0x7FFFFFFF, 0xFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := uint32(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint32(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint32(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint32(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint32 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestUint64(t *testing.T) {
	totry := [5]uint64{0, 1, 0x7FFFFFFFFFFFFFFE, 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := uint64(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteUint64(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeUint64(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeUint64(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Uint64 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt8(t *testing.T) {
	for i := -0x80; i < 0x80; i += 1 {
		x0 := int8(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt8(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt8(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt8(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int8 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt16(t *testing.T) {
	for i := -0x8000; i < 0x8000; i += 1 {
		x0 := int16(i)
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt16(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt16(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt16(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int16 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}

func TestInt32(t *testing.T) {
	totry := [7]int32{-0x80000000, -0x7FFFFFFF, -1, 0, 1,
		0x7FFFFFFE, 0x7FFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := int32(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt32(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt32(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt32(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int32 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}
func TestInt64(t *testing.T) {
	totry := [7]int64{-0x8000000000000000, -0x7FFFFFFFFFFFFFFF, -1, 0, 1,
		0x7FFFFFFFFFFFFFFE, 0x7FFFFFFFFFFFFFFF}
	for i := 0; i < len(totry); i += 1 {
		x0 := int64(totry[i])
		buf1 := new(bytes.Buffer)
		n1, err1 := new(int), new(error)
		legacy.WriteInt64(x0, buf1, n1, err1)
		b1 := buf1.Bytes()
		b2 := pure.EncodeInt64(x0)
		if !bytes.Equal(b1, b2) {
			t.Fatalf("Bytes do not match for %#v and %#v", b1, b2)
		}
		b3, n3, err3 := dec.DecodeInt64(b1)
		if b3 != x0 {
			t.Fatalf("Decoded Int64 do not match for %#v and %#v", b3, x0)
		}
		if n3 != *n1 {
			t.Fatalf("Decoded byte count is not correct: %d and %d", n3, *n1)
		}
		assert.Nil(t, err3)
	}
}
<|endoftext|>


<commit_before>package imagecommands

import (
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/fatih/structs"
	"github.com/jrperritt/gophercloud/rackspace/compute/v2/images"
	"github.com/jrperritt/rack/auth"
	"github.com/jrperritt/rack/output"
	"github.com/jrperritt/rack/util"
	osImages "github.com/rackspace/gophercloud/openstack/compute/v2/images"
)

var get = cli.Command{
	Name:        "get",
	Usage:       util.Usage(commandPrefix, "get", util.IDOrNameUsage("image")),
	Description: "Retreives an image",
	Action:      commandGet,
	Flags:       util.CommandFlags(flagsGet, keysGet),
	BashComplete: func(c *cli.Context) {
		util.CompleteFlags(util.CommandFlags(flagsGet, keysGet))
	},
}

func flagsGet() []cli.Flag {
	return util.IDAndNameFlags
}

var keysGet = []string{"ID", "Name", "Status", "Progress", "MinDisk", "MinRAM", "Created", "Updated"}

func commandGet(c *cli.Context) {
	var err error
	outputParams := &output.Params{
		Context: c,
		Keys:    keysGet,
	}
	err = util.CheckArgNum(c, 0)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}

	outputParams.ServiceClientType = serviceClientType
	client, err := auth.NewClient(c, outputParams.ServiceClientType)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}

	imageID, err := util.IDOrName(c, client, osImages.IDFromName)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}
	o, err := images.Get(client, imageID).Extract()
	outputParams.ServiceClient = client
	if err != nil {
		outputParams.Err = fmt.Errorf("Error retrieving image [%s]: %s\n", imageID, err)
		output.Print(outputParams)
		return
	}

	f := func() interface{} {
		return structs.Map(o)
	}
	outputParams.F = &f
	output.Print(outputParams)
}
<commit_msg>use rackspace gophercloud repo<commit_after>package imagecommands

import (
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/fatih/structs"
	"github.com/rackspace/gophercloud/rackspace/compute/v2/images"
	"github.com/jrperritt/rack/auth"
	"github.com/jrperritt/rack/output"
	"github.com/jrperritt/rack/util"
	osImages "github.com/rackspace/gophercloud/openstack/compute/v2/images"
)

var get = cli.Command{
	Name:        "get",
	Usage:       util.Usage(commandPrefix, "get", util.IDOrNameUsage("image")),
	Description: "Retreives an image",
	Action:      commandGet,
	Flags:       util.CommandFlags(flagsGet, keysGet),
	BashComplete: func(c *cli.Context) {
		util.CompleteFlags(util.CommandFlags(flagsGet, keysGet))
	},
}

func flagsGet() []cli.Flag {
	return util.IDAndNameFlags
}

var keysGet = []string{"ID", "Name", "Status", "Progress", "MinDisk", "MinRAM", "Created", "Updated"}

func commandGet(c *cli.Context) {
	var err error
	outputParams := &output.Params{
		Context: c,
		Keys:    keysGet,
	}
	err = util.CheckArgNum(c, 0)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}

	outputParams.ServiceClientType = serviceClientType
	client, err := auth.NewClient(c, outputParams.ServiceClientType)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}

	imageID, err := util.IDOrName(c, client, osImages.IDFromName)
	if err != nil {
		outputParams.Err = err
		output.Print(outputParams)
		return
	}
	o, err := images.Get(client, imageID).Extract()
	outputParams.ServiceClient = client
	if err != nil {
		outputParams.Err = fmt.Errorf("Error retrieving image [%s]: %s\n", imageID, err)
		output.Print(outputParams)
		return
	}

	f := func() interface{} {
		return structs.Map(o)
	}
	outputParams.F = &f
	output.Print(outputParams)
}
<|endoftext|>


<commit_before>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

package oneview

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceUplinkSet() *schema.Resource {
	return &schema.Resource{
		Create: resourceUplinkSetCreate,
		Read:   resourceUplinkSetRead,
		Update: resourceUplinkSetUpdate,
		Delete: resourceUplinkSetDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"logical_interconnect_uri": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"fc_network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"fcoe_network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"connection_mode": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"network_type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"ethernet_network_type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "uplink-setV4",
			},
			"description": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"status": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"category": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"eTag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"created": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"modified": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"lcaptimer": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"manual_login_redistribution_state": {
				Type:     schema.TypeString,
				Required: true,
			},
			"native_network_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"reachability": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"fc_mode": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"expected_neighbour": {
				Type:     schema.TypeList,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"remote_chasis_id": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"remote_port_id": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"port_config_infos": {
				Type:     schema.TypeSet,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"desired_speed": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"location": {
							Type:     schema.TypeSet,
							Optional: true,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"location_entries": {
										Type:     schema.TypeSet,
										Optional: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"value": {
													Type:     schema.TypeString,
													Optional: true,
												},
												"type": {
													Type:     schema.TypeString,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func resourceUplinkSetCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet := ov.UplinkSet{
		Name: d.Get("name").(string),
		LogicalInterconnectURI: utils.NewNstring(d.Get("logical_interconnect_uri").(string)),
		ConnectionMode:         d.Get("connection_mode").(string),
		NetworkType:            d.Get("network_type").(string),
		EthernetNetworkType:    d.Get("ethernet_network_type").(string),
		Type:                   d.Get("type").(string),
		ManualLoginRedistributionState: d.Get("manual_login_redistribution_state").(string),
	}

	if val, ok := d.GetOk("network_uris"); ok {
		rawNetworkUris := val.(*schema.Set).List()
		NetworkUris := make([]utils.Nstring, len(rawNetworkUris))
		for i, raw := range rawNetworkUris {
			NetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.NetworkURIs = NetworkUris
	}

	if val, ok := d.GetOk("fc_network_uris"); ok {
		rawFcNetworkUris := val.(*schema.Set).List()
		FcNetworkUris := make([]utils.Nstring, len(rawFcNetworkUris))
		for i, raw := range rawFcNetworkUris {
			FcNetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.FcNetworkURIs = FcNetworkUris
	}

	if val, ok := d.GetOk("fcoe_network_uris"); ok {
		rawFcoeNetworkUris := val.(*schema.Set).List()
		FcoeNetworkUris := make([]utils.Nstring, len(rawFcoeNetworkUris))
		for i, raw := range rawFcoeNetworkUris {
			FcoeNetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.FcoeNetworkURIs = FcoeNetworkUris
	}

portConfigInfosCount := d.Get("portConfigInfos.#").(int)

portConfigInfosAll := make([]ov.portConfigInfos, 0, portConfigInfosCount)

for i := 0; i < portConfigInfosCount; i++ {

	portConfigInfosPrefix := fmt.Sprintf("port_config_infos.%d",i)
	location =ov.Location{}

	locationPrefix := fmt.Sprintf(portConfigInfosPrefix + ".location.0")

	locationEntriesCount := d.Get(locationPrefix + "locationEntries.#").(int)

	locationEntries := make([]ov.LocationEntries, 0, locationEntriesCount)

	for i := 0; i < locationEntriesCount; i++ {

		locationEntriesPrefix := fmt.Sprintf(locationPrefix+"locationEntries.%d", i)

		locationEntries := ov.LocationEntries{

			Value:    d.Get(locationEntriesPrefix + ".value").(string),

			Type:    d.Get(locationEntriesPrefix + ".type").(string),

		}

	locationEntriesAll = append(locationEntriesAll, locationEntries)

	}

	if locationEntriesCount > 0 {

	location.LocationEntries = locationEntriesAll

	}
	portConfigInfos = ov.PortConfigInfos {
		DesiredSpeed: d.Get(portConfigInfosPrefix + ".desired_speed").(string),
		Location: location,
	}

portConfigInfosAll = append(portConfigInfosAll, portConfigInfos)

}
uplinkSet.PortConfigInfos = &portConfigInfosAll

}
	uplinkSetError := config.ovClient.CreateUplinkSet(uplinkSet)
	d.SetId(d.Get("name").(string))
	if uplinkSetError != nil {
		d.SetId("")
		return uplinkSetError
	}
	return resourceUplinkSetRead(d, meta)
}

func resourceUplinkSetRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet, err := config.ovClient.GetUplinkSetByName(d.Get("name").(string))
	if err != nil || uplinkSet.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.Set("name", uplinkSet.Name)
	d.Set("logical_interconnect_uri", uplinkSet.LogicalInterconnectURI)
	d.Set("network_uris", uplinkSet.NetworkURIs)
	d.Set("manual_login_redistribution_state", uplinkSet.ManualLoginRedistributionState)
	d.Set("description", uplinkSet.Description)
	d.Set("type", uplinkSet.Type)
	d.Set("uri", uplinkSet.URI.String())
	d.Set("fcoe_network_uris", uplinkSet.FcoeNetworkURIs)
	d.Set("status", uplinkSet.Status)
	d.Set("category", uplinkSet.Category)
	d.Set("state", uplinkSet.State)
	d.Set("fc_network_uris", uplinkSet.FcNetworkURIs)
	d.Set("created", uplinkSet.Created)
	d.Set("modified", uplinkSet.Modified)
	d.Set("eTag", uplinkSet.Etag)
	d.Set("reachability", uplinkSet.Reachability)
	d.Set("expected_neighbor", uplinkSet.ExpectedNeighbor)
	d.Set("network_type", uplinkSet.NetworkType)
	d.Set("ethernet_network_type", uplinkSet.EthernetNetworkType)
	d.Set("port_config_infos", uplinkSet.PortConfigInfos)
	return nil
}

func resourceUplinkSetUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet := ov.UplinkSet{
		Etag:        d.Get("eTag").(string),
		URI:         utils.NewNstring(d.Get("uri").(string)),
		Name:        d.Get("name").(string),
		Type:        d.Get("type").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	err := config.ovClient.UpdateUplinkSet(uplinkSet)
	if err != nil {
		return err
	}
	d.SetId(d.Get("name").(string))

	return resourceUplinkSetRead(d, meta)
}

func resourceUplinkSetDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	err := config.ovClient.DeleteUplinkSet(d.Get("name").(string))
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>formatting lib file<commit_after>// (C) Copyright 2016 Hewlett Packard Enterprise Development LP
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

package oneview

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceUplinkSet() *schema.Resource {
	return &schema.Resource{
		Create: resourceUplinkSetCreate,
		Read:   resourceUplinkSetRead,
		Update: resourceUplinkSetUpdate,
		Delete: resourceUplinkSetDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"logical_interconnect_uri": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"fc_network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"fcoe_network_uris": {
				Optional: true,
				Type:     schema.TypeSet,
				Elem: &schema.Schema{
					Type: schema.TypeString,
				},
				Set: schema.HashString,
			},
			"connection_mode": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"network_type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"ethernet_network_type": {
				Type:     schema.TypeString,
				Required: true,
			},
			"type": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "uplink-setV4",
			},
			"description": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"status": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"category": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"state": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"eTag": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"created": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"modified": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"lcaptimer": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"manual_login_redistribution_state": {
				Type:     schema.TypeString,
				Required: true,
			},
			"native_network_uri": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"reachability": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"fc_mode": {
				Type:     schema.TypeString,
				Computed: true,
			},
			"expected_neighbour": {
				Type:     schema.TypeList,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"remote_chasis_id": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"remote_port_id": {
							Type:     schema.TypeString,
							Optional: true,
						},
					},
				},
			},
			"port_config_infos": {
				Type:     schema.TypeSet,
				Optional: true,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"desired_speed": {
							Type:     schema.TypeString,
							Optional: true,
						},
						"location": {
							Type:     schema.TypeSet,
							Optional: true,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"location_entries": {
										Type:     schema.TypeSet,
										Optional: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"value": {
													Type:     schema.TypeString,
													Optional: true,
												},
												"type": {
													Type:     schema.TypeString,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func resourceUplinkSetCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet := ov.UplinkSet{
		Name: d.Get("name").(string),
		LogicalInterconnectURI: utils.NewNstring(d.Get("logical_interconnect_uri").(string)),
		ConnectionMode:         d.Get("connection_mode").(string),
		NetworkType:            d.Get("network_type").(string),
		EthernetNetworkType:    d.Get("ethernet_network_type").(string),
		Type:                   d.Get("type").(string),
		ManualLoginRedistributionState: d.Get("manual_login_redistribution_state").(string),
	}

	if val, ok := d.GetOk("network_uris"); ok {
		rawNetworkUris := val.(*schema.Set).List()
		NetworkUris := make([]utils.Nstring, len(rawNetworkUris))
		for i, raw := range rawNetworkUris {
			NetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.NetworkURIs = NetworkUris
	}

	if val, ok := d.GetOk("fc_network_uris"); ok {
		rawFcNetworkUris := val.(*schema.Set).List()
		FcNetworkUris := make([]utils.Nstring, len(rawFcNetworkUris))
		for i, raw := range rawFcNetworkUris {
			FcNetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.FcNetworkURIs = FcNetworkUris
	}

	if val, ok := d.GetOk("fcoe_network_uris"); ok {
		rawFcoeNetworkUris := val.(*schema.Set).List()
		FcoeNetworkUris := make([]utils.Nstring, len(rawFcoeNetworkUris))
		for i, raw := range rawFcoeNetworkUris {
			FcoeNetworkUris[i] = utils.Nstring(raw.(string))
		}
		uplinkSet.FcoeNetworkURIs = FcoeNetworkUris
	}

	portConfigInfosCount := d.Get("portConfigInfos.#").(int)

	portConfigInfosAll := make([]ov.PortConfigInfos, 0, portConfigInfosCount)

	for i := 0; i < portConfigInfosCount; i++ {

		portConfigInfosPrefix := fmt.Sprintf("port_config_infos.%d", i)
		location := ov.Location{}

		locationPrefix := fmt.Sprintf(portConfigInfosPrefix + ".location.0")

		locationEntriesCount := d.Get(locationPrefix + "locationEntries.#").(int)

		locationEntriesAll := make([]ov.LocationEntries, 0, locationEntriesCount)

		for i := 0; i < locationEntriesCount; i++ {

			locationEntriesPrefix := fmt.Sprintf(locationPrefix+"locationEntries.%d", i)

			locationEntries := ov.LocationEntries{

				Value: d.Get(locationEntriesPrefix + ".value").(string),

				Type: d.Get(locationEntriesPrefix + ".type").(string),
			}

			locationEntriesAll = append(locationEntriesAll, locationEntries)

		}

		if locationEntriesCount > 0 {

			location.LocationEntries = locationEntriesAll

		}
		portConfigInfos := ov.PortConfigInfos{
			DesiredSpeed: d.Get(portConfigInfosPrefix + ".desired_speed").(string),
			Location:     location,
		}

		portConfigInfosAll = append(portConfigInfosAll, portConfigInfos)

	}
	uplinkSet.PortConfigInfos = portConfigInfosAll

	uplinkSetError := config.ovClient.CreateUplinkSet(uplinkSet)
	d.SetId(d.Get("name").(string))
	if uplinkSetError != nil {
		d.SetId("")
		return uplinkSetError
	}
	return resourceUplinkSetRead(d, meta)
}

func resourceUplinkSetRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet, err := config.ovClient.GetUplinkSetByName(d.Get("name").(string))
	if err != nil || uplinkSet.URI.IsNil() {
		d.SetId("")
		return nil
	}
	d.Set("name", uplinkSet.Name)
	d.Set("logical_interconnect_uri", uplinkSet.LogicalInterconnectURI)
	d.Set("network_uris", uplinkSet.NetworkURIs)
	d.Set("manual_login_redistribution_state", uplinkSet.ManualLoginRedistributionState)
	d.Set("description", uplinkSet.Description)
	d.Set("type", uplinkSet.Type)
	d.Set("uri", uplinkSet.URI.String())
	d.Set("fcoe_network_uris", uplinkSet.FcoeNetworkURIs)
	d.Set("status", uplinkSet.Status)
	d.Set("category", uplinkSet.Category)
	d.Set("state", uplinkSet.State)
	d.Set("fc_network_uris", uplinkSet.FcNetworkURIs)
	d.Set("created", uplinkSet.Created)
	d.Set("modified", uplinkSet.Modified)
	d.Set("eTag", uplinkSet.Etag)
	d.Set("reachability", uplinkSet.Reachability)
	d.Set("expected_neighbor", uplinkSet.ExpectedNeighbor)
	d.Set("network_type", uplinkSet.NetworkType)
	d.Set("ethernet_network_type", uplinkSet.EthernetNetworkType)
	d.Set("port_config_infos", uplinkSet.PortConfigInfos)
	return nil
}

func resourceUplinkSetUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	uplinkSet := ov.UplinkSet{
		Etag:        d.Get("eTag").(string),
		URI:         utils.NewNstring(d.Get("uri").(string)),
		Name:        d.Get("name").(string),
		Type:        d.Get("type").(string),
		Description: utils.NewNstring(d.Get("description").(string)),
	}

	err := config.ovClient.UpdateUplinkSet(uplinkSet)
	if err != nil {
		return err
	}
	d.SetId(d.Get("name").(string))

	return resourceUplinkSetRead(d, meta)
}

func resourceUplinkSetDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)

	err := config.ovClient.DeleteUplinkSet(d.Get("name").(string))
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package sandbox

// messing with various aspects of The Go language
// Here Be Dragons

import (
	//	"errors"
	"fmt"
	"reflect"
	"testing"
)

// try/catch/finally impl.
// dont do this. its wrong. maybe

func Throw(e interface{}) {
	panic(e)
}

type Tryblock struct {
	try      func()
	catchers []interface{}
}

type UncaughtException struct {
}

func Try(f func()) *Tryblock {
	return &Tryblock{try: f}
}

func (t *Tryblock) Catch(f interface{}) *Tryblock {
	t.catchers = append(t.catchers, f)
	return t
}

func convertTo(i interface{}, to reflect.Type) (interface{}, bool) {
	from := reflect.TypeOf(i)
	if from.ConvertibleTo(to) {
		return reflect.ValueOf(i).Convert(to).Interface(), true
	}
	return nil, false
}

func callFunction(f interface{}, arg interface{}) bool {
	fval := reflect.ValueOf(f)

	if fval.Type().NumIn() != 1 {
		return false
	}

	if arg, ok := convertTo(arg, fval.Type().In(0)); ok {
		argVals := []reflect.Value{reflect.ValueOf(arg)}
		fval.Call(argVals)
		return true
	}

	return false
}

func (t *Tryblock) Finally(finally func()) {

	inFinally := false
	defer func() {
		if r := recover(); r != nil {
			called := false
			if !inFinally {
				for _, f := range t.catchers {
					called = callFunction(f, r)
					if called {
						break
					}
				}
				finally()
			}

			if !called {
				panic(r)
			}
		}
	}()

	t.try()
	inFinally = true
	finally()
}

func TestThrow(t *testing.T) {

	Try(func() {
		Throw("dddd")
	}).Catch(func(e int) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Catch(func(e string) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Catch(func(e error) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Finally(func() {
		fmt.Println("finally")
	})
}
<commit_msg>trying some things in sandbox<commit_after>package sandbox

// messing with various aspects of The Go language
// Here Be Dragons

import (
	//	"errors"
	"fmt"
	"github.com/simulatedsimian/assert"
	"reflect"
	"testing"
)

// try/catch/finally impl.
// dont do this. its wrong. maybe

func Throw(e interface{}) {
	panic(e)
}

type Tryblock struct {
	try      func()
	catchers []interface{}
}

type UncaughtException struct {
}

func Try(f func()) *Tryblock {
	return &Tryblock{try: f}
}

func (t *Tryblock) Catch(f interface{}) *Tryblock {
	t.catchers = append(t.catchers, f)
	return t
}

func convertTo(i interface{}, to reflect.Type) (interface{}, bool) {
	from := reflect.TypeOf(i)
	if from.ConvertibleTo(to) {
		return reflect.ValueOf(i).Convert(to).Interface(), true
	}
	return nil, false
}

func callFunction(f interface{}, arg interface{}) bool {
	fval := reflect.ValueOf(f)

	if fval.Type().NumIn() != 1 {
		return false
	}

	if arg, ok := convertTo(arg, fval.Type().In(0)); ok {
		argVals := []reflect.Value{reflect.ValueOf(arg)}
		fval.Call(argVals)
		return true
	}

	return false
}

func (t *Tryblock) Finally(finally func()) {

	inFinally := false
	defer func() {
		if r := recover(); r != nil {
			called := false
			if !inFinally {
				for _, f := range t.catchers {
					called = callFunction(f, r)
					if called {
						break
					}
				}
				finally()
			}

			if !called {
				panic(r)
			}
		}
	}()

	t.try()
	inFinally = true
	finally()
}

func TestThrow(t *testing.T) {

	Try(func() {
		Throw("dddd")
	}).Catch(func(e int) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Catch(func(e string) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Catch(func(e error) {
		fmt.Println("caught:", reflect.TypeOf(e), e)
	}).Finally(func() {
		fmt.Println("finally")
	})
}

func TestThrow2(t *testing.T) {

	assert.MustPanic(t, func(t *testing.T) {

		Try(func() {
		}).Catch(func(e int) {
			fmt.Println("caught:", reflect.TypeOf(e), e)
		}).Catch(func(e string) {
			fmt.Println("caught:", reflect.TypeOf(e), e)
		}).Catch(func(e error) {
			fmt.Println("caught:", reflect.TypeOf(e), e)
		}).Finally(func() {
			Throw("asdf")
		})

	})

}
<|endoftext|>


<commit_before>// +build integ
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pilot

import (
	"testing"

	"istio.io/istio/pkg/test/echo/client"
	"istio.io/istio/pkg/test/echo/common/scheme"
	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/echo"
)

func TestTproxy(t *testing.T) {
	framework.
		NewTest(t).
		Features("traffic.original-source-ip").
		RequiresSingleCluster().
		Run(func(t framework.TestContext) {
			workloads, err := apps.PodA[0].Workloads()
			if err != nil {
				t.Errorf("failed to get Subsets: %v", err)
				return
			}
			// check the server can see the client's original ip
			checkOriginalSrcIP(t, apps.PodA[0], apps.PodTproxy[0], workloads[0].Address())
		})
}

func checkOriginalSrcIP(t framework.TestContext, src, dest echo.Instance, expected string) {
	t.Helper()
	validator := echo.ValidatorFunc(func(resp client.ParsedResponses, inErr error) error {
		return resp.CheckIP(expected)
	})
	_ = src.CallWithRetryOrFail(t, echo.CallOptions{
		Target:    dest,
		PortName:  "http",
		Scheme:    scheme.HTTP,
		Count:     1,
		Validator: validator,
	})
}
<commit_msg>Fix pilot/TestTproxy for multiversion tests (#32808)<commit_after>// +build integ
// Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pilot

import (
	"fmt"
	"testing"

	"istio.io/istio/pkg/test/echo/client"
	"istio.io/istio/pkg/test/echo/common/scheme"
	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/echo"
)

func TestTproxy(t *testing.T) {
	framework.
		NewTest(t).
		Features("traffic.original-source-ip").
		RequiresSingleCluster().
		Run(func(t framework.TestContext) {
			workloads, err := apps.PodA[0].Workloads()
			if err != nil {
				t.Errorf("failed to get Subsets: %v", err)
				return
			}
			// check the server can see the client's original ip
			var srcIps []string
			for _, w := range workloads {
				srcIps = append(srcIps, w.Address())
			}
			checkOriginalSrcIP(t, apps.PodA[0], apps.PodTproxy[0], srcIps)
		})
}

func checkOriginalSrcIP(t framework.TestContext, src echo.Caller, dest echo.Instance, expected []string) {
	t.Helper()
	validator := echo.ValidatorFunc(func(resp client.ParsedResponses, inErr error) error {
		// Check that each response saw one of the workload IPs for the src echo instance
		for _, r := range resp {
			found := false
			for _, ip := range expected {
				if r.IP == ip {
					found = true
				}
			}
			if !found {
				return fmt.Errorf("unexpected IP %s, expected to be contained in %v",
					r.IP, expected)
			}
		}

		return nil
	})
	_ = src.CallWithRetryOrFail(t, echo.CallOptions{
		Target:    dest,
		PortName:  "http",
		Scheme:    scheme.HTTP,
		Count:     1,
		Validator: validator,
	})
}
<|endoftext|>


<commit_before>package integration_test

import (
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("CF Dotnet Buildpack", func() {
	var (
		app         *cutlass.App
		fixtureName string
	)
	AfterEach(func() { app = DestroyApp(app) })

	JustBeforeEach(func() {
		app = cutlass.New(filepath.Join(bpDir, "fixtures", fixtureName))
	})

	Context("Deploying an app with multiple projects", func() {
		BeforeEach(func() {
			fixtureName = "multiple_projects_msbuild"
		})
		It("compiles both apps", func() {
			PushAppAndConfirm(app)
			Expect(app.GetBody("/")).To(ContainSubstring("Hello, I'm a string!"))
			Expect(app.Stdout.String()).To(ContainSubstring("Hello from a secondary project!"))
		})
	})
})
<commit_msg>Test correctly waits for expected log output<commit_after>package integration_test

import (
	"path/filepath"
	"time"

	"github.com/cloudfoundry/libbuildpack/cutlass"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("CF Dotnet Buildpack", func() {
	var (
		app         *cutlass.App
		fixtureName string
	)
	AfterEach(func() { app = DestroyApp(app) })

	JustBeforeEach(func() {
		app = cutlass.New(filepath.Join(bpDir, "fixtures", fixtureName))
	})

	Context("Deploying an app with multiple projects", func() {
		BeforeEach(func() {
			fixtureName = "multiple_projects_msbuild"
		})
		It("compiles both apps", func() {
			PushAppAndConfirm(app)
			Expect(app.GetBody("/")).To(ContainSubstring("Hello, I'm a string!"))
			Eventually(app.Stdout.String, 10*time.Second).Should(ContainSubstring("Hello from a secondary project!"))
		})
	})
})
<|endoftext|>


<commit_before>package fcm

import (
	"fmt"

	"github.com/Bogh/gcm"
	"github.com/smancke/guble/protocol"
	"github.com/smancke/guble/server/connector"
	"github.com/smancke/guble/server/metrics"
	"github.com/smancke/guble/server/router"
	"time"
)

const (
	// schema is the default database schema for FCM
	schema = "fcm_registration"

	deviceTokenKey = "device_token"
	userIDKEy      = "user_id"
)

// Config is used for configuring the Firebase Cloud Messaging component.
type Config struct {
	Enabled              *bool
	APIKey               *string
	Workers              *int
	Endpoint             *string
	Prefix               *string
	AfterMessageDelivery protocol.MessageDeliveryCallback
}

// Connector is the structure for handling the communication with Firebase Cloud Messaging
type fcm struct {
	Config
	connector.Connector
}

// New creates a new *fcm and returns it as an connector.ResponsiveConnector
func New(router router.Router, sender connector.Sender, config Config) (connector.ResponsiveConnector, error) {
	baseConn, err := connector.NewConnector(router, sender, connector.Config{
		Name:       "fcm",
		Schema:     schema,
		Prefix:     *config.Prefix,
		URLPattern: fmt.Sprintf("/{%s}/{%s}/{%s:.*}", deviceTokenKey, userIDKEy, connector.TopicParam),
		Workers:    *config.Workers,
	})
	if err != nil {
		logger.WithError(err).Error("Base connector error")
		return nil, err
	}

	f := &fcm{config, baseConn}
	f.SetResponseHandler(f)
	return f, nil
}

func (f *fcm) Start() error {
	err := f.Connector.Start()
	if err == nil {
		f.startMetrics()
	}
	return err
}

func (f *fcm) startMetrics() {
	mTotalSentMessages.Set(0)
	mTotalSendErrors.Set(0)
	mTotalResponseErrors.Set(0)
	mTotalResponseInternalErrors.Set(0)
	mTotalResponseNotRegisteredErrors.Set(0)
	mTotalReplacedCanonicalErrors.Set(0)
	mTotalResponseOtherErrors.Set(0)

	metrics.RegisterInterval(f.Context(), mMinute, time.Minute, resetIntervalMetrics, processAndResetIntervalMetrics)
	metrics.RegisterInterval(f.Context(), mHour, time.Hour, resetIntervalMetrics, processAndResetIntervalMetrics)
	metrics.RegisterInterval(f.Context(), mDay, time.Hour*24, resetIntervalMetrics, processAndResetIntervalMetrics)
}

func (f *fcm) HandleResponse(request connector.Request, responseIface interface{}, metadata *connector.Metadata, err error) error {
	if err != nil && !isValidResponseError(err) {
		logger.WithField("error", err.Error()).Error("Error sending message to FCM")
		mTotalSendErrors.Add(1)
		addToLatenciesAndCountsMaps(currentTotalErrorsLatenciesKey, currentTotalErrorsKey, metadata.Latency)
		return err
	}
	message := request.Message()
	subscriber := request.Subscriber()

	response, ok := responseIface.(*gcm.Response)
	if !ok {
		mTotalResponseErrors.Add(1)
		return fmt.Errorf("Invalid FCM Response")
	}

	logger.WithField("messageID", message.ID).Debug("Delivered message to FCM")
	subscriber.SetLastID(message.ID)
	if err := f.Manager().Update(request.Subscriber()); err != nil {
		mTotalResponseInternalErrors.Add(1)
		return err
	}
	if response.Ok() {
		mTotalSentMessages.Add(1)
		addToLatenciesAndCountsMaps(currentTotalMessagesLatenciesKey, currentTotalMessagesKey, metadata.Latency)
		return nil
	}

	logger.WithField("success", response.Success).Debug("Handling FCM Error")

	switch errText := response.Error.Error(); errText {
	case "NotRegistered":
		logger.Debug("Removing not registered FCM subscription")
		f.Manager().Remove(subscriber)
		mTotalResponseNotRegisteredErrors.Add(1)
		return response.Error
	case "InvalidRegistration":
		logger.WithField("jsonError", errText).Error("InvalidRegistration of FCM subscription")
	default:
		logger.WithField("jsonError", errText).Error("Unexpected error while sending to FCM")
	}

	if response.CanonicalIDs != 0 {
		mTotalReplacedCanonicalErrors.Add(1)
		// we only send to one receiver, so we know that we can replace the old id with the first registration id (=canonical id)
		return f.replaceCanonical(request.Subscriber(), response.Results[0].RegistrationID)
	}
	mTotalResponseOtherErrors.Add(1)
	return nil
}

func (f *fcm) replaceCanonical(subscriber connector.Subscriber, newToken string) error {
	manager := f.Manager()
	err := manager.Remove(subscriber)
	if err != nil {
		return err
	}

	topic := subscriber.Route().Path
	params := subscriber.Route().RouteParams.Copy()

	params[deviceTokenKey] = newToken

	newSubscriber, err := manager.Create(topic, params)
	go f.Run(newSubscriber)
	return err
}
<commit_msg>refactoring<commit_after>package fcm

import (
	"fmt"

	"github.com/Bogh/gcm"
	"github.com/smancke/guble/protocol"
	"github.com/smancke/guble/server/connector"
	"github.com/smancke/guble/server/metrics"
	"github.com/smancke/guble/server/router"
	"time"
)

const (
	// schema is the default database schema for FCM
	schema = "fcm_registration"

	deviceTokenKey = "device_token"
	userIDKEy      = "user_id"
)

// Config is used for configuring the Firebase Cloud Messaging component.
type Config struct {
	Enabled              *bool
	APIKey               *string
	Workers              *int
	Endpoint             *string
	Prefix               *string
	AfterMessageDelivery protocol.MessageDeliveryCallback
}

// Connector is the structure for handling the communication with Firebase Cloud Messaging
type fcm struct {
	Config
	connector.Connector
}

// New creates a new *fcm and returns it as an connector.ResponsiveConnector
func New(router router.Router, sender connector.Sender, config Config) (connector.ResponsiveConnector, error) {
	baseConn, err := connector.NewConnector(router, sender, connector.Config{
		Name:       "fcm",
		Schema:     schema,
		Prefix:     *config.Prefix,
		URLPattern: fmt.Sprintf("/{%s}/{%s}/{%s:.*}", deviceTokenKey, userIDKEy, connector.TopicParam),
		Workers:    *config.Workers,
	})
	if err != nil {
		logger.WithError(err).Error("Base connector error")
		return nil, err
	}

	f := &fcm{config, baseConn}
	f.SetResponseHandler(f)
	return f, nil
}

func (f *fcm) Start() error {
	err := f.Connector.Start()
	if err == nil {
		f.startMetrics()
	}
	return err
}

func (f *fcm) startMetrics() {
	mTotalSentMessages.Set(0)
	mTotalSendErrors.Set(0)
	mTotalResponseErrors.Set(0)
	mTotalResponseInternalErrors.Set(0)
	mTotalResponseNotRegisteredErrors.Set(0)
	mTotalReplacedCanonicalErrors.Set(0)
	mTotalResponseOtherErrors.Set(0)

	f.startIntervalMetric(mMinute, time.Minute)
	f.startIntervalMetric(mHour, time.Hour)
	f.startIntervalMetric(mDay, time.Hour*24)
}

func (f *fcm) startIntervalMetric(m metrics.Map, td time.Duration) {
	metrics.RegisterInterval(f.Context(), m, td, resetIntervalMetrics, processAndResetIntervalMetrics)
}

func (f *fcm) HandleResponse(request connector.Request, responseIface interface{}, metadata *connector.Metadata, err error) error {
	if err != nil && !isValidResponseError(err) {
		logger.WithField("error", err.Error()).Error("Error sending message to FCM")
		mTotalSendErrors.Add(1)
		addToLatenciesAndCountsMaps(currentTotalErrorsLatenciesKey, currentTotalErrorsKey, metadata.Latency)
		return err
	}
	message := request.Message()
	subscriber := request.Subscriber()

	response, ok := responseIface.(*gcm.Response)
	if !ok {
		mTotalResponseErrors.Add(1)
		return fmt.Errorf("Invalid FCM Response")
	}

	logger.WithField("messageID", message.ID).Debug("Delivered message to FCM")
	subscriber.SetLastID(message.ID)
	if err := f.Manager().Update(request.Subscriber()); err != nil {
		mTotalResponseInternalErrors.Add(1)
		return err
	}
	if response.Ok() {
		mTotalSentMessages.Add(1)
		addToLatenciesAndCountsMaps(currentTotalMessagesLatenciesKey, currentTotalMessagesKey, metadata.Latency)
		return nil
	}

	logger.WithField("success", response.Success).Debug("Handling FCM Error")

	switch errText := response.Error.Error(); errText {
	case "NotRegistered":
		logger.Debug("Removing not registered FCM subscription")
		f.Manager().Remove(subscriber)
		mTotalResponseNotRegisteredErrors.Add(1)
		return response.Error
	case "InvalidRegistration":
		logger.WithField("jsonError", errText).Error("InvalidRegistration of FCM subscription")
	default:
		logger.WithField("jsonError", errText).Error("Unexpected error while sending to FCM")
	}

	if response.CanonicalIDs != 0 {
		mTotalReplacedCanonicalErrors.Add(1)
		// we only send to one receiver, so we know that we can replace the old id with the first registration id (=canonical id)
		return f.replaceCanonical(request.Subscriber(), response.Results[0].RegistrationID)
	}
	mTotalResponseOtherErrors.Add(1)
	return nil
}

func (f *fcm) replaceCanonical(subscriber connector.Subscriber, newToken string) error {
	manager := f.Manager()
	err := manager.Remove(subscriber)
	if err != nil {
		return err
	}

	topic := subscriber.Route().Path
	params := subscriber.Route().RouteParams.Copy()

	params[deviceTokenKey] = newToken

	newSubscriber, err := manager.Create(topic, params)
	go f.Run(newSubscriber)
	return err
}
<|endoftext|>


<commit_before>package server

import (
	"fmt"
	"net/http"
	"strings"
)

const (
	htmlHeader = "<!DOCTYPE html><title>fkarchery ts3</title>\r\n"
	htmlFooter = "\r\n"
)

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//s.handlermutex.Lock()
	//defer s.handlermutex.Unlock()

	var i int

	if !s.closed {
		s.clmutex.Lock()
		clients := s.clientlist.cl
		n := s.clientlist.n
		s.clmutex.Unlock()

		fmt.Fprint(w, htmlHeader)
		if n > 0 {
			fmt.Fprint(w, "
", n, " Clients are online:
\r\n")

			for _, client := range clients {
				nick, ok := client["client_nickname"]
				if ok {
					if strings.Contains(client["client_type"], "0") {
						fmt.Fprintln(w, "
", nick, "
")
					}
				} else {
					fmt.Fprintln(w, "error: ", client, ", empty map")
					if s.logger != nil {
						s.logger.Print("error: " + fmt.Sprint(client))
					}
				}
				i++
			}
		} else {
			fmt.Fprintln(w, "
No one is online right now.
")
		}

		fmt.Fprint(w, htmlFooter)
	} else {
		http.Error(w, "internal error", 500)
	}

	return
}
<commit_msg>bugfix<commit_after>package server

import (
	"fmt"
	"net/http"
	"strings"
)

const (
	htmlHeader = "<!DOCTYPE html><title>fkarchery ts3</title>\r\n"
	htmlFooter = "\r\n"
)

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//s.handlermutex.Lock()
	//defer s.handlermutex.Unlock()

	var i int

	if !s.closed {
		s.clmutex.Lock()
		clients := s.clientlist.cl
		n := s.clientlist.n
		s.clmutex.Unlock()

		fmt.Fprint(w, htmlHeader)
		if n > 0 {
			fmt.Fprint(w, "
", n, " Clients are online:
\r\n")

			for _, client := range clients {
				nick, ok := client["client_nickname"]
				if ok {
					if strings.Contains(client["client_type"], "0") {
						fmt.Fprintln(w, "
", nick, "
")
					}
				} else {
					fmt.Fprintln(w, "error: ", client, ", empty map")
					if s.logger != nil {
						s.logger.Print("error: " + fmt.Sprint(client))
					}
				}
				i++
			}
		} else {
			fmt.Fprintln(w, "
No one is online right now.
")
		}

		fmt.Fprint(w, htmlFooter)
	} else {
		http.Error(w, "internal error", 500)
	}

	return
}
<|endoftext|>


<commit_before>//
// Converts a CSV-formatted stock item file to JSON format.
//
// This will handle large data files, bigger than memory.
//
// Build it, and then run it with no arguments for usage
// information.
//
// Copyright (c) 2014 by Lee Braiden (leebraid@gmail.com)
//

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io"
	"lbgotest.com/lb/stockdatalib"
	"os"
	"strings"
)

// Don't know if there's a better way to get the proper
// exit codes for the os in question in Go.  I figure this
// will do for all intents and purposes.
const (
	EXIT_SUCCESS = 0
	EXIT_ERROR   = 1
)

// small struct to hold a few configuration variables
type Config struct {
	SrcFile string
	DstFile string
	Verbose bool
}

func exitUsage(msg *string) {
	if msg != nil {
		fmt.Fprintf(os.Stderr, "ERROR:\n\n\t%s\n\n", *msg)
	}

	fmt.Fprintf(os.Stderr, "Usage:\n\n")
	fmt.Fprintf(os.Stderr, "\t%s srcFile dstFile\n\n", os.Args[0])

	os.Exit(EXIT_ERROR)
}

func exitError(err error) {
	fmt.Fprintf(os.Stderr, "ERROR:\n\n\t%s\n\n", err)
	os.Exit(EXIT_ERROR)
}

// read the config / operational arguments from the command line
func getConfig() *Config {
	// NOTE: Exits with usage information if config is wrong,
	//       rather than returning, so no need for an error
	//       type to be returned along with the config

	var conf Config

	fileArgsSeen := 0

	for _, arg := range os.Args[1:] {
		switch arg {
		case "--verbose":
			conf.Verbose = true

		default:
			if strings.HasPrefix(arg, "--") {
				err_msg := fmt.Sprintf("Unrecognised command-line option flag: '%s'", arg)
				exitUsage(&err_msg)
			}

			if fileArgsSeen == 0 {
				conf.SrcFile = arg
			} else if fileArgsSeen == 1 {
				conf.DstFile = arg
			} else {
				err_msg := fmt.Sprintf("Too many file arguments given.  extra arg is '%s'", arg)
				exitUsage(&err_msg)
			}

			fileArgsSeen = fileArgsSeen + 1
		}
	}

	if fileArgsSeen < 2 {
		err_msg := "Not enough file arguments given."
		exitUsage(&err_msg)
	}

	return &conf
}

// Main record-conversion loop, which opens files, reads items, writes them,
// and closes files again.
func doConversion(srcFile string, dstFile string, verbose bool) error {
	srcFp, err := os.Open(srcFile)
	if err != nil {
		exitError(err)
	} else {
		defer srcFp.Close()
	}

	dstFp, err := os.Create(dstFile)
	if err != nil {
		exitError(err)
	} else {
		defer dstFp.Close()
	}

	// create the CSV reader
	csvReader := csv.NewReader(srcFp)

	// make sure the basic file format is correct (has title row, valid field names)
	columns_err := stockdatalib.VerifyCsvFields(*csvReader)
	if columns_err != nil {
		exitError(columns_err)
	}

	// begin the json output file
	dstFp.WriteString("[\n    ")

	at_least_one_item_written := false

	// read rows one at a time (streaming, low mem usage), and write them out as json
	for {
		//
		// Create a stock item.  Normally you'd do this outside the loop and re-use it,
		// but I want to be sure I get a new, clean item each time before loading data
		// into it.  Go will (should!) take care of optimising this to use the same
		// memory each time, with minimal data clearing.
		//
		var stock_item stockdatalib.StockItem

		// read the item
		read_err := stock_item.ReadItem(*csvReader)
		if read_err != nil {
			if read_err == io.EOF {
				break
			} else {
				exitError(read_err)
			}
		}

		// Let the user know what we're currently processing, if verbose mode
		// is enabled.
		if verbose {
			fmt.Fprintf(os.Stderr, "   Item %10d: %-50s... ", stock_item.Item_id, stock_item.Description)
		}

		// write the json
		json_bytes, encode_err := json.MarshalIndent(stock_item, "    ", "    ")
		if encode_err != nil {
			exitError(encode_err)
		}

		_, write_err := dstFp.Write(json_bytes)
		if write_err != nil {
			exitError(write_err)
		}

		// finish the current status line, if in verbose mode
		if verbose {
			fmt.Fprintf(os.Stderr, "converted.\n")
		}

		// write the record separator if needed, and if not,
		// flag that we'll need one next time
		if at_least_one_item_written {
			// separate items
			dstFp.WriteString(",\n    ")
		} else {
			at_least_one_item_written = true
		}
	}

	// end the json output file
	dstFp.WriteString("\n]\n")

	return nil
}

func main() {
	conf := getConfig()

	if conf.Verbose {
		fmt.Printf("Reading from CSV file %s\n", conf.SrcFile)
		fmt.Printf("Writing to JSON file %s\n", conf.DstFile)
	}

	err := doConversion(conf.SrcFile, conf.DstFile, conf.Verbose)

	if err != nil {
		exitError(err)
	} else {
		if conf.Verbose {
			fmt.Printf("done.\n")
		}
	}

	// if we reach here, all went well
	os.Exit(EXIT_SUCCESS)
}
<commit_msg>Document --verbose flag<commit_after>//
// Converts a CSV-formatted stock item file to JSON format.
//
// This will handle large data files, bigger than memory.
//
// Build it, and then run it with no arguments for usage
// information.
//
// Copyright (c) 2014 by Lee Braiden (leebraid@gmail.com)
//

package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io"
	"lbgotest.com/lb/stockdatalib"
	"os"
	"strings"
)

// Don't know if there's a better way to get the proper
// exit codes for the os in question in Go.  I figure this
// will do for all intents and purposes.
const (
	EXIT_SUCCESS = 0
	EXIT_ERROR   = 1
)

// small struct to hold a few configuration variables
type Config struct {
	SrcFile string
	DstFile string
	Verbose bool
}

func exitUsage(msg *string) {
	if msg != nil {
		fmt.Fprintf(os.Stderr, "ERROR:\n\n\t%s\n\n", *msg)
	}

	fmt.Fprintf(os.Stderr, "Usage:\n\n")
	fmt.Fprintf(os.Stderr, "\t%s [--verbose] srcFile dstFile\n\n", os.Args[0])

	os.Exit(EXIT_ERROR)
}

func exitError(err error) {
	fmt.Fprintf(os.Stderr, "ERROR:\n\n\t%s\n\n", err)
	os.Exit(EXIT_ERROR)
}

// read the config / operational arguments from the command line
func getConfig() *Config {
	// NOTE: Exits with usage information if config is wrong,
	//       rather than returning, so no need for an error
	//       type to be returned along with the config

	var conf Config

	fileArgsSeen := 0

	for _, arg := range os.Args[1:] {
		switch arg {
		case "--verbose":
			conf.Verbose = true

		default:
			if strings.HasPrefix(arg, "--") {
				err_msg := fmt.Sprintf("Unrecognised command-line option flag: '%s'", arg)
				exitUsage(&err_msg)
			}

			if fileArgsSeen == 0 {
				conf.SrcFile = arg
			} else if fileArgsSeen == 1 {
				conf.DstFile = arg
			} else {
				err_msg := fmt.Sprintf("Too many file arguments given.  extra arg is '%s'", arg)
				exitUsage(&err_msg)
			}

			fileArgsSeen = fileArgsSeen + 1
		}
	}

	if fileArgsSeen < 2 {
		err_msg := "Not enough file arguments given."
		exitUsage(&err_msg)
	}

	return &conf
}

// Main record-conversion loop, which opens files, reads items, writes them,
// and closes files again.
func doConversion(srcFile string, dstFile string, verbose bool) error {
	srcFp, err := os.Open(srcFile)
	if err != nil {
		exitError(err)
	} else {
		defer srcFp.Close()
	}

	dstFp, err := os.Create(dstFile)
	if err != nil {
		exitError(err)
	} else {
		defer dstFp.Close()
	}

	// create the CSV reader
	csvReader := csv.NewReader(srcFp)

	// make sure the basic file format is correct (has title row, valid field names)
	columns_err := stockdatalib.VerifyCsvFields(*csvReader)
	if columns_err != nil {
		exitError(columns_err)
	}

	// begin the json output file
	dstFp.WriteString("[\n    ")

	at_least_one_item_written := false

	// read rows one at a time (streaming, low mem usage), and write them out as json
	for {
		//
		// Create a stock item.  Normally you'd do this outside the loop and re-use it,
		// but I want to be sure I get a new, clean item each time before loading data
		// into it.  Go will (should!) take care of optimising this to use the same
		// memory each time, with minimal data clearing.
		//
		var stock_item stockdatalib.StockItem

		// read the item
		read_err := stock_item.ReadItem(*csvReader)
		if read_err != nil {
			if read_err == io.EOF {
				break
			} else {
				exitError(read_err)
			}
		}

		// Let the user know what we're currently processing, if verbose mode
		// is enabled.
		if verbose {
			fmt.Fprintf(os.Stderr, "   Item %10d: %-50s... ", stock_item.Item_id, stock_item.Description)
		}

		// write the json
		json_bytes, encode_err := json.MarshalIndent(stock_item, "    ", "    ")
		if encode_err != nil {
			exitError(encode_err)
		}

		_, write_err := dstFp.Write(json_bytes)
		if write_err != nil {
			exitError(write_err)
		}

		// finish the current status line, if in verbose mode
		if verbose {
			fmt.Fprintf(os.Stderr, "converted.\n")
		}

		// write the record separator if needed, and if not,
		// flag that we'll need one next time
		if at_least_one_item_written {
			// separate items
			dstFp.WriteString(",\n    ")
		} else {
			at_least_one_item_written = true
		}
	}

	// end the json output file
	dstFp.WriteString("\n]\n")

	return nil
}

func main() {
	conf := getConfig()

	if conf.Verbose {
		fmt.Printf("Reading from CSV file %s\n", conf.SrcFile)
		fmt.Printf("Writing to JSON file %s\n", conf.DstFile)
	}

	err := doConversion(conf.SrcFile, conf.DstFile, conf.Verbose)

	if err != nil {
		exitError(err)
	} else {
		if conf.Verbose {
			fmt.Printf("done.\n")
		}
	}

	// if we reach here, all went well
	os.Exit(EXIT_SUCCESS)
}
<|endoftext|>


<commit_before>package collection

import (
	"context"

	"github.com/pachyderm/pachyderm/src/server/pkg/watch"

	"github.com/gogo/protobuf/proto"
)

// Collection implements helper functions that makes common operations
// on top of etcd more pleasant to work with.  It's called collection
// because most of our data is modelled as collections, such as repos,
// commits, branches, etc.
type Collection interface {
	// Path returns the full etcd path of the given key in the collection
	Path(string) string
	// ReadWrite enables reads and writes on a collection in a
	// transactional manner.  Specifically, all writes are applied
	// atomically, and writes are only applied if reads have not been
	// invalidated at the end of the transaction.  Basically, it's
	// software transactional memory.  See this blog post for details:
	// https://coreos.com/blog/transactional-memory-with-etcd3.html
	ReadWrite(stm STM) ReadWriteCollection
	// ReadWriteInt is the same as ReadWrite except that it operates on
	// integral items, as opposed to protobuf items
	ReadWriteInt(stm STM) ReadWriteIntCollection
	// For read-only operatons, use the ReadOnly for better performance
	ReadOnly(ctx context.Context) ReadonlyCollection
}

// Index specifies a secondary index on a collection.
//
// Indexes are created in a transactional manner thanks to etcd's
// transactional support.
//
// A secondary index for collection "foo" on field "bar" will reside under
// the path `/foo__index_bar`.  Each item under the path is in turn a
// directory whose name is the value of the field `bar`.  For instance,
// if you have a object in collection `foo` whose `bar` field is `test`,
// then you will see a directory at path `/foo__index_bar/test`.
//
// Under that directory, you have keys that point to items in the collection.
// For instance, if the aforementioned object has the key "buzz", then you
// will see an item at `/foo__index_bar/test/buzz`.  The value of this item
// is empty.  Thus, to get all items in collection `foo` whose values of
// field `bar` is `test`, we issue a query for all items under
// `foo__index_bar/test`.
//
// Multi specifies whether this is a multi-index.  A multi-index is an index
// on a field that's a slice.  The item is then indexed on each element of
// the slice.
type Index struct {
	Field string
	Multi bool
}

// ReadWriteCollection is a collection interface that supports read,write and delete
// operations.
type ReadWriteCollection interface {
	Get(key string, val proto.Unmarshaler) error
	Put(key string, val proto.Marshaler) error
	// PutTTL is the same as Put except that the object is removed after
	// TTL seconds.
	// WARNING: using PutTTL with a collection that has secondary indices
	// can result in inconsistency, as the indices are removed at roughly
	// but not exactly the same time as the documents.
	PutTTL(key string, val proto.Marshaler, ttl int64) error
	Create(key string, val proto.Marshaler) error
	Delete(key string) error
	DeleteAll()
}

// ReadWriteIntCollection is a ReadonlyCollection interface specifically for ints.
type ReadWriteIntCollection interface {
	Create(key string, val int) error
	Get(key string) (int, error)
	Increment(key string) error
	IncrementBy(key string, n int) error
	Decrement(key string) error
	DecrementBy(key string, n int) error
	Delete(key string) error
}

// ReadonlyCollection is a collection interface that only supports read ops.
type ReadonlyCollection interface {
	Get(key string, val proto.Unmarshaler) error
	GetByIndex(index Index, val interface{}) (Iterator, error)
	GetBlock(key string, val proto.Unmarshaler) error
	List() (Iterator, error)
	Count() (int64, error)
	Watch() (watch.Watcher, error)
	// WatchWithPrev is like Watch, but the events will include the previous
	// versions of the key/value.
	WatchWithPrev() (watch.Watcher, error)
	WatchOne(key string) (watch.Watcher, error)
	WatchByIndex(index Index, val interface{}) (watch.Watcher, error)
}

// Iterator is an interface for iterating protobufs.
type Iterator interface {
	// Next is a function that, when called, serializes the key and value
	// of the next object in a collection.
	// ok is true if the serialization was successful.  It's false if the
	// collection has been exhausted.
	Next(key *string, val proto.Unmarshaler) (ok bool, retErr error)
}
<commit_msg>Adds comment about GetBlock.<commit_after>package collection

import (
	"context"

	"github.com/pachyderm/pachyderm/src/server/pkg/watch"

	"github.com/gogo/protobuf/proto"
)

// Collection implements helper functions that makes common operations
// on top of etcd more pleasant to work with.  It's called collection
// because most of our data is modelled as collections, such as repos,
// commits, branches, etc.
type Collection interface {
	// Path returns the full etcd path of the given key in the collection
	Path(string) string
	// ReadWrite enables reads and writes on a collection in a
	// transactional manner.  Specifically, all writes are applied
	// atomically, and writes are only applied if reads have not been
	// invalidated at the end of the transaction.  Basically, it's
	// software transactional memory.  See this blog post for details:
	// https://coreos.com/blog/transactional-memory-with-etcd3.html
	ReadWrite(stm STM) ReadWriteCollection
	// ReadWriteInt is the same as ReadWrite except that it operates on
	// integral items, as opposed to protobuf items
	ReadWriteInt(stm STM) ReadWriteIntCollection
	// For read-only operatons, use the ReadOnly for better performance
	ReadOnly(ctx context.Context) ReadonlyCollection
}

// Index specifies a secondary index on a collection.
//
// Indexes are created in a transactional manner thanks to etcd's
// transactional support.
//
// A secondary index for collection "foo" on field "bar" will reside under
// the path `/foo__index_bar`.  Each item under the path is in turn a
// directory whose name is the value of the field `bar`.  For instance,
// if you have a object in collection `foo` whose `bar` field is `test`,
// then you will see a directory at path `/foo__index_bar/test`.
//
// Under that directory, you have keys that point to items in the collection.
// For instance, if the aforementioned object has the key "buzz", then you
// will see an item at `/foo__index_bar/test/buzz`.  The value of this item
// is empty.  Thus, to get all items in collection `foo` whose values of
// field `bar` is `test`, we issue a query for all items under
// `foo__index_bar/test`.
//
// Multi specifies whether this is a multi-index.  A multi-index is an index
// on a field that's a slice.  The item is then indexed on each element of
// the slice.
type Index struct {
	Field string
	Multi bool
}

// ReadWriteCollection is a collection interface that supports read,write and delete
// operations.
type ReadWriteCollection interface {
	Get(key string, val proto.Unmarshaler) error
	Put(key string, val proto.Marshaler) error
	// PutTTL is the same as Put except that the object is removed after
	// TTL seconds.
	// WARNING: using PutTTL with a collection that has secondary indices
	// can result in inconsistency, as the indices are removed at roughly
	// but not exactly the same time as the documents.
	PutTTL(key string, val proto.Marshaler, ttl int64) error
	Create(key string, val proto.Marshaler) error
	Delete(key string) error
	DeleteAll()
}

// ReadWriteIntCollection is a ReadonlyCollection interface specifically for ints.
type ReadWriteIntCollection interface {
	Create(key string, val int) error
	Get(key string) (int, error)
	Increment(key string) error
	IncrementBy(key string, n int) error
	Decrement(key string) error
	DecrementBy(key string, n int) error
	Delete(key string) error
}

// ReadonlyCollection is a collection interface that only supports read ops.
type ReadonlyCollection interface {
	Get(key string, val proto.Unmarshaler) error
	GetByIndex(index Index, val interface{}) (Iterator, error)
	// GetBlock is like Get but waits for the key to exist if it doesn't already.
	GetBlock(key string, val proto.Unmarshaler) error
	List() (Iterator, error)
	Count() (int64, error)
	Watch() (watch.Watcher, error)
	// WatchWithPrev is like Watch, but the events will include the previous
	// versions of the key/value.
	WatchWithPrev() (watch.Watcher, error)
	WatchOne(key string) (watch.Watcher, error)
	WatchByIndex(index Index, val interface{}) (watch.Watcher, error)
}

// Iterator is an interface for iterating protobufs.
type Iterator interface {
	// Next is a function that, when called, serializes the key and value
	// of the next object in a collection.
	// ok is true if the serialization was successful.  It's false if the
	// collection has been exhausted.
	Next(key *string, val proto.Unmarshaler) (ok bool, retErr error)
}
<|endoftext|>