<commit_before>package gondole

import ()
import (
	"github.com/sendgrid/rest"
	"fmt"
	"errors"
)

const (
	APIVersion = "0.0"

	APIEndpoint = "/api/v1"

	NoRedirect = "urn:ietf:wg:oauth:2.0:oob"
)

var (
	ErrAlreadyRegistered = errors.New("App already registered")
)

// prepareRequest insert all pre-defined stuff
func (g *Gondole) prepareRequest(what string) (req rest.Request) {
	endPoint := APIEndpoint + fmt.Sprintf("/%s/", what)

	// Add at least one option, the APIkey if present
	hdrs := make(map[string]string)
	opts := make(map[string]string)

	// Insert our sig
	hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", APIVersion)

	req = rest.Request{
		BaseURL:     endPoint,
		Headers:     hdrs,
		QueryParams: opts,
	}
	return
}
<commit_msg>Remove dup import().<commit_after>package gondole

import (
	"github.com/sendgrid/rest"
	"fmt"
	"errors"
)

const (
	APIVersion = "0.0"

	APIEndpoint = "/api/v1"

	NoRedirect = "urn:ietf:wg:oauth:2.0:oob"
)

var (
	ErrAlreadyRegistered = errors.New("App already registered")
)

// prepareRequest insert all pre-defined stuff
func (g *Gondole) prepareRequest(what string) (req rest.Request) {
	endPoint := APIEndpoint + fmt.Sprintf("/%s/", what)

	// Add at least one option, the APIkey if present
	hdrs := make(map[string]string)
	opts := make(map[string]string)

	// Insert our sig
	hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", APIVersion)

	req = rest.Request{
		BaseURL:     endPoint,
		Headers:     hdrs,
		QueryParams: opts,
	}
	return
}
<|endoftext|>


<commit_before>package main

/*
gophish - Open-Source Phishing Framework

The MIT License (MIT)

Copyright (c) 2013 Jordan Wright

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import (
	"fmt"
	"log"
	"net/http"
	"os"
	"sync"

	"github.com/gophish/gophish/config"
	"github.com/gophish/gophish/controllers"
	"github.com/gophish/gophish/models"
	"github.com/gorilla/handlers"
)

var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)

func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	// Start the web servers
	go func() {
		defer wg.Done()
		if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
			Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		} else {
			Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreateAdminRouter())))
		}
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
			Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		} else {
			Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, controllers.CreatePhishingRouter())))
		}
	}()
	wg.Wait()
}
<commit_msg>Added gzip support on admin/phishing routers. Fixes #2<commit_after>package main

/*
gophish - Open-Source Phishing Framework

The MIT License (MIT)

Copyright (c) 2013 Jordan Wright

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import (
	"fmt"
	"log"
	"net/http"
	"os"
	"sync"

	"github.com/NYTimes/gziphandler"
	"github.com/gophish/gophish/config"
	"github.com/gophish/gophish/controllers"
	"github.com/gophish/gophish/models"
	"github.com/gorilla/handlers"
)

var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)

func main() {
	// Setup the global variables and settings
	err := models.Setup()
	if err != nil {
		fmt.Println(err)
	}
	wg := &sync.WaitGroup{}
	wg.Add(1)
	// Start the web servers
	go func() {
		defer wg.Done()
		adminHandler := gziphandler.GzipHandler(controllers.CreateAdminRouter())
		if config.Conf.AdminConf.UseTLS { // use TLS for Admin web server if available
			Logger.Printf("Starting admin server at https://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.AdminConf.ListenURL, config.Conf.AdminConf.CertPath, config.Conf.AdminConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, adminHandler)))
		} else {
			Logger.Printf("Starting admin server at http://%s\n", config.Conf.AdminConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.AdminConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, adminHandler)))
		}
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		phishHandler := gziphandler.GzipHandler(controllers.CreatePhishingRouter())
		if config.Conf.PhishConf.UseTLS { // use TLS for Phish web server if available
			Logger.Printf("Starting phishing server at https://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServeTLS(config.Conf.PhishConf.ListenURL, config.Conf.PhishConf.CertPath, config.Conf.PhishConf.KeyPath,
				handlers.CombinedLoggingHandler(os.Stdout, phishHandler)))
		} else {
			Logger.Printf("Starting phishing server at http://%s\n", config.Conf.PhishConf.ListenURL)
			Logger.Fatal(http.ListenAndServe(config.Conf.PhishConf.ListenURL, handlers.CombinedLoggingHandler(os.Stdout, phishHandler)))
		}
	}()
	wg.Wait()
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"golang.org/x/sys/windows"
	"syscall"
	"unsafe"
)

// The following definitions assume the OS is greater than or equal to Windows 7.
var (
	modkernel32             = windows.NewLazySystemDLL("kernel32.dll")
	enumProcesses           = modkernel32.NewProc("K32EnumProcesses")
	openProcess             = modkernel32.NewProc("OpenProcess")
	getProcessImageFileName = modkernel32.NewProc("K32GetProcessImageFileNameA")
)

const (
	MAX_PATH                          int = 256
	PROCESS_QUERY_INFORMATION         int = 0x0400
	PROCESS_QUERY_LIMITED_INFORMATION int = 0x1000
)

type Process struct {
	name string
	pid  int // DWORD
}

func GetProcessIds() (procList []int32, err error) {
	// BOOL WINAPI EnumProcesses(
	//   _Out_ DWORD *pProcessIds,
	//   _In_  DWORD cb,
	//   _Out_ DWORD *pBytesReturned
	// );
	var numArgs uintptr = 4
	const numProcIds uint32 = 65535
	var processIds [numProcIds]int32
	cb := numProcIds
	numBytesReturned := 0

	ret, _, err := syscall.Syscall(enumProcesses.Addr(),
		numArgs,
		uintptr(unsafe.Pointer(&processIds[0])),
		uintptr(numProcIds),
		uintptr(unsafe.Pointer(&numBytesReturned)))
	if ret == 0 {
		return nil, err
	}

	const sizeofDword = 4
	numProcs := uint32(numBytesReturned / sizeofDword)

	if numProcs == cb {
		// There may be more processes.
		// Try re-enumerating with a larger array.
		return nil, errors.New("too many process IDs were returned")
	}

	return processIds[:numProcs], nil
}

func OpenProcess(pid int32, accessLevel int32) (hwnd uintptr, err error) {
	// HANDLE WINAPI OpenProcess(
	//   _In_ DWORD dwDesiredAccess,
	//   _In_ BOOL  bInheritHandle,
	//   _In_ DWORD dwProcessId
	// );
	var numArgs uintptr = 3
	ret, _, err := syscall.Syscall(openProcess.Addr(),
		numArgs,
		uintptr(accessLevel),
		uintptr(0),
		uintptr(pid))
	if ret == 0 {
		return uintptr(0), err
	}

	return ret, nil
}

func GetProcessNameFromPid(pid int32) (name string, err error) {
	accessLevel := int32(PROCESS_QUERY_INFORMATION |
		PROCESS_QUERY_LIMITED_INFORMATION)
	hwnd, err := OpenProcess(pid, accessLevel)
	if err != nil {
		return "", err
	}

	// DWORD WINAPI GetProcessImageFileName(
	//   _In_  HANDLE hProcess,
	//   _Out_ LPTSTR lpImageFileName,
	//   _In_  DWORD  nSize
	// );
	var numArgs uintptr = 3
	var imageFileName [MAX_PATH]byte
	ret, _, err := syscall.Syscall(getProcessImageFileName.Addr(),
		numArgs,
		hwnd,
		uintptr(unsafe.Pointer(&imageFileName[0])),
		uintptr(MAX_PATH))
	if ret == 0 {
		return "", err
	}

	return string(imageFileName[:ret]), nil
}

func main() {
	// Get the process list.
	pids, err := GetProcessIds()
	if err != nil {
		fmt.Println("[-] error:", err)
		return
	}

	// Correlate the process IDs with process names.
	for _, p := range pids {
		name, err := GetProcessNameFromPid(p)
		if err != nil {
			fmt.Printf("[-] error for PID: %v: %v\n", p, err)
		} else {
			fmt.Println("PID: ", p, "Name: ", name)
		}
	}

	// Open one of the processes.
	// TODO: hwnd, err := OpenProcess(w32.PROCESS_ALL_ACCESS, false, pid)
	// HANDLE WINAPI OpenProcess(
	//   _In_ DWORD dwDesiredAccess,
	//   _In_ BOOL  bInheritHandle,
	//   _In_ DWORD dwProcessId
	// );

	// Read some memory.
	// TODO: data, err := ReadProcessMemory(hwnd, address, 1)
	// BOOL WINAPI ReadProcessMemory(
	//   _In_  HANDLE  hProcess,
	//   _In_  LPCVOID lpBaseAddress,
	//   _Out_ LPVOID  lpBuffer,
	//   _In_  SIZE_T  nSize,
	//   _Out_ SIZE_T  *lpNumberOfBytesRead
	// );
}
<commit_msg>just return the exe name<commit_after>package main

import (
	"errors"
	"fmt"
	"golang.org/x/sys/windows"
	"path/filepath"
	"syscall"
	"unsafe"
)

// The following definitions assume the OS is greater than or equal to Windows 7.
var (
	modkernel32             = windows.NewLazySystemDLL("kernel32.dll")
	enumProcesses           = modkernel32.NewProc("K32EnumProcesses")
	openProcess             = modkernel32.NewProc("OpenProcess")
	getProcessImageFileName = modkernel32.NewProc("K32GetProcessImageFileNameA")
)

const (
	MAX_PATH                          int = 256
	PROCESS_QUERY_INFORMATION         int = 0x0400
	PROCESS_QUERY_LIMITED_INFORMATION int = 0x1000
)

type Process struct {
	name string
	pid  int // DWORD
}

func GetProcessIds() (procList []int32, err error) {
	// BOOL WINAPI EnumProcesses(
	//   _Out_ DWORD *pProcessIds,
	//   _In_  DWORD cb,
	//   _Out_ DWORD *pBytesReturned
	// );
	var numArgs uintptr = 4
	const numProcIds uint32 = 65535
	var processIds [numProcIds]int32
	cb := numProcIds
	numBytesReturned := 0

	ret, _, err := syscall.Syscall(enumProcesses.Addr(),
		numArgs,
		uintptr(unsafe.Pointer(&processIds[0])),
		uintptr(numProcIds),
		uintptr(unsafe.Pointer(&numBytesReturned)))
	if ret == 0 {
		return nil, err
	}

	const sizeofDword = 4
	numProcs := uint32(numBytesReturned / sizeofDword)

	if numProcs == cb {
		// There may be more processes.
		// Try re-enumerating with a larger array.
		return nil, errors.New("too many process IDs were returned")
	}

	return processIds[:numProcs], nil
}

func OpenProcess(pid int32, accessLevel int32) (hwnd uintptr, err error) {
	// HANDLE WINAPI OpenProcess(
	//   _In_ DWORD dwDesiredAccess,
	//   _In_ BOOL  bInheritHandle,
	//   _In_ DWORD dwProcessId
	// );
	var numArgs uintptr = 3
	ret, _, err := syscall.Syscall(openProcess.Addr(),
		numArgs,
		uintptr(accessLevel),
		uintptr(0),
		uintptr(pid))
	if ret == 0 {
		return uintptr(0), err
	}

	return ret, nil
}

func GetProcessNameFromPid(pid int32) (name string, err error) {
	accessLevel := int32(PROCESS_QUERY_INFORMATION |
		PROCESS_QUERY_LIMITED_INFORMATION)
	hwnd, err := OpenProcess(pid, accessLevel)
	if err != nil {
		return "", err
	}

	// DWORD WINAPI GetProcessImageFileName(
	//   _In_  HANDLE hProcess,
	//   _Out_ LPTSTR lpImageFileName,
	//   _In_  DWORD  nSize
	// );
	var numArgs uintptr = 3
	var imageFileName [MAX_PATH]byte
	ret, _, err := syscall.Syscall(getProcessImageFileName.Addr(),
		numArgs,
		hwnd,
		uintptr(unsafe.Pointer(&imageFileName[0])),
		uintptr(MAX_PATH))
	if ret == 0 {
		return "", err
	}

	imageName := string(imageFileName[:ret])
	_, procName := filepath.Split(imageName)

	return procName, nil
}

func main() {
	// Get the process list.
	pids, err := GetProcessIds()
	if err != nil {
		fmt.Println("[-] error:", err)
		return
	}

	// Correlate the process IDs with process names.
	for _, p := range pids {
		name, err := GetProcessNameFromPid(p)
		if err != nil {
			fmt.Printf("[-] error for PID: %v: %v\n", p, err)
		} else {
			fmt.Println("PID:", p, "Name:", name)
		}
	}

	// Open one of the processes.
	// TODO: hwnd, err := OpenProcess(w32.PROCESS_ALL_ACCESS, false, pid)
	// HANDLE WINAPI OpenProcess(
	//   _In_ DWORD dwDesiredAccess,
	//   _In_ BOOL  bInheritHandle,
	//   _In_ DWORD dwProcessId
	// );

	// Read some memory.
	// TODO: data, err := ReadProcessMemory(hwnd, address, 1)
	// BOOL WINAPI ReadProcessMemory(
	//   _In_  HANDLE  hProcess,
	//   _In_  LPCVOID lpBaseAddress,
	//   _Out_ LPVOID  lpBuffer,
	//   _In_  SIZE_T  nSize,
	//   _Out_ SIZE_T  *lpNumberOfBytesRead
	// );
}
<|endoftext|>


<commit_before>package gps

import(
    // #cgo LDFLAGS: -lgps
    // #include <gps.h>
    "C"
)

func GpsLocation() (float64, float64) {
    var data C.loc_t
    var lat, lon float64

    C.gps_location(&data)

    lat = float64(data.latitude)
    lon = float64(data.longitude)

    return lat, lon
}
<commit_msg>Included C math library<commit_after>package gps

import(
    // #cgo LDFLAGS: -lgps -lm
    // #include <gps.h>
    "C"
    "math"
)

const (
    Earth = 6371
    DegToRad = 180/math.Pi
    RadToDeg = math.Pi/180

)

func GpsLocation() (float64, float64) {
    var data C.loc_t
    var lat, lon float64

    C.gps_location(&data)

    lat = float64(data.latitude)
    lon = float64(data.longitude)

    return lat, lon
}

func Distance(lat1, lon1, lat2, lon2 float64) float64 {
    dLat := (lat2 - lat1) * DegToRad
    dLon := (lon2 - lon1) * DegToRad

    lat1 = lat1 * DegToRad
    lat2 = lat2 * DegToRad

    a := math.Sin(dLat/2) * math.Sin(dLat/2) + math.Sin(dLon/2) * math.Sin(dLon/2) * math.Cos(lat1) * math.Cos(lat2)
    c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a));

    d := Earth * c;
    return d;
}
<|endoftext|>


<commit_before>package radix

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"github.com/mediocregopher/radix/v3/resp"
	"github.com/mediocregopher/radix/v3/resp/resp2"
	"io"
	"math"
	"strconv"
)

// StreamEntryID represents an ID used in a Redis stream with the format <time>-<seq>.
type StreamEntryID struct {
	// Time is the first part of the ID, which is based on the time of the server that Redis runs on.
	Time uint64

	// Seq is the sequence number of the ID for entries with the same Time value.
	Seq uint64
}

// Before returns true if s comes before o in a stream (is less than o).
func (s StreamEntryID) Before(o StreamEntryID) bool {
	if s.Time != o.Time {
		return s.Time < o.Time
	}

	return s.Seq < o.Seq
}

// Prev returns the previous stream entry ID or s if there is no prior id (s is 0-0).
func (s StreamEntryID) Prev() StreamEntryID {
	if s.Seq > 0 {
		s.Seq--
		return s
	}

	if s.Time > 0 {
		s.Time--
		s.Seq = math.MaxUint64
		return s
	}

	return s
}

// Next returns the next stream entry ID or s if there is no higher id (s is 18446744073709551615-18446744073709551615).
func (s StreamEntryID) Next() StreamEntryID {
	if s.Seq < math.MaxUint64 {
		s.Seq++
		return s
	}

	if s.Time < math.MaxUint64 {
		s.Time++
		s.Seq = 0
		return s
	}

	return s
}

var _ resp.Marshaler = (*StreamEntryID)(nil)
var _ resp.Unmarshaler = (*StreamEntryID)(nil)

const maxUint64Len = len("18446744073709551615")

// MarshalRESP implements the resp.Marshaler interface.
func (s *StreamEntryID) MarshalRESP(w io.Writer) error {
	var buf [maxUint64Len*2 + 1]byte
	b := strconv.AppendUint(buf[:0], s.Time, 10)
	b = append(b, '-')
	b = strconv.AppendUint(b, s.Seq, 10)

	return resp2.BulkStringBytes{B: b}.MarshalRESP(w)
}

var errInvalidStreamID = errors.New("invalid stream entry id")

// UnmarshalRESP implements the resp.Unmarshaler interface.
func (s *StreamEntryID) UnmarshalRESP(br *bufio.Reader) error {
	var buf [maxUint64Len*2 + 1]byte

	bsb := resp2.BulkStringBytes{B: buf[:0]}
	if err := bsb.UnmarshalRESP(br); err != nil {
		return err
	}

	split := bytes.IndexByte(bsb.B, '-')
	if split == -1 {
		return errInvalidStreamID
	}

	// TODO(nussjustin): use readUint from the resp2 package
	time, err := strconv.ParseUint(string(bsb.B[:split]), 10, 64)
	if err != nil {
		return errInvalidStreamID
	}

	// TODO(nussjustin): use readUint from the resp2 package
	seq, err := strconv.ParseUint(string(bsb.B[split+1:]), 10, 64)
	if err != nil {
		return errInvalidStreamID
	}

	s.Time, s.Seq = time, seq
	return nil
}

var _ fmt.Stringer = (*StreamEntryID)(nil)

// String returns the ID in the format <time>-<seq> (the same format used by Redis).
//
// String implements the fmt.Stringer interface.
func (s StreamEntryID) String() string {
	var buf [maxUint64Len*2 + 1]byte
	b := strconv.AppendUint(buf[:0], s.Time, 10)
	b = append(b, '-')
	b = strconv.AppendUint(b, s.Seq, 10)
	return string(b)
}

// StreamEntry is an entry in a Redis stream as returned by XRANGE, XREAD and XREADGROUP.
type StreamEntry struct {
	// ID is the ID of the entry in a stream.
	ID StreamEntryID

	// Fields contains the fields and values for the stream entry.
	Fields map[string]string
}

var _ resp.Unmarshaler = (*StreamEntry)(nil)

var errInvalidStreamEntry = errors.New("invalid stream entry")

// UnmarshalRESP implements the resp.Unmarshaler interface.
func (s *StreamEntry) UnmarshalRESP(br *bufio.Reader) error {
	var ah resp2.ArrayHeader
	if err := ah.UnmarshalRESP(br); err != nil {
		return err
	}

	if ah.N != 2 {
		return errInvalidStreamEntry
	}

	if err := s.ID.UnmarshalRESP(br); err != nil {
		return err
	}

	return resp2.Any{I: &s.Fields}.UnmarshalRESP(br)
}<commit_msg>Use bytesutil package for stream entry id parsing<commit_after>package radix

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"github.com/mediocregopher/radix/v3/internal/bytesutil"
	"github.com/mediocregopher/radix/v3/resp"
	"github.com/mediocregopher/radix/v3/resp/resp2"
	"io"
	"math"
	"strconv"
)

// StreamEntryID represents an ID used in a Redis stream with the format <time>-<seq>.
type StreamEntryID struct {
	// Time is the first part of the ID, which is based on the time of the server that Redis runs on.
	Time uint64

	// Seq is the sequence number of the ID for entries with the same Time value.
	Seq uint64
}

// Before returns true if s comes before o in a stream (is less than o).
func (s StreamEntryID) Before(o StreamEntryID) bool {
	if s.Time != o.Time {
		return s.Time < o.Time
	}

	return s.Seq < o.Seq
}

// Prev returns the previous stream entry ID or s if there is no prior id (s is 0-0).
func (s StreamEntryID) Prev() StreamEntryID {
	if s.Seq > 0 {
		s.Seq--
		return s
	}

	if s.Time > 0 {
		s.Time--
		s.Seq = math.MaxUint64
		return s
	}

	return s
}

// Next returns the next stream entry ID or s if there is no higher id (s is 18446744073709551615-18446744073709551615).
func (s StreamEntryID) Next() StreamEntryID {
	if s.Seq < math.MaxUint64 {
		s.Seq++
		return s
	}

	if s.Time < math.MaxUint64 {
		s.Time++
		s.Seq = 0
		return s
	}

	return s
}

var _ resp.Marshaler = (*StreamEntryID)(nil)
var _ resp.Unmarshaler = (*StreamEntryID)(nil)

const maxUint64Len = len("18446744073709551615")

// MarshalRESP implements the resp.Marshaler interface.
func (s *StreamEntryID) MarshalRESP(w io.Writer) error {
	var buf [maxUint64Len*2 + 1]byte
	b := strconv.AppendUint(buf[:0], s.Time, 10)
	b = append(b, '-')
	b = strconv.AppendUint(b, s.Seq, 10)

	return resp2.BulkStringBytes{B: b}.MarshalRESP(w)
}

var errInvalidStreamID = errors.New("invalid stream entry id")

// UnmarshalRESP implements the resp.Unmarshaler interface.
func (s *StreamEntryID) UnmarshalRESP(br *bufio.Reader) error {
	var buf [maxUint64Len*2 + 1]byte

	bsb := resp2.BulkStringBytes{B: buf[:0]}
	if err := bsb.UnmarshalRESP(br); err != nil {
		return err
	}

	split := bytes.IndexByte(bsb.B, '-')
	if split == -1 {
		return errInvalidStreamID
	}

	time, err := bytesutil.ParseUint(bsb.B[:split])
	if err != nil {
		return errInvalidStreamID
	}

	seq, err := bytesutil.ParseUint(bsb.B[split+1:])
	if err != nil {
		return errInvalidStreamID
	}

	s.Time, s.Seq = time, seq
	return nil
}

var _ fmt.Stringer = (*StreamEntryID)(nil)

// String returns the ID in the format <time>-<seq> (the same format used by Redis).
//
// String implements the fmt.Stringer interface.
func (s StreamEntryID) String() string {
	var buf [maxUint64Len*2 + 1]byte
	b := strconv.AppendUint(buf[:0], s.Time, 10)
	b = append(b, '-')
	b = strconv.AppendUint(b, s.Seq, 10)
	return string(b)
}

// StreamEntry is an entry in a Redis stream as returned by XRANGE, XREAD and XREADGROUP.
type StreamEntry struct {
	// ID is the ID of the entry in a stream.
	ID StreamEntryID

	// Fields contains the fields and values for the stream entry.
	Fields map[string]string
}

var _ resp.Unmarshaler = (*StreamEntry)(nil)

var errInvalidStreamEntry = errors.New("invalid stream entry")

// UnmarshalRESP implements the resp.Unmarshaler interface.
func (s *StreamEntry) UnmarshalRESP(br *bufio.Reader) error {
	var ah resp2.ArrayHeader
	if err := ah.UnmarshalRESP(br); err != nil {
		return err
	}

	if ah.N != 2 {
		return errInvalidStreamEntry
	}

	if err := s.ID.UnmarshalRESP(br); err != nil {
		return err
	}

	return resp2.Any{I: &s.Fields}.UnmarshalRESP(br)
}<|endoftext|>


<commit_before>package quic

import (
	"fmt"
	"io"
	"sync"

	"github.com/lucas-clemente/quic-go/flowcontrol"
	"github.com/lucas-clemente/quic-go/frames"
	"github.com/lucas-clemente/quic-go/protocol"
	"github.com/lucas-clemente/quic-go/utils"
)

// A Stream assembles the data from StreamFrames and provides a super-convenient Read-Interface
//
// Read() and Write() may be called concurrently, but multiple calls to Read() or Write() individually must be synchronized manually.
type stream struct {
	mutex sync.Mutex

	streamID protocol.StreamID
	onData   func()

	readPosInFrame int
	writeOffset    protocol.ByteCount
	readOffset     protocol.ByteCount

	// Once set, the errors must not be changed!
	err error

	// cancelled is set when Cancel() is called
	cancelled utils.AtomicBool
	// finishedReading is set once we read a frame with a FinBit
	finishedReading utils.AtomicBool
	// finisedWriting is set once Close() is called
	finishedWriting utils.AtomicBool
	// resetLocally is set if Reset() is called
	resetLocally utils.AtomicBool
	// resetRemotely is set if RegisterRemoteError() is called
	resetRemotely utils.AtomicBool

	frameQueue        *streamFrameSorter
	newFrameOrErrCond sync.Cond

	dataForWriting       []byte
	finSent              utils.AtomicBool
	doneWritingOrErrCond sync.Cond

	flowControlManager flowcontrol.FlowControlManager
}

// newStream creates a new Stream
func newStream(StreamID protocol.StreamID, onData func(), flowControlManager flowcontrol.FlowControlManager) (*stream, error) {
	s := &stream{
		onData:             onData,
		streamID:           StreamID,
		flowControlManager: flowControlManager,
		frameQueue:         newStreamFrameSorter(),
	}

	s.newFrameOrErrCond.L = &s.mutex
	s.doneWritingOrErrCond.L = &s.mutex

	return s, nil
}

// Read implements io.Reader. It is not thread safe!
func (s *stream) Read(p []byte) (int, error) {
	if s.cancelled.Get() || s.resetLocally.Get() {
		return 0, s.err
	}
	if s.finishedReading.Get() {
		return 0, io.EOF
	}

	bytesRead := 0
	for bytesRead < len(p) {
		s.mutex.Lock()
		frame := s.frameQueue.Head()

		if frame == nil && bytesRead > 0 {
			s.mutex.Unlock()
			return bytesRead, s.err
		}

		var err error
		for {
			// Stop waiting on errors
			if s.resetLocally.Get() || s.cancelled.Get() {
				err = s.err
				break
			}
			if frame != nil {
				s.readPosInFrame = int(s.readOffset - frame.Offset)
				break
			}
			s.newFrameOrErrCond.Wait()
			frame = s.frameQueue.Head()
		}
		s.mutex.Unlock()

		if err != nil {
			return bytesRead, err
		}

		m := utils.Min(len(p)-bytesRead, int(frame.DataLen())-s.readPosInFrame)

		if bytesRead > len(p) {
			return bytesRead, fmt.Errorf("BUG: bytesRead (%d) > len(p) (%d) in stream.Read", bytesRead, len(p))
		}
		if s.readPosInFrame > int(frame.DataLen()) {
			return bytesRead, fmt.Errorf("BUG: readPosInFrame (%d) > frame.DataLen (%d) in stream.Read", s.readPosInFrame, frame.DataLen())
		}
		copy(p[bytesRead:], frame.Data[s.readPosInFrame:])

		s.readPosInFrame += m
		bytesRead += m
		s.readOffset += protocol.ByteCount(m)

		s.flowControlManager.AddBytesRead(s.streamID, protocol.ByteCount(m))
		s.onData() // so that a possible WINDOW_UPDATE is sent

		if s.readPosInFrame >= int(frame.DataLen()) {
			fin := frame.FinBit
			s.mutex.Lock()
			s.frameQueue.Pop()
			s.mutex.Unlock()
			if fin {
				s.finishedReading.Set(true)
				return bytesRead, io.EOF
			}
		}
	}

	return bytesRead, nil
}

func (s *stream) Write(p []byte) (int, error) {
	if s.resetLocally.Get() {
		return 0, s.err
	}

	s.mutex.Lock()
	defer s.mutex.Unlock()

	if s.err != nil {
		return 0, s.err
	}

	if len(p) == 0 {
		return 0, nil
	}

	s.dataForWriting = make([]byte, len(p))
	copy(s.dataForWriting, p)

	s.onData()

	for s.dataForWriting != nil && s.err == nil {
		s.doneWritingOrErrCond.Wait()
	}

	if s.err != nil {
		return 0, s.err
	}

	return len(p), nil
}

func (s *stream) lenOfDataForWriting() protocol.ByteCount {
	s.mutex.Lock()
	var l protocol.ByteCount
	if s.err == nil {
		l = protocol.ByteCount(len(s.dataForWriting))
	}
	s.mutex.Unlock()
	return l
}

func (s *stream) getDataForWriting(maxBytes protocol.ByteCount) []byte {
	s.mutex.Lock()
	if s.err != nil {
		s.mutex.Unlock()
		return nil
	}
	if s.dataForWriting == nil {
		s.mutex.Unlock()
		return nil
	}
	var ret []byte
	if protocol.ByteCount(len(s.dataForWriting)) > maxBytes {
		ret = s.dataForWriting[:maxBytes]
		s.dataForWriting = s.dataForWriting[maxBytes:]
	} else {
		ret = s.dataForWriting
		s.dataForWriting = nil
		s.doneWritingOrErrCond.Signal()
	}
	s.writeOffset += protocol.ByteCount(len(ret))
	s.mutex.Unlock()
	return ret
}

// Close implements io.Closer
func (s *stream) Close() error {
	s.finishedWriting.Set(true)
	s.onData()
	return nil
}

func (s *stream) shouldSendFin() bool {
	s.mutex.Lock()
	res := s.finishedWriting.Get() && !s.finSent.Get() && s.err == nil && s.dataForWriting == nil
	s.mutex.Unlock()
	return res
}

func (s *stream) sentFin() {
	s.finSent.Set(true)
}

// AddStreamFrame adds a new stream frame
func (s *stream) AddStreamFrame(frame *frames.StreamFrame) error {
	maxOffset := frame.Offset + frame.DataLen()
	err := s.flowControlManager.UpdateHighestReceived(s.streamID, maxOffset)
	if err != nil {
		return err
	}

	s.mutex.Lock()
	defer s.mutex.Unlock()
	err = s.frameQueue.Push(frame)
	if err != nil && err != errDuplicateStreamData {
		return err
	}
	s.newFrameOrErrCond.Signal()
	return nil
}

// CloseRemote makes the stream receive a "virtual" FIN stream frame at a given offset
func (s *stream) CloseRemote(offset protocol.ByteCount) {
	s.AddStreamFrame(&frames.StreamFrame{FinBit: true, Offset: offset})
}

// Cancel is called by session to indicate that an error occurred
// The stream should will be closed immediately
func (s *stream) Cancel(err error) {
	s.cancelled.Set(true)

	s.mutex.Lock()
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.newFrameOrErrCond.Signal()
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

// resets the stream locally
func (s *stream) Reset(err error) {
	s.resetLocally.Set(true)
	s.mutex.Lock()
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.newFrameOrErrCond.Signal()
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

// resets the stream remotely
func (s *stream) RegisterRemoteError(err error) {
	s.resetRemotely.Set(true)
	s.mutex.Lock()
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

func (s *stream) finishedWriteAndSentFin() bool {
	return s.finishedWriting.Get() && s.finSent.Get()
}

func (s *stream) finished() bool {
	return s.cancelled.Get() || (s.finishedReading.Get() && s.finishedWriteAndSentFin())
}

func (s *stream) StreamID() protocol.StreamID {
	return s.streamID
}
<commit_msg>fix race condition in stream<commit_after>package quic

import (
	"fmt"
	"io"
	"sync"

	"github.com/lucas-clemente/quic-go/flowcontrol"
	"github.com/lucas-clemente/quic-go/frames"
	"github.com/lucas-clemente/quic-go/protocol"
	"github.com/lucas-clemente/quic-go/utils"
)

// A Stream assembles the data from StreamFrames and provides a super-convenient Read-Interface
//
// Read() and Write() may be called concurrently, but multiple calls to Read() or Write() individually must be synchronized manually.
type stream struct {
	mutex sync.Mutex

	streamID protocol.StreamID
	onData   func()

	readPosInFrame int
	writeOffset    protocol.ByteCount
	readOffset     protocol.ByteCount

	// Once set, the errors must not be changed!
	err error

	// cancelled is set when Cancel() is called
	cancelled utils.AtomicBool
	// finishedReading is set once we read a frame with a FinBit
	finishedReading utils.AtomicBool
	// finisedWriting is set once Close() is called
	finishedWriting utils.AtomicBool
	// resetLocally is set if Reset() is called
	resetLocally utils.AtomicBool
	// resetRemotely is set if RegisterRemoteError() is called
	resetRemotely utils.AtomicBool

	frameQueue        *streamFrameSorter
	newFrameOrErrCond sync.Cond

	dataForWriting       []byte
	finSent              utils.AtomicBool
	doneWritingOrErrCond sync.Cond

	flowControlManager flowcontrol.FlowControlManager
}

// newStream creates a new Stream
func newStream(StreamID protocol.StreamID, onData func(), flowControlManager flowcontrol.FlowControlManager) (*stream, error) {
	s := &stream{
		onData:             onData,
		streamID:           StreamID,
		flowControlManager: flowControlManager,
		frameQueue:         newStreamFrameSorter(),
	}

	s.newFrameOrErrCond.L = &s.mutex
	s.doneWritingOrErrCond.L = &s.mutex

	return s, nil
}

// Read implements io.Reader. It is not thread safe!
func (s *stream) Read(p []byte) (int, error) {
	if s.cancelled.Get() || s.resetLocally.Get() {
		return 0, s.err
	}
	if s.finishedReading.Get() {
		return 0, io.EOF
	}

	bytesRead := 0
	for bytesRead < len(p) {
		s.mutex.Lock()
		frame := s.frameQueue.Head()

		if frame == nil && bytesRead > 0 {
			s.mutex.Unlock()
			return bytesRead, s.err
		}

		var err error
		for {
			// Stop waiting on errors
			if s.resetLocally.Get() || s.cancelled.Get() {
				err = s.err
				break
			}
			if frame != nil {
				s.readPosInFrame = int(s.readOffset - frame.Offset)
				break
			}
			s.newFrameOrErrCond.Wait()
			frame = s.frameQueue.Head()
		}
		s.mutex.Unlock()

		if err != nil {
			return bytesRead, err
		}

		m := utils.Min(len(p)-bytesRead, int(frame.DataLen())-s.readPosInFrame)

		if bytesRead > len(p) {
			return bytesRead, fmt.Errorf("BUG: bytesRead (%d) > len(p) (%d) in stream.Read", bytesRead, len(p))
		}
		if s.readPosInFrame > int(frame.DataLen()) {
			return bytesRead, fmt.Errorf("BUG: readPosInFrame (%d) > frame.DataLen (%d) in stream.Read", s.readPosInFrame, frame.DataLen())
		}
		copy(p[bytesRead:], frame.Data[s.readPosInFrame:])

		s.readPosInFrame += m
		bytesRead += m
		s.readOffset += protocol.ByteCount(m)

		s.flowControlManager.AddBytesRead(s.streamID, protocol.ByteCount(m))
		s.onData() // so that a possible WINDOW_UPDATE is sent

		if s.readPosInFrame >= int(frame.DataLen()) {
			fin := frame.FinBit
			s.mutex.Lock()
			s.frameQueue.Pop()
			s.mutex.Unlock()
			if fin {
				s.finishedReading.Set(true)
				return bytesRead, io.EOF
			}
		}
	}

	return bytesRead, nil
}

func (s *stream) Write(p []byte) (int, error) {
	if s.resetLocally.Get() {
		return 0, s.err
	}

	s.mutex.Lock()
	defer s.mutex.Unlock()

	if s.err != nil {
		return 0, s.err
	}

	if len(p) == 0 {
		return 0, nil
	}

	s.dataForWriting = make([]byte, len(p))
	copy(s.dataForWriting, p)

	s.onData()

	for s.dataForWriting != nil && s.err == nil {
		s.doneWritingOrErrCond.Wait()
	}

	if s.err != nil {
		return 0, s.err
	}

	return len(p), nil
}

func (s *stream) lenOfDataForWriting() protocol.ByteCount {
	s.mutex.Lock()
	var l protocol.ByteCount
	if s.err == nil {
		l = protocol.ByteCount(len(s.dataForWriting))
	}
	s.mutex.Unlock()
	return l
}

func (s *stream) getDataForWriting(maxBytes protocol.ByteCount) []byte {
	s.mutex.Lock()
	if s.err != nil {
		s.mutex.Unlock()
		return nil
	}
	if s.dataForWriting == nil {
		s.mutex.Unlock()
		return nil
	}
	var ret []byte
	if protocol.ByteCount(len(s.dataForWriting)) > maxBytes {
		ret = s.dataForWriting[:maxBytes]
		s.dataForWriting = s.dataForWriting[maxBytes:]
	} else {
		ret = s.dataForWriting
		s.dataForWriting = nil
		s.doneWritingOrErrCond.Signal()
	}
	s.writeOffset += protocol.ByteCount(len(ret))
	s.mutex.Unlock()
	return ret
}

// Close implements io.Closer
func (s *stream) Close() error {
	s.finishedWriting.Set(true)
	s.onData()
	return nil
}

func (s *stream) shouldSendFin() bool {
	s.mutex.Lock()
	res := s.finishedWriting.Get() && !s.finSent.Get() && s.err == nil && s.dataForWriting == nil
	s.mutex.Unlock()
	return res
}

func (s *stream) sentFin() {
	s.finSent.Set(true)
}

// AddStreamFrame adds a new stream frame
func (s *stream) AddStreamFrame(frame *frames.StreamFrame) error {
	maxOffset := frame.Offset + frame.DataLen()
	err := s.flowControlManager.UpdateHighestReceived(s.streamID, maxOffset)
	if err != nil {
		return err
	}

	s.mutex.Lock()
	defer s.mutex.Unlock()
	err = s.frameQueue.Push(frame)
	if err != nil && err != errDuplicateStreamData {
		return err
	}
	s.newFrameOrErrCond.Signal()
	return nil
}

// CloseRemote makes the stream receive a "virtual" FIN stream frame at a given offset
func (s *stream) CloseRemote(offset protocol.ByteCount) {
	s.AddStreamFrame(&frames.StreamFrame{FinBit: true, Offset: offset})
}

// Cancel is called by session to indicate that an error occurred
// The stream should will be closed immediately
func (s *stream) Cancel(err error) {
	s.mutex.Lock()
	s.cancelled.Set(true)
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.newFrameOrErrCond.Signal()
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

// resets the stream locally
func (s *stream) Reset(err error) {
	s.mutex.Lock()
	s.resetLocally.Set(true)
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.newFrameOrErrCond.Signal()
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

// resets the stream remotely
func (s *stream) RegisterRemoteError(err error) {
	s.mutex.Lock()
	s.resetRemotely.Set(true)
	// errors must not be changed!
	if s.err == nil {
		s.err = err
		s.doneWritingOrErrCond.Signal()
	}
	s.mutex.Unlock()
}

func (s *stream) finishedWriteAndSentFin() bool {
	return s.finishedWriting.Get() && s.finSent.Get()
}

func (s *stream) finished() bool {
	return s.cancelled.Get() || (s.finishedReading.Get() && s.finishedWriteAndSentFin())
}

func (s *stream) StreamID() protocol.StreamID {
	return s.streamID
}
<|endoftext|>


<commit_before>package main

import (
	"koding/db/mongodb/modelhelper"
	"log"
	"socialapi/config"
	"socialapi/workers/email/emailsender"

	"github.com/koding/eventexporter"
	"github.com/koding/runner"
)

var (
	Name        = "MailSender"
	QueueLength = 1
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		log.Fatal(err)
	}

	appConfig := config.MustRead(r.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	segmentExporter := eventexporter.NewSegmentIOExporter(appConfig.Segment, QueueLength)
	datadogExporter := eventexporter.NewDatadogExporter(r.DogStatsD)

	// TODO
	// use config file for druid address
	druidExporter := eventexporter.NewDruidExporter("address")

	exporter := eventexporter.NewMultiExporter(segmentExporter, datadogExporter, druidExporter)

	constructor := emailsender.New(exporter, r.Log, appConfig)
	r.ShutdownHandler = constructor.Close

	r.SetContext(constructor)

	r.Register(emailsender.Mail{}).On(emailsender.SendEmailEventName).Handle((*emailsender.Controller).Process)

	r.Listen()
	r.Wait()
}
<commit_msg>go/druid : commentout exporter functions to pass build for now<commit_after>package main

import (
	"koding/db/mongodb/modelhelper"
	"log"
	"socialapi/config"
	"socialapi/workers/email/emailsender"

	"github.com/koding/eventexporter"
	"github.com/koding/runner"
)

var (
	Name        = "MailSender"
	QueueLength = 1
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		log.Fatal(err)
	}

	appConfig := config.MustRead(r.Conf.Path)
	modelhelper.Initialize(appConfig.Mongo)
	defer modelhelper.Close()

	segmentExporter := eventexporter.NewSegmentIOExporter(appConfig.Segment, QueueLength)

	// TODO
	// this lines will not be commentout
	// datadogExporter := eventexporter.NewDatadogExporter(r.DogStatsD)

	// TODO
	// use config file for druid address
	// open this line !!
	// druidExporter := eventexporter.NewDruidExporter("address")

	// TODO
	//open this line also!!!
	// exporter := eventexporter.NewMultiExporter(segmentExporter, datadogExporter, druidExporter)
	exporter := eventexporter.NewMultiExporter(segmentExporter)

	constructor := emailsender.New(exporter, r.Log, appConfig)
	r.ShutdownHandler = constructor.Close

	r.SetContext(constructor)

	r.Register(emailsender.Mail{}).On(emailsender.SendEmailEventName).Handle((*emailsender.Controller).Process)

	r.Listen()
	r.Wait()
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gorilla/handlers"
	"github.com/twpayne/gombtiles/mbtiles"
)

func addACAOHeader(value string, h http.Handler) http.Handler {
	if value == "" {
		return h
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", value)
		h.ServeHTTP(w, r)
	})
}

func stripExt(path string) string {
	return path[:len(path)-len(filepath.Ext(path))]
}

func main() {

	var (
		acao     = flag.String("acao", "*", "Access-Control-Allow-Origin")
		addr     = flag.String("addr", "127.0.0.1:8080", "addr")
		root     = flag.String("root", ".", "root")
		mbtiles_ = flag.String("mbtiles", "", "MBTiles")
		prefix   = flag.String("prefix", "/", "prefix")
	)
	flag.Parse()

	http.Handle(*prefix,
		handlers.LoggingHandler(os.Stdout,
			addACAOHeader(*acao,
				http.StripPrefix(*prefix,
					http.FileServer(http.Dir(*root))))))

	if *mbtiles_ != "" {
		if mbtilesBase := filepath.Base(*mbtiles_); mbtilesBase != "." {
			mbtilesPrefix := "/" + stripExt(mbtilesBase) + "/"
			ts, err := mbtiles.NewTileServer(*mbtiles_)
			if err != nil {
				log.Fatal(err)
			}
			defer ts.Close()
			http.Handle(mbtilesPrefix,
				handlers.LoggingHandler(os.Stdout,
					addACAOHeader(*acao,
						http.StripPrefix(mbtilesPrefix,
							ts))))
		}
	}

	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal(err)
	}

}
<commit_msg>Remove mbtiles serving<commit_after>package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gorilla/handlers"
)

func addACAOHeader(value string, h http.Handler) http.Handler {
	if value == "" {
		return h
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", value)
		h.ServeHTTP(w, r)
	})
}

func stripExt(path string) string {
	return path[:len(path)-len(filepath.Ext(path))]
}

func main() {

	var (
		acao   = flag.String("acao", "*", "Access-Control-Allow-Origin")
		addr   = flag.String("addr", "127.0.0.1:8080", "addr")
		root   = flag.String("root", ".", "root")
		prefix = flag.String("prefix", "/", "prefix")
	)
	flag.Parse()

	http.Handle(*prefix,
		handlers.LoggingHandler(os.Stdout,
			addACAOHeader(*acao,
				http.StripPrefix(*prefix,
					http.FileServer(http.Dir(*root))))))

	if err := http.ListenAndServe(*addr, nil); err != nil {
		log.Fatal(err)
	}

}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/signal"

	"golang.org/x/tools/imports"
)

func run(fileName string) error {
	cmd := exec.Command("go", "run", fileName)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func tempFile() (*os.File, error) {
	curDir, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	file, err := ioutil.TempFile(curDir, "temp")
	if err != nil {
		return nil, err
	}
	file.Close()

	// Add the .go suffix to the temp file.
	if err = os.Rename(file.Name(), file.Name()+".go"); err != nil {
		return nil, err
	}
	return os.Open(file.Name() + ".go")
}

func editImports(fileName string) error {
	// Read the code from the temp go file.
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		return err
	}

	// res holds the go file re-written with imports added.
	opt := &imports.Options{}
	res, err := imports.Process(fileName, data, opt)
	if err != nil {
		return err
	}

	// Write the edited file into the original temp file.
	if err = ioutil.WriteFile(fileName, res, 0644); err != nil {
		return err
	}
	return nil
}

func usage() {
	fmt.Println("Usage: gommand [code]")
	fmt.Println("Example: gommand 'name := \"Sno6\"; fmt.Println(name)'")
	os.Exit(1)
}

func clean(f *os.File) {
	f.Close()
	if err := os.Remove(f.Name()); err != nil {
		log.Printf("main: error removing tempfile: %v\n", err)
	}
}

func main() {
	if len(os.Args) < 2 {
		usage()
	}
	code := os.Args[1]
	if code == "" {
		usage()
	}

	file, err := tempFile()
	if err != nil {
		log.Fatalf("main: error creating temp file: %v\n", err)
	}
	defer func() {
		clean(file)
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		for range c {
			clean(file)
			os.Exit(1)
		}
	}()

	// bp holds the go boiler plate code with user inputted code added.
	bp := fmt.Sprintf("package main\nfunc main() {\n\t%v\n}", code)

	// Write go code to temp file and add missing imports.
	// Use Printf over Fatalf so removing of temp file will run through defer.
	if err = ioutil.WriteFile(file.Name(), []byte(bp), 0644); err != nil {
		log.Printf("main: error writing code to temp file: %v\n", err)
	}
	if err = editImports(file.Name()); err != nil {
		log.Printf("main: error editing imports: %v\n", err)
	}
	if err = run(file.Name()); err != nil {
		log.Printf("main: error running go code query: %v\n", err)
	}
}
<commit_msg>remove unnecessary comments and clean syscall handler<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/signal"

	"golang.org/x/tools/imports"
)

func run(fileName string) error {
	cmd := exec.Command("go", "run", fileName)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func tempFile() (*os.File, error) {
	curDir, err := os.Getwd()
	if err != nil {
		return nil, err
	}
	file, err := ioutil.TempFile(curDir, "temp")
	if err != nil {
		return nil, err
	}
	file.Close()

	// Add the .go suffix to the temp file.
	if err = os.Rename(file.Name(), file.Name()+".go"); err != nil {
		return nil, err
	}
	return os.Open(file.Name() + ".go")
}

func editImports(fileName string) error {
	data, err := ioutil.ReadFile(fileName)
	if err != nil {
		return err
	}

	// res holds the go file re-written with imports added.
	opt := &imports.Options{}
	res, err := imports.Process(fileName, data, opt)
	if err != nil {
		return err
	}

	// Write the edited file into the original temp file.
	if err = ioutil.WriteFile(fileName, res, 0644); err != nil {
		return err
	}
	return nil
}

func usage() {
	fmt.Fprintln(os.Stderr, "Usage: gommand [code]")
	os.Exit(2)
}

func clean(f *os.File) {
	f.Close()
	if err := os.Remove(f.Name()); err != nil {
		log.Printf("main: error removing tempfile: %v\n", err)
	}
}

func main() {
	if len(os.Args) < 2 {
		usage()
	}
	code := os.Args[1]
	if code == "" {
		usage()
	}

	file, err := tempFile()
	if err != nil {
		log.Fatalf("main: error creating temp file: %v\n", err)
	}
	defer clean(file)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	go func() {
		<-c
		clean(file)
		os.Exit(1)
	}()

	// bp holds the go boiler plate code with user code added.
	bp := fmt.Sprintf("package main\nfunc main() {\n\t%v\n}", code)

	// Write go code to temp file and add missing imports.
	// Use Printf over Fatalf so removing of temp file will run through defer.
	if err = ioutil.WriteFile(file.Name(), []byte(bp), 0644); err != nil {
		log.Printf("main: error writing code to temp file: %v\n", err)
	}
	if err = editImports(file.Name()); err != nil {
		log.Printf("main: error editing imports: %v\n", err)
	}
	if err = run(file.Name()); err != nil {
		log.Printf("main: error running go code query: %v\n", err)
	}
}
<|endoftext|>


<commit_before>package network

import (
	"sort"

	"golang.org/x/net/context"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/docker/docker/cli/command/formatter"
	"github.com/docker/docker/opts"
	"github.com/spf13/cobra"
)

type byNetworkName []types.NetworkResource

func (r byNetworkName) Len() int           { return len(r) }
func (r byNetworkName) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r byNetworkName) Less(i, j int) bool { return r[i].Name < r[j].Name }

type listOptions struct {
	quiet   bool
	noTrunc bool
	format  string
	filter  opts.FilterOpt
}

func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
	opts := listOptions{filter: opts.NewFilterOpt()}

	cmd := &cobra.Command{
		Use:     "ls [OPTIONS]",
		Aliases: []string{"list"},
		Short:   "List networks",
		Args:    cli.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runList(dockerCli, opts)
		},
	}

	flags := cmd.Flags()
	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display network IDs")
	flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate the output")
	flags.StringVar(&opts.format, "format", "", "Pretty-print networks using a Go template")
	flags.VarP(&opts.filter, "filter", "f", "Provide filter values (i.e. 'dangling=true')")

	return cmd
}

func runList(dockerCli *command.DockerCli, opts listOptions) error {
	client := dockerCli.Client()
	options := types.NetworkListOptions{Filters: opts.filter.Value()}
	networkResources, err := client.NetworkList(context.Background(), options)
	if err != nil {
		return err
	}

	format := opts.format
	if len(format) == 0 {
		if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !opts.quiet {
			format = dockerCli.ConfigFile().NetworksFormat
		} else {
			format = formatter.TableFormatKey
		}
	}

	sort.Sort(byNetworkName(networkResources))

	networksCtx := formatter.Context{
		Output: dockerCli.Out(),
		Format: formatter.NewNetworkFormat(format, opts.quiet),
		Trunc:  !opts.noTrunc,
	}
	return formatter.NetworkWrite(networksCtx, networkResources)
}
<commit_msg>Update docs of `docker network ls --filter`<commit_after>package network

import (
	"sort"

	"golang.org/x/net/context"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/docker/docker/cli/command/formatter"
	"github.com/docker/docker/opts"
	"github.com/spf13/cobra"
)

type byNetworkName []types.NetworkResource

func (r byNetworkName) Len() int           { return len(r) }
func (r byNetworkName) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
func (r byNetworkName) Less(i, j int) bool { return r[i].Name < r[j].Name }

type listOptions struct {
	quiet   bool
	noTrunc bool
	format  string
	filter  opts.FilterOpt
}

func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
	opts := listOptions{filter: opts.NewFilterOpt()}

	cmd := &cobra.Command{
		Use:     "ls [OPTIONS]",
		Aliases: []string{"list"},
		Short:   "List networks",
		Args:    cli.NoArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runList(dockerCli, opts)
		},
	}

	flags := cmd.Flags()
	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display network IDs")
	flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate the output")
	flags.StringVar(&opts.format, "format", "", "Pretty-print networks using a Go template")
	flags.VarP(&opts.filter, "filter", "f", "Provide filter values (e.g. 'driver=bridge')")

	return cmd
}

func runList(dockerCli *command.DockerCli, opts listOptions) error {
	client := dockerCli.Client()
	options := types.NetworkListOptions{Filters: opts.filter.Value()}
	networkResources, err := client.NetworkList(context.Background(), options)
	if err != nil {
		return err
	}

	format := opts.format
	if len(format) == 0 {
		if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !opts.quiet {
			format = dockerCli.ConfigFile().NetworksFormat
		} else {
			format = formatter.TableFormatKey
		}
	}

	sort.Sort(byNetworkName(networkResources))

	networksCtx := formatter.Context{
		Output: dockerCli.Out(),
		Format: formatter.NewNetworkFormat(format, opts.quiet),
		Trunc:  !opts.noTrunc,
	}
	return formatter.NetworkWrite(networksCtx, networkResources)
}
<|endoftext|>


<commit_before>package command

import (
	"fmt"
	"strings"

	"github.com/mitchellh/cli"
	"github.com/posener/complete"
)

var _ cli.Command = (*SecretsMoveCommand)(nil)
var _ cli.CommandAutocomplete = (*SecretsMoveCommand)(nil)

type SecretsMoveCommand struct {
	*BaseCommand
}

func (c *SecretsMoveCommand) Synopsis() string {
	return "Move a secrets engine to a new path"
}

func (c *SecretsMoveCommand) Help() string {
	helpText := `
Usage: vault secrets move [options] SOURCE DESTINATION

  Moves an existing secrets engine to a new path. Any leases from the old
  secrets engine are revoked, but all configuration associated with the engine
  is preserved.

  WARNING! Moving an existing secrets engine will revoke any leases from the
  old engine.

  Move the existing secrets engine at secret/ to generic/:

      $ vault secrets move secret/ generic/

` + c.Flags().Help()

	return strings.TrimSpace(helpText)
}

func (c *SecretsMoveCommand) Flags() *FlagSets {
	return c.flagSet(FlagSetHTTP)
}

func (c *SecretsMoveCommand) AutocompleteArgs() complete.Predictor {
	return c.PredictVaultMounts()
}

func (c *SecretsMoveCommand) AutocompleteFlags() complete.Flags {
	return c.Flags().Completions()
}

func (c *SecretsMoveCommand) Run(args []string) int {
	f := c.Flags()

	if err := f.Parse(args); err != nil {
		c.UI.Error(err.Error())
		return 1
	}

	args = f.Args()
	switch {
	case len(args) < 2:
		c.UI.Error(fmt.Sprintf("Not enough arguments (expected 2, got %d)", len(args)))
		return 1
	case len(args) > 2:
		c.UI.Error(fmt.Sprintf("Too many arguments (expected 2, got %d)", len(args)))
		return 1
	}

	// Grab the source and destination
	source := ensureTrailingSlash(args[0])
	destination := ensureTrailingSlash(args[1])

	client, err := c.Client()
	if err != nil {
		c.UI.Error(err.Error())
		return 2
	}

	if err := client.Sys().Remount(source, destination); err != nil {
		c.UI.Error(fmt.Sprintf("Error moving secrets engine %s to %s: %s", source, destination, err))
		return 2
	}

	c.UI.Output(fmt.Sprintf("Success! Moved secrets engine %s to: %s", source, destination))
	return 0
}
<commit_msg>Explicitly state that secrets move doesn't work across namespaces<commit_after>package command

import (
	"fmt"
	"strings"

	"github.com/mitchellh/cli"
	"github.com/posener/complete"
)

var _ cli.Command = (*SecretsMoveCommand)(nil)
var _ cli.CommandAutocomplete = (*SecretsMoveCommand)(nil)

type SecretsMoveCommand struct {
	*BaseCommand
}

func (c *SecretsMoveCommand) Synopsis() string {
	return "Move a secrets engine to a new path"
}

func (c *SecretsMoveCommand) Help() string {
	helpText := `
Usage: vault secrets move [options] SOURCE DESTINATION

  Moves an existing secrets engine to a new path. Any leases from the old
  secrets engine are revoked, but all configuration associated with the engine
  is preserved.

  This command only works within a namespace; it cannot be used to move engines
  to different namespaces.

  WARNING! Moving an existing secrets engine will revoke any leases from the
  old engine.

  Move the existing secrets engine at secret/ to generic/:

      $ vault secrets move secret/ generic/

` + c.Flags().Help()

	return strings.TrimSpace(helpText)
}

func (c *SecretsMoveCommand) Flags() *FlagSets {
	return c.flagSet(FlagSetHTTP)
}

func (c *SecretsMoveCommand) AutocompleteArgs() complete.Predictor {
	return c.PredictVaultMounts()
}

func (c *SecretsMoveCommand) AutocompleteFlags() complete.Flags {
	return c.Flags().Completions()
}

func (c *SecretsMoveCommand) Run(args []string) int {
	f := c.Flags()

	if err := f.Parse(args); err != nil {
		c.UI.Error(err.Error())
		return 1
	}

	args = f.Args()
	switch {
	case len(args) < 2:
		c.UI.Error(fmt.Sprintf("Not enough arguments (expected 2, got %d)", len(args)))
		return 1
	case len(args) > 2:
		c.UI.Error(fmt.Sprintf("Too many arguments (expected 2, got %d)", len(args)))
		return 1
	}

	// Grab the source and destination
	source := ensureTrailingSlash(args[0])
	destination := ensureTrailingSlash(args[1])

	client, err := c.Client()
	if err != nil {
		c.UI.Error(err.Error())
		return 2
	}

	if err := client.Sys().Remount(source, destination); err != nil {
		c.UI.Error(fmt.Sprintf("Error moving secrets engine %s to %s: %s", source, destination, err))
		return 2
	}

	c.UI.Output(fmt.Sprintf("Success! Moved secrets engine %s to: %s", source, destination))
	return 0
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"strconv"

	"github.com/codegangsta/cli"
)

func registerCapability(app cli.App) *cli.App {
	app.Commands = append(app.Commands,
		[]cli.Command{
			// capability
			{
				Name:   "capabilities",
				Usage:  "SUBCOMMANDS for monitoring capability declarations",
				Before: runtimePreCmd,
				Subcommands: []cli.Command{
					{
						Name:   "declare",
						Usage:  "Declare a new monitoring system capability",
						Action: cmdCapabilityDeclare,
					},
					{
						Name:   "revoke",
						Usage:  "Revoke a monitoring system capability",
						Action: cmdCapabilityRevoke,
					},
					{
						Name:   "list",
						Usage:  "List monitoring system capabilities",
						Action: cmdCapabilityList,
					},
					{
						Name:   "show",
						Usage:  "Show details about a monitoring system capability",
						Action: cmdCapabilityShow,
					},
				},
			}, // end capability
		}...,
	)
	return &app
}

func cmdCapabilityDeclare(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 7)
	multiple := []string{}
	unique := []string{"metric", "view", "thresholds"}
	required := []string{"metric", "view", "thresholds"}

	opts := utl.ParseVariadicArguments(
		multiple,
		unique,
		required,
		c.Args().Tail())

	thresholds, err := strconv.ParseUint(opts["thresholds"][0], 10, 64)
	utl.AbortOnError(err, "Syntax error, threshold argument not numeric")

	req := proto.Request{
		Capability: &proto.Capability{
			MonitoringId: utl.TryGetMonitoringByUUIDOrName(
				c.Args().First(),
			),
			Metric:     opts["metric"][0],
			View:       opts["view"][0],
			Thresholds: thresholds,
		},
	}

	resp := utl.PostRequestWithBody(req, "/capability/")
	fmt.Println(resp)
}

func cmdCapabilityRevoke(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 1)

	id := utl.TryGetCapabilityByUUIDOrName(c.Args().First())
	path := fmt.Sprintf("/capability/%s", id)

	resp := utl.DeleteRequest(path)
	fmt.Println(resp)
}

func cmdCapabilityList(c *cli.Context) {
	resp := utl.GetRequest("/capability/")
	fmt.Println(resp)
}

func cmdCapabilityShow(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 1)

	id := utl.TryGetCapabilityByUUIDOrName(c.Args().First())
	path := fmt.Sprintf("/capability/%s", id)

	resp := utl.GetRequest(path)
	fmt.Println(resp)
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<commit_msg>Hook up capability/declare help text<commit_after>package main

import (
	"fmt"
	"strconv"

	"github.com/codegangsta/cli"
)

func registerCapability(app cli.App) *cli.App {
	app.Commands = append(app.Commands,
		[]cli.Command{
			// capability
			{
				Name:   "capabilities",
				Usage:  "SUBCOMMANDS for monitoring capability declarations",
				Before: runtimePreCmd,
				Subcommands: []cli.Command{
					{
						Name:        "declare",
						Usage:       "Declare a new monitoring system capability",
						Description: help.CmdCapabilityDeclare,
						Action:      cmdCapabilityDeclare,
					},
					{
						Name:   "revoke",
						Usage:  "Revoke a monitoring system capability",
						Action: cmdCapabilityRevoke,
					},
					{
						Name:   "list",
						Usage:  "List monitoring system capabilities",
						Action: cmdCapabilityList,
					},
					{
						Name:   "show",
						Usage:  "Show details about a monitoring system capability",
						Action: cmdCapabilityShow,
					},
				},
			}, // end capability
		}...,
	)
	return &app
}

func cmdCapabilityDeclare(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 7)
	multiple := []string{}
	unique := []string{"metric", "view", "thresholds"}
	required := []string{"metric", "view", "thresholds"}

	opts := utl.ParseVariadicArguments(
		multiple,
		unique,
		required,
		c.Args().Tail())

	thresholds, err := strconv.ParseUint(opts["thresholds"][0], 10, 64)
	utl.AbortOnError(err, "Syntax error, threshold argument not numeric")

	req := proto.Request{
		Capability: &proto.Capability{
			MonitoringId: utl.TryGetMonitoringByUUIDOrName(
				c.Args().First(),
			),
			Metric:     opts["metric"][0],
			View:       opts["view"][0],
			Thresholds: thresholds,
		},
	}

	resp := utl.PostRequestWithBody(req, "/capability/")
	fmt.Println(resp)
}

func cmdCapabilityRevoke(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 1)

	id := utl.TryGetCapabilityByUUIDOrName(c.Args().First())
	path := fmt.Sprintf("/capability/%s", id)

	resp := utl.DeleteRequest(path)
	fmt.Println(resp)
}

func cmdCapabilityList(c *cli.Context) {
	resp := utl.GetRequest("/capability/")
	fmt.Println(resp)
}

func cmdCapabilityShow(c *cli.Context) {
	utl.ValidateCliArgumentCount(c, 1)

	id := utl.TryGetCapabilityByUUIDOrName(c.Args().First())
	path := fmt.Sprintf("/capability/%s", id)

	resp := utl.GetRequest(path)
	fmt.Println(resp)
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<|endoftext|>


<commit_before>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package utils_test

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"

	"github.com/juju/testing"
	jc "github.com/juju/testing/checkers"
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/utils"
)

func init() {
	// The default Proxy implementation for HTTP transports,
	// ProxyFromEnvironment, uses a sync.Once in Go 1.3 onwards.
	// No tests should be dialing out, so no proxy should be
	// used.
	os.Setenv("http_proxy", "")
	os.Setenv("HTTP_PROXY", "")
	os.Setenv("https_proxy", "")
	os.Setenv("HTTPS_PROXY", "")
}

type httpSuite struct {
	Server *httptest.Server
}

var _ = gc.Suite(&httpSuite{})

type trivialResponseHandler struct{}

func (t *trivialResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Greetings!\n")
}

func (s *httpSuite) SetUpTest(c *gc.C) {
	s.Server = httptest.NewTLSServer(&trivialResponseHandler{})
}

func (s *httpSuite) TearDownTest(c *gc.C) {
	if s.Server != nil {
		s.Server.Close()
	}
}

func (s *httpSuite) TestDefaultClientFails(c *gc.C) {
	_, err := http.Get(s.Server.URL)
	c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}

func (s *httpSuite) TestValidatingClientGetter(c *gc.C) {
	client1 := utils.GetValidatingHTTPClient()
	client2 := utils.GetHTTPClient(utils.VerifySSLHostnames)
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestNonValidatingClientGetter(c *gc.C) {
	client1 := utils.GetNonValidatingHTTPClient()
	client2 := utils.GetHTTPClient(utils.NoVerifySSLHostnames)
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestValidatingClientFails(c *gc.C) {
	client := utils.GetValidatingHTTPClient()
	_, err := client.Get(s.Server.URL)
	c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}

func (s *httpSuite) TestInsecureClientSucceeds(c *gc.C) {
	response, err := utils.GetNonValidatingHTTPClient().Get(s.Server.URL)
	c.Assert(err, gc.IsNil)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	c.Assert(err, gc.IsNil)
	c.Check(string(body), gc.Equals, "Greetings!\n")
}

func (s *httpSuite) TestInsecureClientCached(c *gc.C) {
	client1 := utils.GetNonValidatingHTTPClient()
	client2 := utils.GetNonValidatingHTTPClient()
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestBasicAuthHeader(c *gc.C) {
	header := utils.BasicAuthHeader("eric", "sekrit")
	c.Assert(len(header), gc.Equals, 1)
	auth := header.Get("Authorization")
	fields := strings.Fields(auth)
	c.Assert(len(fields), gc.Equals, 2)
	basic, encoded := fields[0], fields[1]
	c.Assert(basic, gc.Equals, "Basic")
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	c.Assert(err, gc.IsNil)
	c.Assert(string(decoded), gc.Equals, "eric:sekrit")
}

type dialSuite struct {
	testing.CleanupSuite
}

var _ = gc.Suite(&dialSuite{})

func (s *dialSuite) TestDialRejectsNonLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.Dial("tcp", "10.0.0.1:80")
	c.Assert(err, gc.ErrorMatches, `access to address "10.0.0.1:80" not allowed`)
	_, err = utils.Dial("tcp", "somehost:80")
	c.Assert(err, gc.ErrorMatches, `access to address "somehost:80" not allowed`)
}

func (s *dialSuite) assertDial(c *gc.C, addr string) {
	dialed := false
	s.PatchValue(utils.NetDial, func(network, addr string) (net.Conn, error) {
		c.Assert(network, gc.Equals, "tcp")
		c.Assert(addr, gc.Equals, addr)
		dialed = true
		return nil, nil
	})
	_, err := utils.Dial("tcp", addr)
	c.Assert(err, gc.IsNil)
	c.Assert(dialed, jc.IsTrue)
}

func (s *dialSuite) TestDialAllowsNonLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, true)
	s.assertDial(c, "10.0.0.1:80")
}

func (s *dialSuite) TestDialAllowsLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	s.assertDial(c, "127.0.0.1:1234")
	s.assertDial(c, "localhost:1234")
}

func (s *dialSuite) TestInsecureClientNoAccess(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.GetNonValidatingHTTPClient().Get("http://10.0.0.1:1234")
	c.Assert(err, gc.ErrorMatches, `.*access to address "10.0.0.1:1234" not allowed`)
}

func (s *dialSuite) TestSecureClientNoAccess(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.GetValidatingHTTPClient().Get("http://10.0.0.1:1234")
	c.Assert(err, gc.ErrorMatches, `.*access to address "10.0.0.1:1234" not allowed`)
}
<commit_msg>Remove $https_proxy<commit_after>// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package utils_test

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"

	"github.com/juju/testing"
	jc "github.com/juju/testing/checkers"
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/utils"
)

func init() {
	// The default Proxy implementation for HTTP transports,
	// ProxyFromEnvironment, uses a sync.Once in Go 1.3 onwards.
	// No tests should be dialing out, so no proxy should be
	// used.
	os.Setenv("http_proxy", "")
	os.Setenv("HTTP_PROXY", "")
}

type httpSuite struct {
	Server *httptest.Server
}

var _ = gc.Suite(&httpSuite{})

type trivialResponseHandler struct{}

func (t *trivialResponseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Greetings!\n")
}

func (s *httpSuite) SetUpTest(c *gc.C) {
	s.Server = httptest.NewTLSServer(&trivialResponseHandler{})
}

func (s *httpSuite) TearDownTest(c *gc.C) {
	if s.Server != nil {
		s.Server.Close()
	}
}

func (s *httpSuite) TestDefaultClientFails(c *gc.C) {
	_, err := http.Get(s.Server.URL)
	c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}

func (s *httpSuite) TestValidatingClientGetter(c *gc.C) {
	client1 := utils.GetValidatingHTTPClient()
	client2 := utils.GetHTTPClient(utils.VerifySSLHostnames)
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestNonValidatingClientGetter(c *gc.C) {
	client1 := utils.GetNonValidatingHTTPClient()
	client2 := utils.GetHTTPClient(utils.NoVerifySSLHostnames)
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestValidatingClientFails(c *gc.C) {
	client := utils.GetValidatingHTTPClient()
	_, err := client.Get(s.Server.URL)
	c.Assert(err, gc.ErrorMatches, "(.|\n)*x509: certificate signed by unknown authority")
}

func (s *httpSuite) TestInsecureClientSucceeds(c *gc.C) {
	response, err := utils.GetNonValidatingHTTPClient().Get(s.Server.URL)
	c.Assert(err, gc.IsNil)
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	c.Assert(err, gc.IsNil)
	c.Check(string(body), gc.Equals, "Greetings!\n")
}

func (s *httpSuite) TestInsecureClientCached(c *gc.C) {
	client1 := utils.GetNonValidatingHTTPClient()
	client2 := utils.GetNonValidatingHTTPClient()
	c.Check(client1, gc.Equals, client2)
}

func (s *httpSuite) TestBasicAuthHeader(c *gc.C) {
	header := utils.BasicAuthHeader("eric", "sekrit")
	c.Assert(len(header), gc.Equals, 1)
	auth := header.Get("Authorization")
	fields := strings.Fields(auth)
	c.Assert(len(fields), gc.Equals, 2)
	basic, encoded := fields[0], fields[1]
	c.Assert(basic, gc.Equals, "Basic")
	decoded, err := base64.StdEncoding.DecodeString(encoded)
	c.Assert(err, gc.IsNil)
	c.Assert(string(decoded), gc.Equals, "eric:sekrit")
}

type dialSuite struct {
	testing.CleanupSuite
}

var _ = gc.Suite(&dialSuite{})

func (s *dialSuite) TestDialRejectsNonLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.Dial("tcp", "10.0.0.1:80")
	c.Assert(err, gc.ErrorMatches, `access to address "10.0.0.1:80" not allowed`)
	_, err = utils.Dial("tcp", "somehost:80")
	c.Assert(err, gc.ErrorMatches, `access to address "somehost:80" not allowed`)
}

func (s *dialSuite) assertDial(c *gc.C, addr string) {
	dialed := false
	s.PatchValue(utils.NetDial, func(network, addr string) (net.Conn, error) {
		c.Assert(network, gc.Equals, "tcp")
		c.Assert(addr, gc.Equals, addr)
		dialed = true
		return nil, nil
	})
	_, err := utils.Dial("tcp", addr)
	c.Assert(err, gc.IsNil)
	c.Assert(dialed, jc.IsTrue)
}

func (s *dialSuite) TestDialAllowsNonLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, true)
	s.assertDial(c, "10.0.0.1:80")
}

func (s *dialSuite) TestDialAllowsLocal(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	s.assertDial(c, "127.0.0.1:1234")
	s.assertDial(c, "localhost:1234")
}

func (s *dialSuite) TestInsecureClientNoAccess(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.GetNonValidatingHTTPClient().Get("http://10.0.0.1:1234")
	c.Assert(err, gc.ErrorMatches, `.*access to address "10.0.0.1:1234" not allowed`)
}

func (s *dialSuite) TestSecureClientNoAccess(c *gc.C) {
	s.PatchValue(&utils.OutgoingAccessAllowed, false)
	_, err := utils.GetValidatingHTTPClient().Get("http://10.0.0.1:1234")
	c.Assert(err, gc.ErrorMatches, `.*access to address "10.0.0.1:1234" not allowed`)
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.

package utils

import (
	"fmt"
	"github.com/ardielle/ardielle-go/rdl"
	"io"
	"os"
	"strings"
	"text/template"
)

func JavaGenerationHeader(banner string) string {
	return fmt.Sprintf("%s// Please DO NOT edit directly; changes could be overwritten.\n//", javaGenerationBanner(banner))
}

func JavaGenerationOrigHeader(banner string) string {
	return fmt.Sprintf("%s// WILL NOT be auto-generated if file has already existed.\n//", javaGenerationBanner(banner));
}

func javaGenerationBanner(banner string) string {
	return fmt.Sprintf("//\n// This file is generated by %s\n", banner)
}

func JavaGenerationPackage(schema *rdl.Schema, namespace string) string {
	return JavaGenerationOrigPackage(schema, namespace) + ".parsec_generated"
}

func JavaGenerationOrigPackage(schema *rdl.Schema, namespace string) string {
	if namespace != "" {
		return namespace
	}
	return string(schema.Namespace)
}

func JavaGenerationRootPath(schema *rdl.Schema, basePath string) string {
	if basePath != "" {
		if schema.Version != nil {
			if basePath != "/" {
				return fmt.Sprintf("%s/v%d", basePath, *schema.Version)
			}
			return fmt.Sprintf("/v%d", *schema.Version)
		}
		return basePath
	} else if schema.Name != "" {
		if schema.Version != nil {
			return fmt.Sprintf("/%s/v%d", string(schema.Name), *schema.Version)
		} else {
			return fmt.Sprintf("/%s", string(schema.Name))
		}
	}

	return "/"
}

func JavaGenerationDir(outdir string, schema *rdl.Schema, namespace string) (string, error) {
        return _javaGenerationDir(outdir, schema, "./target/generated-sources/java", JavaGenerationPackage(schema, namespace))
}

func JavaGenerationSourceDir(schema *rdl.Schema, namespace string) (string, error) {
        return _javaGenerationDir("", schema, "./src/main/java", JavaGenerationOrigPackage(schema, namespace))
}

func _javaGenerationDir(outdir string, schema *rdl.Schema, defaultDir string, pack string) (string, error) {
	dir := outdir
	if dir == "" {
		dir = defaultDir
	}
	//pack := javaGenerationPackage(schema)
	if pack != "" {
		dir += "/" + strings.Replace(pack, ".", "/", -1)
	}
	_, err := os.Stat(dir)
	if err != nil {
		err = os.MkdirAll(dir, 0755)
	}
	return dir, err
}

func JavaGenerateResourceError(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaResourceErrorTemplate, namespace)
}

func JavaGenerateParsecResourceError(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecResourceErrorTemplate, namespace)
}

func JavaGenerateParsecErrorBody(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecErrorBodyTemplate, namespace)
}

func JavaGenerateParsecErrorDetail(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecErrorDetailTemplate, namespace)
}

func _javaGenerateTemplate(schema *rdl.Schema, writer io.Writer, content string, namespace string) error {
	funcMap := template.FuncMap{
		"package": func() string {
			s := JavaGenerationPackage(schema, namespace)
			if s == "" {
				return s
			}
			return "package " + s + ";\n"
		},
	}
	t := template.Must(template.New("util").Funcs(funcMap).Parse(content))
	return t.Execute(writer, schema)
}

const javaResourceErrorTemplate = `{{package}}
public class ResourceError {

    public int code;
    public String message;

    public ResourceError code(int code) {
        this.code = code;
        return this;
    }

    public ResourceError message(String message) {
        this.message = message;
        return this;
    }

    public String toString() {
        return "{code: " + code + ", message: \"" + message + "\"}";
    }

}
`

const javaParsecResourceErrorTemplate = `{{package}}
public final class ParsecResourceError implements java.io.Serializable {

    private ParsecErrorBody error;

    public ParsecResourceError() { }

    public ParsecErrorBody getError() { return error; }

    public ParsecResourceError setError(ParsecErrorBody error) { this.error = error; return this; }
}
`

const javaParsecErrorBodyTemplate = `{{package}}
import java.util.List;

public final class ParsecErrorBody implements java.io.Serializable {

    private Integer code;
    private String message;

    private List<ParsecErrorDetail> detail;

    public ParsecErrorBody() { }

    public Integer getCode() { return code; }

    public String getMessage() { return message; }

    public List<ParsecErrorDetail> getDetail() { return detail; }

    public ParsecErrorBody setCode(Integer code) { this.code = code; return this; }

    public ParsecErrorBody setMessage(String message) { this.message = message; return this; }

    public ParsecErrorBody setDetail(List<ParsecErrorDetail> detail) { this.detail = detail; return this; }
}
`

const javaParsecErrorDetailTemplate = `{{package}}
public final class ParsecErrorDetail implements java.io.Serializable {

    private String message;

    private String invalidValue;

    public ParsecErrorDetail() { }

    public String getMessage() { return message; }

    public String getInvalidValue() { return invalidValue; }

    public ParsecErrorDetail setMessage(String message) { this.message = message; return this; }

    public ParsecErrorDetail setInvalidValue(String invalidValue) { this.invalidValue = invalidValue; return this; }
}
`

func JavaGenerateResourceException(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaResourceExceptionTemplate, namespace)
}

const javaResourceExceptionTemplate = `{{package}}
public class ResourceException extends RuntimeException {
    public final static int OK = 200;
    public final static int CREATED = 201;
    public final static int ACCEPTED = 202;
    public final static int NO_CONTENT = 204;
    public final static int MOVED_PERMANENTLY = 301;
    public final static int FOUND = 302;
    public final static int SEE_OTHER = 303;
    public final static int NOT_MODIFIED = 304;
    public final static int TEMPORARY_REDIRECT = 307;
    public final static int BAD_REQUEST = 400;
    public final static int UNAUTHORIZED = 401;
    public final static int FORBIDDEN = 403;
    public final static int NOT_FOUND = 404;
    public final static int CONFLICT = 409;
    public final static int GONE = 410;
    public final static int PRECONDITION_FAILED = 412;
    public final static int REQUEST_ENTITY_TOO_LARGE = 413;
    public final static int UNSUPPORTED_MEDIA_TYPE = 415;
    public final static int MISDIRECTED_REQUEST = 421;
    public final static int PRECONDITION_REQUIRED = 428;
    public final static int TOO_MANY_REQUESTS = 429;

    public final static int INTERNAL_SERVER_ERROR = 500;
    public final static int NOT_IMPLEMENTED = 501;

    public final static int SERVICE_UNAVAILABLE = 503;

    public static String codeToString(int code) {
        switch (code) {
        case OK: return "OK";
        case CREATED: return "Created";
        case ACCEPTED: return "Accepted";
        case NO_CONTENT: return "No Content";
        case MOVED_PERMANENTLY: return "Moved Permanently";
        case FOUND: return "Found";
        case SEE_OTHER: return "See Other";
        case NOT_MODIFIED: return "Not Modified";
        case TEMPORARY_REDIRECT: return "Temporary Redirect";
        case BAD_REQUEST: return "Bad Request";
        case UNAUTHORIZED: return "Unauthorized";
        case FORBIDDEN: return "Forbidden";
        case NOT_FOUND: return "Not Found";
        case CONFLICT: return "Conflict";
        case GONE: return "Gone";
        case PRECONDITION_FAILED: return "Precondition Failed";
        case UNSUPPORTED_MEDIA_TYPE: return "Unsupported Media Type";
        case INTERNAL_SERVER_ERROR: return "Internal Server Error";
        case NOT_IMPLEMENTED: return "Not Implemented";
        case MISDIRECTED_REQUEST : return "Misdirected Request";
        case PRECONDITION_REQUIRED: return "Precondition Required";
        case TOO_MANY_REQUESTS: return "Too Many Requests";
        case REQUEST_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        default: return "" + code;
        }
    }

    int code;
    Object data;

    public ResourceException(int code) {
        this(code, new ResourceError().code(code).message(codeToString(code)));
    }

    public ResourceException(int code, Object data) {
        super("ResourceException (" + code + "): " + data);
        this.code = code;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public Object getData() {
        return data;
    }

    public <T> T getData(Class<T> cl) {
        return cl.cast(data);
    }

}
`
func GetUserDefinedTypeAnnotations(userDefinedType rdl.TypeRef, schemaTypes []*rdl.Type) map[rdl.ExtendedAnnotation]string {
	for _, schemaType := range schemaTypes {
		switch schemaType.Variant {
		case rdl.TypeVariantStructTypeDef:
			if string(userDefinedType) == string(schemaType.StructTypeDef.Name) {
				return schemaType.StructTypeDef.Annotations
			}
		case rdl.TypeVariantStringTypeDef:
			if string(userDefinedType) == string(schemaType.StringTypeDef.Name) {
				return schemaType.StringTypeDef.Annotations
			}
		case rdl.TypeVariantMapTypeDef:
			if string(userDefinedType) == string(schemaType.MapTypeDef.Name) {
				return schemaType.MapTypeDef.Annotations
			}
		case rdl.TypeVariantArrayTypeDef:
			if string(userDefinedType) == string(schemaType.ArrayTypeDef.Name) {
				return schemaType.ArrayTypeDef.Annotations
			}
		case rdl.TypeVariantBytesTypeDef:
			if string(userDefinedType) == string(schemaType.BytesTypeDef.Name) {
				return schemaType.BytesTypeDef.Annotations
			}
		case rdl.TypeVariantNumberTypeDef:
			if string(userDefinedType) == string(schemaType.NumberTypeDef.Name) {
				return schemaType.NumberTypeDef.Annotations
			}
		case rdl.TypeVariantUnionTypeDef:
			if string(userDefinedType) == string(schemaType.UnionTypeDef.Name) {
				return schemaType.UnionTypeDef.Annotations
			}
		}
	}
	return make(map[rdl.ExtendedAnnotation]string, 0)
}

func JavaType(reg rdl.TypeRegistry, rdlType rdl.TypeRef, optional bool, items rdl.TypeRef, keys rdl.TypeRef) string {
	t := reg.FindType(rdlType)
	if t == nil || t.Variant == 0 {
		panic("Cannot find type '" + rdlType + "'")
	}
	bt := reg.BaseType(t)
	switch bt {
	case rdl.BaseTypeAny:
		return "Object"
	case rdl.BaseTypeString:
		return "String"
	case rdl.BaseTypeSymbol, rdl.BaseTypeTimestamp, rdl.BaseTypeUUID:
		return "String"
	case rdl.BaseTypeBool:
		if optional {
			return "Boolean"
		}
		return "boolean"
	case rdl.BaseTypeInt8:
		if optional {
			return "Byte"
		}
		return "byte"
	case rdl.BaseTypeInt16:
		if optional {
			return "Short"
		}
		return "short"
	case rdl.BaseTypeInt32:
		if optional {
			return "Integer"
		}
		return "int"
	case rdl.BaseTypeInt64:
		if optional {
			return "Long"
		}
		return "long"
	case rdl.BaseTypeFloat32:
		if optional {
			return "Float"
		}
		return "float"
	case rdl.BaseTypeFloat64:
		if optional {
			return "Double"
		}
		return "double"
	case rdl.BaseTypeArray:
		i := rdl.TypeRef("Any")
		switch t.Variant {
		case rdl.TypeVariantArrayTypeDef:
			i = t.ArrayTypeDef.Items
		default:
			if items != "" && items != "Any" {
				i = items
			}
		}
		gitems := JavaType(reg, i, false, "", "")
		//return gitems + "[]" //if arrays, not lists
		return "List<" + gitems + ">"
	case rdl.BaseTypeMap:
		k := rdl.TypeRef("Any")
		i := rdl.TypeRef("Any")
		switch t.Variant {
		case rdl.TypeVariantMapTypeDef:
			k = t.MapTypeDef.Keys
			i = t.MapTypeDef.Items
		default:
			if keys != "" && keys != "Any" {
				k = keys
			}
			if items != "" && keys != "Any" {
				i = items
			}
		}
		gkeys := JavaType(reg, k, false, "", "")
		gitems := JavaType(reg, i, false, "", "")
		return "Map<" + gkeys + "," + gitems + ">"
	case rdl.BaseTypeStruct:
		switch t.Variant {
		case rdl.TypeVariantStructTypeDef:
			if t.StructTypeDef.Name == "Struct" {
				return "Object"
			}
		}
		return string(rdlType)
	default:
		return string(rdlType)
	}
}
<commit_msg>change optional to true for Array type case<commit_after>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.

package utils

import (
	"fmt"
	"github.com/ardielle/ardielle-go/rdl"
	"io"
	"os"
	"strings"
	"text/template"
)

func JavaGenerationHeader(banner string) string {
	return fmt.Sprintf("%s// Please DO NOT edit directly; changes could be overwritten.\n//", javaGenerationBanner(banner))
}

func JavaGenerationOrigHeader(banner string) string {
	return fmt.Sprintf("%s// WILL NOT be auto-generated if file has already existed.\n//", javaGenerationBanner(banner));
}

func javaGenerationBanner(banner string) string {
	return fmt.Sprintf("//\n// This file is generated by %s\n", banner)
}

func JavaGenerationPackage(schema *rdl.Schema, namespace string) string {
	return JavaGenerationOrigPackage(schema, namespace) + ".parsec_generated"
}

func JavaGenerationOrigPackage(schema *rdl.Schema, namespace string) string {
	if namespace != "" {
		return namespace
	}
	return string(schema.Namespace)
}

func JavaGenerationRootPath(schema *rdl.Schema, basePath string) string {
	if basePath != "" {
		if schema.Version != nil {
			if basePath != "/" {
				return fmt.Sprintf("%s/v%d", basePath, *schema.Version)
			}
			return fmt.Sprintf("/v%d", *schema.Version)
		}
		return basePath
	} else if schema.Name != "" {
		if schema.Version != nil {
			return fmt.Sprintf("/%s/v%d", string(schema.Name), *schema.Version)
		} else {
			return fmt.Sprintf("/%s", string(schema.Name))
		}
	}

	return "/"
}

func JavaGenerationDir(outdir string, schema *rdl.Schema, namespace string) (string, error) {
        return _javaGenerationDir(outdir, schema, "./target/generated-sources/java", JavaGenerationPackage(schema, namespace))
}

func JavaGenerationSourceDir(schema *rdl.Schema, namespace string) (string, error) {
        return _javaGenerationDir("", schema, "./src/main/java", JavaGenerationOrigPackage(schema, namespace))
}

func _javaGenerationDir(outdir string, schema *rdl.Schema, defaultDir string, pack string) (string, error) {
	dir := outdir
	if dir == "" {
		dir = defaultDir
	}
	//pack := javaGenerationPackage(schema)
	if pack != "" {
		dir += "/" + strings.Replace(pack, ".", "/", -1)
	}
	_, err := os.Stat(dir)
	if err != nil {
		err = os.MkdirAll(dir, 0755)
	}
	return dir, err
}

func JavaGenerateResourceError(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaResourceErrorTemplate, namespace)
}

func JavaGenerateParsecResourceError(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecResourceErrorTemplate, namespace)
}

func JavaGenerateParsecErrorBody(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecErrorBodyTemplate, namespace)
}

func JavaGenerateParsecErrorDetail(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaParsecErrorDetailTemplate, namespace)
}

func _javaGenerateTemplate(schema *rdl.Schema, writer io.Writer, content string, namespace string) error {
	funcMap := template.FuncMap{
		"package": func() string {
			s := JavaGenerationPackage(schema, namespace)
			if s == "" {
				return s
			}
			return "package " + s + ";\n"
		},
	}
	t := template.Must(template.New("util").Funcs(funcMap).Parse(content))
	return t.Execute(writer, schema)
}

const javaResourceErrorTemplate = `{{package}}
public class ResourceError {

    public int code;
    public String message;

    public ResourceError code(int code) {
        this.code = code;
        return this;
    }

    public ResourceError message(String message) {
        this.message = message;
        return this;
    }

    public String toString() {
        return "{code: " + code + ", message: \"" + message + "\"}";
    }

}
`

const javaParsecResourceErrorTemplate = `{{package}}
public final class ParsecResourceError implements java.io.Serializable {

    private ParsecErrorBody error;

    public ParsecResourceError() { }

    public ParsecErrorBody getError() { return error; }

    public ParsecResourceError setError(ParsecErrorBody error) { this.error = error; return this; }
}
`

const javaParsecErrorBodyTemplate = `{{package}}
import java.util.List;

public final class ParsecErrorBody implements java.io.Serializable {

    private Integer code;
    private String message;

    private List<ParsecErrorDetail> detail;

    public ParsecErrorBody() { }

    public Integer getCode() { return code; }

    public String getMessage() { return message; }

    public List<ParsecErrorDetail> getDetail() { return detail; }

    public ParsecErrorBody setCode(Integer code) { this.code = code; return this; }

    public ParsecErrorBody setMessage(String message) { this.message = message; return this; }

    public ParsecErrorBody setDetail(List<ParsecErrorDetail> detail) { this.detail = detail; return this; }
}
`

const javaParsecErrorDetailTemplate = `{{package}}
public final class ParsecErrorDetail implements java.io.Serializable {

    private String message;

    private String invalidValue;

    public ParsecErrorDetail() { }

    public String getMessage() { return message; }

    public String getInvalidValue() { return invalidValue; }

    public ParsecErrorDetail setMessage(String message) { this.message = message; return this; }

    public ParsecErrorDetail setInvalidValue(String invalidValue) { this.invalidValue = invalidValue; return this; }
}
`

func JavaGenerateResourceException(schema *rdl.Schema, writer io.Writer, namespace string) error {
	return _javaGenerateTemplate(schema, writer, javaResourceExceptionTemplate, namespace)
}

const javaResourceExceptionTemplate = `{{package}}
public class ResourceException extends RuntimeException {
    public final static int OK = 200;
    public final static int CREATED = 201;
    public final static int ACCEPTED = 202;
    public final static int NO_CONTENT = 204;
    public final static int MOVED_PERMANENTLY = 301;
    public final static int FOUND = 302;
    public final static int SEE_OTHER = 303;
    public final static int NOT_MODIFIED = 304;
    public final static int TEMPORARY_REDIRECT = 307;
    public final static int BAD_REQUEST = 400;
    public final static int UNAUTHORIZED = 401;
    public final static int FORBIDDEN = 403;
    public final static int NOT_FOUND = 404;
    public final static int CONFLICT = 409;
    public final static int GONE = 410;
    public final static int PRECONDITION_FAILED = 412;
    public final static int REQUEST_ENTITY_TOO_LARGE = 413;
    public final static int UNSUPPORTED_MEDIA_TYPE = 415;
    public final static int MISDIRECTED_REQUEST = 421;
    public final static int PRECONDITION_REQUIRED = 428;
    public final static int TOO_MANY_REQUESTS = 429;

    public final static int INTERNAL_SERVER_ERROR = 500;
    public final static int NOT_IMPLEMENTED = 501;

    public final static int SERVICE_UNAVAILABLE = 503;

    public static String codeToString(int code) {
        switch (code) {
        case OK: return "OK";
        case CREATED: return "Created";
        case ACCEPTED: return "Accepted";
        case NO_CONTENT: return "No Content";
        case MOVED_PERMANENTLY: return "Moved Permanently";
        case FOUND: return "Found";
        case SEE_OTHER: return "See Other";
        case NOT_MODIFIED: return "Not Modified";
        case TEMPORARY_REDIRECT: return "Temporary Redirect";
        case BAD_REQUEST: return "Bad Request";
        case UNAUTHORIZED: return "Unauthorized";
        case FORBIDDEN: return "Forbidden";
        case NOT_FOUND: return "Not Found";
        case CONFLICT: return "Conflict";
        case GONE: return "Gone";
        case PRECONDITION_FAILED: return "Precondition Failed";
        case UNSUPPORTED_MEDIA_TYPE: return "Unsupported Media Type";
        case INTERNAL_SERVER_ERROR: return "Internal Server Error";
        case NOT_IMPLEMENTED: return "Not Implemented";
        case MISDIRECTED_REQUEST : return "Misdirected Request";
        case PRECONDITION_REQUIRED: return "Precondition Required";
        case TOO_MANY_REQUESTS: return "Too Many Requests";
        case REQUEST_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        default: return "" + code;
        }
    }

    int code;
    Object data;

    public ResourceException(int code) {
        this(code, new ResourceError().code(code).message(codeToString(code)));
    }

    public ResourceException(int code, Object data) {
        super("ResourceException (" + code + "): " + data);
        this.code = code;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public Object getData() {
        return data;
    }

    public <T> T getData(Class<T> cl) {
        return cl.cast(data);
    }

}
`
func GetUserDefinedTypeAnnotations(userDefinedType rdl.TypeRef, schemaTypes []*rdl.Type) map[rdl.ExtendedAnnotation]string {
	for _, schemaType := range schemaTypes {
		switch schemaType.Variant {
		case rdl.TypeVariantStructTypeDef:
			if string(userDefinedType) == string(schemaType.StructTypeDef.Name) {
				return schemaType.StructTypeDef.Annotations
			}
		case rdl.TypeVariantStringTypeDef:
			if string(userDefinedType) == string(schemaType.StringTypeDef.Name) {
				return schemaType.StringTypeDef.Annotations
			}
		case rdl.TypeVariantMapTypeDef:
			if string(userDefinedType) == string(schemaType.MapTypeDef.Name) {
				return schemaType.MapTypeDef.Annotations
			}
		case rdl.TypeVariantArrayTypeDef:
			if string(userDefinedType) == string(schemaType.ArrayTypeDef.Name) {
				return schemaType.ArrayTypeDef.Annotations
			}
		case rdl.TypeVariantBytesTypeDef:
			if string(userDefinedType) == string(schemaType.BytesTypeDef.Name) {
				return schemaType.BytesTypeDef.Annotations
			}
		case rdl.TypeVariantNumberTypeDef:
			if string(userDefinedType) == string(schemaType.NumberTypeDef.Name) {
				return schemaType.NumberTypeDef.Annotations
			}
		case rdl.TypeVariantUnionTypeDef:
			if string(userDefinedType) == string(schemaType.UnionTypeDef.Name) {
				return schemaType.UnionTypeDef.Annotations
			}
		}
	}
	return make(map[rdl.ExtendedAnnotation]string, 0)
}

func JavaType(reg rdl.TypeRegistry, rdlType rdl.TypeRef, optional bool, items rdl.TypeRef, keys rdl.TypeRef) string {
	t := reg.FindType(rdlType)
	if t == nil || t.Variant == 0 {
		panic("Cannot find type '" + rdlType + "'")
	}
	bt := reg.BaseType(t)
	switch bt {
	case rdl.BaseTypeAny:
		return "Object"
	case rdl.BaseTypeString:
		return "String"
	case rdl.BaseTypeSymbol, rdl.BaseTypeTimestamp, rdl.BaseTypeUUID:
		return "String"
	case rdl.BaseTypeBool:
		if optional {
			return "Boolean"
		}
		return "boolean"
	case rdl.BaseTypeInt8:
		if optional {
			return "Byte"
		}
		return "byte"
	case rdl.BaseTypeInt16:
		if optional {
			return "Short"
		}
		return "short"
	case rdl.BaseTypeInt32:
		if optional {
			return "Integer"
		}
		return "int"
	case rdl.BaseTypeInt64:
		if optional {
			return "Long"
		}
		return "long"
	case rdl.BaseTypeFloat32:
		if optional {
			return "Float"
		}
		return "float"
	case rdl.BaseTypeFloat64:
		if optional {
			return "Double"
		}
		return "double"
	case rdl.BaseTypeArray:
		i := rdl.TypeRef("Any")
		switch t.Variant {
		case rdl.TypeVariantArrayTypeDef:
			i = t.ArrayTypeDef.Items
		default:
			if items != "" && items != "Any" {
				i = items
			}
		}
		gitems := JavaType(reg, i, true, "", "")
		//return gitems + "[]" //if arrays, not lists
		return "List<" + gitems + ">"
	case rdl.BaseTypeMap:
		k := rdl.TypeRef("Any")
		i := rdl.TypeRef("Any")
		switch t.Variant {
		case rdl.TypeVariantMapTypeDef:
			k = t.MapTypeDef.Keys
			i = t.MapTypeDef.Items
		default:
			if keys != "" && keys != "Any" {
				k = keys
			}
			if items != "" && keys != "Any" {
				i = items
			}
		}
		gkeys := JavaType(reg, k, false, "", "")
		gitems := JavaType(reg, i, false, "", "")
		return "Map<" + gkeys + "," + gitems + ">"
	case rdl.BaseTypeStruct:
		switch t.Variant {
		case rdl.TypeVariantStructTypeDef:
			if t.StructTypeDef.Name == "Struct" {
				return "Object"
			}
		}
		return string(rdlType)
	default:
		return string(rdlType)
	}
}
<|endoftext|>