Exemple #1
0
func startVoting() {
	fmt.Println("Start voting!")
	time.Sleep(time.Second * 10)
	// Send you adress to all. In this case it really doesn't matter
	msg := message.NewVoteMessage(myAddress)
	mm, _ := xml.Marshal(msg)
	_, err := writeMulticast.WriteToUDP(mm, multicastAddr)
	check(err)

	// Wait 10 seconds
	c := time.After(time.Second * 10)
	<-c

	// Check if we got any address that is bigger
	for addr, _ := range knownAddresess {
		if addr > myAddress {
			return
		}
	}

	// Become the server if we are the greatest
	msga := message.NewCoordinatorMessage(string(myAddress))
	mmm, _ := xml.Marshal(msga)
	writeMulticast.WriteToUDP(mmm, multicastAddr)
	fmt.Println("NOW I AM BECOME DEATH")
}
Exemple #2
0
// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request
func (a apiCore) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*request, error) {
	op := &operation{
		HTTPServer: a.config.Endpoint,
		HTTPMethod: "POST",
		HTTPPath:   separator + bucket + separator + object + "?uploadId=" + uploadID,
	}
	var completeMultipartUploadBytes []byte
	var err error
	switch {
	case a.config.AcceptType == "application/xml":
		completeMultipartUploadBytes, err = xml.Marshal(complete)
	case a.config.AcceptType == "application/json":
		completeMultipartUploadBytes, err = json.Marshal(complete)
	default:
		completeMultipartUploadBytes, err = xml.Marshal(complete)
	}
	if err != nil {
		return nil, err
	}
	completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
	r, err := newRequest(op, a.config, completeMultipartUploadBuffer)
	if err != nil {
		return nil, err
	}
	r.req.ContentLength = int64(completeMultipartUploadBuffer.Len())
	return r, nil
}
Exemple #3
0
// Build builds an Envelope for the specified SOAP version.
func (bldr *EnvBuilder) Build(version string) (Envelope, error) {
	if !isValidVersion(version) {
		return nil, ErrInvalidVersion
	}

	bdy, err := xml.Marshal(bldr.payload)
	if err != nil {
		return nil, err
	}

	var env Envelope = &Envelope11{BodyElem: Body11{PayloadElem: bdy}, Xmlns: bldr.xmlns}
	if version == V12 {
		env = &Envelope12{BodyElem: Body12{PayloadElem: bdy}, Xmlns: bldr.xmlns}
	}

	if len(bldr.headers) > 0 {
		hdr, err := xml.Marshal(bldr.headers)
		if err != nil {
			return nil, err
		}

		if len(hdr) > 0 {
			env.setHeader(&Header{Content: hdr})
		}
	}

	return env, nil
}
Exemple #4
0
//
// SetBucketLogging 修改Bucket的日志设置。
//
// OSS为您提供自动保存访问日志记录功能。Bucket的拥有者可以开启访问日志记录功能。当一个bucket开启访问日志记录功能后,
// OSS自动将访问这个bucket的请求日志,以小时为单位,按照固定的命名规则,生成一个Object写入用户指定的bucket中。
// 如果您需要更多,请参看 https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
//
// bucketName   需要记录访问日志的Bucket。
// targetBucket 访问日志记录到的Bucket。
// targetPrefix bucketName中需要存储访问日志记录的object前缀。为空记录所有object的访问日志。
//
// error 操作无错误为nil,非nil为错误信息。
//
func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
	isEnable bool) error {
	var err error
	var bs []byte
	if isEnable {
		lxml := LoggingXML{}
		lxml.LoggingEnabled.TargetBucket = targetBucket
		lxml.LoggingEnabled.TargetPrefix = targetPrefix
		bs, err = xml.Marshal(lxml)
	} else {
		lxml := loggingXMLEmpty{}
		bs, err = xml.Marshal(lxml)
	}

	if err != nil {
		return err
	}

	buffer := new(bytes.Buffer)
	buffer.Write(bs)
	fmt.Println(isEnable, "; xml: ", string(bs))

	contentType := http.DetectContentType(buffer.Bytes())
	headers := map[string]string{}
	headers[HTTPHeaderContentType] = contentType

	resp, err := client.do("PUT", bucketName, "logging", "logging", headers, buffer)
	if err != nil {
		return err
	}
	defer resp.body.Close()
	return checkRespCode(resp.statusCode, []int{http.StatusOK})
}
Exemple #5
0
func handleConnection(conn net.Conn) {

	b := xml.NewDecoder(conn)
	fmt.Fprintf(conn, `<?xml version='1.0'?>
		<stream:stream
			from='localhost'
			id='abc123'
			to='james@localhost'
			version='1.0'
			xml:lang='en'
			xmlns='jabber:server'
			xmlns:stream='http://etherx.jabber.org/streams'>`)

	fmt.Fprintf(conn, "<stream:features/>")
	for {
		iqData := new(Iq)
		b.Decode(iqData)
		switch iqData.Type {
		case "get":
			r := &Iq{Id: iqData.Id, Type: "result"}
			r.Query = Query{Xmlns: "jabber:iq:auth"}
			output, _ := xml.Marshal(r)
			fmt.Fprintf(conn, string(output))
		case "set":
			// Need to perform auth lookup here
			i := Iq{Id: iqData.Id, Type: "result"}
			output, _ := xml.Marshal(i)
			fmt.Fprintf(conn, string(output))
		default:
			// Nothing
		}
	}

}
Exemple #6
0
//http handler to handle http request
func kvHandler(w http.ResponseWriter, r *http.Request) {
	var xcel Xcel
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err)
	}
	xml.Unmarshal(body, &xcel)
	fmt.Println(xcel)
	if xcelDB.xcelReplicator.IsLeader() {
		fmt.Println(xcelDB.xcelId, ":  ", xcel)
		ApplyCommandTOSM(&xcel)
		//xcel.ServerResponse = true
		responseXML, _ := xml.Marshal(xcel)
		fmt.Fprintf(w, string(responseXML))
	} else {

		leader := xcelDB.xcelReplicator.GetLeader()
		if leader == 0 {
			xcel.ServerResponse = leaderUnknown
			xcel.Leader = "unknown"
		} else {
			xcel.ServerResponse = leaderNotMe
			xcel.Leader = "http://" + xcelDB.xcelPeermap[leader]

		}
	}
	responseXML, _ := xml.Marshal(xcel)
	fmt.Fprintf(w, string(responseXML))

}
Exemple #7
0
func TestChangesetMarshalXML(t *testing.T) {
	cs := Changeset{
		ID: 123,
	}

	data, err := xml.Marshal(cs)
	if err != nil {
		t.Fatalf("xml marshal error: %v", err)
	}

	expected := `<changeset id="123" user="" uid="0" created_at="0001-01-01T00:00:00Z" closed_at="0001-01-01T00:00:00Z" open="false" min_lat="0" max_lat="0" min_lon="0" max_lon="0"></changeset>`
	if !bytes.Equal(data, []byte(expected)) {
		t.Errorf("incorrect marshal, got: %s", string(data))
	}

	// changeset with discussion
	cs.Discussion = ChangesetDiscussion{
		Comments: []*ChangesetComment{
			&ChangesetComment{Text: "foo"},
		},
	}

	data, err = xml.Marshal(cs)
	if err != nil {
		t.Fatalf("xml marshal error: %v", err)
	}

	expected = `<changeset id="123" user="" uid="0" created_at="0001-01-01T00:00:00Z" closed_at="0001-01-01T00:00:00Z" open="false" min_lat="0" max_lat="0" min_lon="0" max_lon="0"><discussion><comment user="" uid="0" date="0001-01-01T00:00:00Z"><text>foo</text></comment></discussion></changeset>`
	if !bytes.Equal(data, []byte(expected)) {
		t.Errorf("incorrect marshal, got: %s", string(data))
	}
}
Exemple #8
0
// closeSetup does the same as closeError, except on a connection that has not finished stream setup.
func (s *Stream) closeSetup(c *Conn, err *Error) error {
	// Build response header
	reply := new(header)
	reply.Lang = "en"
	reply.Version = Version
	if len(s.config.Records) > 0 {
		reply.From = s.config.Records[0].Domain
	}

	if c.header != nil {
		if len(c.header.From) != 0 {
			recvFrom := JID{}
			recvFrom.Set(c.header.From)
			reply.To = recvFrom.String()
		}
		if len(c.header.To) != 0 {
			for _, record := range s.config.Records {
				if record.Domain == c.header.To {
					reply.From = c.header.To
					break
				}
			}
		}
		if len(c.header.Version) == 0 {
			reply.Version = ""
		} else if Version != c.header.Version {
			recvMajor, recvMinor := parseVersion(c.header.Version)
			thisMajor, thisMinor := parseVersion(Version)
			if recvMajor < thisMajor || (recvMajor == thisMajor && recvMinor < thisMinor) {
				reply.Version = c.header.Version
			}
		}
	}

	// Build tcp error packet
	xmlBytes := []byte(xml.Header)
	headerBytes, _ := xml.Marshal(reply)
	headerBytes = headerBytes[:len(headerBytes)-len("</stream>")]
	condBytes, _ := xml.Marshal(err)
	closeBytes := []byte("</stream>")

	errorPacket := bytes.Join([][]byte{xmlBytes, headerBytes, condBytes, closeBytes}, []byte{})

	c.Write(errorPacket)

	decoder := xml.NewDecoder(c)
	for {
		token, err := decoder.RawToken()
		if err != nil {
			break
		}
		if t, ok := token.(xml.EndElement); ok && t.Name.Local == "stream" {
			break
		}
	}

	return c.Close()
}
// This example demonstrates how SetUseNullEndTag changes the end tag syntax for Marshal.
func ExampleSetUseNullEndTag() {
	type NullValStruct struct {
		I int
		B []byte
		S string
	}
	s := new(NullValStruct)

	v, err := xml.Marshal(s)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("s:", string(v))
	}

	xml.SetUseNullEndTag(true)
	v, err = xml.Marshal(s)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("s:", string(v))
	}

	type NewStruct struct {
		NVS NullValStruct
		S   string
		F   float64
	}
	ss := new(NewStruct)

	v, err = xml.Marshal(ss)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("ss:", string(v))
	}

	v, err = xml.MarshalIndent(ss, "  ", "   ")
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("ss indent:\n", string(v))
	}
	// Output:
	// s: <NullValStruct><I>0</I><B></B><S></S></NullValStruct>
	// s: <NullValStruct><I>0</I><B/><S/></NullValStruct>
	// ss: <NewStruct><NVS><I>0</I><B/><S/></NVS><S/><F>0</F></NewStruct>
	// ss indent:
	//    <NewStruct>
	//      <NVS>
	//         <I>0</I>
	//         <B/>
	//         <S/>
	//      </NVS>
	//      <S/>
	//      <F>0</F>
	//   </NewStruct>
}
Exemple #10
0
func TestVASTWithAds(t *testing.T) {
	vast := VAST{Version: "2.0"}

	vast.Ad = append(vast.Ad, Ad{})
	data, err := xml.Marshal(vast)
	assert.Nil(t, err)
	assert.Equal(t, string(data), `<VAST version="2.0"><Ad id=""></Ad></VAST>`)

	vast.Ad = append(vast.Ad, Ad{})
	data, err = xml.Marshal(vast)
	assert.Nil(t, err)
	assert.Equal(t, string(data), `<VAST version="2.0"><Ad id=""></Ad><Ad id=""></Ad></VAST>`)
}
Exemple #11
0
// putBucketRequest wrapper creates a new putBucket request
func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error) {
	var r *request
	var err error
	op := &operation{
		HTTPServer: a.config.Endpoint,
		HTTPMethod: "PUT",
		HTTPPath:   separator + bucket,
	}
	var createBucketConfigBuffer *bytes.Reader
	// If location is set use it and create proper bucket configuration
	switch {
	case location != "":
		createBucketConfig := new(createBucketConfiguration)
		createBucketConfig.Location = location
		var createBucketConfigBytes []byte
		switch {
		case a.config.AcceptType == "application/xml":
			createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
		case a.config.AcceptType == "application/json":
			createBucketConfigBytes, err = json.Marshal(createBucketConfig)
		default:
			createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
		}
		if err != nil {
			return nil, err
		}
		createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
	}
	switch {
	case createBucketConfigBuffer == nil:
		r, err = newRequest(op, a.config, nil)
		if err != nil {
			return nil, err
		}
	default:
		r, err = newRequest(op, a.config, createBucketConfigBuffer)
		if err != nil {
			return nil, err
		}
		r.req.ContentLength = int64(createBucketConfigBuffer.Len())
	}
	// by default bucket is private
	switch {
	case acl != "":
		r.Set("x-amz-acl", acl)
	default:
		r.Set("x-amz-acl", "private")
	}

	return r, nil
}
func New(code int, body interface{}, dataType string, ssl bool) (*httptest.Server, error) {

	if dataType == "xml" {

		_, err := xml.Marshal(body)

		if err != nil {
			return nil, err
		}

	} else if dataType == "json" {

		_, err := json.Marshal(body)

		if err != nil {
			return nil, err
		}

	} else {
		return nil, errors.New("dataType in MockServer not recognized")

	}

	f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var bodyMarshalled []byte

		if dataType == "xml" {
			w.Header().Set("Content-Type", "application/xml")
			bodyMarshalled, _ = xml.Marshal(body)

		} else if dataType == "json" {
			w.Header().Set("Content-Type", "application/json")
			bodyMarshalled, _ = json.Marshal(body)
		}

		w.WriteHeader(code)

		fmt.Fprintln(w, string(bodyMarshalled))
	})

	var server *httptest.Server

	if ssl {
		server = httptest.NewTLSServer(f)
	} else {
		server = httptest.NewServer(f)
	}

	return server, nil
}
Exemple #13
0
func Marshal(resource interface{}, accept string, writer io.Writer, alt bool) (r *Error) {
	var err error
	var marshaller gocoding.Marshaller
	var renderer gocoding.Renderer

	if alt {
		marshaller = M.Alt
	} else {
		marshaller = M.Main
	}

	switch accept {
	case "text":
		renderer = json.RenderIndented(writer, "", "  ")

	case "json":
		renderer = json.Render(writer)

	case "xml":
		data, err := xml.Marshal(resource)
		if err != nil {
			r = CreateError(ErrorXMLMarshal, err.Error())
			data, err = xml.Marshal(r)
			if err != nil {
				panic(err)
			}
		}
		writer.Write(data)
		return

	case "html":
		renderer = html.Render(writer)

	default:
		resource = CreateError(ErrorUnsupportedMarshal, fmt.Sprintf(`"%s" is an unsupported marshalling format`, accept))
		renderer = json.Render(writer)
	}

	err = marshaller.Marshal(renderer, resource)
	if err != nil {
		r = CreateError(ErrorJSONMarshal, err.Error())
		err = marshaller.Marshal(renderer, r)
		if err != nil {
			panic(err)
		}
	}
	return
}
Exemple #14
0
func (c Client) Capture(cloudServiceName, deploymentName, roleName string,
	name, label string, osState OSState, parameters CaptureParameters) (management.OperationID, error) {
	if cloudServiceName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "cloudServiceName")
	}
	if deploymentName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "deploymentName")
	}
	if roleName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "roleName")
	}

	request := CaptureRoleAsVMImageOperation{
		VMImageName:       name,
		VMImageLabel:      label,
		OSState:           osState,
		CaptureParameters: parameters,
	}
	data, err := xml.Marshal(request)
	if err != nil {
		return "", err
	}

	return c.SendAzurePostRequest(fmt.Sprintf(azureRoleOperationsURL,
		cloudServiceName, deploymentName, roleName), data)
}
Exemple #15
0
// WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)
func (r *Response) WriteAsXml(value interface{}) error {
	var output []byte
	var err error

	if value == nil { // do not write a nil representation
		return nil
	}
	if r.prettyPrint {
		output, err = xml.MarshalIndent(value, " ", " ")
	} else {
		output, err = xml.Marshal(value)
	}

	if err != nil {
		return r.WriteError(http.StatusInternalServerError, err)
	}
	r.Header().Set(HEADER_ContentType, MIME_XML)
	if r.statusCode > 0 { // a WriteHeader was intercepted
		r.ResponseWriter.WriteHeader(r.statusCode)
	}
	_, err = r.Write([]byte(xml.Header))
	if err != nil {
		return err
	}
	if _, err = r.Write(output); err != nil {
		return err
	}
	return nil
}
Exemple #16
0
func (ø StringType) Xml() string {
	b, err := xl.Marshal(string(ø))
	if err != nil {
		panic("can't convert " + string(ø) + " to xml")
	}
	return string(b)
}
Exemple #17
0
func WriteAsXml(w http.ResponseWriter, status int, value interface{}, writeHeader bool, indent bool) (int, error) {
	var output []byte
	var err error

	if value == nil {
		return 0, nil
	}
	if indent {
		output, err = xml.MarshalIndent(value, " ", " ")
	} else {
		output, err = xml.Marshal(value)
	}

	if err != nil {
		return WriteString(w, http.StatusInternalServerError, err.Error())
	}
	w.Header().Set(constants.HEADER_ContentType, constants.MIME_XML)
	w.WriteHeader(status)
	if writeHeader {
		cl, err := w.Write([]byte(xml.Header))
		if err != nil {
			return cl, err
		}
	}
	return w.Write(output)

}
func CreateStorageService(name, location string) (*StorageService, error) {
	if len(name) == 0 {
		return nil, fmt.Errorf(azure.ParamNotSpecifiedError, "name")
	}
	if len(location) == 0 {
		return nil, fmt.Errorf(azure.ParamNotSpecifiedError, "location")
	}

	storageDeploymentConfig := createStorageServiceDeploymentConf(name, location)
	deploymentBytes, err := xml.Marshal(storageDeploymentConfig)
	if err != nil {
		return nil, err
	}

	requestId, err := azure.SendAzurePostRequest(azureStorageServiceListURL, deploymentBytes)
	if err != nil {
		return nil, err
	}

	azure.WaitAsyncOperation(requestId)
	storageService, err := GetStorageServiceByName(storageDeploymentConfig.ServiceName)
	if err != nil {
		return nil, err
	}

	return storageService, nil
}
Exemple #19
0
func FileSetXML(filename string, data interface{}) error {
	bytes, err := xml.Marshal(data)
	if err != nil {
		return err
	}
	return FileSetBytes(filename, bytes)
}
Exemple #20
0
func (w *writer) complete() error {

	b, err := xml.Marshal(w.xml)
	if err != nil {
		return err
	}

	uv := make(url.Values)
	uv.Set("uploadId", w.uploadId)

	url := w.o.url(`?` + uv.Encode())
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
	if err != nil {
		return err
	}

	w.o.s3.signRequest(req)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if c := resp.StatusCode; c != 200 {
		return newS3Error(resp, "could not complete upload: %d", c)
	}
	return nil
}
func (xe XmlEncoder) Encode(data interface{}) ([]byte, error) {
	if xe.PrettyPrint {
		return xml.MarshalIndent(data, "", "  ")
	} else {
		return xml.Marshal(data)
	}
}
Exemple #22
0
func xmlMarshal(v interface{}) (io.Reader, int, error) {
	b, err := xml.Marshal(v)
	if err != nil {
		return nil, 0, err
	}
	return bytes.NewReader(b), len(b), nil
}
Exemple #23
0
func (g *Braintree) execute(method, path string, xmlObj interface{}) (*Response, error) {
	var buf bytes.Buffer
	if xmlObj != nil {
		xmlBody, err := xml.Marshal(xmlObj)
		if err != nil {
			return nil, err
		}
		_, err = buf.Write(xmlBody)
		if err != nil {
			return nil, err
		}
	}

	url := g.MerchantURL() + "/" + path

	if g.Logger != nil {
		g.Logger.Printf("> %s %s\n%s", method, url, buf.String())
	}

	req, err := http.NewRequest(method, url, &buf)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/xml")
	req.Header.Set("Accept", "application/xml")
	req.Header.Set("Accept-Encoding", "gzip")
	req.Header.Set("User-Agent", "Braintree Go 0.3.1")
	req.Header.Set("X-ApiVersion", "3")
	req.SetBasicAuth(g.PublicKey, g.PrivateKey)

	httpClient := g.HttpClient
	if httpClient == nil {
		httpClient = http.DefaultClient
	}

	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	btr := &Response{
		Response: resp,
	}
	err = btr.unpackBody()
	if err != nil {
		return nil, err
	}

	if g.Logger != nil {
		g.Logger.Printf("<\n%s", string(btr.Body))
	}

	err = btr.apiError()
	if err != nil {
		return nil, err
	}
	return btr, nil
}
Exemple #24
0
// Post returns an HTML form suitable for using the HTTP-POST binding with the request
func (req *AuthnRequest) Post(relayState string) []byte {
	reqBuf, err := xml.Marshal(req)
	if err != nil {
		panic(err)
	}
	encodedReqBuf := base64.StdEncoding.EncodeToString(reqBuf)

	tmpl := template.Must(template.New("saml-post-form").Parse(`` +
		`<form method="post" action="{{.URL}}" id="SAMLRequestForm">` +
		`<input type="hidden" name="SAMLRequest" value="{{.SAMLRequest}}" />` +
		`<input type="hidden" name="RelayState" value="{{.RelayState}}" />` +
		`<input type="submit" value="Submit" />` +
		`</form>` +
		`<script>document.getElementById('SAMLRequestForm').submit();</script>`))
	data := struct {
		URL         string
		SAMLRequest string
		RelayState  string
	}{
		URL:         req.Destination,
		SAMLRequest: encodedReqBuf,
		RelayState:  relayState,
	}

	rv := bytes.Buffer{}
	if err := tmpl.Execute(&rv, data); err != nil {
		panic(err)
	}

	return rv.Bytes()
}
Exemple #25
0
func (s *azureVolumeSuite) TestAttachVolumesNotAttached(c *gc.C) {
	vs := s.volumeSource(c, nil)

	machine := names.NewMachineTag("0")
	volume := names.NewVolumeTag("0")

	env := makeEnviron(c)
	prefix := env.getEnvPrefix()
	service := makeDeployment(env, prefix+"service")
	roleName := service.Deployments[0].RoleList[0].RoleName
	inst, err := env.getInstance(service, roleName)
	c.Assert(err, jc.ErrorIsNil)

	getRoleResponse, err := xml.Marshal(&gwacl.PersistentVMRole{})
	c.Assert(err, jc.ErrorIsNil)

	gwacl.PatchManagementAPIResponses([]gwacl.DispatcherResponse{
		gwacl.NewDispatcherResponse(getRoleResponse, http.StatusOK, nil),
	})

	results, err := vs.AttachVolumes([]storage.VolumeAttachmentParams{{
		Volume:   volume,
		VolumeId: "volume-0.vhd",
		AttachmentParams: storage.AttachmentParams{
			Machine:    machine,
			InstanceId: inst.Id(),
		},
	}})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(results, gc.HasLen, 1)
	c.Assert(results[0].Error, gc.ErrorMatches, "attaching volumes not supported")
}
Exemple #26
0
func (s *azureVolumeSuite) TestListVolumes(c *gc.C) {
	vs := s.volumeSource(c, nil)

	type disks struct {
		Disks []gwacl.Disk `xml:"Disk"`
	}

	listDisksResponse, err := xml.Marshal(&disks{Disks: []gwacl.Disk{{
		MediaLink:       mediaLinkPrefix + "volume-1.vhd",
		LogicalSizeInGB: 22,
	}, {
		MediaLink:       mediaLinkPrefix + "volume-0.vhd",
		LogicalSizeInGB: 11,
	}, {
		MediaLink:       "someOtherJunk.vhd",
		LogicalSizeInGB: 33,
	}}})
	c.Assert(err, jc.ErrorIsNil)

	gwacl.PatchManagementAPIResponses([]gwacl.DispatcherResponse{
		gwacl.NewDispatcherResponse(listDisksResponse, http.StatusOK, nil),
	})

	volIds, err := vs.ListVolumes()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(volIds, jc.SameContents, []string{"volume-0.vhd", "volume-1.vhd"})
}
Exemple #27
0
// DelMulti removes up to 1000 objects from the S3 bucket.
//
// See http://goo.gl/jx6cWK for details.
func (b *Bucket) DelMulti(objects Delete) error {
	doc, err := xml.Marshal(objects)
	if err != nil {
		return err
	}

	buf := makeXmlBuffer(doc)
	digest := md5.New()
	size, err := digest.Write(buf.Bytes())
	if err != nil {
		return err
	}

	headers := map[string][]string{
		"Content-Length": {strconv.FormatInt(int64(size), 10)},
		"Content-MD5":    {base64.StdEncoding.EncodeToString(digest.Sum(nil))},
		"Content-Type":   {"text/xml"},
	}
	req := &request{
		path:    "/",
		method:  "POST",
		params:  url.Values{"delete": {""}},
		bucket:  b.Name,
		headers: headers,
		payload: buf,
	}

	return b.S3.query(req, nil)
}
Exemple #28
0
// Complete assembles the given previously uploaded parts into the
// final object. This operation may take several minutes.
//
// See http://goo.gl/2Z7Tw for details.
func (m *Multi) Complete(parts []Part) error {
	params := map[string][]string{
		"uploadId": {m.UploadId},
	}
	c := completeUpload{}
	for _, p := range parts {
		c.Parts = append(c.Parts, completePart{p.N, p.ETag})
	}
	sort.Sort(c.Parts)
	data, err := xml.Marshal(&c)
	if err != nil {
		return err
	}
	for attempt := attempts.Start(); attempt.Next(); {
		req := &request{
			method:  "POST",
			bucket:  m.Bucket.Name,
			path:    m.Key,
			params:  params,
			payload: bytes.NewReader(data),
		}
		err := m.Bucket.S3.query(req, nil)
		if shouldRetry(err) && attempt.HasNext() {
			continue
		}
		return err
	}
	panic("unreachable")
}
func PayloadEncode(v interface{}) (err error, payloadStr string) {
	bytes, err := xml.Marshal(v)
	if err != nil {
		return err, ""
	}
	return nil, string(bytes)
}
Exemple #30
0
// Test that we can create a Workbook and marshal it to XML.
func (l *FileSuite) TestMarshalWorkbook(c *C) {
	var f *File

	f = NewFile()

	f.AddSheet("MyFirstSheet")
	f.AddSheet("MySecondSheet")
	workbook := f.makeWorkbook()
	workbook.Sheets.Sheet[0] = xlsxSheet{
		Name:    "MyFirstSheet",
		SheetId: "1",
		Id:      "rId1",
		State:   "visible"}

	workbook.Sheets.Sheet[1] = xlsxSheet{
		Name:    "MySecondSheet",
		SheetId: "2",
		Id:      "rId2",
		State:   "visible"}

	expectedWorkbook := `<?xml version="1.0" encoding="UTF-8"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="Go XLSX"></fileVersion><workbookPr showObjects="all" date1904="false"></workbookPr><workbookProtection></workbookProtection><bookViews><workbookView showHorizontalScroll="true" showVerticalScroll="true" showSheetTabs="true" tabRatio="204" windowHeight="8192" windowWidth="16384" xWindow="0" yWindow="0"></workbookView></bookViews><sheets><sheet name="MyFirstSheet" sheetId="1" r:id="rId1" state="visible"></sheet><sheet name="MySecondSheet" sheetId="2" r:id="rId2" state="visible"></sheet></sheets><definedNames></definedNames><calcPr iterateCount="100" refMode="A1" iterateDelta="0.001"></calcPr></workbook>`
	output, err := xml.Marshal(workbook)
	c.Assert(err, IsNil)
	outputStr := replaceRelationshipsNameSpace(string(output))
	stringOutput := xml.Header + outputStr
	c.Assert(stringOutput, Equals, expectedWorkbook)
}