// ListByWorkItem returns the work item links that have wiID as source or target.
// TODO: Handle pagination
776962
func (r *GormWorkItemLinkRepository) ListByWorkItem(ctx context.Context, wiID uuid.UUID) ([]WorkItemLink, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemlink", "listByWorkItem"}, time.Now())
	var modelLinks []WorkItemLink
	wi, err := r.workItemRepo.LoadFromDB(ctx, wiID)
	if err != nil {
		return nil, errs.WithStack(err)
	}
	// Now fetch all links for that work item
	db := r.db.Model(modelLinks).Where("? IN (source_id, target_id)", wi.ID).Find(&modelLinks)
	if db.Error != nil {
		return nil, db.Error
	}
	return modelLinks, nil
}
1192638
func (d *DataBagService) ListItems(name string) (data *DataBagListResult, err error) {
	path := fmt.Sprintf("data/%s", name)
	err = d.client.magicRequestDecoder("GET", path, nil, &data)
	return
}
1326802
func (r *GormWorkItemRepository) LoadBatchByID(ctx context.Context, ids []uuid.UUID) ([]*WorkItem, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitem", "loadBatchById"}, time.Now())
	res, err := r.LoadBatchFromDB(ctx, ids)
	if err != nil {
		return nil, errs.WithStack(err)
	}
	workitems := []*WorkItem{}
	for _, ele := range res {
		wiType, err := r.witr.Load(ctx, ele.Type)
		if err != nil {
			log.Error(nil, map[string]interface{}{
				"wit_id": ele.Type,
				"err":    err,
			}, "error in loading type from DB")
			return nil, errors.NewInternalError(ctx, err)
		}
		convertedWI, err := ConvertWorkItemStorageToModel(wiType, &ele)
		if err != nil {
			log.Error(nil, map[string]interface{}{
				"wi_id": ele.ID,
				"err":   err,
			}, "error in converting WI")
		}
		workitems = append(workitems, convertedWI)
	}
	return workitems, nil
}
95115
func (c *CloudPersister) ListItemTypes() ([]*types.ItemType, error) {
	ctx := context.Background()
	ItemTypes := make([]*types.ItemType, 0)
	q := datastore.NewQuery("ItemType")

	keys, err := c.DatastoreClient().GetAll(ctx, q, &ItemTypes)

	if err != nil {
		return nil, fmt.Errorf("datastoredb: could not list ItemTypes: %v", err)
	}

	for i, k := range keys {
		ItemTypes[i].ID = k.ID()
	}

	return ItemTypes, nil
}
1227892
func (c *FakeWorkflows) List(opts v1.ListOptions) (result *v1alpha1.WorkflowList, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewListAction(workflowsResource, workflowsKind, c.ns, opts), &v1alpha1.WorkflowList{})

	if obj == nil {
		return nil, err
	}

	label, _, _ := testing.ExtractFromListOptions(opts)
	if label == nil {
		label = labels.Everything()
	}
	list := &v1alpha1.WorkflowList{ListMeta: obj.(*v1alpha1.WorkflowList).ListMeta}
	for _, item := range obj.(*v1alpha1.WorkflowList).Items {
		if label.Matches(labels.Set(item.Labels)) {
			list.Items = append(list.Items, item)
		}
	}
	return list, err
}
912017
func (c *Client) ListOpenWorkflowExecutions(request ListOpenWorkflowExecutionsRequest) (*ListOpenWorkflowExecutionsResponse, error) {
	resp := &ListOpenWorkflowExecutionsResponse{}
	err := c.swfReqWithResponse("ListOpenWorkflowExecutions", request, resp)
	return resp, err
}
702593
func (c *Manager) ListLibraryItemFiles(ctx context.Context, id string) ([]File, error) {
	url := internal.URL(c, internal.LibraryItemFilePath).WithParameter("library_item_id", id)
	var res []File
	return res, c.Do(ctx, url.Request(http.MethodGet), &res)
}
269431
func (s *BrocadeVCSService) ListBrocadeVcsDeviceNetworks(p *ListBrocadeVcsDeviceNetworksParams) (*ListBrocadeVcsDeviceNetworksResponse, error) {
	resp, err := s.cs.newRequest("listBrocadeVcsDeviceNetworks", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListBrocadeVcsDeviceNetworksResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
692481
func (r *GormEventRepository) List(ctx context.Context, wiID uuid.UUID) (List, error) {
	revisionList, err := r.wiRevisionRepo.List(ctx, wiID)
	if err != nil {
		return nil, errs.Wrapf(err, "failed to list revisions for work item %s", wiID)
	}
	if revisionList == nil {
		return List{}, nil
	}
	if err = r.workItemRepo.CheckExists(ctx, wiID); err != nil {
		return nil, errs.Wrapf(err, "failed to find work item: %s", wiID)
	}

	eventList := List{}
	for k := 1; k < len(revisionList); k++ {

		oldRev := revisionList[k-1]
		newRev := revisionList[k]

		wit, err := r.workItemTypeRepo.Load(ctx, oldRev.WorkItemTypeID)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to load old work item type: %s", oldRev.WorkItemTypeID)
		}

		modifierID, err := r.identityRepo.Load(ctx, newRev.ModifierIdentity)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to load modifier identity %s", newRev.ModifierIdentity)
		}

		// TODO(kwk): make sure we have a proper "changed work item type"
		// revision entry in one way or another.
		// TODO(ibrahim): type change event should have more information than just the new and old type IDs
		if oldRev.WorkItemTypeID != newRev.WorkItemTypeID {
			event := Event{
				RevisionID:     newRev.ID,
				Name:           WorkitemTypeChangeEvent,
				WorkItemTypeID: newRev.WorkItemTypeID,
				Timestamp:      newRev.Time,
				Modifier:       modifierID.ID,
				Old:            oldRev.WorkItemTypeID,
				New:            newRev.WorkItemTypeID,
			}
			eventList = append(eventList, event)
			// We do not compare any of the fields since this is a type change event.
			continue
		}

		for fieldName, fieldDef := range wit.Fields {

			oldVal := oldRev.WorkItemFields[fieldName]
			newVal := newRev.WorkItemFields[fieldName]

			event := Event{
				RevisionID:     newRev.ID,
				Name:           fieldName,
				WorkItemTypeID: newRev.WorkItemTypeID,
				Timestamp:      newRev.Time,
				Modifier:       modifierID.ID,
				Old:            oldVal,
				New:            newVal,
			}

			// The enum type can be handled by the simple type since it's just a
			// single value after all.
			ft := fieldDef.Type
			enumType, isEnumType := ft.(workitem.EnumType)
			if isEnumType {
				ft = enumType.BaseType
			}

			switch fieldType := ft.(type) {
			case workitem.ListType:
				var p, n []interface{}
				var ok bool

				switch t := oldVal.(type) {
				case nil:
					p = []interface{}{}
				case []interface{}:
					converted, err := fieldType.ConvertFromModel(t)
					if err != nil {
						return nil, errs.Wrapf(err, "failed to convert old value for field %s from storage representation: %+v", fieldName, t)
					}
					p, ok = converted.([]interface{})
					if !ok {
						return nil, errs.Errorf("failed to convert old value for field %s from to []interface{}: %+v", fieldName, t)
					}
				}

				switch t := newVal.(type) {
				case nil:
					n = []interface{}{}
				case []interface{}:
					converted, err := fieldType.ConvertFromModel(t)
					if err != nil {
						return nil, errs.Wrapf(err, "failed to convert new value for field %s from storage representation: %+v", fieldName, t)
					}
					n, ok = converted.([]interface{})
					if !ok {
						return nil, errs.Errorf("failed to convert new value for field %s from to []interface{}: %+v", fieldName, t)
					}
				}

				// Avoid duplicate entries for empty labels or assignees, etc.
				if !reflect.DeepEqual(p, n) {
					event.Old = p
					event.New = n
					eventList = append(eventList, event)
				}
			case workitem.SimpleType:
				// compensate conversion from storage if this really was an enum field
				converter := fieldType.ConvertFromModel
				if isEnumType {
					converter = enumType.ConvertFromModel
				}

				p, err := converter(oldVal)
				if err != nil {
					return nil, errs.Wrapf(err, "failed to convert old value for field %s from storage representation: %+v", fieldName, oldVal)
				}
				n, err := converter(newVal)
				if err != nil {
					return nil, errs.Wrapf(err, "failed to convert new value for field %s from storage representation: %+v", fieldName, newVal)
				}
				if !reflect.DeepEqual(p, n) {
					event.Old = p
					event.New = n
					eventList = append(eventList, event)
				}
			default:
				return nil, errors.NewNotFoundError("unknown field type", fieldType.GetKind().String())
			}
		}
	}

	return eventList, nil
}
980232
func TypeGroupByName(name string) *WorkItemTypeGroup {
	for _, t := range TypeGroups() {
		if t.Name == name {
			return &t
		}
	}
	return nil
}
548139
func (s *NetworkOfferingService) ListNetworkOfferings(p *ListNetworkOfferingsParams) (*ListNetworkOfferingsResponse, error) {
	resp, err := s.cs.newRequest("listNetworkOfferings", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListNetworkOfferingsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
695550
func (wit WorkItemType) ConvertWorkItemStorageToModel(workItem WorkItemStorage) (*WorkItem, error) {
	result := WorkItem{
		ID:                     workItem.ID,
		Number:                 workItem.Number,
		Type:                   workItem.Type,
		Version:                workItem.Version,
		Fields:                 map[string]interface{}{},
		SpaceID:                workItem.SpaceID,
		relationShipsChangedAt: workItem.RelationShipsChangedAt,
	}

	for name, field := range wit.Fields {
		var err error
		if name == SystemCreatedAt {
			continue
		}
		result.Fields[name], err = field.ConvertFromModel(name, workItem.Fields[name])
		if err != nil {
			return nil, errs.WithStack(err)
		}
		result.Fields[SystemOrder] = workItem.ExecutionOrder
	}

	return &result, nil
}
252528
func (c *Host) ListJobs() (map[string]host.ActiveJob, error) {
	var jobs map[string]host.ActiveJob
	err := c.c.Get("/host/jobs", &jobs)
	return jobs, err
}
451037
func (r *GormWorkItemTypeRepository) loadChildTypeList(ctx context.Context, parentTypeID uuid.UUID) ([]uuid.UUID, error) {
	types := []ChildType{}
	db := r.db.Model(&types).Where("parent_work_item_type_id=?", parentTypeID).Order("position ASC").Find(&types)
	if db.RecordNotFound() {
		log.Error(ctx, map[string]interface{}{"wit_id": parentTypeID}, "work item type child types not found")
		return nil, errors.NewNotFoundError("work item type child types", parentTypeID.String())
	}
	if err := db.Error; err != nil {
		return nil, errors.NewInternalError(ctx, err)
	}
	res := make([]uuid.UUID, len(types))
	for i, childType := range types {
		res[i] = childType.ChildWorkItemTypeID
	}
	return res, nil
}
396110
func (c *WorkitemsController) List(ctx *app.ListWorkitemsContext) error {
	var additionalQuery []string
	exp, err := query.Parse(ctx.Filter)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("could not parse filter", err))
	}
	if ctx.FilterExpression != nil {
		q := *ctx.FilterExpression
		// Better approach would be to convert string to Query instance itself.
		// Then add new AND clause with spaceID as another child of input query
		// Then convert new Query object into simple string
		queryWithSpaceID := fmt.Sprintf(`{"%s":[{"space": "%s" }, %s]}`, search.AND, ctx.SpaceID, q)
		queryWithSpaceID = fmt.Sprintf("?filter[expression]=%s", queryWithSpaceID)
		searchURL := app.SearchHref() + queryWithSpaceID
		ctx.ResponseData.Header().Set("Location", searchURL)
		return ctx.TemporaryRedirect()
	}
	if ctx.FilterAssignee != nil {
		if *ctx.FilterAssignee == none {
			exp = criteria.And(exp, criteria.IsNull("system.assignees"))
			additionalQuery = append(additionalQuery, "filter[assignee]=none")

		} else {
			exp = criteria.And(exp, criteria.Equals(criteria.Field("system.assignees"), criteria.Literal([]string{*ctx.FilterAssignee})))
			additionalQuery = append(additionalQuery, "filter[assignee]="+*ctx.FilterAssignee)
		}
	}
	if ctx.FilterIteration != nil {
		exp = criteria.And(exp, criteria.Equals(criteria.Field(workitem.SystemIteration), criteria.Literal(string(*ctx.FilterIteration))))
		additionalQuery = append(additionalQuery, "filter[iteration]="+*ctx.FilterIteration)
		// Update filter by adding child iterations if any
		application.Transactional(c.db, func(tx application.Application) error {
			iterationUUID, errConversion := uuid.FromString(*ctx.FilterIteration)
			if errConversion != nil {
				return jsonapi.JSONErrorResponse(ctx, errs.Wrap(errConversion, "Invalid iteration ID"))
			}
			childrens, err := tx.Iterations().LoadChildren(ctx.Context, iterationUUID)
			if err != nil {
				return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, "Unable to fetch children"))
			}
			for _, child := range childrens {
				childIDStr := child.ID.String()
				exp = criteria.Or(exp, criteria.Equals(criteria.Field(workitem.SystemIteration), criteria.Literal(childIDStr)))
				additionalQuery = append(additionalQuery, "filter[iteration]="+childIDStr)
			}
			return nil
		})
	}
	if ctx.FilterWorkitemtype != nil {
		exp = criteria.And(exp, criteria.Equals(criteria.Field("Type"), criteria.Literal([]uuid.UUID{*ctx.FilterWorkitemtype})))
		additionalQuery = append(additionalQuery, "filter[workitemtype]="+ctx.FilterWorkitemtype.String())
	}
	if ctx.FilterArea != nil {
		exp = criteria.And(exp, criteria.Equals(criteria.Field(workitem.SystemArea), criteria.Literal(string(*ctx.FilterArea))))
		additionalQuery = append(additionalQuery, "filter[area]="+*ctx.FilterArea)
	}
	if ctx.FilterWorkitemstate != nil {
		exp = criteria.And(exp, criteria.Equals(criteria.Field(workitem.SystemState), criteria.Literal(string(*ctx.FilterWorkitemstate))))
		additionalQuery = append(additionalQuery, "filter[workitemstate]="+*ctx.FilterWorkitemstate)
	}
	if ctx.FilterParentexists != nil {
		// no need to build expression: it is taken care in wi.List call
		// we need additionalQuery to make sticky filters in URL links
		additionalQuery = append(additionalQuery, "filter[parentexists]="+strconv.FormatBool(*ctx.FilterParentexists))
	}

	offset, limit := computePagingLimits(ctx.PageOffset, ctx.PageLimit)
	var workitems []workitem.WorkItem
	var count int
	sort, err := workitem.ParseSortWorkItemsBy(ctx.Sort)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	err = application.Transactional(c.db, func(tx application.Application) error {
		var err error
		workitems, count, err = tx.WorkItems().List(ctx.Context, ctx.SpaceID, exp, ctx.FilterParentexists, &offset, &limit, sort)
		if err != nil {
			return errs.Wrap(err, "Error listing work items")
		}
		return nil
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return ctx.ConditionalEntities(workitems, c.config.GetCacheControlWorkItems, func() error {
		hasChildren := workItemIncludeHasChildren(ctx, c.db)
		wits, err := loadWorkItemTypesFromArr(ctx.Context, c.db, workitems)
		if err != nil {
			return jsonapi.JSONErrorResponse(ctx, err)
		}
		converted, err := ConvertWorkItems(ctx.Request, wits, workitems, hasChildren)
		if err != nil {
			return jsonapi.JSONErrorResponse(ctx, err)
		}
		response := app.WorkItemList{
			Links: &app.PagingLinks{},
			Meta:  &app.WorkItemListResponseMeta{TotalCount: count},
			Data:  converted,
		}
		setPagingLinks(response.Links, buildAbsoluteURL(ctx.Request), len(workitems), offset, limit, count, additionalQuery...)
		addFilterLinks(response.Links, ctx.Request)
		return ctx.OK(&response)
	})
}
397768
func (list WorkItemLinkList) GetDistinctListOfTargetIDs(linkTypeID uuid.UUID) id.Slice {
	m := id.Map{}
	for _, l := range list {
		if l.LinkTypeID == linkTypeID {
			m[l.TargetID] = struct{}{}
		}
	}
	return m.ToSlice()
}
1331167
func getWorkItemsOfLinks(ctx context.Context, appl application.Application, req *http.Request, linksDataArr []*app.WorkItemLinkData) ([]*app.WorkItem, error) {
	// Build our "set" of distinct work item IDs
	idMap := map[uuid.UUID]struct{}{}
	idArr := []uuid.UUID{}
	for _, linkData := range linksDataArr {
		src := linkData.Relationships.Source.Data.ID
		tgt := linkData.Relationships.Target.Data.ID
		if _, ok := idMap[src]; !ok {
			idMap[src] = struct{}{}
			idArr = append(idArr, src)
		}
		if _, ok := idMap[tgt]; !ok {
			idMap[tgt] = struct{}{}
			idArr = append(idArr, tgt)
		}
	}

	// Fetch all work items specified in the array
	res := []*app.WorkItem{}
	for _, id := range idArr {
		wi, err := appl.WorkItems().LoadByID(ctx, id)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		wit, err := appl.WorkItemTypes().Load(ctx, wi.Type)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to load work item type: %s", wi.Type)
		}
		converted, err := ConvertWorkItem(req, *wit, *wi)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		res = append(res, converted)
	}
	return res, nil
}