doc
stringlengths 10
26.3k
| code
stringlengths 52
3.87M
|
---|---|
//
// Cache
//
// NewLRUCache creates a new Cache that caches content for the given client
// for up to the maximum duration.
//
// See NewCachedClient
|
func NewLRUCache(
clientID string,
duration time.Duration,
cache *lru.LRUCache) *LRUCache {
return &LRUCache{
ClientID: clientID,
Duration: duration,
DurationSeconds: int64(duration.Seconds()),
Cache: cache,
}
}
|
// Set specifies that the given content was retrieved for the given URL at the
// given time. The content for that URL will be available by LRUCache.Get from
// the given 'time' up to 'time + l.Duration'
|
func (l *LRUCache) Set(url string, time time.Time, content *FantasyContent) {
l.Cache.Set(l.getKey(url, time), &LRUCacheValue{content: content})
}
|
// Get the content for the given URL at the given time.
|
func (l *LRUCache) Get(url string, time time.Time) (content *FantasyContent, ok bool) {
value, ok := l.Cache.Get(l.getKey(url, time))
if !ok {
return nil, ok
}
lruCacheValue, ok := value.(*LRUCacheValue)
if !ok {
return nil, ok
}
return lruCacheValue.content, true
}
|
// getKey converts a base key to a key that is unique for the client of the
// LRUCache and the current time period.
//
// The created keys have the following format:
//
// <client-id>:<originalKey>:<period>
//
// Given a client with ID "client-id-01", original key of "key-01", a current
// time of "08/17/2014 1:21pm", and a maximum cache duration of 1 hour, this
// will generate the following key:
//
// client-id-01:key-01:391189
//
|
func (l *LRUCache) getKey(originalKey string, time time.Time) string {
period := time.Unix() / l.DurationSeconds
return fmt.Sprintf("%s:%s:%d", l.ClientID, originalKey, period)
}
|
//
// ContentProvider
//
|
func (p *cachedContentProvider) Get(url string) (*FantasyContent, error) {
currentTime := time.Now()
content, ok := p.cache.Get(url, currentTime)
if !ok {
content, err := p.delegate.Get(url)
if err == nil {
p.cache.Set(url, currentTime, content)
}
return content, err
}
return content, nil
}
|
// fixContent updates the fantasy data with content that can't be unmarshalled
// directly from XML
|
func fixContent(c *FantasyContent) *FantasyContent {
fixTeam(&c.Team)
for i := range c.League.Teams {
fixTeam(&c.League.Teams[i])
}
for i := range c.League.Standings {
fixTeam(&c.League.Standings[i])
}
for i := range c.League.Players {
fixPoints(&c.League.Players[i].PlayerPoints)
}
for i := range c.League.Scoreboard.Matchups {
fixTeam(&c.League.Scoreboard.Matchups[i].Teams[0])
fixTeam(&c.League.Scoreboard.Matchups[i].Teams[1])
}
return c
}
|
//
// httpAPIClient
//
// Get returns the HTTP response of a GET request to the given URL.
|
func (o *countingHTTPApiClient) Get(url string) (*http.Response, error) {
o.requestCount++
response, err := o.client.Get(url)
// Known issue where "consumer_key_unknown" is returned for valid
// consumer keys. If this happens, try re-requesting the content a few
// times to see if it fixes itself
//
// See https://developer.yahoo.com/forum/OAuth-General-Discussion-YDN-SDKs/oauth-problem-consumer-key-unknown-/1375188859720-5cea9bdb-0642-4606-9fd5-c5f369112959
for attempts := 0; attempts < 4 &&
err != nil &&
strings.Contains(err.Error(), "consumer_key_unknown"); attempts++ {
o.requestCount++
response, err = o.client.Get(url)
}
if err != nil &&
strings.Contains(
err.Error(),
"You are not allowed to view this page") {
err = ErrAccessDenied
}
return response, err
}
|
//
// Yahoo interface
//
// GetFantasyContent directly access Yahoo fantasy resources.
//
// See http://developer.yahoo.com/fantasysports/guide/ for more information
|
func (c *Client) GetFantasyContent(url string) (*FantasyContent, error) {
return c.Provider.Get(url)
}
|
//
// Convenience functions
//
// GetUserLeagues returns a list of the current user's leagues for the given
// year.
|
func (c *Client) GetUserLeagues(year string) ([]League, error) {
yearKey, ok := YearKeys[year]
if !ok {
return nil, fmt.Errorf("data not available for year=%s", year)
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/users;use_login=1/games;game_keys=%s/leagues",
YahooBaseURL,
yearKey))
if err != nil {
return nil, err
}
if len(content.Users) == 0 {
return nil, errors.New("no users returned for current user")
}
if len(content.Users[0].Games) == 0 ||
content.Users[0].Games[0].Leagues == nil {
return make([]League, 0), nil
}
return content.Users[0].Games[0].Leagues, nil
}
|
// GetPlayersStats returns a list of Players containing their stats for the
// given week in the given year.
|
func (c *Client) GetPlayersStats(leagueKey string, week int, players []Player) ([]Player, error) {
playerKeys := ""
for index, player := range players {
if index != 0 {
playerKeys += ","
}
playerKeys += player.PlayerKey
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/players;player_keys=%s/stats;type=week;week=%d",
YahooBaseURL,
leagueKey,
playerKeys,
week))
if err != nil {
return nil, err
}
return content.League.Players, nil
}
|
// GetTeamRoster returns a team's roster for the given week.
|
func (c *Client) GetTeamRoster(teamKey string, week int) ([]Player, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/team/%s/roster;week=%d",
YahooBaseURL,
teamKey,
week))
if err != nil {
return nil, err
}
return content.Team.Roster.Players, nil
}
|
// GetAllTeamStats gets teams stats for a given week.
|
func (c *Client) GetAllTeamStats(leagueKey string, week int) ([]Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/teams/stats;type=week;week=%d",
YahooBaseURL,
leagueKey,
week))
if err != nil {
return nil, err
}
return content.League.Teams, nil
}
|
// GetTeam returns all available information about the given team.
|
func (c *Client) GetTeam(teamKey string) (*Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/team/%s;out=stats,metadata,players,standings,roster",
YahooBaseURL,
teamKey))
if err != nil {
return nil, err
}
if content.Team.TeamID == 0 {
return nil, fmt.Errorf("no team returned for key='%s'", teamKey)
}
return &content.Team, nil
}
|
// GetLeagueMetadata returns the metadata associated with the given league.
|
func (c *Client) GetLeagueMetadata(leagueKey string) (*League, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/metadata",
YahooBaseURL,
leagueKey))
if err != nil {
return nil, err
}
return &content.League, nil
}
|
// GetAllTeams returns all teams playing in the given league.
|
func (c *Client) GetAllTeams(leagueKey string) ([]Team, error) {
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/teams", YahooBaseURL, leagueKey))
if err != nil {
return nil, err
}
return content.League.Teams, nil
}
|
// GetMatchupsForWeekRange returns a list of matchups for each week in the
// requested range.
|
func (c *Client) GetMatchupsForWeekRange(leagueKey string, startWeek, endWeek int) (map[int][]Matchup, error) {
leagueList := strconv.Itoa(startWeek)
for i := startWeek + 1; i <= endWeek; i++ {
leagueList += "," + strconv.Itoa(i)
}
content, err := c.GetFantasyContent(
fmt.Sprintf("%s/league/%s/scoreboard;week=%s",
YahooBaseURL,
leagueKey,
leagueList))
if err != nil {
return nil, err
}
all := make(map[int][]Matchup)
for _, matchup := range content.League.Scoreboard.Matchups {
week := matchup.Week
list, ok := all[week]
if !ok {
list = make([]Matchup, 0)
}
all[week] = append(list, matchup)
}
return all, nil
}
|
// List spaces using the provided options.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces
|
func (s *SpacesService) List(opt *SpaceListOptions) ([]Space, *http.Response, error) {
u, err := urlWithOptions("spaces", opt)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var spacesResp listSpacesResponse
resp, err := s.client.Do(req, &spacesResp)
if err != nil {
return nil, resp, err
}
return spacesResp.Spaces, resp, nil
}
|
// Get fetches a space based on the provided ID.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces/:id
|
func (s *SpacesService) Get(id uint) (*Space, *http.Response, error) {
u, err := urlWithOptions(fmt.Sprintf("spaces/%d", id), nil)
if err != nil {
return nil, nil, err
}
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
sp := new(Space)
resp, err := s.client.Do(req, sp)
if err != nil {
return nil, resp, err
}
return sp, resp, err
}
|
// Create a space with a given name.
//
// Librato API docs: http://dev.librato.com/v1/post/spaces
|
func (s *SpacesService) Create(space *Space) (*Space, *http.Response, error) {
req, err := s.client.NewRequest("POST", "spaces", space)
if err != nil {
return nil, nil, err
}
sp := new(Space)
resp, err := s.client.Do(req, sp)
if err != nil {
return nil, resp, err
}
return sp, resp, err
}
|
// Update a space.
//
// Librato API docs: http://dev.librato.com/v1/put/spaces/:id
|
func (s *SpacesService) Update(spaceID uint, space *Space) (*http.Response, error) {
u := fmt.Sprintf("spaces/%d", spaceID)
req, err := s.client.NewRequest("PUT", u, space)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
|
// NewStringLexer creates a new StringLexer instance. This lexer can be
// used only once per input string. Do not try to reuse it
|
func NewStringLexer(input string, fn LexFn) *StringLexer {
return &StringLexer{
input: input,
inputLength: len(input),
start: 0,
pos: 0,
line: 1,
width: 0,
items: make(chan LexItem, 1),
entryPoint: fn,
}
}
|
// Current returns the current rune being considered
|
func (l *StringLexer) Current() (r rune) {
r, _ = utf8.DecodeRuneInString(l.input[l.pos:])
return r
}
|
// Next returns the next rune
|
func (l *StringLexer) Next() (r rune) {
if l.pos >= l.inputLen() {
l.width = 0
return EOF
}
// if the previous char was a new line, then we're at a new line
if l.pos >= 0 {
if l.input[l.pos] == '\n' {
l.line++
}
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
}
|
// Peek returns the next rune, but does not move the position
|
func (l *StringLexer) Peek() (r rune) {
r = l.Next()
l.Backup()
return r
}
|
// Backup moves the cursor position (as many bytes as the last read rune)
|
func (l *StringLexer) Backup() {
l.pos -= l.width
if l.width == 1 && l.pos >= 0 && l.inputLen() > l.pos {
if l.input[l.pos] == '\n' {
l.line--
}
}
}
|
// AcceptString returns true if the given string can be matched exactly.
// This is a utility function to be called from concrete Lexer types
|
func (l *StringLexer) AcceptString(word string) bool {
return AcceptString(l, word, false)
}
|
// PeekString returns true if the given string can be matched exactly,
// but does not move the position
|
func (l *StringLexer) PeekString(word string) bool {
return AcceptString(l, word, true)
}
|
// AcceptRunFunc takes a function, and moves the cursor forward as long as
// the function returns true
|
func (l *StringLexer) AcceptRunFunc(fn func(r rune) bool) bool {
guard := Mark("AcceptRun")
defer guard()
return AcceptRunFunc(l, fn)
}
|
// AcceptRunExcept takes a string, and moves the cursor forward as
// long as the input DOES NOT match one of the given runes in the string
|
func (l *StringLexer) AcceptRunExcept(valid string) bool {
guard := Mark("AcceptRunExcept")
defer guard()
return AcceptRunExcept(l, valid)
}
|
// Grab creates a new Item of type `t`. The value in the item is created
// from the position of the last read item to current cursor position
|
func (l *StringLexer) Grab(t ItemType) Item {
// special case
str := l.BufferString()
line := l.line
if len(str) > 0 && str[0] == '\n' {
line--
}
return NewItem(t, l.start, line, str)
}
|
// Emit creates and sends a new Item of type `t` through the output
// channel. The Item is generated using `Grab`
|
func (l *StringLexer) Emit(t ItemType) {
l.items <- l.Grab(t)
l.start = l.pos
}
|
// BufferString reutrns the string beween LastCursor and Cursor
|
func (l *StringLexer) BufferString() string {
return l.input[l.start:l.pos]
}
|
// convertProcedureStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-procedure-status.html
|
func (p *Procedure) convertProcedureStatus() string {
var status string
statusConcept := p.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "aborted"):
status = "aborted"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "active"):
status = "in-progress"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "obsolete"):
status = "entered-in-error"
case len(p.StatusCode) == 0 && p.EndTime == nil:
status = "in-progress"
default:
status = "completed"
}
return status
}
|
// convertProcedureRequestStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-procedure-request-status.html
|
func (p *Procedure) convertProcedureRequestStatus() string {
var status string
statusConcept := p.StatusCode.FHIRCodeableConcept("")
switch {
case p.NegationInd == true:
status = "rejected"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "cancelled"):
status = "rejected"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "held"):
status = "suspended"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "suspended"):
status = "suspended"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "nullified"):
status = "rejected"
// NOTE: this is not a real ActStatus, but HDS seems to use it
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "recommended"):
status = "proposed"
default:
status = "accepted"
}
return status
}
|
// NewItem creates a new Item
|
func NewItem(t ItemType, pos int, line int, v string) Item {
return Item{t, pos, line, v}
}
|
// String returns the string representation of the Item
|
func (l Item) String() string {
return fmt.Sprintf("%s (%q)", l.typ, l.val)
}
|
// convertStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-encounter-state.html
// If the status cannot be reliably mapped, "finished" will be assumed. Note that this code is
// built to handle even some statuses that HDS does not currently return (active, cancelled, etc.)
|
func (e *Encounter) convertStatus() string {
var status string
statusConcept := e.StatusCode.FHIRCodeableConcept("")
switch {
// Negated encounters are rare, but if we run into one, call it cancelled
case e.NegationInd:
status = "cancelled"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "active"):
status = "in-progress"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "cancelled"):
status = "cancelled"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "held"):
status = "planned"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "new"):
status = "planned"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "suspended"):
status = "onleave"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "nullified"):
status = "cancelled"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "obsolete"):
status = "cancelled"
// NOTE: this is not a real ActStatus, but HDS seems to use it
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "ordered"):
status = "planned"
case e.MoodCode == "RQO":
status = "planned"
default:
status = "finished"
}
return status
}
|
// Async Send mail message
|
func (s *SesMailer) SendAsync(to, subject, htmlbody string) {
go func() {
if err := s.SendMail(to, subject, htmlbody); err != nil {
beego.Error(fmt.Sprintf("Async send email not send emails: %s", err))
}
}()
}
|
/*
Dialect: RandomInt
*/
|
func RandomBuiltinFunc() string {
d := orm.NewOrm().Driver()
if d.Type() == orm.DR_Oracle {
return "dbms_random.value(1,100000)"
} else if d.Type() == orm.DR_MySQL {
return "RAND()"
} else {
return "RANDOM()"
}
}
|
// MustCompile parses a regular expression and panic if str can not parsed.
// This compatible with regexp.MustCompile but this uses a cache.
|
func MustCompile(str string) *regexp.Regexp {
re, err := regexpContainer.Get(str)
if err != nil {
// regexp.MustCompile() like message
panic(`regexpcache: Compile(` + quote(str) + `): ` + err.Error())
}
return re
}
|
// MustCompilePOSIX parses a regular expression with POSIX ERE syntax and panic if str can not parsed.
// This compatible with regexp.MustCompilePOSIX but this uses a cache.
|
func MustCompilePOSIX(str string) *regexp.Regexp {
re, err := posixContainer.Get(str)
if err != nil {
// regexp.MustCompilePOSIX() like message
panic(`regexpcache: CompilePOSIX(` + quote(str) + `): ` + err.Error())
}
return re
}
|
// Match checks whether a textual regular expression matches a byte slice.
// This compatible with regexp.Match but this uses a cache.
|
func Match(pattern string, b []byte) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.Match(b), nil
}
|
// Match checks whether a textual regular expression matches the RuneReader.
// This compatible with regexp.MatchReader but this uses a cache.
|
func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.MatchReader(r), nil
}
|
// simple doubling back-off
|
func createBackoff(retryIn, maxBackOff time.Duration) func() {
return func() {
log.Debugf("backoff called. will retry in %s.", retryIn)
time.Sleep(retryIn)
retryIn = retryIn * time.Duration(2)
if retryIn > maxBackOff {
retryIn = maxBackOff
}
}
}
|
// retrieveBundle retrieves bundle data from a URI
|
func getURIFileReader(uriString string) (io.ReadCloser, error) {
uri, err := url.Parse(uriString)
if err != nil {
return nil, fmt.Errorf("DownloadFileUrl: Failed to parse urlStr: %s", uriString)
}
// todo: add authentication - TBD?
// assume it's a file if no scheme - todo: remove file support?
if uri.Scheme == "" || uri.Scheme == "file" {
f, err := os.Open(uri.Path)
if err != nil {
return nil, err
}
return f, nil
}
// GET the contents at uriString
client := http.Client{
Timeout: bundleDownloadConnTimeout,
}
res, err := client.Get(uriString)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, fmt.Errorf("Bundle uri %s failed with status %d", uriString, res.StatusCode)
}
return res.Body, nil
}
|
// NewClient factory Client
|
func NewClient() *Client {
detector := newDetector()
session := session.NewClient(nil)
return &Client{
detector: detector,
session: session,
}
}
|
// Parse get gss.Result
|
func (c *Client) Parse(url string) (*Result, error) {
header := make(map[string]string)
bytes, err := c.session.Get(url, header)
if err != nil {
return nil, err
}
rssType, err := c.detector.detect(bytes)
if err != nil {
return nil, err
}
parser, err := getParser(rssType)
if err != nil {
return nil, err
}
mappableFeed, err := parser.Parse(bytes)
if err != nil {
return nil, err
}
feedBytes, err := mappableFeed.ToJSON()
if err != nil {
return nil, err
}
feed := Feed{}
err = feed.Map(feedBytes)
if err != nil {
return nil, err
}
ret := makeResult(rssType, feed, mappableFeed)
return &ret, nil
}
|
// NewHTTPClient creates a new BOSH Registry Client.
|
func NewHTTPClient(
options ClientOptions,
logger boshlog.Logger,
) HTTPClient {
return HTTPClient{
options: options,
logger: logger,
}
}
|
// Delete deletes the instance settings for a given instance ID.
|
func (c HTTPClient) Delete(instanceID string) error {
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointWithCredentials(), instanceID)
c.logger.Debug(httpClientLogTag, "Deleting agent settings from registry endpoint '%s'", endpoint)
request, err := http.NewRequest("DELETE", endpoint, nil)
if err != nil {
return bosherr.WrapErrorf(err, "Creating DELETE request for registry endpoint '%s'", endpoint)
}
httpResponse, err := c.doRequest(request)
if err != nil {
return bosherr.WrapErrorf(err, "Deleting agent settings from registry endpoint '%s'", endpoint)
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK {
return bosherr.Errorf("Received status code '%d' when deleting agent settings from registry endpoint '%s'", httpResponse.StatusCode, endpoint)
}
c.logger.Debug(httpClientLogTag, "Deleted agent settings from registry endpoint '%s'", endpoint)
return nil
}
|
// Fetch gets the agent settings for a given instance ID.
|
func (c HTTPClient) Fetch(instanceID string) (AgentSettings, error) {
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointWithCredentials(), instanceID)
c.logger.Debug(httpClientLogTag, "Fetching agent settings from registry endpoint '%s'", endpoint)
request, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return AgentSettings{}, bosherr.WrapErrorf(err, "Creating GET request for registry endpoint '%s'", endpoint)
}
httpResponse, err := c.doRequest(request)
if err != nil {
return AgentSettings{}, bosherr.WrapErrorf(err, "Fetching agent settings from registry endpoint '%s'", endpoint)
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK {
return AgentSettings{}, bosherr.Errorf("Received status code '%d' when fetching agent settings from registry endpoint '%s'", httpResponse.StatusCode, endpoint)
}
httpBody, err := ioutil.ReadAll(httpResponse.Body)
if err != nil {
return AgentSettings{}, bosherr.WrapErrorf(err, "Reading agent settings response from registry endpoint '%s'", endpoint)
}
var settingsResponse agentSettingsResponse
if err = json.Unmarshal(httpBody, &settingsResponse); err != nil {
return AgentSettings{}, bosherr.WrapErrorf(err, "Unmarshalling agent settings response from registry endpoint '%s', contents: '%s'", endpoint, httpBody)
}
var agentSettings AgentSettings
if err = json.Unmarshal([]byte(settingsResponse.Settings), &agentSettings); err != nil {
return AgentSettings{}, bosherr.WrapErrorf(err, "Unmarshalling agent settings response from registry endpoint '%s', contents: '%s'", endpoint, httpBody)
}
c.logger.Debug(httpClientLogTag, "Received agent settings from registry endpoint '%s', contents: '%s'", endpoint, httpBody)
return agentSettings, nil
}
|
// Update updates the agent settings for a given instance ID. If there are not already agent settings for the instance, it will create ones.
|
func (c HTTPClient) Update(instanceID string, agentSettings AgentSettings) error {
settingsJSON, err := json.Marshal(agentSettings)
if err != nil {
return bosherr.WrapErrorf(err, "Marshalling agent settings, contents: '%#v", agentSettings)
}
endpoint := fmt.Sprintf("%s/instances/%s/settings", c.options.EndpointWithCredentials(), instanceID)
c.logger.Debug(httpClientLogTag, "Updating registry endpoint '%s' with agent settings '%s'", endpoint, settingsJSON)
putPayload := bytes.NewReader(settingsJSON)
request, err := http.NewRequest("PUT", endpoint, putPayload)
if err != nil {
return bosherr.WrapErrorf(err, "Creating PUT request for registry endpoint '%s' with agent settings '%s'", endpoint, settingsJSON)
}
httpResponse, err := c.doRequest(request)
if err != nil {
return bosherr.WrapErrorf(err, "Updating registry endpoint '%s' with agent settings: '%s'", endpoint, settingsJSON)
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK && httpResponse.StatusCode != http.StatusCreated {
return bosherr.Errorf("Received status code '%d' when updating registry endpoint '%s' with agent settings: '%s'", httpResponse.StatusCode, endpoint, settingsJSON)
}
c.logger.Debug(httpClientLogTag, "Updated registry endpoint '%s' with agent settings '%s'", endpoint, settingsJSON)
return nil
}
|
// Reset resets an existing timer or creates a new one with given duration
|
func (timer *RealRTimer) Reset(d time.Duration) {
if timer.innerTimer == nil {
timer.innerTimer = time.NewTimer(d)
} else {
timer.innerTimer.Reset(d)
}
}
|
// CreateUser issues the nimbusec API to create the given user.
|
func (a *API) CreateUser(user *User) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user")
err := a.Post(url, Params{}, user, dst)
return dst, err
}
|
// GetUser fetches an user by its ID.
|
func (a *API) GetUser(user int) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user/%d", user)
err := a.Get(url, Params{}, dst)
return dst, err
}
|
// GetUserByLogin fetches an user by its login name.
|
func (a *API) GetUserByLogin(login string) (*User, error) {
users, err := a.FindUsers(fmt.Sprintf("login eq \"%s\"", login))
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, ErrNotFound
}
if len(users) > 1 {
return nil, fmt.Errorf("login %q matched too many users. please contact nimbusec.", login)
}
return &users[0], nil
}
|
// FindUsers searches for users that match the given filter criteria.
|
func (a *API) FindUsers(filter string) ([]User, error) {
params := Params{}
if filter != EmptyFilter {
params["q"] = filter
}
dst := make([]User, 0)
url := a.BuildURL("/v2/user")
err := a.Get(url, params, &dst)
return dst, err
}
|
// UpdateUser issues the nimbusec API to update an user.
|
func (a *API) UpdateUser(user *User) (*User, error) {
dst := new(User)
url := a.BuildURL("/v2/user/%d", user.Id)
err := a.Put(url, Params{}, user, dst)
return dst, err
}
|
// DeleteUser issues the nimbusec API to delete an user. The root user or tennant
// can not be deleted via this method.
|
func (a *API) DeleteUser(user *User) error {
url := a.BuildURL("/v2/user/%d", user.Id)
return a.Delete(url, Params{})
}
|
// GetDomainSet fetches the set of allowed domains for an restricted user.
|
func (a *API) GetDomainSet(user *User) ([]int, error) {
dst := make([]int, 0)
url := a.BuildURL("/v2/user/%d/domains", user.Id)
err := a.Get(url, Params{}, &dst)
return dst, err
}
|
// UpdateDomainSet updates the set of allowed domains of an restricted user.
|
func (a *API) UpdateDomainSet(user *User, domains []int) ([]int, error) {
dst := make([]int, 0)
url := a.BuildURL("/v2/user/%d/domains", user.Id)
err := a.Put(url, Params{}, domains, &dst)
return dst, err
}
|
// LinkDomain links the given domain id to the given user and adds the priviledges for
// the user to view the domain.
|
func (a *API) LinkDomain(user *User, domain int) error {
url := a.BuildURL("/v2/user/%d/domains", user.Id)
return a.Post(url, Params{}, domain, nil)
}
|
// UnlinkDomain unlinks the given domain id to the given user and removes the priviledges
// from the user to view the domain.
|
func (a *API) UnlinkDomain(user *User, domain int) error {
url := a.BuildURL("/v2/user/%d/domains/%d", user.Id, domain)
return a.Delete(url, Params{})
}
|
// ListuserConfigs fetches the list of all available configuration keys for the
// given domain.
|
func (a *API) ListUserConfigs(user int) ([]string, error) {
dst := make([]string, 0)
url := a.BuildURL("/v2/user/%d/config", user)
err := a.Get(url, Params{}, &dst)
return dst, err
}
|
// GetUserConfig fetches the requested user configuration.
|
func (a *API) GetUserConfig(user int, key string) (string, error) {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.getTextPlain(url, Params{})
}
|
// SetUserConfig sets the user configuration `key` to the requested value.
// This method will create the user configuration if it does not exist yet.
|
func (a *API) SetUserConfig(user int, key string, value string) (string, error) {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.putTextPlain(url, Params{}, value)
}
|
// DeleteUserConfig issues the API to delete the user configuration with
// the provided key.
|
func (a *API) DeleteUserConfig(user int, key string) error {
url := a.BuildURL("/v2/user/%d/config/%s/", user, key)
return a.Delete(url, Params{})
}
|
// GetNotification fetches a notification by its ID.
|
func (a *API) GetNotification(user int, id int) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification/%d", user, id)
err := a.Get(url, Params{}, dst)
return dst, err
}
|
// FindNotifications fetches all notifications for the given user that match the
// filter criteria.
|
func (a *API) FindNotifications(user int, filter string) ([]Notification, error) {
params := Params{}
if filter != EmptyFilter {
params["q"] = filter
}
dst := make([]Notification, 0)
url := a.BuildURL("/v2/user/%d/notification", user)
err := a.Get(url, params, &dst)
return dst, err
}
|
// CreateOrGetNotifcation issues the nimbusec API to create the given notification. Instead of
// failing when attempting to create a duplicate notification, this method will fetch the
// remote notification instead.
|
func (a *API) CreateOrGetNotification(user int, notification *Notification) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification", user)
err := a.Post(url, Params{"upsert": "false"}, notification, dst)
return dst, err
}
|
// UpdateNotification updates the notification for the given user.
|
func (a *API) UpdateNotification(user int, notification *Notification) (*Notification, error) {
dst := new(Notification)
url := a.BuildURL("/v2/user/%d/notification/%d", user, notification.Id)
err := a.Put(url, Params{}, notification, dst)
return dst, err
}
|
// DeleteNotification deletes the given notification.
|
func (a *API) DeleteNotification(user int, notification *Notification) error {
url := a.BuildURL("/v2/user/%d/notification/%d", user, notification.Id)
return a.Delete(url, Params{})
}
|
// handle client API
|
func (a *ApiManager) HandleRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var returnValue interface{}
verifyApiKeyReq, err := validateRequest(r.Body, w)
if err != nil {
errorResponse, jsonErr := json.Marshal(errorResponse("Bad_REQUEST", err.Error(), http.StatusBadRequest))
if jsonErr != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(jsonErr.Error()))
}
w.WriteHeader(http.StatusBadRequest)
w.Write(errorResponse)
return
}
verifyApiKeyResponse, errorResponse := a.verifyAPIKey(verifyApiKeyReq)
if errorResponse != nil {
setResponseHeader(errorResponse, w)
returnValue = errorResponse
} else {
returnValue = verifyApiKeyResponse
}
b, _ := json.Marshal(returnValue)
log.Debugf("handleVerifyAPIKey result %s", b)
w.Write(b)
}
|
// returns []byte to be written to client
|
func (apiM ApiManager) verifyAPIKey(verifyApiKeyReq VerifyApiKeyRequest) (*VerifyApiKeySuccessResponse, *common.ErrorResponse) {
dataWrapper := VerifyApiKeyRequestResponseDataWrapper{
verifyApiKeyRequest: verifyApiKeyReq,
}
dataWrapper.verifyApiKeySuccessResponse.ClientId.ClientId = verifyApiKeyReq.Key
dataWrapper.verifyApiKeySuccessResponse.Environment = verifyApiKeyReq.EnvironmentName
err := apiM.DbMan.getApiKeyDetails(&dataWrapper)
switch {
case err != nil && err.Error() == "InvalidApiKey":
reason := "API Key verify failed for (" + verifyApiKeyReq.Key + ", " + verifyApiKeyReq.OrganizationName + ")"
errorCode := "oauth.v2.InvalidApiKey"
errResponse := errorResponse(reason, errorCode, http.StatusOK)
return nil, &errResponse
case err != nil:
reason := err.Error()
errorCode := "SEARCH_INTERNAL_ERROR"
errResponse := errorResponse(reason, errorCode, http.StatusInternalServerError)
return nil, &errResponse
}
dataWrapper.verifyApiKeySuccessResponse.ApiProduct = shortListApiProduct(dataWrapper.apiProducts, verifyApiKeyReq)
/*
* Perform all validations
*/
errResponse := apiM.performValidations(dataWrapper)
if errResponse != nil {
return nil, errResponse
}
apiM.enrichAttributes(&dataWrapper)
setDevOrCompanyInResponseBasedOnCtype(dataWrapper.ctype, dataWrapper.tempDeveloperDetails, &dataWrapper.verifyApiKeySuccessResponse)
return &dataWrapper.verifyApiKeySuccessResponse, nil
}
|
// Request issues an HTTP request, marshaling parameters, and unmarshaling results, as configured in the provided Options parameter.
// The Response structure returned, if any, will include accumulated results recovered from the HTTP server.
// See the Response structure for more details.
|
func Request(method string, url string, opts Options) (*Response, error) {
var body io.Reader
var response Response
client := opts.CustomClient
if client == nil {
client = new(http.Client)
}
contentType := opts.ContentType
body = nil
if opts.ReqBody != nil {
// if the content-type header is empty, but the user expicitly asked for it
// to be unset, then don't set contentType to application/json.
if contentType == "" && !opts.OmitContentType {
contentType = "application/json"
}
if contentType == "application/json" {
bodyText, err := json.Marshal(opts.ReqBody)
if err != nil {
return nil, err
}
body = strings.NewReader(string(bodyText))
if opts.DumpReqJson {
log.Printf("Making request:\n%#v\n", string(bodyText))
}
} else {
// assume opts.ReqBody implements the correct interface
body = opts.ReqBody.(io.Reader)
}
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Add("Content-Type", contentType)
}
if opts.ContentLength > 0 {
req.ContentLength = opts.ContentLength
req.Header.Add("Content-Length", string(opts.ContentLength))
}
if opts.MoreHeaders != nil {
for k, v := range opts.MoreHeaders {
req.Header.Add(k, v)
}
}
// if the accept header is empty, but the user expicitly asked for it
// to be unset, then don't set accept to application/json.
if accept := req.Header.Get("Accept"); accept == "" && !opts.OmitAccept {
accept = opts.Accept
if accept == "" {
accept = "application/json"
}
req.Header.Add("Accept", accept)
}
if opts.SetHeaders != nil {
err = opts.SetHeaders(req)
if err != nil {
return &response, err
}
}
httpResponse, err := client.Do(req)
if httpResponse != nil {
response.HttpResponse = *httpResponse
response.StatusCode = httpResponse.StatusCode
}
if err != nil {
return &response, err
}
// This if-statement is legacy code, preserved for backward compatibility.
if opts.StatusCode != nil {
*opts.StatusCode = httpResponse.StatusCode
}
acceptableResponseCodes := opts.OkCodes
if len(acceptableResponseCodes) != 0 {
if not_in(httpResponse.StatusCode, acceptableResponseCodes) {
b, _ := ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
return &response, &UnexpectedResponseCodeError{
Url: url,
Expected: acceptableResponseCodes,
Actual: httpResponse.StatusCode,
Body: b,
}
}
}
if opts.Results != nil {
defer httpResponse.Body.Close()
jsonResult, err := ioutil.ReadAll(httpResponse.Body)
response.JsonResult = jsonResult
if err != nil {
return &response, err
}
err = json.Unmarshal(jsonResult, opts.Results)
// This if-statement is legacy code, preserved for backward compatibility.
if opts.ResponseJson != nil {
*opts.ResponseJson = jsonResult
}
}
return &response, err
}
|
// not_in returns false if, and only if, the provided needle is _not_
// in the given set of integers.
|
func not_in(needle int, haystack []int) bool {
for _, straw := range haystack {
if needle == straw {
return false
}
}
return true
}
|
// Post makes a POST request against a server using the provided HTTP client.
// The url must be a fully-formed URL string.
// DEPRECATED. Use Request() instead.
|
func Post(url string, opts Options) error {
r, err := Request("POST", url, opts)
if opts.Response != nil {
*opts.Response = r
}
return err
}
|
// Fetch gets access token from UAA server. This auth token
// is s used for accessing traffic-controller. It retuns error if any.
|
func (tf *defaultTokenFetcher) Fetch() (string, error) {
tf.logger.Printf("[INFO] Getting auth token of %q from UAA (%s)", tf.username, tf.uaaAddr)
client, err := uaago.NewClient(tf.uaaAddr)
if err != nil {
return "", err
}
resCh, errCh := make(chan string), make(chan error)
go func() {
token, err := client.GetAuthToken(tf.username, tf.password, tf.insecure)
if err != nil {
errCh <- err
}
resCh <- token
}()
timeout := defaultUAATimeout
if tf.timeout != 0 {
timeout = tf.timeout
}
select {
case err := <-errCh:
return "", err
case <-time.After(timeout):
return "", fmt.Errorf("request timeout: %s", timeout)
case token := <-resCh:
return token, nil
}
}
|
// Parse RSS1.0 feed parse
|
func (p *Parser) Parse(data []byte) (interfaces.Mappable, error) {
r := bytes.NewReader(data)
decoder := xmlp.NewDecoder(r)
err := decoder.RootElement()
if err != nil {
return nil, err
}
var feed Feed
err = p.decode(decoder, &feed)
if err != nil {
return nil, err
}
return feed, nil
}
|
// Initialize a new EOSClient instance
|
func (e *EOSClient) Initialize() error {
eosError := C.EdsInitializeSDK()
if eosError != C.EDS_ERR_OK {
return errors.New("Error when initializing Canon SDK")
}
return nil
}
|
// Release the EOSClient, must be called on termination
|
func (p *EOSClient) Release() error {
eosError := C.EdsTerminateSDK()
if eosError != C.EDS_ERR_OK {
return errors.New("Error when terminating Canon SDK")
}
return nil
}
|
// Get an array representing the cameras currently connected. Each CameraModel
// instance must be released by invoking the Release function once no longer
// needed.
|
func (e *EOSClient) GetCameraModels() ([]CameraModel, error) {
var eosCameraList *C.EdsCameraListRef
var eosError C.EdsError
var cameraCount int
// get a reference to the cameras list record
if eosError = C.EdsGetCameraList((*C.EdsCameraListRef)(unsafe.Pointer(&eosCameraList))); eosError != C.EDS_ERR_OK {
return nil, errors.New(fmt.Sprintf("Error when obtaining reference to list of cameras (code=%d)", eosError))
}
defer C.EdsRelease((*C.struct___EdsObject)(unsafe.Pointer(&eosCameraList)))
// get the number of cameras connected
if eosError = C.EdsGetChildCount((*C.struct___EdsObject)(unsafe.Pointer(eosCameraList)), (*C.EdsUInt32)(unsafe.Pointer(&cameraCount))); eosError != C.EDS_ERR_OK {
return nil, errors.New(fmt.Sprintf("Error when obtaining count of connected cameras (code=%d)", eosError))
}
// get details for each camera detected
cameras := make([]CameraModel, 0)
for i := 0; i < cameraCount; i++ {
var eosCameraRef *C.EdsCameraRef
if eosError = C.EdsGetChildAtIndex((*C.struct___EdsObject)(unsafe.Pointer(eosCameraList)), (C.EdsInt32)(i), (*C.EdsBaseRef)(unsafe.Pointer(&eosCameraRef))); eosError != C.EDS_ERR_OK {
return nil, errors.New(fmt.Sprintf("Error when obtaining reference to camera (code=%d)", eosError))
}
var eosCameraDeviceInfo C.EdsDeviceInfo
if eosError = C.EdsGetDeviceInfo((*C.struct___EdsObject)(unsafe.Pointer(eosCameraRef)), (*C.EdsDeviceInfo)(unsafe.Pointer(&eosCameraDeviceInfo))); eosError != C.EDS_ERR_OK {
return nil, errors.New(fmt.Sprintf("Error when obtaining camera device info (code=%d)", eosError))
}
// instantiate new CameraModel with the camera reference and model details
camera := CameraModel{
camera: eosCameraRef,
szPortName: C.GoString((*_Ctype_char)(&eosCameraDeviceInfo.szPortName[0])),
szDeviceDescription: C.GoString((*_Ctype_char)(&eosCameraDeviceInfo.szDeviceDescription[0])),
deviceSubType: (uint32)(eosCameraDeviceInfo.deviceSubType),
reserved: (uint32)(eosCameraDeviceInfo.reserved),
}
cameras = append(cameras, camera)
}
return cameras, nil
}
|
// IsModule current Element is RSS module?
|
func (md *Decoder) IsModule(d *xmlp.Decoder) bool {
space := d.Space
if space == dublinCoreSpace || space == mediaSpace || space == contentSpace {
return true
}
return false
}
|
// DecodeElement RSS module decode
|
func (md *Decoder) DecodeElement(d *xmlp.Decoder, m *Modules) error {
space := d.Space
switch space {
case dublinCoreSpace:
if err := md.decodeDublinCore(d, &m.DublinCore); err != nil {
return err
}
case mediaSpace:
if err := md.decodeMedia(d, &m.Media); err != nil {
return err
}
case contentSpace:
if err := md.decodeContent(d, &m.Content); err != nil {
return err
}
default:
if err := d.Skip(); err != nil {
return err
}
}
return nil
}
|
// MarshalJSON assemble gss.Feed struct
|
func (f Feed) MarshalJSON() ([]byte, error) {
var date string
if f.Channel.Modules.DublinCore.Date != "" {
date = f.Channel.Modules.DublinCore.Date
}
var updated string
if f.Channel.Modules.DublinCore.Modified != "" {
updated = f.Channel.Modules.DublinCore.Modified
}
gf := &struct {
Title string `json:"title"`
Link string `json:"link"`
Description string `json:"description"`
Image Image `json:"image"`
PubDate string `json:"pubdate"`
Updated string `json:"updated"`
Items []Item `json:"items"`
}{
Title: f.Channel.Title,
Link: f.Channel.Link,
Description: f.Channel.Description,
Image: f.Image,
PubDate: date,
Updated: updated,
Items: f.Items,
}
return json.Marshal(gf)
}
|
// MarshalJSON assemble gss.Image struct
|
func (i Image) MarshalJSON() ([]byte, error) {
gi := &struct {
Title string `json:"title"`
URL string `json:"url"`
Link string `json:"link"`
}{
Title: i.Title,
URL: i.URL,
Link: i.Link,
}
return json.Marshal(gi)
}
|
// MarshalJSON assemble gss.Item struct
|
func (i Item) MarshalJSON() ([]byte, error) {
var creator string
if i.Modules.DublinCore.Creator != "" {
creator = i.Modules.DublinCore.Creator
}
type author struct {
Name string `json:"name"`
Email string `json:"email"`
}
a := author{
Name: creator,
}
var authors []author
if a.Name != "" {
authors = append(authors, a)
}
var date string
if i.Modules.DublinCore.Date != "" {
date = i.Modules.DublinCore.Date
}
var updated string
if i.Modules.DublinCore.Modified != "" {
updated = i.Modules.DublinCore.Modified
}
gi := &struct {
Title string `json:"title"`
Link string `json:"link"`
Description string `json:"description"`
PubDate string `json:"pubdate"`
Updated string `json:"updated"`
Authors []author `json:"authors"`
}{
Title: i.Title,
Link: i.Link,
Description: i.Description,
PubDate: date,
Updated: updated,
Authors: authors,
}
return json.Marshal(gi)
}
|
// NewAPI creates a new nimbusec API client.
|
func NewAPI(rawurl, key, secret string) (*API, error) {
client := oauth.NewConsumer(key, secret, oauth.ServiceProvider{})
token := &oauth.AccessToken{}
parsed, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
return &API{
url: parsed,
client: client,
token: token,
}, nil
}
|
// BuildURL builds the fully qualified url to the nimbusec API.
|
func (a *API) BuildURL(relpath string, args ...interface{}) string {
if url, err := a.url.Parse(fmt.Sprintf(relpath, args...)); err == nil {
return url.String()
}
return ""
}
|
// try is used to encapsulate a HTTP operation and retrieve the optional
// nimbusec error if one happened.
|
func try(resp *http.Response, err error) (*http.Response, error) {
if resp == nil {
return resp, err
}
if resp.StatusCode < 300 {
return resp, err
}
msg := resp.Header.Get("x-nimbusec-error")
if msg != "" {
return resp, errors.New(msg)
}
return resp, err
}
|
// Get is a helper for all GET request with json payload.
|
func (a *API) Get(url string, params Params, dst interface{}) error {
resp, err := try(a.client.Get(url, params, a.token))
if err != nil {
return err
}
defer resp.Body.Close()
// no destination, so caller was only interested in the
// side effects.
if dst == nil {
return nil
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&dst)
if err != nil {
return err
}
return nil
}
|
// Delete is a helper for all DELETE request with json payload.
|
func (a *API) Delete(url string, params Params) error {
resp, err := a.client.Delete(url, params, a.token)
resp.Body.Close()
return err
}
|
// getTextPlain is a helper for all GET request with plain text payload.
|
func (a *API) getTextPlain(url string, params Params) (string, error) {
data, err := a.getBytes(url, params)
if err != nil {
return "", err
}
return string(data), nil
}
|
// putTextPlain is a helper for all PUT request with plain text payload.
|
func (a *API) putTextPlain(url string, params Params, payload string) (string, error) {
resp, err := try(a.client.Put(url, "text/plain", string(payload), params, a.token))
if err != nil {
return "", err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(data), nil
}
|
// getBytes is a helper for all GET request with raw byte payload.
|
func (a *API) getBytes(url string, params Params) ([]byte, error) {
resp, err := try(a.client.Get(url, params, a.token))
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}
|
// RandomBirthDate generates a random birth date between 65 and 85 years ago
|
func RandomBirthDate() time.Time {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomYears := r.Intn(20)
yearsAgo := randomYears + 65
randomMonth := r.Intn(11)
randomDay := r.Intn(28)
t := time.Now()
return t.AddDate(-yearsAgo, -randomMonth, -randomDay).Truncate(time.Hour * 24)
}
|
// NewContext generates a new context with randomly populated content
|
func NewContext() Context {
ctx := Context{}
smokingChoices := []randutil.Choice{
{2, "Smoker"},
{3, "Non-smoker"},
{1, "Ex-smoker"}}
sc, _ := randutil.WeightedChoice(smokingChoices)
ctx.Smoker = sc.Item.(string)
alcoholChoices := []randutil.Choice{
{2, "Occasional"},
{1, "Heavy"},
{1, "None"}}
ac, _ := randutil.WeightedChoice(alcoholChoices)
ctx.Alcohol = ac.Item.(string)
cholesterolChoices := []randutil.Choice{
{3, "Optimal"},
{1, "Near Optimal"},
{2, "Borderline"},
{1, "High"},
{2, "Very High"}}
cc, _ := randutil.WeightedChoice(cholesterolChoices)
ctx.Cholesterol = cc.Item.(string)
hc, _ := randutil.ChoiceString([]string{"Normal", "Pre-hypertension", "Hypertension"})
ctx.Hypertention = hc
dc, _ := randutil.ChoiceString([]string{"Normal", "Pre-diabetes", "Diabetes"})
ctx.Diabetes = dc
return ctx
}
|
// Truename returns the shortest absolute pathname
// leading to the specified existing file.
// Note that a single file may have multiple
// hard links or be accessible via multiple bind mounts.
// Truename doesn't account for these situations.
|
func Truename(filePath string) (string, error) {
p, err := filepath.EvalSymlinks(filePath)
if err != nil {
return filePath, err
}
p, err = filepath.Abs(p)
if err != nil {
return filePath, err
}
return filepath.Clean(p), nil
}
|
// IsSubpath returns true if maybeSubpath is a subpath of basepath. It
// uses filepath to be compatible with os-dependent paths.
|
func IsSubpath(basepath, maybeSubpath string) bool {
rel, err := filepath.Rel(basepath, maybeSubpath)
if err != nil {
return false
}
if strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
// not a subpath if "../" has to be used for the relative path
return false
}
return true
}
|
// createAttrPrefix finds the name space prefix attribute to use for the given name space,
// defining a new prefix if necessary. It returns the prefix.
|
func (p *printer) createAttrPrefix(url string) string {
if prefix := p.attrPrefix[url]; prefix != "" {
return prefix
}
// The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml"
// and must be referred to that way.
// (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns",
// but users should not be trying to use that one directly - that's our job.)
if url == xmlURL {
return xmlPrefix
}
// Need to define a new name space.
if p.attrPrefix == nil {
p.attrPrefix = make(map[string]string)
p.attrNS = make(map[string]string)
}
// Pick a name. We try to use the final element of the path
// but fall back to _.
prefix := strings.TrimRight(url, "/")
if i := strings.LastIndex(prefix, "/"); i >= 0 {
prefix = prefix[i+1:]
}
if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") {
prefix = "_"
}
if strings.HasPrefix(prefix, "xml") {
// xmlanything is reserved.
prefix = "_" + prefix
}
if p.attrNS[prefix] != "" {
// Name is taken. Find a better one.
for p.seq++; ; p.seq++ {
if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" {
prefix = id
break
}
}
}
p.attrPrefix[url] = prefix
p.attrNS[prefix] = url
p.WriteString(`xmlns:`)
p.WriteString(prefix)
p.WriteString(`="`)
EscapeText(p, []byte(url))
p.WriteString(`" `)
p.prefixes = append(p.prefixes, prefix)
return prefix
}
|
// marshalValue writes one or more XML elements representing val.
// If val was obtained from a struct field, finfo must have its details.
|
func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error {
if startTemplate != nil && startTemplate.Name.Local == "" {
return fmt.Errorf("xml: EncodeElement of StartElement with missing name")
}
if !val.IsValid() {
return nil
}
if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) {
return nil
}
// Drill into interfaces and pointers.
// This can turn into an infinite loop given a cyclic chain,
// but it matches the Go 1 behavior.
for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil
}
val = val.Elem()
}
kind := val.Kind()
typ := val.Type()
// Check for marshaler.
if val.CanInterface() && typ.Implements(marshalerType) {
return p.marshalInterface(val.Interface().(Marshaler), defaultStart(typ, finfo, startTemplate))
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(marshalerType) {
return p.marshalInterface(pv.Interface().(Marshaler), defaultStart(pv.Type(), finfo, startTemplate))
}
}
// Check for text marshaler.
if val.CanInterface() && typ.Implements(textMarshalerType) {
return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), defaultStart(typ, finfo, startTemplate))
}
if val.CanAddr() {
pv := val.Addr()
if pv.CanInterface() && pv.Type().Implements(textMarshalerType) {
return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), defaultStart(pv.Type(), finfo, startTemplate))
}
}
// Slices and arrays iterate over the elements. They do not have an enclosing tag.
if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 {
for i, n := 0, val.Len(); i < n; i++ {
if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil {
return err
}
}
return nil
}
tinfo, err := getTypeInfo(typ)
if err != nil {
return err
}
// Create start element.
// Precedence for the XML element name is:
// 0. startTemplate
// 1. XMLName field in underlying struct;
// 2. field name/tag in the struct field; and
// 3. type name
var start StartElement
if startTemplate != nil {
start.Name = startTemplate.Name
start.Attr = append(start.Attr, startTemplate.Attr...)
} else if tinfo.xmlname != nil {
xmlname := tinfo.xmlname
if xmlname.name != "" {
start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name
} else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" {
start.Name = v
}
}
if start.Name.Local == "" && finfo != nil {
start.Name.Space, start.Name.Local = finfo.xmlns, finfo.name
}
if start.Name.Local == "" {
name := typ.Name()
if name == "" {
return &UnsupportedTypeError{typ}
}
start.Name.Local = name
}
// Attributes
for i := range tinfo.fields {
finfo := &tinfo.fields[i]
if finfo.flags&fAttr == 0 {
continue
}
fv := finfo.value(val)
if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) {
continue
}
if fv.Kind() == reflect.Interface && fv.IsNil() {
continue
}
name := Name{Space: finfo.xmlns, Local: finfo.name}
if err := p.marshalAttr(&start, name, fv); err != nil {
return err
}
}
if err := p.writeStart(&start); err != nil {
return err
}
if val.Kind() == reflect.Struct {
err = p.marshalStruct(tinfo, val)
} else {
s, b, err1 := p.marshalSimple(typ, val)
if err1 != nil {
err = err1
} else if b != nil {
EscapeText(p, b)
} else {
p.EscapeString(s)
}
}
if err != nil {
return err
}
if err := p.writeEnd(start.Name); err != nil {
return err
}
return p.cachedWriteError()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.