// Parse jenkins ajax response in order find the current jenkins build history
3483
func parseBuildHistory(d io.Reader) []*History {
	z := html.NewTokenizer(d)
	depth := 0
	buildRowCellDepth := -1
	builds := make([]*History, 0)
	isInsideDisplayName := false
	var curBuild *History
	for {
		tt := z.Next()
		switch tt {
		case html.ErrorToken:
			if z.Err() == io.EOF {
				return builds
			}
		case html.SelfClosingTagToken:
			tn, hasAttr := z.TagName()
			// fmt.Println("START__", string(tn), hasAttr)
			if hasAttr {
				a := attr(z)
				// <img src="/static/f2881562/images/16x16/red.png" alt="Failed &gt; Console Output" tooltip="Failed &gt; Console Output" style="width: 16px; height: 16px; " class="icon-red icon-sm" />
				if string(tn) == "img" {
					if hasCSSClass(a, "icon-sm") && buildRowCellDepth > -1 {
						if alt, found := a["alt"]; found {
							curBuild.BuildStatus = strings.Fields(alt)[0]
						}
					}
				}
			}
		case html.StartTagToken:
			depth++
			tn, hasAttr := z.TagName()
			// fmt.Println("START__", string(tn), hasAttr)
			if hasAttr {
				a := attr(z)
				// <td class="build-row-cell">
				if string(tn) == "td" {
					if hasCSSClass(a, "build-row-cell") {
						buildRowCellDepth = depth
						curBuild = &History{}
						builds = append(builds, curBuild)
					}
				}
				// <a update-parent-class=".build-row" href="/job/appscode/job/43/job/build-binary/227/" class="tip model-link inside build-link display-name">#227</a>
				if string(tn) == "a" {
					if hasCSSClass(a, "display-name") && buildRowCellDepth > -1 {
						if href, found := a["href"]; found {
							parts := strings.Split(href, "/")
							if num, err := strconv.Atoi(parts[len(parts)-2]); err == nil {
								curBuild.BuildNumber = num
								isInsideDisplayName = true
							}
						}
					}
				}
				// <div time="1469024602546" class="pane build-details"> ... </div>
				if string(tn) == "div" {
					if hasCSSClass(a, "build-details") && buildRowCellDepth > -1 {
						if t, found := a["time"]; found {
							if msec, err := strconv.ParseInt(t, 10, 0); err == nil {
								curBuild.BuildTimestamp = msec / 1000
							}
						}
					}
				}
			}
		case html.TextToken:
			if isInsideDisplayName {
				curBuild.BuildDisplayName = z.Token().Data
				isInsideDisplayName = false
			}
		case html.EndTagToken:
			tn, _ := z.TagName()
			if string(tn) == "td" && depth == buildRowCellDepth {
				buildRowCellDepth = -1
				curBuild = nil
			}
			depth--
		}
	}
}
53930
func ParseReleaseVersion(bytes []byte) (int, error) {
	var hook BuildHookResponse
	if err := json.Unmarshal(bytes, &hook); err != nil {
		return 0, fmt.Errorf("invalid application json configuration")
	}

	if hook.Release == nil {
		return 0, fmt.Errorf("invalid application version")
	}

	return hook.Release["version"], nil
}
786496
func PostJSON(ctx context.Context, url string, req interface{}) (*tracetest.TraceResponse, error) {
	data, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}

	httpReq, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	httpReq.Header.Set("Content-Type", "application/json")

	span, err := injectSpan(ctx, httpReq)
	if span != nil {
		defer span.Finish()
	}
	if err != nil {
		return nil, err
	}

	resp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return nil, err
	}

	var result tracetest.TraceResponse
	err = utils.ReadJSON(resp, &result)
	return &result, err
}
464719
func (c *ApiController) GetBuildLogsAll() {
	log.Info("Get all build logs")

	//buildId := c.GetString(":buildId")
	//field := 0
	//result := redisutil.HgetString(buildId, field)
	//c.Ctx.WriteString(result)

	// TODO(tobe): change to hgetall  from redis
	mystruct := `{0: "apt-get install", 1: "go test"}`

	c.Data["json"] = &mystruct
	c.ServeJson()
}
696693
func (f *FailureResponseBuilder) Build() *FailureResponse {
	return &FailureResponse{
		error:         f.error,
		statusCode:    f.statusCode,
		loggerAction:  f.loggerAction,
		emptyResponse: f.emptyResponse,
		errorKey:      f.errorKey,
	}
}
11187
func (js *JSONConfig) Parse(filename string) (Configer, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	content, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	return js.ParseData(content)
}
555716
func getBuilderHistories(c context.Context, builders []string, project string, limit int) ([]*builderHistory, error) {
	// Populate the recent histories.
	hists := make([]*builderHistory, len(builders))
	err := parallel.WorkPool(16, func(ch chan<- func() error) {
		for i, builder := range builders {
			i := i
			builder := builder
			ch <- func() error {
				hist, err := getHistory(c, buildsource.BuilderID(builder), project, limit)
				if err != nil {
					return errors.Annotate(
						err, "error populating history for builder %s", builder).Err()
				}
				hists[i] = hist
				return nil
			}
		}
	})
	if err != nil {
		return nil, err
	}

	// for all buildbot builders, we don't have pending BuildSummary entities,
	// so load pending counts from buildstore.
	var buildbotBuilders []string // "<master>/<builder>" strings
	var buildbotHists []*builderHistory
	for _, h := range hists {
		backend, master, builder, err := h.BuilderID.Split()
		if backend == "buildbot" && err == nil {
			buildbotHists = append(buildbotHists, h)
			buildbotBuilders = append(buildbotBuilders, fmt.Sprintf("%s/%s", master, builder))
		}
	}
	if len(buildbotBuilders) > 0 {
		pendingCounts, err := buildstore.GetPendingCounts(c, buildbotBuilders)
		if err != nil {
			return nil, err
		}
		for i, count := range pendingCounts {
			buildbotHists[i].NumPending = count
		}
	}

	return hists, nil
}
1342324
func (s *Service) GetBuildbotBuildJSON(c context.Context, req *milo.BuildbotBuildRequest) (
	*milo.BuildbotBuildJSON, error) {

	apiUsage.Add(c, 1, "GetBuildbotBuildJSON", req.Master, req.Builder, req.ExcludeDeprecated, false)

	if req.Master == "" {
		return nil, status.Errorf(codes.InvalidArgument, "No master specified")
	}
	if req.Builder == "" {
		return nil, status.Errorf(codes.InvalidArgument, "No builder specified")
	}
	cu := auth.CurrentUser(c)
	logging.Debugf(c, "%s is requesting %s/%s/%d",
		cu.Identity, req.Master, req.Builder, req.BuildNum)

	if err := buildstore.CanAccessMaster(c, req.Master); err != nil {
		return nil, err
	}

	b, err := buildstore.GetBuild(c, buildbot.BuildID{
		Master:  req.Master,
		Builder: req.Builder,
		Number:  int(req.BuildNum),
	})
	switch code := grpcutil.Code(err); {
	case code == codes.PermissionDenied, code == codes.NotFound:
		return nil, errNotFoundGRPC
	case err != nil:
		return nil, err
	case b == nil:
		return nil, errNotFoundGRPC
	}

	if req.ExcludeDeprecated {
		excludeDeprecatedFromBuild(b)
	}

	bs, err := json.Marshal(b)
	if err != nil {
		return nil, err
	}

	// Marshal the build back into JSON format.
	return &milo.BuildbotBuildJSON{Data: bs}, nil
}
164829
func (c *Client) responseJSONMap(requestName string, resp *http.Response) (map[string]interface{}, error) {
	if resp.StatusCode != 200 {
		c.printf("After %s request, failed to JSON from response; status code is %d", requestName, resp.StatusCode)
		io.Copy(os.Stderr, resp.Body)
		return nil, fmt.Errorf("after %s request, HTTP response code is %d; no JSON to parse", requestName, resp.StatusCode)
	}
	jmap := make(map[string]interface{})
	if err := httputil.DecodeJSON(resp, &jmap); err != nil {
		return nil, err
	}
	return jmap, nil
}
1027950
func (wc *WebhookContext) Response(code int, s string) {
	wc.gin.String(code, s)
}
236134
func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
	allowIdPInitiated := ""
	possibleRequestIDs := []string{allowIdPInitiated}

	// Find the request id that relates to this RelayState.
	relayState := r.PostFormValue("RelayState")
	if sp.cookieSecret() != nil && relayState != "" {
		cookieName := fmt.Sprintf("saml_%s", relayState)
		cookie, err := r.Cookie(cookieName)
		if err != nil {
			return nil, fmt.Errorf("cannot find %s cookie", cookieName)
		}

		// Verify the integrity of the cookie.
		state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
			return sp.cookieSecret(), nil
		})
		if err != nil || !state.Valid {
			return nil, fmt.Errorf("could not decode state JWT: %v", err)
		}

		claims := state.Claims.(jwt.MapClaims)
		id := claims["id"].(string)

		possibleRequestIDs = append(possibleRequestIDs, id)

		// delete the cookie
		cookie.Value = ""
		cookie.Expires = time.Time{}
		http.SetCookie(w, cookie)
	}

	samlResponse := r.PostFormValue("SAMLResponse")
	return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
}
1113566
func ParseJSON(r io.Reader, options ...ParserOptions) (Slice, error) {
	builder := &Builder{}
	p := NewParser(r, builder, options...)
	if err := p.Parse(); err != nil {
		return nil, WithStack(err)
	}
	slice, err := builder.Slice()
	if err != nil {
		return nil, WithStack(err)
	}
	return slice, nil
}
811070
func Convert_build_BuildStatusOutput_To_v1_BuildStatusOutput(in *build.BuildStatusOutput, out *v1.BuildStatusOutput, s conversion.Scope) error {
	return autoConvert_build_BuildStatusOutput_To_v1_BuildStatusOutput(in, out, s)
}
838653
func (jsonConf *JSONConf) Parse(conf io.Reader) ([]*Job, error) {
	buf, err := ioutil.ReadAll(conf)
	if err != nil {
		log.Fatal(err)
	}

	var c []*Job
	err = json.Unmarshal(buf, &c)
	if err != nil {
		return nil, err
	}

	return c, nil
}
388922
func (a Artifact) GetData() ([]byte, error) {
	var data string
	response, err := a.Jenkins.Requester.Get(a.Path, &data, nil)

	if err != nil {
		return nil, err
	}

	code := response.StatusCode
	if code != 200 {
		Error.Printf("Jenkins responded with StatusCode: %d", code)
		return nil, errors.New("Could not get File Contents")
	}
	return []byte(data), nil
}
1172512
func (c *ApiController) GetBuildLogsIndex() {
	log.Info("Get build log with index")

	buildId := c.GetString(":buildId")
	index, _ := c.GetInt(":index")

	log := redisutil.HgetString(buildId, index)

	next := false

	finish := redisutil.HgetBool(buildId, "finish")
	if finish == false {
		next = true
		fmt.Println("finish == false")
	}

	current := redisutil.HgetInt(buildId, "current")
	if index < current {
		next = true
		fmt.Println("index != current")
	}

	// TODO(tobe): throw error if index is larger than current
	// TODO(tobe): handle when get the index is more than current but it's not total

	response := &GetBuildLogsIndexResponse{
		Log:  log,
		Next: next}

	c.Data["json"] = response
	c.ServeJson()

}
467753
func getHistory(c context.Context, builderID buildsource.BuilderID, project string, limit int) (*builderHistory, error) {
	hist := builderHistory{
		BuilderID:    builderID,
		BuilderLink:  builderID.SelfLink(project),
		RecentBuilds: make([]*model.BuildSummary, 0, limit),
	}

	// Do fetches.
	return &hist, parallel.FanOutIn(func(fetch chan<- func() error) {
		// Get BuilderSummary for builderID, because the passed project may differ
		// from the BuilderSummary's actual project (e.g. a chrome builder that also
		// appears in the chromium console will pass "chromium" as the project and
		// fail to link it). If no BuilderSummary is found, fall back on passed
		// project.
		fetch <- func() error {
			matchingBuilder := model.BuilderSummary{BuilderID: string(builderID)}
			switch err := datastore.Get(c, &matchingBuilder); err {
			case nil:
				hist.BuilderLink = matchingBuilder.SelfLink()
			case datastore.ErrNoSuchEntity:
				// fall back
			default:
				return err
			}
			return nil
		}

		if !builderID.Buildbot() {
			// Pending builds
			fetch <- func() error {
				q := datastore.NewQuery("BuildSummary").
					Eq("BuilderID", builderID).
					Eq("Summary.Status", model.NotRun)
				pending, err := datastore.Count(c, q)
				hist.NumPending = int(pending)
				return err
			}
		}

		// Running builds
		fetch <- func() error {
			q := datastore.NewQuery("BuildSummary").
				Eq("BuilderID", builderID).
				Eq("Summary.Status", model.Running)
			running, err := datastore.Count(c, q)
			hist.NumRunning = int(running)
			return err
		}

		// Last {limit} builds
		fetch <- func() error {
			q := datastore.NewQuery("BuildSummary").
				Eq("BuilderID", builderID).
				Order("-Created")
			return datastore.Run(c, q, func(b *model.BuildSummary) error {
				if !b.Summary.Status.Terminal() {
					return nil
				}

				hist.RecentBuilds = append(hist.RecentBuilds, b)
				if len(hist.RecentBuilds) >= limit {
					return datastore.Stop
				}
				return nil
			})
		}
	})
}