rest

package
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 11, 2023 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRestNoLoginMeth  = errors.New("no login method")
	ErrRestNotLoggedIn  = errors.New("not logged in")
	ErrRestExpired      = errors.New("session expired")
	ErrInvalidPersid    = errors.New("persid must be a semicolon separated <factory:value>")
	ErrRestBadRequest   = errors.New("bad request")
	ErrRestUnathorized  = errors.New("unauthorized")
	ErrRestNotFound     = errors.New("not found")
	ErrRestConflict     = errors.New("conflict")
	ErrRestInternal     = errors.New("internal")
	ErrRestUploadFailed = errors.New("file upload failed")
)
View Source
var SdmReturnAllFields = []string{"*"}

SdmReturnAllFields pass this as fields parametr to fetch all attributes of returned entity.

Functions

func NewLoginSecretKey

func NewLoginSecretKey(username, password string, signFields []string, hmacAlg HmacAlgorithm) *loginSecretKey

NewLoginSecretKey is a built-in function to create an instance of RestLogin compatible struct. With authorization by CA SDM username, password, and encrypted key.

Proper CA SDM Options MUST be specified.

  1. signFields refersh to Admin Tab > Options > WebService > string_to_sign_fields If string_to_sign_fields is uninstalled the nil value should be passed as signFields. Array order must be same as arguments in the option comma separated.
  2. hmacAlg refers to Admin Tab > Options > WebService > hmac_algorithm

Read more: REST Secret Key Authentication Postman Sample: TEC10660

func NewLoginUserPassword

func NewLoginUserPassword(username, password string) *loginUserPassword

NewLoginUserPassword is a built-in function to create an instance of Login compatible struct. With authorization using username and password.

func SdmNull

func SdmNull() *sdmNull

SdmNull is used as NULL value in CA SDM data

Types

type Access

type Access struct {
	// contains filtered or unexported fields
}

Access stores CA Service Desk REST session details

func NewAccess

func NewAccess(id string, accessKey int, expirationDate int64, secretKey string) *Access

NewAccess creates an instance of Access struct.

type AccessJSON

type AccessJSON struct {
	AccessDataJSON struct {
		ID             string `json:"@id"`
		AccessKey      int    `json:"access_key"`
		ExpirationDate int64  `json:"expiration_date"`
		SecretKey      string `json:"secret_key"`
	} `json:"rest_access"`
}

AccessJSON matches SDM REST rest_access response body when Accept-Content is specified as application/json.

func (*AccessJSON) Access

func (b *AccessJSON) Access() *Access

Access method converts JSON struct to unified Access struct.

type AccessXML

type AccessXML struct {
	ID             string `xml:"id,attr"`
	AccessKey      int    `xml:"access_key"`
	ExpirationDate int64  `xml:"expiration_date"`
	SecretKey      string `xml:"secret_key"`
}

AccessXML matches SDM REST rest_access response body when Accept-Content is specified as application/xml.

func (*AccessXML) Access

func (b *AccessXML) Access() *Access

Access method converts XML struct to unified Access struct.

type Attmnt

type Attmnt struct {
	XMLName     xml.Name    `xml:"attmnt" json:"-"`
	Repo        *AttmntRepo `json:"repository" xml:"repository"`
	FileName    string      `json:"orig_file_name" xml:"orig_file_name"`
	AttmntName  string      `json:"attmnt_name" xml:"attmnt_name"`
	Description string      `json:"description" xml:"description"`
}

Attmnt is a struct used as attachment payload during upload.

type AttmntContentType

type AttmntContentType uint8

AttmntContentType is a flag to define file encdoing.

const (
	AttmntContentTypeBinary AttmntContentType = iota // for most cases
	AttmntContentTypeBase64                          // when data is encoded in Base64
)

type AttmntRepo

type AttmntRepo struct {
	Id string `json:"@id" xml:"id,attr"`
}

Attmnt is a struct used as attachment payload during upload.

type AttmntReq

type AttmntReq struct {
	XMLName xml.Name `xml:"attmnt" json:"-"`
	Attmnt  *Attmnt  `json:"attmnt"`
}

AttmntReq is a struct used as attachment payload during upload.

type GetFilter

type GetFilter uint8

GetFilter is enum to switch between supported filters

Deprecated

const (
	GetFilterAll GetFilter = iota
	GetFilterWC
	GetFilterID
	GetFilterCommonName
	GetFilterRelAttr
	GetFilterCollection
	GetFilterUndefined
)

Deprecated

type HmacAlgorithm

type HmacAlgorithm uint
const (
	HmacSHA1 HmacAlgorithm = iota
	HmacSHA256
	HmacSHA384
	HmacSHA512
	HmacMD5
)

Enum of HMAC Algorithms supported by CA SDM

type Login

type Login interface {
	// Login is unified login method which reduces need to implement
	// preparation for each method manually.
	//
	// You can pass nil Login to use data from the [Client] struct
	Login(*client) error
	// Logout is unified logout method which reduces need to implement
	// preparation for each method manually.
	//
	// You can pass nil Login to use data from the [Client] struct
	Logout(*client) error
	// Token returns Token that is used as Authorization HTTP Request Header.
	//
	// The reason for calling this method manually might be ONLY if
	// you're using a custom implementation of the Login method.
	Token(*http.Request) error
	// Session returns CA Service Desk REST session stored inside the sturct,
	//
	// Can be used in save/load routintes if you're restarting the
	// app more often than session TTL.
	//
	// The reason for calling this method manually might be ONLY if
	// you're using a custom implementation of the Login method.
	Session() *Access
	// UpdSession updates CA Service Desk REST session stored inside the sturct,
	//
	// Can be used in save/load routintes if you're restarting the
	// app more often than session TTL.
	//
	// The reason for calling this method manually might be ONLY if
	// you're using a custom implementation of the Login method.
	UpdSession(*Access)
}

Login interface implements an authentication struct that attaches to the REST Client and authorizes it.

This file is part of implementation of standart REST Cli implementation and relay on it's methods.

type LoginRequestBody

type LoginRequestBody struct {
	XMLName xml.Name `xml:"rest_access" json:"-"`
	Access  *string  `json:"rest_access"`
}

LoginRequestBody matches SDM REST rest_access request body.

type RestError

type RestError struct {
	Message string
	Code    int
}

RestError is a struct to separate errors with same messages and different codes or vise-versa.

func (*RestError) Error

func (e *RestError) Error() string

type ResultShift

type ResultShift struct {
	Start int
	Size  int
}

ResultShift is a struct to pass param to fetches to perform shifting resuls.

Start < 1 will be 1.

func (*ResultShift) Next

func (s *ResultShift) Next() *ResultShift

Next increases start pos with size, the method can be called in a loop to fetch the next results. Note: CA Service Desk REST API doesn't throw an exception when start or size reaches out of boundaries.

func (*ResultShift) String

func (s *ResultShift) String() string

String converts ResultShift in URL compatible strng.

type ResultType

type ResultType interface{}

ResultType is an interface to be passed to response writer

type ResultTypeAttmnt

type ResultTypeAttmnt string

ResultTypeAttmnt POINTER should be passed as request param to get attachment id as response

type ResultTypeDecoded

type ResultTypeDecoded map[string]interface{}

ResultTypeDecoded POINTER should be passed as request param to get response decoded into map[string]interface{}

type ResultTypeRaw

type ResultTypeRaw []byte

ResultTypeRaw POINTER should be passed as request param to get response as-is

type SdmID

type SdmID uint

SdmID is a basic SDM positive number id.

func NewSdmID

func NewSdmID(intfc interface{}) SdmID

NewSdmID is a function that sould convert incoming interface into a proper SDM ID depending on it's param.

func (SdmID) ToID

func (id SdmID) ToID() string

ToID returns SdmID as SDM ID compatible string.

type SdmIDType

type SdmIDType interface {
	ToID() string
}

SdmIDType is a data type that implements logic of CA Service Desk API acceptable IDs.

func NewSdmIDType

func NewSdmIDType(intfc interface{}) SdmIDType

NewSdmIDType is a function that sould convert incoming interface into a proper SDM ID depending on it's param.

type SdmPersid

type SdmPersid struct {
	// contains filtered or unexported fields
}

SdmPersid is a CA Service Desk unique identifier which represents concatenation of table (factory) and id.

func NewSdmPersid

func NewSdmPersid(s string) (*SdmPersid, error)

NewSdmPersid returns SdmPersid parsed from the passed string.

func (*SdmPersid) ToID

func (id *SdmPersid) ToID() string

ToID returns SdmPersid as SDM ID compatible string.

type SdmRest

type SdmRest struct {
	SdmRestInterface
}

SdmRest is a struct that implements Client for CA Service Desk REST API

func NewSdmRest

func NewSdmRest(restURI, repoID, serverName string, schema SdmRestSchema, auth Login, httpCli *http.Client) *SdmRest

NewSdmRest is a quick definition of a proper CA Service Desk REST WebServices Client with default implementation.

func NewSdmRestWithCli

func NewSdmRestWithCli(cli SdmRestInterface) *SdmRest

NewSdmRestWithCli is a quick definition of a proper CA Service Desk REST WebServices Client with custom implementation.

func (*SdmRest) Create

func (c *SdmRest) Create(factory string, fields []string, data *SdmRestData, result ResultType) error

Create creates a new entry in the factory specified with writing result back in result structure with fields requested

func Create(c *RestClient) error {
	data := &rest.SdmRestData{
		"lrel_attachments_requests": &rest.SdmRestData{
			"attmnt": &rest.SdmRestData{
				"@REL_ATTR": *attmntid,
			},
			"cr": &rest.SdmRestData{
				"@REL_ATTR": "cr:410206",
			},
		},
	}
	result := new(rest.ResultTypeDecoded)
	err := c.Create("lrel_attachments_requests", nil, data, result); err != nil {
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print creation result
	return nil
}

func (*SdmRest) Delete

func (c *SdmRest) Delete(factory, id string, result ResultType) error

Delete deletes an entry within factory and id specified. Result will be written back in the result interface.

func Delete(c *RestClient) error {
	result := new(ResultDecoded)
	err := c.Delete("rest_access", "42", result) // deleting rest_access session with id 42
	if err != nil {
		return err
	}
	// result will be null on success
	fmt.Printf("%v", result)
	return nil
}

func (*SdmRest) Download

func (c *SdmRest) Download(attmntID string) ([]byte, error)

Download downloads attachment as []byte

func Download(c *RestClient) error {
	// downloading attachment by id
	b, err := c.Download("42")
	if err != nil {
		return err
	}
	// result will contain file content as []byte
	fmt.Printf("%v", b)
	return nil
}

func (*SdmRest) DownloadFile

func (c *SdmRest) DownloadFile(attmntID string, path string) error

Download downloads attachment and writes it to thepath

func DownloadFile(c *RestClient) error {
	// downloading attachment by id and writing to current dir
	b, err := c.DownloadFile("42", "./myfile.dat")
	if err != nil {
		return err
	}
	return nil
}

func (*SdmRest) GetAll

func (c *SdmRest) GetAll(factory string, shift *ResultShift, returnFlds []string, result ResultType) error

GetAll fetches all entries of selected factory with requested fields

func GetAll(c *RestClient) error {
	shift := &ResultShift{Start: 1, Size: 10}
	result := new(ResultDecoded)
	err := c.GetAll("cr", shift, []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a some map that contains first 10 result of the query
	return nil
}

func (*SdmRest) GetByCommonName

func (c *SdmRest) GetByCommonName(factory, name string, shift *ResultShift, returnFlds []string, result ResultType) error

GetByCommonName fetches entries of selected factory matched by their COMMON_NAMEs with requested fields. COMMON_NAME is not unique for most factories so shift might be helpuf.

func GetByCommonName(c *RestClient) error {
	result := new(ResultDecoded)
	err := c.GetByCommonName("cr", "R42", nil, []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains ref_num and status of request with ref_num R42
	return nil
}

func (*SdmRest) GetByID

func (c *SdmRest) GetByID(factory string, id SdmIDType, returnFlds []string, result ResultType) error

GetByID fetches an entry of selected factory matched by id with requested fields

func GetByID(c *RestClient) error {
	result := new(ResultDecoded)
	err := c.GetByID("cr", NewSdmID(42), []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains ref_num and status of request with id 42
	return nil
}

func (*SdmRest) GetByPersid

func (c *SdmRest) GetByPersid(persid string, returnFlds []string, result ResultType) error

GetByPersid fetches an entry with id and factory extracted from persid with requested fields

func GetByPersid(c *RestClient) error {
	result := new(ResultDecoded)
	err := c.GetByPersid("cr:42", []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains ref_num and status of request with id 42
	return nil
}

func (*SdmRest) GetByRelAttr

func (c *SdmRest) GetByRelAttr(factory, val string, returnFlds []string, result ResultType) error

GetByRelAttr fetches an entry of selected factory matched by REL_ATTR with requested fields. REL_ATTR is an external key for the factory. Can be obtained by `bop_sinfo -f <factory_name>`

func GetByRelAttr(c *RestClient) error {
	result := new(ResultDecoded)
	err := c.GetByRelAttr("cr", "42", []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains ref_num and status of request with id 42
	return nil
}

func (*SdmRest) GetByWhereClause

func (c *SdmRest) GetByWhereClause(factory, wc string, shift *ResultShift, returnFlds []string, result ResultType) error

GetByWhereClause fetches entries of selected factory matched by SQL-like search criteria with requested fields

func GetByWhereClause(c *RestClient) error {
	result := new(ResultDecoded)
	shift := &ResultShift{Start: 1, Size: 10}
	err := c.GetByWhereClause("cr", "active = 1 OR id = 42", shift, []string{"ref_num", "status"}, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains ref_num and status of first 10 requests that are active (active = 1) OR with id = 42
	return nil
}

func (*SdmRest) GetColletction

func (c *SdmRest) GetColletction(factory, id, collection string, shift *ResultShift, returnFlds []string, result ResultType) error

GetColletction fetches collection (BLREL) from the specific entry with fields writing them to result

func GetColletction(c *RestClient) error {
	result := new(ResultDecoded)
	shift := &ResultShift{Start: 1, Size: 10}
	err := c.GetColletction("cr", "42", "attachments", shift, SdmReturnAllFields, result)
	if err != nil {
		return err
	}
	fmt.Printf("%v", result) // should print a map that contains all fields of first 10 attachments attached to request with id 42
	return nil
}

func (*SdmRest) Login

func (c *SdmRest) Login() error

Login logs in

func (*SdmRest) Logout

func (c *SdmRest) Logout() error

Logout logs out

func (*SdmRest) Update

func (c *SdmRest) Update(factory, id string, returnFlds []string, data *SdmRestData, result ResultType) error

Update updates an entry with data that matches factory and id provided. Result will be written back in the result interface.

func Update(c *RestClient) error {
	result := new(ResultDecoded)
	data := make(SdmRestData)
	data["summary"] = "hello"
	data["call_back_date"] = SdmNull()
	err := c.Update("cr", "42", SdmReturnAllFields, data, result)
	if err != nil {
		return err
	}
	// should print a map that contains all fields of request with id 42
	// where 2 fields where updated the corresponding values
	fmt.Printf("%v", result)
	return nil
}

func (*SdmRest) Upload

func (c *SdmRest) Upload(data []byte, fileName, mime, description string, content AttmntContentType) (*string, error)

Upload uploads []byte as attachment

func Upload(c *RestClient) error {
	// uploading plain text as attachment
	attmntid, err := c.Upload([]byte("this is text"), "text.txt", "plain/text", "42", AttmntContentTypeBinary)
	if err != nil {
		return err
	}
	// result will contain attachment id
	fmt.Printf("%v", *attmntid)
	return nil
}

func (*SdmRest) UploadFile

func (c *SdmRest) UploadFile(path, fileName, description string, content AttmntContentType) (*string, error)

UploadFile uploads file by it's path

func UploadFile(c *RestClient) error {
	// uploading plain txt file as attachment
	attmntid, err := c.UploadFile("./text.txt", "text.txt", "42", AttmntContentTypeBinary)
	if err != nil {
		return err
	}
	// result will contain attachment id
	fmt.Printf("%v", *attmntid)
	return nil
}

type SdmRestData

type SdmRestData map[string]interface{}

SdmRestData is a common interface for passing any attributes to SDM API, following rules must be met:

  • factory name must be always on top,
  • SDM objects must have @REL_ATTR with Related Attr as value, for example: -- use persistent_id for cr, -- UUID for cnt, -- id for attmnt, -- and code for status,
  • plain objects can just key-value pair.

Example:

data := &SdmRestData{
	"grpmem": &SdmRestData{
		"member": &SdmRestData{
			"@REL_ATTR": NewSdmUUID("<UUID_HERE>"),
		},
		"group": &SdmRestData{
			"@REL_ATTR": NewSdmUUID("<UUID_HERE>"),
		},
		"manager": false,
	},
}

type SdmRestInterface

type SdmRestInterface interface {
	// contains filtered or unexported methods
}

type SdmRestSchema

type SdmRestSchema string

SdmRestSchema defenies content type of request/response.

var (
	SdmRestSchemaJSON SdmRestSchema = "application/json" // to send and retrive data as JSON
	SdmRestSchemaXML  SdmRestSchema = "application/xml"  // to send and retrive data as XML
)

func NewSchema

func NewSchema(s string) SdmRestSchema

NewSchema parses schema from string.

func (SdmRestSchema) Decode

func (s SdmRestSchema) Decode(r io.Reader, v interface{}) error

Decode decodes content into struct with method depending on schema.

func (SdmRestSchema) Marshal

func (s SdmRestSchema) Marshal(v interface{}) ([]byte, error)

Marshal marshalises struct into []byte with method depending on schema.

type SdmUUID

type SdmUUID [16]byte

SdmUUID is a CA Service Desk UUID type.

func NewSdmUUID

func NewSdmUUID(s string) (id SdmUUID)

NewSdmUUID create a new SdmUUID from string.

func (SdmUUID) String

func (id SdmUUID) String() string

String returns SdmUUID as string.

func (SdmUUID) ToID

func (id SdmUUID) ToID() string

ToID returns SdmUUID as SDM ID compatible string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL