API アクセス制御の例

これらの例は Python で記述されていますが、この言語の深い知識がなくても理解できるほど簡単なはずです。

サンプルプロジェクトまたは自分のプロジェクトで、サンプルスクリプトを試すことができます。自分のプロジェクトで使用する場合は、projectの値を変更する必要があります。また場合によっては、hostの値を localhost から自分の Klocwork サーバー ホストに変更する必要があります。

リクエストパラメータの詳細情報は以下をご覧ください。http(s)://<klocwork_server_host>:<klocwork_server_port>/review/api.

新しい役割を作成するには

以下の例に従って、新しい役割を作成することができます。役割は、Klocwork Static Code Analysis または Klocwork Code Review にアクセスする際にユーザーができることを定義します。

import urllib, urllib2, os.path, getpass, sys, socket

            def getToken(host, port, user):
                ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
                ltokenFile = open(ltoken, 'r')
                for r in ltokenFile:
                    rd = r.strip().split(';')
                    if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
                        ltokenFile.close()
                        return rd[3]
                ltokenFile.close()


            def set_role_permission_parameters(values, name, access_source_files, allowed_status_transitions, assign_role,
                                            change_issue_status, change_project_settings, create_build, create_project,
                                            create_stream, delete_build, delete_project, delete_stream, manage_modules,
                                            manage_roles, manage_users, use_local_configuration, webapi_access, execute_kwxsync):
                values['name'] = name
                if create_project is not None:
                    values['create_project'] = create_project
                if create_stream is not None:
                    values['create_stream'] = create_stream
                if manage_roles is not None:
                    values['manage_roles'] = manage_roles
                if manage_users is not None:
                    values['manage_users'] = manage_users
                if access_source_files is not None:
                    values['access_source_files'] = access_source_files
                if assign_role is not None:
                    values['assign_role'] = assign_role
                if change_project_settings is not None:
                    values['change_project_settings'] = change_project_settings
                if create_build is not None:
                    values['create_build'] = create_build
                if delete_build is not None:
                    values['delete_build'] = delete_build
                if delete_project is not None:
                    values['delete_project'] = delete_project
                if delete_stream is not None:
                    values['delete_stream'] = delete_stream
                if manage_modules is not None:
                    values['manage_modules'] = manage_modules
                if use_local_configuration is not None:
                    values['use_local_configuration'] = use_local_configuration
                if change_issue_status is not None:
                    values['change_issue_status'] = change_issue_status
                if allowed_status_transitions is not None:
                    values['allowed_status_transitions'] = allowed_status_transitions
                if webapi_access is not None:        
                    values['webapi_access'] = webapi_access  
                if execute_kwxsync is not None:
                    values['execute_kwxsync'] = execute_kwxsync      

            def create_role(url,
                            user,
                            name,
                            create_project=None,
                            create_stream=None,
                            manage_roles=None,
                            manage_users=None,
                            access_source_files=None,
                            assign_role=None,
                            change_project_settings=None,
                            create_build=None,
                            delete_build=None,
                            delete_project=None,
                            delete_stream=None,
                            manage_modules=None,
                            use_local_configuration=None,
                            change_issue_status=None,
                            allowed_status_transitions=None,
                            webapi_access=None,
                            execute_kwxsync=None):
                values = {'action': 'create_role'}
                set_role_permission_parameters(values, name, access_source_files, allowed_status_transitions, assign_role,
                                            change_issue_status, change_project_settings, create_build, create_project,
                                            create_stream, delete_build, delete_project, delete_stream, manage_modules,
                                            manage_roles, manage_users, use_local_configuration, webapi_access, execute_kwxsync)

                values['user'] = user
                loginToken = getToken(host, port, user)
                if loginToken is not None:
                    values["ltoken"] = loginToken
                data = urllib.urlencode(values)
                req = urllib2.Request(url, data)
                response = urllib2.urlopen(req)

            host = "localhost"
            port = 8080
            user = getpass.getuser()
            url = "http://%s:%d/review/api" % (host, port)
            role_name = "myrole"
            create_project = False
            create_stream = False
            manage_roles = True
            allowed_status_transitions = "Any,Analyze;Analyze,Fix"
            webapi_access = True
            execute_kwxsync = True
            try: create_role(url, user, role_name, create_project=create_project, create_stream=create_stream, manage_roles=manage_roles, allowed_status_transitions=allowed_status_transitions, webapi_access=webapi_access, execute_kwxsync=execute_kwxsync)
            except urllib2.HTTPError as e:
                print "Request failed: " + e.reason + ": " + e.read()
            else:
                print "Role created!"

役割を削除するには

以下の例に従って、以前に作成されたが、もはや必要とされない役割を削除することができます。

import urllib, urllib2, os.path, getpass, sys, socket

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def delete_role(url,
                user,
                name):
    values = {'action': 'delete_role', "name": name}

    values['user'] = user
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
role_name = "myrole"
try: delete_role(url, user, role_name)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Role deleted!"

役割割り当てリストの印刷

以下の例は、各ユーザーに割り当てられた役割の一覧表示方法を示しています。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

class Assignment(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.project_id = attrs['projectId'] if 'projectId' in attrs else None
        self.group = attrs['group']

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.project_id == other.project_id and self.group == other.group

    def __repr__(self):
        return '{name:%s, projectId:%s, group:%s}' % (self.name, str(self.project_id), str(self.group))

class RoleAssignment(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.readonly = attrs['readonly']
        self.assignments = []
        for assign in attrs['assignments']:
            self.assignments.append(Assignment(assign))

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.readonly == other.readonly and self.assignments == other.assignments

    def __repr__(self):
        return '{name:%s, readonly:%s, assignments:%s}' % (self.name, str(self.readonly), str(self.assignments))

def role_assignments(url, user, search):
    values = {"action":"role_assignments", "user": user}
    if search is not None:
        values["search"] = search
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

    role_assignments = []
    for role_assignment in response:
        role_assignments.append(RoleAssignment(json.loads(role_assignment)))

    return role_assignments

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
search = "myrole"
try: response = role_assignments(url, user, search)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print response

役割リストの印刷

以下の例は、ユーザーに割り当てることができるすべての役割の一覧表示方法を示しています。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

class Permission(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.enabled = attrs['enabled']

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.enabled == other.enabled

    def __repr__(self):
        return '{name:%s, enabled:%s}' % (self.name, str(self.enabled))

class StatusPermission(object):
    def __init__(self, attrs):
        self.fromStatus = attrs['from']
        self.toStatus = attrs['to']

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.fromStatus == other.fromStatus and self.toStatus == other.toStatus

    def __repr__(self):
        return '{from:%s, to:%s}' % (self.fromStatus, self.toStatus)

class Role(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.readonly = attrs['readonly']
        self.permissions = []
        for perm in attrs['permissions']:
            self.permissions.append(Permission(perm))
        self.statusPermissions = []
        for perm in attrs['statusPermissions']:
            self.statusPermissions.append(StatusPermission(perm))

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.readonly == other.readonly and self.permissions == other.permissions and self.statusPermissions == other.statusPermissions

    def __repr__(self):
        return '{name:%s, readonly:%s, permissions:%s, statusPermissions:%s}' % (
            self.name, str(self.readonly), self.permissions, self.statusPermissions)

def roles(url, user, search):
    values = {"action":"roles", "user": user}
    if search is not None:
        values["search"] = search
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

    roles = []
    for role in response:
        roles.append(Role(json.loads(role)))

    return roles

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
search = "myrole"
try: response = roles(url, user, search)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print response

役割割り当ての更新

以下の例は、特定ユーザーに割り当てられた役割を更新する方法を示しています。

import urllib, urllib2, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def update_role_assignment(url, user, name, account, group=None, project=None, remove=None):
    values = {'action': 'update_role_assignment'}
    values['name'] = name
    values['account'] = account
    if group is not None:
        values['group'] = group
    if project is not None:
        values['project'] = project
    if remove is not None:
        values['remove'] = remove

    values['user'] = user
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
role_name = "myrole"
account = "usera"
is_group = False
project = "my project"
remove = False
try: update_role_assignment(url, user, role_name, account, is_group, project, remove)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Role assignment updated!"

役割パーミッションの更新

以下の例は、特定の役割と関連するパーミッションを更新する方法を示しています。

import urllib, urllib2, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def set_role_permission_parameters(values, name, access_source_files, allowed_status_transitions, assign_role,
                                   change_issue_status, change_project_settings, create_build, create_project,
                                   create_stream, delete_build, delete_project, delete_stream, manage_modules,
                                   manage_roles, manage_users, use_local_configuration, webapi_access, execute_kwxsync):
    values['name'] = name
    if create_project is not None:
        values['create_project'] = create_project
    if create_stream is not None:
        values['create_stream'] = create_stream
    if manage_roles is not None:
        values['manage_roles'] = manage_roles
    if manage_users is not None:
        values['manage_users'] = manage_users
    if access_source_files is not None:
        values['access_source_files'] = access_source_files
    if assign_role is not None:
        values['assign_role'] = assign_role
    if change_project_settings is not None:
        values['change_project_settings'] = change_project_settings
    if create_build is not None:
        values['create_build'] = create_build
    if delete_build is not None:
        values['delete_build'] = delete_build
    if delete_project is not None:
        values['delete_project'] = delete_project
    if delete_stream is not None:
        values['delete_stream'] = delete_stream
    if manage_modules is not None:
        values['manage_modules'] = manage_modules
    if use_local_configuration is not None:
        values['use_local_configuration'] = use_local_configuration
    if change_issue_status is not None:
        values['change_issue_status'] = change_issue_status
    if allowed_status_transitions is not None:
        values['allowed_status_transitions'] = allowed_status_transitions
    if webapi_access is not None:
        values['webapi_access'] = webapi_acess
    if execute_kwxsync is not None:
        values['execute_kwxsync'] = execute_kwxsync

def update_role_permissions(url,
                            user,
                            name,
                            create_project=None,
                            create_stream = None,
                            manage_roles=None,
                            manage_users=None,
                            access_source_files=None,
                            assign_role=None,
                            change_project_settings=None,
                            create_build=None,
                            delete_build=None,
                            delete_project=None,
                            delete_stream = None,
                            manage_modules=None,
                            use_local_configuration=None,
                            change_issue_status=None,
                            allowed_status_transitions=None,
                            webapi_access=None,
                            execute_kwxsync):
    values = {'action': 'update_role_permissions'}
    set_role_permission_parameters(values, name, access_source_files, allowed_status_transitions, assign_role,
                                   change_issue_status, change_project_settings, create_build, create_project,
                                   create_stream, delete_build, delete_project, delete_stream, manage_modules,
                                   manage_roles, manage_users, use_local_configuration, webapi_access, execute_kwxsync)

    values['user'] = user
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
role_name = "myrole"
create_project = False
create_stream = False
manage_roles = True
allowed_status_transitions = "Any,Analyze;Analyze,Fix"
webapi_access = True
execute_kwxsync = True
try: update_role_permissions(url, user, role_name, create_project=create_project, create_stream=create_stream, manage_roles=manage_roles, allowed_status_transitions=allowed_status_transitions, webapi_access=webapi_access, execute_kwxsync=execute_kwxsync)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Role permissions updated!"

新規ユーザーを作成するには

以下の例に従って、Klocwork 製品ポータルにアクセスできる新規ユーザーを作成することができます。

import urllib, urllib2, os.path, getpass, sys, socket

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def create_user(url, user, name, password=None):
    values = {'action': 'create_user'}
    values['name'] = name
    if password is not None:
        values['password'] = password

    values['user'] = user
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
name = "user_a"
password = "password"
try: create_user(url, user, name, password)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "User created!"

ユーザーを削除するには

以下の例に従って、以前に作成されたが、もはや必要とされないユーザーを削除することができます。

import urllib, urllib2, os.path, getpass, sys, socket

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def delete_user(url, user, name):
    values = {'action': 'delete_user'}
    values['name'] = name

    values['user'] = user
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
name = "user_a"
try: delete_user(url, user, name)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "User deleted!"

ユーザーリストの印刷

以下の例では、ユーザーリストの印刷方法を示しています。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

class RoleDescr(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.project_id = attrs['projectId'] if 'projectId' in attrs else None
        if attrs.has_key('group'):
            self.group = attrs['group']
        else:
            self.group = None

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.project_id == other.project_id and self.group == other.group

    def __repr__(self):
        return '{name:%s, projectId:%s, group:%s}' % (self.name, self.project_id, self.group)

class GroupDescr(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.readonly = attrs['readonly']

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.readonly == other.readonly

    def __repr__(self):
        return '{name:%s, readonly:%s}' % (self.name, str(self.readonly))

class User(object):
    def __init__(self, attrs):
        print attrs
        self.name = attrs['name']
        self.readonly = attrs['readonly']
        self.roles = []
        for r in attrs['roles']:
            self.roles.append(RoleDescr(r))
        self.groups = []
        for g in attrs['groups']:
            self.groups.append(GroupDescr(g))
        self.users = None
        if attrs.has_key('users'):
            self.users = attrs['users']

    def __hash__(self):
        return hash(self.__repr__())

    def __eq__(self, other):
        return self.name == other.name and self.readonly == other.readonly and self.roles == other.roles and self.groups == other.groups and self.users == other.users

    def __repr__(self):
        return '{name:%s, readonly:%s, roles:%s, groups:%s, users:%s}' % (self.name, str(self.readonly), self.roles, self.groups, self.users)

def users(url, user, search, limit):
    values = {"action":"users", "user": user, "search": search, "limit": limit}
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

    users = []
    for user in response:
        users.append(User(json.loads(user)))

    return users

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)
search = "*"
limit = 1000
try: response = users(url, user, search, limit)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print response

新規グループを作成するには

以下の例に従って、数名のユーザーのアクセスを一度に制御するために使えるグループを新規作成することができます。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()


def create_group(url, user, name, users_text=None):
    values = {'action': 'create_group'}
    values['name'] = name
    if users_text is not None:
        values['users'] = users_text
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
group = "group_name"
users_text = "user_name"
url = "http://%s:%d/review/api" % (host, port)

try: create_group(url, user, group, users_text)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Group created!"

グループを削除するには

以下の例に従って、以前に作成されたが、もはや必要とされないグループを削除することができます。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

def delete_group(url, user, name):
    values = {'action': 'delete_group'}
    values['name'] = name
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
group = "group_name"
url = "http://%s:%d/review/api" % (host, port)

try: delete_group(url, user, group)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:	
	print "Group deleted!"

グループリストの印刷

以下の例では、グループリストの印刷方法を示しています。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()

class Account(object):
    def __init__(self, attrs):
        self.name = attrs['name']
        self.readonly = attrs['readonly']
        self.roles = []
        for r in attrs['roles']:
            self.roles.append(RoleDescr(r))
        self.groups = []
        for g in attrs['groups']:
            self.groups.append(GroupDescr(g))
        self.users = None
        if 'users' in attrs:
            self.users = attrs['users']

    def __str__(self):
        return 'name:%s, readonly:%s, roles:%s, groups:%s, users:%s' % (self.name, str(self.readonly), self.roles, self.groups, self.users)
	
def from_json(json_object):
    return Account(json_object)

def groups(url, user, search=None, limit=None, list_users=None):
    values = {'action': 'groups'}
    if search is not None:
        values['search'] = search
    if limit is not None:
        values['limit'] = limit
    if list_users is not None:
        values['list_users'] = list_users
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    result = []
    for record in response:
        result.append(json.loads(record, object_hook=from_json))
    return result

host = "localhost"
port = 8080
user = getpass.getuser()
url = "http://%s:%d/review/api" % (host, port)

try: groups = groups(url, user)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Groups:"
	for group in groups:
		print group

グループの更新

以下の例では、グループ内のユーザーリストの更新方法を示しています。

import urllib, urllib2, json, sys, os.path, getpass

def getToken(host, port, user):
    ltoken = os.path.normpath(os.path.expanduser("~/.klocwork/ltoken"))
    ltokenFile = open(ltoken, 'r')
    for r in ltokenFile:
        rd = r.strip().split(';')
        if (rd[0] == socket.getfqdn(host) or rd[0] == socket.gethostbyname(socket.gethostname())) and rd[1] == str(port) and rd[2] == user:
            ltokenFile.close()
            return rd[3]
    ltokenFile.close()


def update_group(url, user, name, users_text=None, remove_all=None):
    values = {'action': 'update_group'}
    values['name'] = name
    if users_text is not None:
        values['users'] = users_text
    if remove_all is not None:
        values['remove_all'] = remove_all
    loginToken = getToken(host, port, user)
    if loginToken is not None:
        values["ltoken"] = loginToken
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)

host = "localhost"
port = 8080
user = getpass.getuser()
group = "group_name"
users_text = "user_name"
url = "http://%s:%d/review/api" % (host, port)

try: update_group(url, user, group, users_text)
except urllib2.HTTPError as e:
	print "Request failed: " + e.reason + ": " + e.read()
else:
	print "Group updated!"