text:
package client_test

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"strings"

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

	"github.com/tidepool-org/platform/client"
	"github.com/tidepool-org/platform/errors"
	errorsTest "github.com/tidepool-org/platform/errors/test"
	"github.com/tidepool-org/platform/log"
	logTest "github.com/tidepool-org/platform/log/test"
	oauthClient "github.com/tidepool-org/platform/oauth/client"
	oauthTest "github.com/tidepool-org/platform/oauth/test"
	"github.com/tidepool-org/platform/request"
	structureValidator "github.com/tidepool-org/platform/structure/validator"
	"github.com/tidepool-org/platform/test"
	testHttp "github.com/tidepool-org/platform/test/http"
)

type RequestBody struct {
	Request string `json:"request"`
}

type ResponseBody struct {
	Response string `json:"response"`
}

var _ = Describe("Client", func() {
	var userAgent string
	var config *client.Config
	var tokenSourceSource *oauthTest.TokenSourceSource

	BeforeEach(func() {
		userAgent = testHttp.NewUserAgent()
		config = client.NewConfig()
		config.UserAgent = userAgent
		tokenSourceSource = oauthTest.NewTokenSourceSource()
	})

	AfterEach(func() {
		tokenSourceSource.AssertOutputsEmpty()
	})

	Context("New", func() {
		BeforeEach(func() {
			config.Address = testHttp.NewAddress()
		})

		It("returns an error when config is missing", func() {
			clnt, err := oauthClient.New(nil, tokenSourceSource)
			Expect(err).To(MatchError("config is missing"))
			Expect(clnt).To(BeNil())
		})

		It("returns an error when token source source is missing", func() {
			clnt, err := oauthClient.New(config, nil)
			Expect(err).To(MatchError("token source source is missing"))
			Expect(clnt).To(BeNil())
		})

		It("returns an error when config is invalid", func() {
			config.Address = ""
			clnt, err := oauthClient.New(config, tokenSourceSource)
			Expect(err).To(MatchError("config is invalid; address is missing"))
			Expect(clnt).To(BeNil())
		})

		It("returns successfully", func() {
			Expect(oauthClient.New(config, tokenSourceSource)).ToNot(BeNil())
		})
	})

	Context("with new client", func() {
		var address string
		var clnt *oauthClient.Client

		BeforeEach(func() {
			address = testHttp.NewAddress()
			config.Address = address
		})

		JustBeforeEach(func() {
			var err error
			clnt, err = oauthClient.New(config, tokenSourceSource)
			Expect(err).ToNot(HaveOccurred())
			Expect(clnt).ToNot(BeNil())
		})

		Context("ConstructURL", func() {
			constructURLAssertions := func() {
				It("returns a valid URL with no paths", func() {
					Expect(clnt.ConstructURL()).To(Equal(address + "/"))
				})

				It("returns a valid URL with one path", func() {
					path := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					Expect(clnt.ConstructURL(path)).To(Equal(fmt.Sprintf("%s/%s", address, path)))
				})

				It("returns a valid URL with multiple paths", func() {
					path1 := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					path2 := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					path3 := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					Expect(clnt.ConstructURL(path1, path2, path3)).To(Equal(fmt.Sprintf("%s/%s/%s/%s", address, path1, path2, path3)))
				})

				It("returns a valid URL with multiple paths that need to be escaped", func() {
					path1 := test.RandomStringFromRangeAndCharset(1, 4, test.CharsetAlphaNumeric) + test.RandomStringFromRangeAndCharset(1, 4, " /;,?") + test.RandomStringFromRangeAndCharset(1, 4, test.CharsetAlphaNumeric)
					path2 := test.RandomStringFromRangeAndCharset(1, 4, test.CharsetAlphaNumeric) + test.RandomStringFromRangeAndCharset(1, 4, " /;,?") + test.RandomStringFromRangeAndCharset(1, 4, test.CharsetAlphaNumeric)
					Expect(clnt.ConstructURL(path1, path2)).To(Equal(fmt.Sprintf("%s/%s/%s", address, url.PathEscape(path1), url.PathEscape(path2))))
				})

				It("returns a valid URL with multiple paths with surrounding slashes", func() {
					path1 := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					path2 := test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric)
					Expect(clnt.ConstructURL("/"+path1+"/", "/"+path2+"/")).To(Equal(fmt.Sprintf("%s/%s/%s", address, path1, path2)))
				})
			}

			Context("without trailing slash on address", func() {
				constructURLAssertions()
			})

			Context("with trailing slashes on address", func() {
				BeforeEach(func() {
					config.Address += "///"
				})

				constructURLAssertions()
			})
		})

		Context("AppendURLQuery", func() {
			var urlString string

			JustBeforeEach(func() {
				urlString = clnt.ConstructURL(test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric), test.RandomStringFromRangeAndCharset(1, 8, test.CharsetAlphaNumeric))
			})

			It("returns a URL without change when the query is nil", func() {
				Expect(clnt.AppendURLQuery(urlString, nil)).To(Equal(urlString))
			})

			It("returns a URL without change when the query is empty", func() {
				Expect(clnt.AppendURLQuery(urlString, map[string]string{})).To(Equal(urlString))
			})

			It("returns a URL with associated query", func() {
				key1 := testHttp.NewParameterKey()
				value1 := testHttp.NewParameterValue()
				key2 := key1 + testHttp.NewParameterKey()
				value2 := testHttp.NewParameterValue()
				query := map[string]string{
					key1: value1,
					key2: value2,
				}
				Expect(clnt.AppendURLQuery(urlString, query)).To(Equal(fmt.Sprintf("%s?%s=%s&%s=%s", urlString, key1, value1, key2, value2)))
			})

			It("returns a URL with associated query even when it already has a query string", func() {
				urlString += "?" + testHttp.NewParameterKey() + "=" + testHttp.NewParameterValue()
				key1 := testHttp.NewParameterKey()
				value1 := testHttp.NewParameterValue()
				key2 := key1 + testHttp.NewParameterKey()
				value2 := testHttp.NewParameterValue()
				query := map[string]string{
					key1: value1,
					key2: value2,
				}
				Expect(clnt.AppendURLQuery(urlString, query)).To(Equal(fmt.Sprintf("%s&%s=%s&%s=%s", urlString, key1, value1, key2, value2)))
			})
		})
	})

	Context("with started server and new client", func() {
		var server *Server
		var responseHeaders http.Header
		var ctx context.Context
		var method string
		var path string
		var url string
		var headerMutator *request.HeaderMutator
		var parameterMutator *request.ParameterMutator
		var mutators []request.RequestMutator
		var requestString string
		var requestBody *RequestBody
		var responseString string
		var httpClientSource *oauthTest.HTTPClientSource
		var clnt *oauthClient.Client

		BeforeEach(func() {
			server = NewServer()
			responseHeaders = http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}
			ctx = log.NewContextWithLogger(context.Background(), logTest.NewLogger())
			method = testHttp.NewMethod()
			path = testHttp.NewPath()
			url = server.URL() + path
			headerMutator = request.NewHeaderMutator(testHttp.NewHeaderKey(), testHttp.NewHeaderValue())
			parameterMutator = request.NewParameterMutator(testHttp.NewParameterKey(), testHttp.NewParameterValue())
			mutators = []request.RequestMutator{headerMutator, parameterMutator}
			requestString = test.RandomStringFromRangeAndCharset(0, 32, test.CharsetText)
			requestBody = &RequestBody{Request: requestString}
			responseString = test.RandomStringFromRangeAndCharset(0, 32, test.CharsetText)
			httpClientSource = oauthTest.NewHTTPClientSource()
		})

		JustBeforeEach(func() {
			config.Address = server.URL()
			var err error
			clnt, err = oauthClient.New(config, tokenSourceSource)
			Expect(err).ToNot(HaveOccurred())
			Expect(clnt).ToNot(BeNil())
		})

		AfterEach(func() {
			if server != nil {
				server.Close()
			}
			httpClientSource.AssertOutputsEmpty()
		})

		Context("SendOAuthRequest", func() {
			var responseBody *ResponseBody

			BeforeEach(func() {
				responseBody = &ResponseBody{}
			})

			It("returns error when http client source is missing", func() {
				Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, nil)).To(MatchError("http client source is missing"))
				Expect(server.ReceivedRequests()).To(BeEmpty())
			})

			When("http client source is not missing", func() {
				AfterEach(func() {
					Expect(httpClientSource.HTTPClientInputs).To(Equal([]oauthTest.HTTPClientInput{{Context: ctx, TokenSourceSource: tokenSourceSource}}))
				})

				It("returns error when http client source returns an error", func() {
					responseErr := errorsTest.RandomError()
					httpClientSource.HTTPClientOutputs = []oauthTest.HTTPClientOutput{{HTTPClient: nil, Error: responseErr}}
					Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)).To(Equal(responseErr))
					Expect(server.ReceivedRequests()).To(BeEmpty())
				})

				When("http client source returns successfully", func() {
					var httpClient *http.Client

					BeforeEach(func() {
						httpClient = http.DefaultClient
						httpClientSource.HTTPClientOutputs = []oauthTest.HTTPClientOutput{{HTTPClient: httpClient, Error: nil}}
					})

					It("returns error when context is missing", func() {
						ctx = nil
						Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)).To(MatchError("context is missing"))
						Expect(server.ReceivedRequests()).To(BeEmpty())
					})

					It("returns error when method is missing", func() {
						Expect(clnt.SendOAuthRequest(ctx, "", url, mutators, requestBody, responseBody, httpClientSource)).To(MatchError("method is missing"))
						Expect(server.ReceivedRequests()).To(BeEmpty())
					})

					It("returns error when url is missing", func() {
						Expect(clnt.SendOAuthRequest(ctx, method, "", mutators, requestBody, responseBody, httpClientSource)).To(MatchError("url is missing"))
						Expect(server.ReceivedRequests()).To(BeEmpty())
					})

					It("returns error when the request object cannot be encoded", func() {
						invalidRequestBody := struct{ Func interface{} }{func() {}}
						Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, invalidRequestBody, responseBody, httpClientSource).Error()).To(MatchRegexp("unable to serialize request to .*; json: unsupported type: func()"))
						Expect(server.ReceivedRequests()).To(BeEmpty())
					})

					It("returns error when mutator returns an error", func() {
						errorMutator := request.NewHeaderMutator("", "")
						invalidMutators := []request.RequestMutator{headerMutator, errorMutator, parameterMutator}
						Expect(clnt.SendOAuthRequest(ctx, method, url, invalidMutators, requestBody, responseBody, httpClientSource).Error()).To(MatchRegexp("unable to mutate request to .*; key is missing"))
						Expect(server.ReceivedRequests()).To(BeEmpty())
					})

					It("returns error when the server is not reachable", func() {
						server.Close()
						server = nil
						Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource).Error()).To(MatchRegexp("unable to perform request to .*: connect: connection refused"))
					})

					Context("with a successful response and no request body", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(nil),
									RespondWith(http.StatusOK, test.MarshalResponseBody(&ResponseBody{Response: responseString}), responseHeaders),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, nil, responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(Equal(responseString))
						})
					})

					Context("with an bad request 400 without deserializable error body", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusBadRequest, []byte{255, 255, 255}, responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorBadRequest())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an bad request 400 with deserializable error body", func() {
						var responseErr error

						BeforeEach(func() {
							responseErr = errors.Append(structureValidator.ErrorValueNotEmpty(), structureValidator.ErrorValueBoolNotTrue(), structureValidator.ErrorValueIntNotOneOf(1, []int{0, 2, 4}))
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWithJSONEncoded(http.StatusBadRequest, errors.NewSerializable(responseErr), responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, responseErr)
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an unauthorized response 401", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusUnauthorized, "NOT JSON", responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorUnauthenticated())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an forbidden response 403", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusForbidden, "NOT JSON", responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorUnauthorized())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an resource not found 404 without deserializable error body", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusNotFound, "NOT JSON", responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorResourceNotFound())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an resource not found 404 with deserializable error body", func() {
						var responseErr error

						BeforeEach(func() {
							responseErr = request.ErrorResourceNotFoundWithID(test.RandomStringFromRangeAndCharset(1, 16, test.CharsetHexidecimalLowercase))
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWithJSONEncoded(http.StatusNotFound, errors.NewSerializable(responseErr), responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, responseErr)
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with a too many requests response 429", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusTooManyRequests, "NOT JSON", responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorTooManyRequests())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an unexpected response 500 without deserializable error body", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusInternalServerError, nil, responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							Expect(err).To(MatchError(fmt.Sprintf(`unexpected response status code 500 from %s "%s?%s=%s"`, method, url, parameterMutator.Key, parameterMutator.Value)))
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an unexpected response 500 with deserializable error body", func() {
						var responseErr error

						BeforeEach(func() {
							responseErr = errorsTest.RandomError()
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWithJSONEncoded(http.StatusInternalServerError, errors.NewSerializable(responseErr), responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, responseErr)
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with an unparseable response", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusOK, []byte("{\"response\":"), responseHeaders),
								),
							)
						})

						It("returns an error", func() {
							err := clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)
							errorsTest.ExpectEqual(err, request.ErrorJSONMalformed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})

					Context("with a successful response 204 without parsing content", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusNoContent, nil),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(BeEmpty())
						})
					})

					Context("with a successful response 205 without parsing content", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusResetContent, nil),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(BeEmpty())
						})
					})

					Context("with a successful response and no request body", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(nil),
									RespondWith(http.StatusOK, test.MarshalResponseBody(&ResponseBody{Response: responseString}), responseHeaders),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, nil, responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(Equal(responseString))
						})
					})

					Context("with a successful response and request body reader", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody([]byte(requestString)),
									RespondWith(http.StatusOK, test.MarshalResponseBody(&ResponseBody{Response: responseString}), responseHeaders),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, strings.NewReader(requestString), responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(Equal(responseString))
						})
					})

					Context("with a successful response and request body object", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusOK, test.MarshalResponseBody(&ResponseBody{Response: responseString}), responseHeaders),
								),
							)
						})

						It("returns success", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, responseBody, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
							Expect(responseBody).ToNot(BeNil())
							Expect(responseBody.Response).To(Equal(responseString))
						})
					})

					Context("with a successful response and no response body object", func() {
						BeforeEach(func() {
							server.AppendHandlers(
								CombineHandlers(
									VerifyRequest(method, path, fmt.Sprintf("%s=%s", parameterMutator.Key, parameterMutator.Value)),
									VerifyHeaderKV("User-Agent", userAgent),
									VerifyHeaderKV("Content-Type", "application/json; charset=utf-8"),
									VerifyHeaderKV(headerMutator.Key, headerMutator.Value),
									VerifyBody(test.MarshalRequestBody(requestBody)),
									RespondWith(http.StatusOK, test.MarshalResponseBody(&ResponseBody{Response: responseString}), responseHeaders),
								),
							)
						})

						It("returns success without parsing response body", func() {
							Expect(clnt.SendOAuthRequest(ctx, method, url, mutators, requestBody, nil, httpClientSource)).To(Succeed())
							Expect(server.ReceivedRequests()).To(HaveLen(1))
						})
					})
				})
			})
		})
	})
})


text:
<?php

class Checkuser extends CI_Model {

	//extend the parent model construct
	function __construct()
	{
		parent::__construct();

	}

	public function check($variable)
	{
		$variable = (object)$variable;

		$sql = $this->db->query(" SELECT * FROM users WHERE username= '$variable->username' ");

		//$sql = $this->db->get_where('users', array('username' => $variable->username));

		return $sql;

	}

	public function getClientInfo($variable)
	{
		$variable = (object)$variable;

		$sql = $this->db->query(" SELECT p_address, p_code, city, phone, email, status, startDate, stopDate FROM clients WHERE client_id = '$variable->client_id' ");

		return $sql;

	}
}

redpajama_set_name: RedPajamaGithub


text:
ECMAScript is a standardized version of JavaScript with the goal of unifying the language's specifications and features. As all major browsers and JavaScript-runtimes follow this specification, the term ECMAScript is interchangeable with the term JavaScript.

Most of the challenges on freeCodeCamp use the ECMAScript 5 (ES5) specification of the language, finalized in 2009. But JavaScript is an evolving programming language. As features are added and revisions are made, new versions of the language are released for use by developers.

The most recent standardized version is called ECMAScript 6 (ES6), released in 2015. This new version of the language adds some powerful features that will be covered in this section of challenges, including:

    Arrow functions
    Classes
    Modules
    Promises
    Generators
    let and const

Note
Not all browsers support ES6 features. If you use ES6 in your own projects, you may need to use a program (transpiler) to convert your ES6 code into ES5 until browsers support ES6.


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../茨/index.html">
<meta http-equiv=refresh content="0; url='../茨/index.html'">

Redirecting...

Click here if you are not redirected.


text:
package com.validation.manager.core.db;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;

/**
 *
 * @author Javier A. Ortiz Bultron javier.ortiz.78@gmail.com
 */
@Embeddable
public class ExceptionHasCorrectiveActionPK implements Serializable {

    @Basic(optional = false)
    @NotNull
    @Column(name = "exception_id")
    private int exceptionId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "exception_reporter_id")
    private int exceptionReporterId;
    @Basic(optional = false)
    @NotNull
    @Column(name = "corrective_action_id")
    private int correctiveActionId;

    public ExceptionHasCorrectiveActionPK() {
    }

    public ExceptionHasCorrectiveActionPK(int exceptionId,
            int exceptionReporterId, int correctiveActionId) {
        this.exceptionId = exceptionId;
        this.exceptionReporterId = exceptionReporterId;
        this.correctiveActionId = correctiveActionId;
    }

    public int getExceptionId() {
        return exceptionId;
    }

    public void setExceptionId(int exceptionId) {
        this.exceptionId = exceptionId;
    }

    public int getExceptionReporterId() {
        return exceptionReporterId;
    }

    public void setExceptionReporterId(int exceptionReporterId) {
        this.exceptionReporterId = exceptionReporterId;
    }

    public int getCorrectiveActionId() {
        return correctiveActionId;
    }

    public void setCorrectiveActionId(int correctiveActionId) {
        this.correctiveActionId = correctiveActionId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) exceptionId;
        hash += (int) exceptionReporterId;
        hash += (int) correctiveActionId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {

        if (!(object instanceof ExceptionHasCorrectiveActionPK)) {
            return false;
        }
        ExceptionHasCorrectiveActionPK other = (ExceptionHasCorrectiveActionPK) object;
        if (this.exceptionId != other.exceptionId) {
            return false;
        }
        if (this.exceptionReporterId != other.exceptionReporterId) {
            return false;
        }
        return this.correctiveActionId == other.correctiveActionId;
    }

    @Override
    public String toString() {
        return "com.validation.manager.core.db.ExceptionHasCorrectiveActionPK[ "
                + "exceptionId=" + exceptionId + ", exceptionReporterId="
                + exceptionReporterId + ", correctiveActionId="
                + correctiveActionId + " ]";
    }
}


text: To rule them all


text:
Editar Tabla

La tabla que llena la mayor parte de esta página muestra la estructura de
la tabla seleccionada de tu base de datos. Cada fila detalla un campo dentro
de la tabla, mostrando el nombre, tipo de datos y otras opciones.

En la parte inferior izquierda hay un botón para añadir un nuevo campo a
la tabla. Antes de hacer click en él, debes de seleccionar el tipo de campo
a añadir - mira la documentación de MySQL para más información sobre los
tipos de campo. También en la parte inferior hay botones para ver todos
los datos de la tabla y borrar la tabla entera y todos sus datos.


text:
<!DOCTYPE html>

  <title>fusion-point-polygon-legend iframe</title>
  <meta charset='utf-8' />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta content='' name='description' />
  <meta content='' name='author' />

  <link rel="stylesheet" href="css/bootstrap.iframe.css"/>
  <link rel="stylesheet" href="css/custom.css"/>

      <form class="form-inline" role="form">

            <input class='form-control' id='search_address' placeholder='Enter an address/intersection' type='text' />

            within
            <select id='search_radius'>
              <option value='400'>2 blocks</option>
              <option value='805'>1/2 mile</option>
              <option value='1610'>1 mile</option>
              <option value='3220'>2 miles</option>
            </select>

          CT Schools 2014-15 (point layer)

              <input type='checkbox' id='cbType1' />

              District Schools

              <input type='checkbox' id='cbType2' />

              Interdistrict Magnets

              <input type='checkbox' id='cbType3' />

              Charter Schools

              <input type='checkbox' id='cbType4' />

              Technical Schools

              <input type='checkbox' id='cbType5' />

              Other Public Schools

Census Est 2008-12 (polygon layers)

              <input type='radio' name='types' id='rbPolygon1' checked />
              Median Household Income

              <input type='radio' name='types' id='rbPolygon2' />
              Unemployment Rate

              <input type='radio' name='types' id='rbPolygonOff' />
              Off

      </form>

Your JavaScript is disabled

Please enable JavaScript to view the map.

      Data sources: view point data from SmartChoices; view Median Household Income and view Unemployment data from US Census, American Community Survey 5-year estimates, 2008-12; Map boundaries from MAGIC at UConn Libraries

        Visualization by DataViz at Trinity College, based on Searchable Map Template by Derek Eder


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Transaction (Hazelcast Root 3.4.2 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.hazelcast.transaction.impl

Interface Transaction

public interface Transaction

Nested Class Summary

static class
Transaction.State

Method Summary

 void
begin()

 void
commit()

 Transaction.State
getState()

 long
getTimeoutMillis()

 String
getTxnId()

 void
prepare()

 void
rollback()

 void
setRollbackOnly()

Method Detail

begin

void begin()
           throws IllegalStateException

Throws:

IllegalStateException

prepare

void prepare()
             throws TransactionException

Throws:

TransactionException

commit

void commit()
            throws TransactionException,
                   IllegalStateException

Throws:

TransactionException

IllegalStateException

rollback

void rollback()
              throws IllegalStateException

Throws:

IllegalStateException

setRollbackOnly

void setRollbackOnly()

getTxnId

String getTxnId()

getState

Transaction.State getState()

getTimeoutMillis

long getTimeoutMillis()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2015 Hazelcast, Inc.. All Rights Reserved.


text:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.db import models
from message.models import *

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    publicKey = models.CharField(max_length=1024)
    privateKey = models.CharField(max_length=1024, default=1)
    sentMessagesScene= models.IntegerField(default=0)
    recMessagesScene = models.IntegerField(default=0)
    def __str__(self):
          return "%s's profile" % self.user


text:
#ifndef LIGHTGBM_METRIC_RANK_METRIC_HPP_
#define LIGHTGBM_METRIC_RANK_METRIC_HPP_

#include <LightGBM/metric.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/log.h>
#include <LightGBM/utils/openmp_wrapper.h>

#include <string>
#include <sstream>
#include <vector>

namespace LightGBM {

class NDCGMetric:public Metric {
 public:
  explicit NDCGMetric(const Config& config) {
    // get eval position
    eval_at_ = config.eval_at;
    auto label_gain = config.label_gain;
    DCGCalculator::DefaultEvalAt(&eval_at_);
    DCGCalculator::DefaultLabelGain(&label_gain);
    // initialize DCG calculator
    DCGCalculator::Init(label_gain);
  }

  ~NDCGMetric() {
  }
  void Init(const Metadata& metadata, data_size_t num_data) override {
    for (auto k : eval_at_) {
      name_.emplace_back(std::string("ndcg@") + std::to_string(k));
    }
    num_data_ = num_data;
    // get label
    label_ = metadata.label();
    num_queries_ = metadata.num_queries();
    DCGCalculator::CheckMetadata(metadata, num_queries_);
    DCGCalculator::CheckLabel(label_, num_data_);
    // get query boundaries
    query_boundaries_ = metadata.query_boundaries();
    if (query_boundaries_ == nullptr) {
      Log::Fatal("The NDCG metric requires query information");
    }
    // get query weights
    query_weights_ = metadata.query_weights();
    if (query_weights_ == nullptr) {
      sum_query_weights_ = static_cast<double>(num_queries_);
    } else {
      sum_query_weights_ = 0.0f;
      for (data_size_t i = 0; i < num_queries_; ++i) {
        sum_query_weights_ += query_weights_[i];
      }
    }
    inverse_max_dcgs_.resize(num_queries_);
    // cache the inverse max DCG for all queries, used to calculate NDCG
    #pragma omp parallel for schedule(static)
    for (data_size_t i = 0; i < num_queries_; ++i) {
      inverse_max_dcgs_[i].resize(eval_at_.size(), 0.0f);
      DCGCalculator::CalMaxDCG(eval_at_, label_ + query_boundaries_[i],
                               query_boundaries_[i + 1] - query_boundaries_[i],
                               &inverse_max_dcgs_[i]);
      for (size_t j = 0; j < inverse_max_dcgs_[i].size(); ++j) {
        if (inverse_max_dcgs_[i][j] > 0.0f) {
          inverse_max_dcgs_[i][j] = 1.0f / inverse_max_dcgs_[i][j];
        } else {
          // marking negative for all negative queries.
          // if one meet this query, it's ndcg will be set as -1.
          inverse_max_dcgs_[i][j] = -1.0f;
        }
      }
    }
  }

  const std::vector<std::string>& GetName() const override {
    return name_;
  }

  double factor_to_bigger_better() const override {
    return 1.0f;
  }

  std::vector<double> Eval(const double* score, const ObjectiveFunction*) const override {
    int num_threads = OMP_NUM_THREADS();
    // some buffers for multi-threading sum up
    std::vector<std::vector<double>> result_buffer_;
    for (int i = 0; i < num_threads; ++i) {
      result_buffer_.emplace_back(eval_at_.size(), 0.0f);
    }
    std::vector<double> tmp_dcg(eval_at_.size(), 0.0f);
    if (query_weights_ == nullptr) {
      #pragma omp parallel for schedule(static) firstprivate(tmp_dcg)
      for (data_size_t i = 0; i < num_queries_; ++i) {
        const int tid = omp_get_thread_num();
        // if all doc in this query are all negative, let its NDCG=1
        if (inverse_max_dcgs_[i][0] <= 0.0f) {
          for (size_t j = 0; j < eval_at_.size(); ++j) {
            result_buffer_[tid][j] += 1.0f;
          }
        } else {
          // calculate DCG
          DCGCalculator::CalDCG(eval_at_, label_ + query_boundaries_[i],
                                score + query_boundaries_[i],
                                query_boundaries_[i + 1] - query_boundaries_[i], &tmp_dcg);
          // calculate NDCG
          for (size_t j = 0; j < eval_at_.size(); ++j) {
            result_buffer_[tid][j] += tmp_dcg[j] * inverse_max_dcgs_[i][j];
          }
        }
      }
    } else {
      #pragma omp parallel for schedule(static) firstprivate(tmp_dcg)
      for (data_size_t i = 0; i < num_queries_; ++i) {
        const int tid = omp_get_thread_num();
        // if all doc in this query are all negative, let its NDCG=1
        if (inverse_max_dcgs_[i][0] <= 0.0f) {
          for (size_t j = 0; j < eval_at_.size(); ++j) {
            result_buffer_[tid][j] += 1.0f;
          }
        } else {
          // calculate DCG
          DCGCalculator::CalDCG(eval_at_, label_ + query_boundaries_[i],
                                score + query_boundaries_[i],
                                query_boundaries_[i + 1] - query_boundaries_[i], &tmp_dcg);
          // calculate NDCG
          for (size_t j = 0; j < eval_at_.size(); ++j) {
            result_buffer_[tid][j] += tmp_dcg[j] * inverse_max_dcgs_[i][j] * query_weights_[i];
          }
        }
      }
    }
    // Get final average NDCG
    std::vector<double> result(eval_at_.size(), 0.0f);
    for (size_t j = 0; j < result.size(); ++j) {
      for (int i = 0; i < num_threads; ++i) {
        result[j] += result_buffer_[i][j];
      }
      result[j] /= sum_query_weights_;
    }
    return result;
  }

 private:
  /*! \brief Number of data */
  data_size_t num_data_;
  /*! \brief Pointer of label */
  const label_t* label_;
  /*! \brief Name of test set */
  std::vector<std::string> name_;
  /*! \brief Query boundaries information */
  const data_size_t* query_boundaries_;
  /*! \brief Number of queries */
  data_size_t num_queries_;
  /*! \brief Weights of queries */
  const label_t* query_weights_;
  /*! \brief Sum weights of queries */
  double sum_query_weights_;
  /*! \brief Evaluate position of NDCG */
  std::vector<data_size_t> eval_at_;
  /*! \brief Cache the inverse max dcg for all queries */
  std::vector<std::vector<double>> inverse_max_dcgs_;
};

}  // namespace LightGBM

#endif   // LightGBM_METRIC_RANK_METRIC_HPP_


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import os
import unittest

from pants.java.junit.junit_xml_parser import Test as JUnitTest
# NB: The Test -> JUnitTest import re-name above is needed to work around conflicts with pytest test
# collection and a conflicting Test type in scope during that process.
from pants.java.junit.junit_xml_parser import ParseError, TestRegistry, parse_failed_targets
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import safe_open
from pants.util.xml_parser import XmlParser

class TestTest(unittest.TestCase):
  def setUp(self):
    self.class_test = JUnitTest('class')
    self.method_test = JUnitTest('class', 'method')

  def test_no_method_normalization(self):
    def test_normalization(variant):
      self.assertEqual(variant, self.class_test)
      self.assertIsNone(variant.methodname)

    test_normalization(JUnitTest('class', ''))
    test_normalization(JUnitTest('class', None))
    test_normalization(JUnitTest('class'))

  def test_enclosing(self):
    self.assertIs(self.class_test, self.class_test.enclosing())
    self.assertEqual(self.class_test, self.method_test.enclosing())

  def test_render_test_spec(self):
    self.assertEqual('class', self.class_test.render_test_spec())
    self.assertEqual('class#method', self.method_test.render_test_spec())

class TestTestRegistry(unittest.TestCase):
  def test_empty(self):
    self.assertTrue(TestRegistry({}).empty)
    self.assertTrue(TestRegistry(()).empty)
    self.assertTrue(TestRegistry([]).empty)

  def test_get_owning_target(self):
    registry = TestRegistry(((JUnitTest('class1'), 'Bob'),
                             (JUnitTest('class2'), 'Jane'),
                             (JUnitTest('class3', 'method1'), 'Heidi')))

    self.assertEqual('Bob', registry.get_owning_target(JUnitTest('class1')))
    self.assertEqual('Bob', registry.get_owning_target(JUnitTest('class1', 'method1')))

    self.assertEqual('Jane', registry.get_owning_target(JUnitTest('class2')))
    self.assertEqual('Jane', registry.get_owning_target(JUnitTest('class2', 'method1')))

    self.assertIsNone(registry.get_owning_target(JUnitTest('class3')))
    self.assertEqual('Heidi', registry.get_owning_target(JUnitTest('class3', 'method1')))

  def _assert_index(self, expected, actual):
    def sorted_values(index):
      # Eliminate unimportant ordering differences in the index values.
      return {key: sorted(values) for key, values in index.items()}

    self.assertEqual(sorted_values(expected), sorted_values(actual))

  def test_index_nominal(self):
    registry = TestRegistry({JUnitTest('class1'): (1, 'a'),
                             JUnitTest('class2'): (2, 'b'),
                             JUnitTest('class3', 'method1'): (1, 'a'),
                             JUnitTest('class3', 'method2'): (4, 'b')})

    actual_index = registry.index(lambda t: t[0], lambda t: t[1])
    expected_index = {(1, 'a'): (JUnitTest('class1'), JUnitTest('class3', 'method1')),
                      (2, 'b'): (JUnitTest('class2'),),
                      (4, 'b'): (JUnitTest('class3', 'method2'),)}
    self._assert_index(expected_index, actual_index)

  def test_index_empty(self):
    self._assert_index({}, TestRegistry({}).index())

  def test_index_no_indexers(self):
    registry = TestRegistry({JUnitTest('class1'): (1, 'a'),
                             JUnitTest('class2'): (2, 'b')})

    self._assert_index({(): (JUnitTest('class1'), JUnitTest('class2'))}, registry.index())

class TestParseFailedTargets(unittest.TestCase):
  @staticmethod
  def _raise_handler(e):
    raise e

  class CollectHandler(object):
    def __init__(self):
      self._errors = []

    def __call__(self, e):
      self._errors.append(e)

    @property
    def errors(self):
      return self._errors

  def test_parse_failed_targets_no_files(self):
    registry = TestRegistry({})
    with temporary_dir() as junit_xml_dir:
      failed_targets = parse_failed_targets(registry, junit_xml_dir, self._raise_handler)

      self.assertEqual({}, failed_targets)

  def test_parse_failed_targets_nominal(self):
    registry = TestRegistry({JUnitTest('org.pantsbuild.Failure'): 'Bob',
                             JUnitTest('org.pantsbuild.Error'): 'Jane',
                             JUnitTest('org.pantsbuild.AnotherError'): 'Bob'})

    with temporary_dir() as junit_xml_dir:
      with open(os.path.join(junit_xml_dir, 'TEST-a.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="1" errors="1">
          <testcase classname="org.pantsbuild.Green" name="testOK"/>
          <testcase classname="org.pantsbuild.Failure" name="testFailure">
            <failure/>
          </testcase>
          <testcase classname="org.pantsbuild.Error" name="testError">
            <error/>
          </testcase>
        </testsuite>
        """)
      with open(os.path.join(junit_xml_dir, 'TEST-b.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="0" errors="1">
          <testcase classname="org.pantsbuild.AnotherError" name="testAnotherError">
            <error/>
          </testcase>
        </testsuite>
        """)
      with open(os.path.join(junit_xml_dir, 'random.xml'), 'w') as fp:
        fp.write('<invalid></xml>')
      with safe_open(os.path.join(junit_xml_dir, 'subdir', 'TEST-c.xml'), 'w') as fp:
        fp.write('<invalid></xml>')

      failed_targets = parse_failed_targets(registry, junit_xml_dir, self._raise_handler)
      self.assertEqual({'Bob': {JUnitTest('org.pantsbuild.Failure', 'testFailure'),
                                JUnitTest('org.pantsbuild.AnotherError', 'testAnotherError')},
                        'Jane': {JUnitTest('org.pantsbuild.Error', 'testError')}},
                       failed_targets)

  def test_parse_failed_targets_error_raise(self):
    registry = TestRegistry({})
    with temporary_dir() as junit_xml_dir:
      junit_xml_file = os.path.join(junit_xml_dir, 'TEST-bad.xml')
      with open(junit_xml_file, 'w') as fp:
        fp.write('<invalid></xml>')
      with self.assertRaises(ParseError) as exc:
        parse_failed_targets(registry, junit_xml_dir, self._raise_handler)
      self.assertEqual(junit_xml_file, exc.exception.junit_xml_path)
      self.assertIsInstance(exc.exception.cause, XmlParser.XmlError)

  def test_parse_failed_targets_error_continue(self):
    registry = TestRegistry({})
    with temporary_dir() as junit_xml_dir:
      bad_file1 = os.path.join(junit_xml_dir, 'TEST-bad1.xml')
      with open(bad_file1, 'w') as fp:
        fp.write('<testsuite failures="nan" errors="0"/>')
      with open(os.path.join(junit_xml_dir, 'TEST-good.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="0" errors="1">
          <testcase classname="org.pantsbuild.Error" name="testError">
            <error/>
          </testcase>
        </testsuite>
        """)
      bad_file2 = os.path.join(junit_xml_dir, 'TEST-bad2.xml')
      with open(bad_file2, 'w') as fp:
        fp.write('<invalid></xml>')

      collect_handler = self.CollectHandler()
      failed_targets = parse_failed_targets(registry, junit_xml_dir, collect_handler)
      self.assertEqual(2, len(collect_handler.errors))
      self.assertEqual({bad_file1, bad_file2}, {e.junit_xml_path for e in collect_handler.errors})

      self.assertEqual({None: {JUnitTest('org.pantsbuild.Error', 'testError')}}, failed_targets)


text:
namespace polaris
{
	template<typename MasterType>
	struct Routable_Agent_Implementation
	{
		template<typename CurrentEdgeType, typename ConnectionType>
		bool process_connection_set(CurrentEdgeType* current)
		{
			return true;
		}

		bool at_destination(Base_Edge_A_Star<MasterType>* current, Base_Edge_A_Star<MasterType>* destination)
		{
			if(current->_edge_id == destination->_edge_id) return true;
			else return false;
		}

		template<typename CurrentEdgeType>
		float estimated_cost_between(CurrentEdgeType* current, Base_Edge_A_Star<MasterType>* destination)
		{
			float x_dist = current->_x - destination->_x;
			x_dist *= x_dist;

			float y_dist = current->_y - destination->_y;
			y_dist *= y_dist;

			// vehicle speed
			float cost = sqrt(x_dist + y_dist)/89.0f;

			return cost;
		}

		template<typename CurrentEdgeType, typename NeighborEdgeType, typename ConnectionType>
		float cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
		{
			if(neighbor->_is_highway)
			{
				//cout << "is highway" << endl;
				//return (current->_cost + connection->_cost)*.75f;
				return (current->_cost + connection->_cost)*.95f;
			}
			else
			{
				//cout << "is not highway" << endl;
				return current->_cost + connection->_cost;
			}
		}

		template<>
		float cost_between(typename MT::time_dependent_edge_type* current, typename MT::time_dependent_edge_type* neighbor, typename MT::time_dependent_to_time_dependent_type* connection)
		{
			// moe lookup
			int current_time = current->time_label();
			float* moe_ptr = current->moe_ptr();

			if(moe_ptr != nullptr)
			{
				float time_cost = current->moe_data()->get_closest_element(moe_ptr,current_time);

				if(neighbor->_is_highway)
				{
					//t_pointer(float,moe_ptr);
					//static t_pointer(Layered_Data_Array<float>,moe_data);

					return time_cost*.75f;
				}
				else
				{

					return time_cost;
				}
			}
			else
			{

				if(neighbor->_is_highway)
				{
					//cout << "is highway" << endl;
					return (current->_cost + connection->_cost)*.75f;
				}
				else
				{
					//cout << "is not highway" << endl;
					return current->_cost + connection->_cost;
				}

			}
		}

		template<typename CurrentEdgeType,typename NeighborEdgeType, typename ConnectionType>
		float time_cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
		{
			return current->_time_cost + connection->_time_cost;
		}

		template<>
		float time_cost_between(typename MT::time_dependent_edge_type* current, typename MT::time_dependent_edge_type* neighbor, typename MT::time_dependent_to_time_dependent_type* connection)
		{
			// moe lookup
			int current_time = current->time_label();
			float* moe_ptr = current->moe_ptr();

			if(moe_ptr != nullptr)
			{
				//cout << "curent time: " << current_time << endl;

				float time_cost = current->moe_data()->get_closest_element(moe_ptr,current_time);

				//cout << "moe cost: " << time_cost << endl;

				if(neighbor->_is_highway)
				{
					//t_pointer(float,moe_ptr);
					//static t_pointer(Layered_Data_Array<float>,moe_data);

					return time_cost*.75f;
				}
				else
				{

					return time_cost;
				}
			}
			else
			{

				if(neighbor->_is_highway)
				{
					//cout << "is highway" << endl;
					return (current->_cost + connection->_cost)*.75f;
				}
				else
				{
					//cout << "is not highway" << endl;
					return current->_cost + connection->_cost;
				}

			}
		}

		template<typename CurrentEdgeType,typename NeighborEdgeType, typename ConnectionType>
		void update_label(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection){}

		t_data(float,wait_horizon);
	};

	template<typename MasterType>
	struct Tree_Agent_Implementation
	{
		template<typename CurrentEdgeType, typename ConnectionType>
		bool process_connection_set(CurrentEdgeType* current)
		{
			return true;
		}

		bool at_destination(Base_Edge_A_Star<MasterType>* current, Base_Edge_A_Star<MasterType>* destination)
		{
			return false;
		}

		template<typename CurrentEdgeType>
		float estimated_cost_between(CurrentEdgeType* current, Base_Edge_A_Star<MasterType>* destination)
		{
			return 0.0f;
		}

		template<typename CurrentEdgeType, typename NeighborEdgeType, typename ConnectionType>
		float cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
		{
			return current->_cost + connection->_cost;
		}

		template<typename CurrentEdgeType,typename NeighborEdgeType, typename ConnectionType>
		float time_cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
		{
			return current->_time_cost + connection->_time_cost;
		}

		template<typename CurrentEdgeType,typename NeighborEdgeType, typename ConnectionType>
		void update_label(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection){}
	};

	//template<typename MasterType>
	//struct Time_Dependent_Agent_Implementation
	//{
	//	template<typename CurrentEdgeType, typename ConnectionType>
	//	bool process_connection_set(CurrentEdgeType* current)
	//	{
	//		return true;
	//	}

	//	//template<>
	//	//bool process_connection_set<typename MasterType::transit_edge,typename MasterType::walk_transfer_type>(typename MasterType::transit_edge* current)
	//	//{
	//	//	if(current->_transfers_made < 3) return true;
	//	//	else return false;
	//	//}

	//	//template<>
	//	//bool process_connection_set<typename MasterType::transit_edge,typename MasterType::transfer_at_stop_type>(typename MasterType::transit_edge* current)
	//	//{
	//	//	if(current->_transfers_made < 3) return true;
	//	//	else return false;
	//	//}
	//	//
	//	//template<>
	//	//bool process_connection_set<typename MasterType::stop_edge,typename MasterType::stop_to_stop_type>(typename MasterType::stop_edge* current)
	//	//{
	//	//	if(current->_walk_transfers_made < 2) return true;
	//	//	else return false;
	//	//}

	//	bool at_destination(Base_Edge_A_Star<MasterType>* current, Base_Edge_A_Star<MasterType>* destination)
	//	{
	//		if(current->_edge_id == destination->_edge_id) return true;
	//		else return false;
	//	}

	//	template<typename CurrentEdgeType>
	//	float estimated_cost_between(CurrentEdgeType* current, Base_Edge_A_Star<MasterType>* destination)
	//	{
	//		float x_dist = current->_x - destination->_x;
	//		x_dist *= x_dist;
	//
	//		float y_dist = current->_y - destination->_y;
	//		y_dist *= y_dist;

	//		// vehicle speed
	//		float cost = sqrt(x_dist + y_dist)/89.0f;
	//
	//		return cost;
	//	}

	//	//template<>
	//	//float estimated_cost_between<typename MasterType::stop_edge>(typename MasterType::stop_edge* current, Base_Edge_A_Star<MasterType>* destination)
	//	//{
	//	//	float x_dist = current->_x - destination->_x;
	//	//	x_dist *= x_dist;
	//	//
	//	//	float y_dist = current->_y - destination->_y;
	//	//	y_dist *= y_dist;

	//	//	// walk speed
	//	//	float cost = sqrt(x_dist + y_dist)/1.34f;
	//	//
	//	//	return cost;
	//	//}

	//	template<typename CurrentEdgeType, typename NeighborEdgeType, typename ConnectionType>
	//	float cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
	//	{
	//		// moe lookup
	//		int current_time = current->time_label();
	//		float* moe_ptr = current->moe_ptr();

	//		if(moe_ptr != nullptr)
	//		{
	//			float time_cost = current->moe_data()->get_closest_element(moe_ptr,current_time);

	//			if(neighbor->_is_highway)
	//			{
	//				//t_pointer(float,moe_ptr);
	//				//static t_pointer(Layered_Data_Array<float>,moe_data);

	//				return time_cost*.75f;
	//			}
	//			else
	//			{

	//				return time_cost;
	//			}
	//		}
	//		else
	//		{

	//			if(neighbor->_is_highway)
	//			{
	//				return (current->_time_cost + connection->_time_cost)*.75f;
	//			}
	//			else
	//			{
	//				return current->_time_cost + connection->_time_cost;
	//			}
	//
	//		}
	//	}

	//	//template<>
	//	//float cost_between<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::ride_on_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::ride_on_type* connection)
	//	//{
	//	//	return current->_time_cost + connection->_time_cost;
	//	//}
	//	//
	//	//template<>
	//	//float cost_between<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::transfer_at_stop_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::transfer_at_stop_type* connection)
	//	//{
	//	//	// disincentivize these sort of transfers
	//	//	//const float transfer_penalty = 2.0f;
	//	//	const float transfer_penalty = 1.0f;
	//	//	return (current->_time_cost + connection->_time_cost)*transfer_penalty;
	//	//}

	//	//template<>
	//	//float cost_between<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::walk_transfer_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::walk_transfer_type* connection)
	//	//{
	//	//	// strongly disincentivize these sort of transfers
	//	//	//const float walk_transfer_penalty = 3.0f;
	//	//	const float walk_transfer_penalty = 1.0f;
	//	//	return (current->_time_cost + connection->_time_cost)*walk_transfer_penalty;
	//	//}

	//	//template<>
	//	//float cost_between<typename MasterType::transit_edge,typename MasterType::stop_edge,typename MasterType::transit_to_stop_type>(typename MasterType::transit_edge* current, typename MasterType::stop_edge* neighbor, typename MasterType::transit_to_stop_type* connection)
	//	//{
	//	//	return current->_time_cost + connection->_time_cost;
	//	//}
	//	//
	//	//template<>
	//	//float cost_between<typename MasterType::stop_edge,typename MasterType::transit_edge,typename MasterType::stop_to_transit_type>(typename MasterType::stop_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::stop_to_transit_type* connection)
	//	//{
	//	//	// have to wait at the stop until the trip leaves
	//	//	return connection->_departure_time - current->_time_label;
	//	//}

	//	template<typename CurrentEdgeType, typename NeighborEdgeType, typename ConnectionType>
	//	float time_cost_between(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection)
	//	{
	//		// moe lookup
	//		int current_time = current->time_label();
	//		float* moe_ptr = current->moe_ptr();

	//		if(moe_ptr != nullptr)
	//		{
	//			float time_cost = current->moe_data()->get_closest_element(moe_ptr,current_time);

	//			if(neighbor->_is_highway)
	//			{
	//				//t_pointer(float,moe_ptr);
	//				//static t_pointer(Layered_Data_Array<float>,moe_data);

	//				return time_cost*.75f;
	//			}
	//			else
	//			{

	//				return time_cost;
	//			}
	//		}
	//		else
	//		{

	//			if(neighbor->_is_highway)
	//			{
	//				return (current->_time_cost + connection->_time_cost)*.75f;
	//			}
	//			else
	//			{
	//				return current->_time_cost + connection->_time_cost;
	//			}
	//
	//		}
	//	}

	//	//template<>
	//	//float time_cost_between<typename MasterType::stop_edge,typename MasterType::transit_edge,typename MasterType::stop_to_transit_type>(typename MasterType::stop_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::stop_to_transit_type* connection)
	//	//{
	//	//	// have to wait at the stop until the trip leaves
	//	//	return connection->_departure_time - current->_time_label;
	//	//}

	//	template<typename CurrentEdgeType,typename NeighborEdgeType, typename ConnectionType>
	//	void update_label(CurrentEdgeType* current, NeighborEdgeType* neighbor, ConnectionType* connection){}

	//	//template<>
	//	//void update_label<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::ride_on_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::ride_on_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made;
	//	//}
	//	//
	//	//template<>
	//	//void update_label<typename MasterType::transit_edge,typename MasterType::stop_edge,typename MasterType::transit_to_stop_type>(typename MasterType::transit_edge* current, typename MasterType::stop_edge* neighbor, typename MasterType::transit_to_stop_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made;
	//	//}

	//	//template<>
	//	//void update_label<typename MasterType::stop_edge,typename MasterType::transit_edge,typename MasterType::stop_to_transit_type>(typename MasterType::stop_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::stop_to_transit_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made;
	//	//}

	//	//template<>
	//	//void update_label<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::transfer_at_stop_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::transfer_at_stop_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made + 1;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made;
	//	//}

	//	//template<>
	//	//void update_label<typename MasterType::transit_edge,typename MasterType::transit_edge,typename MasterType::walk_transfer_type>(typename MasterType::transit_edge* current, typename MasterType::transit_edge* neighbor, typename MasterType::walk_transfer_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made + 1;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made;
	//	//}

	//	//template<>
	//	//void update_label<typename MasterType::stop_edge,typename MasterType::stop_edge,typename MasterType::stop_to_stop_type>(typename MasterType::stop_edge* current, typename MasterType::stop_edge* neighbor, typename MasterType::stop_to_stop_type* connection)
	//	//{
	//	//	neighbor->_transfers_made = current->_transfers_made;
	//	//	neighbor->_walk_transfers_made = current->_walk_transfers_made + 1;
	//	//}

	//	t_data(float,wait_horizon);
	//};
}


text:
using System;
using Twilio;
using Twilio.Rest.Chat.V2.Service.Channel;

class Example
{
    static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string channelSid = "CHXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string messageSid = "IMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        TwilioClient.Init(accountSid, authToken);

        // Delete the message
        var status = MessageResource.Delete(serviceSid, channelSid, messageSid);
        Console.WriteLine(status);
    }
}


text:
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

#include "NXEventAction.hh"

#include "G4Event.hh"
#include "G4EventManager.hh"
#include "G4TrajectoryContainer.hh"
#include "G4Trajectory.hh"
#include "G4ios.hh"

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

NXEventAction::NXEventAction()
{}

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

NXEventAction::~NXEventAction()
{}

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

void NXEventAction::BeginOfEventAction(const G4Event*)
{}

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......

void NXEventAction::EndOfEventAction(const G4Event* evt)
{
    G4int event_id = evt->GetEventID();

    /*
    // get number of stored trajectories
    //
    G4TrajectoryContainer* trajectoryContainer = evt->GetTrajectoryContainer();
    G4int n_trajectories = 0;
    if (trajectoryContainer) n_trajectories = trajectoryContainer->entries();

    // periodic printing
    //
    if (event_id < 100 || event_id%100 == 0) {
        G4cout << ">>> Event " << evt->GetEventID() << G4endl;
        G4cout << "    " << n_trajectories
            << " trajectories stored in this event." << G4endl;
    }
    */
}

//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......


text:
#ifndef RBX_CHANNEL_HPP
#define RBX_CHANNEL_HPP

#include "builtin/object.hpp"
#include "type_info.hpp"

#include "virtual.hpp" // ObjectCallback
#include "gc/root.hpp" // TypedRoot

#include "builtin/thread.hpp"

namespace rubinius {
  class Float;
  class List;
  class IO;
  class IOBuffer;
  class Message;
  class Executable;

  class Channel : public Object {
  public:

    /** Register class. */
    static void  init(STATE);

    const static object_type type = ChannelType;

  private:
    List* value_;  // slot

    thread::Condition condition_;
    thread::Mutex mutex_;
    int waiters_;

  public:
    /* accessors */

    attr_accessor(value, List);

    /* interface */

    // Ruby.primitive :channel_new
    static Channel* create(STATE);

    /** Remove Thread from waiting list, if it is there. */
    void    cancel_waiter(STATE, const Thread* waiter);

    // Ruby.primitive :channel_send
    Object* send(STATE, Object*);

    // Ruby.primitive :channel_receive
    Object* receive(STATE, CallFrame* calling_environment);

    // Ruby.primitive :channel_try_receive
    Object* try_receive(STATE);

    // Ruby.primitive :channel_receive_timeout
    Object* receive_timeout(STATE, Object* duration, CallFrame* calling_environment);

    bool has_readers_p();

    class Info : public TypeInfo {
    public:
      BASIC_TYPEINFO(TypeInfo)
    };

  };

  class ChannelCallback : public ObjectCallback {
  public:
    TypedRoot<Channel*> channel;

    ChannelCallback(STATE, Channel* chan);
    virtual void call(Object* obj);
  };

}

#endif


text:
/*
Probar las foreign key en la tabla RESERVA, donde EMAIL_CLIENTE es la primary key de la tabla CLIENTEFR y
ID_MENU la primary key de MENU
*/

INSERT INTO USUARIOS VALUES ('jc.ruiz@sa.com', 'Juan Camilo', 100000);

INSERT INTO CATEGORIA VALUES ('FUERTE');

INSERT INTO CLIENTEFR VALUES ('jc.ruiz@sa.com', 'laclave', 'jc.ruiz', 2000, 'FUERTE', 'Juan Camilo', 100000);

INSERT INTO ZONA (NOMBRE, CAPACIDAD, ABIERTO, APTODISCAPACIDAD, DESCRIPCIONTECNICA)
VALUES ('ZONA COLOMBIA', 250, 1, 1, 'Zona tematica de Colombia, comida y ambiente tipicos');

INSERT INTO RESTAURANTES (NOMBRE,REPRESENTANTE,TIPOCOMIDA,ZONA, VALOR_COSTOS,VALOR_VENTAS)
VALUES ('LA BANDEJA PAISA', 'JORGE', 'COMIDA COLOMBIANA', 'ZONA COLOMBIA', 3000,8000);

INSERT INTO MENU VALUES ('Combo 1', 1000,3000, 20, 30,'LA BANDEJA PAISA', 1);
/*
Caso en que la foreign key exista
*/
INSERT INTO RESERVA VALUES ('23/05/2016', 100, 'ZONA COLOMBIA', 1, 'jc.ruiz@sa.com');

/*
Caso en que la foreign key EMAIL_CLIENTE no exista
*/
INSERT INTO RESERVA VALUES ('22/02/2016', 100, 'ZONA COLOMBIA', 1, 'otro@sa.com');

/*
Caso en que la foreign key ID_MENU no exista
*/
INSERT INTO RESERVA VALUES ('21/01/2016', 100, 'ZONA COLOMBIA', 2,  'jc.ruiz@sa.com');

/*
Para borrar, primero se boora RESERVA luego MENU, luego RESTAURANTE, luego ZONA, luego CLIENTE, luego USUARIO
*/
DELETE FROM RESERVA WHERE ZONA = 'ZONA COLOMBIA';
DELETE FROM MENU WHERE ID_MENU = 1;
DELETE FROM RESTAURANTES WHERE NOMBRE = 'LA BANDEJA PAISA';
DELETE FROM ZONA WHERE NOMBRE = 'ZONA COLOMBIA';
DELETE FROM CLIENTEFR WHERE EMAIL = 'jc.ruiz@sa.com';
DELETE FROM USUARIOS WHERE EMAIL = 'jc.ruiz@sa.com';


text:
package org.wso2.andes.store.jdbc.h2;

import org.apache.log4j.Logger;
import org.wso2.andes.configuration.ConfigurationProperties;
import org.wso2.andes.kernel.AndesContext;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.kernel.DurableStoreConnection;
import org.wso2.andes.store.jdbc.JDBCConnection;
import org.wso2.andes.store.jdbc.JDBCMessageStoreImpl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * This is H2 in memory mode specific MessageStore implementation Table creation at startup is done
 * in this implementation
 */
public class H2MemMessageStoreImpl extends JDBCMessageStoreImpl {

    private static final Logger logger = Logger.getLogger(H2MemMessageStoreImpl.class);
    /**
     * Create messages table in H2 database
     */
    protected static final String CREATE_MESSAGES_TABLE = "CREATE TABLE IF NOT EXISTS messages (" +
            "message_id BIGINT, " +
            "offset INT, " +
            "content BLOB NOT NULL, " +
            "PRIMARY KEY (message_id,offset)" +
            ");";

    /**
     * Create queues table in H2 database
     */
    protected static final String CREATE_QUEUES_TABLE = "CREATE TABLE IF NOT EXISTS queues (" +
            "queue_id INT AUTO_INCREMENT, " +
            "name VARCHAR NOT NULL, " +
            "UNIQUE (name)," +
            "PRIMARY KEY (queue_id)" +
            ");";

    /**
     * Create metadata table in H2 database
     */
    protected static final String CREATE_METADATA_TABLE = "CREATE TABLE IF NOT EXISTS metadata (" +
            "message_id BIGINT, " +
            "queue_id INT, " +
            "data BINARY, " +
            "PRIMARY KEY (message_id, queue_id), " +
            "FOREIGN KEY (queue_id) " +
            "REFERENCES queues (queue_id) " +
            ");";

    /**
     * Creates expiration data table in H2 database
     */
    protected static final String CREATE_EXPIRATION_DATA_TABLE = "CREATE TABLE IF NOT EXISTS expiration_data (" +
            "message_id BIGINT UNIQUE," +
            "expiration_time BIGINT, " +
            "destination VARCHAR NOT NULL, " +
            "FOREIGN KEY (message_id) " +
            "REFERENCES metadata " +
            "(message_id)" +
            ");";

    /**
     * Creates reference counts table in H2 database
     */
    protected static final String CREATE_REF_COUNT_TABLE = "CREATE TABLE IF NOT EXISTS " +
            "reference_counts ( " +
            "message_id BIGINT, " +
            "reference_count INT, " +
            "PRIMARY KEY (message_id)" +
            ");";

    /**
     * logging string for task of creating database tables
     */
    protected static final String TASK_CREATING_DB_TABLES = "creating database tables";

    /**
     * Creates an in memory database connection and initialise the in memory data source.
     * connectionProperties provided here are IGNORED and in-memory mode connection properties
     * used internally.
     * <p/>
     * NOTE: connectionProperties are ignored to minimise error in pointing the in memory store
     * to a wrong message store
     *
     * @param connectionProperties IGNORED
     * @return DurableStoreConnection
     * @throws AndesException
     */
    @Override
    public DurableStoreConnection initializeMessageStore(ConfigurationProperties connectionProperties)
            throws AndesException {

        // in memory mode should only run in single node mode
        if(AndesContext.getInstance().isClusteringEnabled()) {
            throw new AndesException("In memory mode is not supported in cluster setup");
        }

        // use the initialisation logic of JDBC MessageStore
        DurableStoreConnection durableStoreConnection = super.initializeMessageStore(JDBCConnection
                .getInMemoryConnectionProperties());

        // Additionally create in memory database tables
        createTables();
        logger.info("In-memory message store initialised");
        return durableStoreConnection;
    }

    /**
     * This method creates all the DB tables used for H2 based In memory Message Store.
     *
     * @throws AndesException
     */
    public void createTables() throws AndesException {
        String[] queries = {
                CREATE_MESSAGES_TABLE,
                CREATE_QUEUES_TABLE,
                CREATE_METADATA_TABLE,
                CREATE_EXPIRATION_DATA_TABLE,
                CREATE_REF_COUNT_TABLE
        };

        Connection connection = null;
        Statement stmt = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            for (String q : queries) {
                stmt.addBatch(q);
            }
            stmt.executeBatch();

        } catch (SQLException e) {
            rollback(connection, TASK_CREATING_DB_TABLES);
            throw new AndesException("Error occurred while creating in memory database tables", e);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                logger.error(TASK_CREATING_DB_TABLES, e);
            }
            close(connection, TASK_CREATING_DB_TABLES);
        }
    }
}


text:
[![Build Status](https://secure.travis-ci.org/erlcloud/erlcloud.png?branch=master)](http://travis-ci.org/erlcloud/erlcloud)

Service APIs implemented:

- Amazon Elastic Compute Cloud (EC2)
- Amazon Simple Storage Service (S3)
- Amazon Simple Queue Service (SQS)
- Amazon SimpleDB
- Amazon Mechanical Turk
- Amazon CloudWatch (MON)
- Amazon DynamoDB (ddb2)

All API functions have been implemented.  Not all functions have been thoroughly tested, so exercise care when integrating this library into production code.  Please send bug reports and patches.

The libraries can be used two ways: either you can specify configuration parameters in the process dictionary, or you can create a configuration object and pass that to each request as the final parameter.

## Getting started ##
You need to clone the repository and download rebar (if it's not already available in your path).

```
git clone https://github.com/erlcloud/erlcloud.git
cd erlcloud
wget http://cloud.github.com/downloads/basho/rebar/rebar && chmod u+x rebar
```

You can provide your amazon credentials in environmental variables.

```
export AWS_ACCESS_KEY_ID=<Your AWS Access Key>
export AWS_SECRET_ACCESS_KEY=<Your AWS Secret Access Key>
```
To compile and run erlcloud
```
make
make run
```

If you're using erlcloud in your application, add it as a dependency in your application's configuration file.  To use erlcloud in the shell, you can start it by calling:

```
ssl:start().
erlcloud:start().
```

If you did not provide your amazon credentials in the environmental variables, then you need to provide the per-process configuration:

```
erlcloud_ec2:configure(AccessKeyId, SecretAccessKey [, Hostname]).
```

Hostname defaults to "ec2.amazonaws.com".

Then you can start making api calls, like:

```
erlcloud_ec2:describe_images().
erlcloud_s3:list_buckets().
```

Configuration object usage:

```
EC2 = erlcloud_ec2:new(AccessKeyId, SecretAccessKey [, Hostname])
erlcloud_ec2:describe_images(EC2).
```

Creating an EC2 instance may look like this:
```
start_instance(Ami, KeyPair, UserData, Type, Zone) ->
    Config = #aws_config{
            access_key_id = application:get_env(aws_key),
            secret_access_key = application:get_env(aws_secret)
           },

    InstanceSpec = #ec2_instance_spec{image_id = Ami,
                                      key_name = KeyPair,
                                      instance_type = Type,
                                      availability_zone = Zone,
                                      user_data = UserData},
    erlcloud_ec2:run_instances(InstanceSpec, Config).
```

For usage information, consult the source code and refer to the API reference at:

- http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Welcome.html
- http://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html
- http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/

## Roadmap ##

v0.8.0
* Existing code

v0.9.0
* Make unit tests useful and improve documentation

v1.0.0
* Refactored code for better return values (issue #7)

## Notes ##

Indentation in contributions should follow indentation style of surrounding text. In general it follows default indentation rules of official erlang-mode as provided by OTP team.