Standardize Formatting
[osm/osmclient.git] / osmclient / sol005 / project.py
1 #
2 # Copyright 2018 Telefonica Investigacion y Desarrollo S.A.U.
3 #
4 # All Rights Reserved.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17
18 """
19 OSM project mgmt API
20 """
21
22 from osmclient.common import utils
23 from osmclient.common.exceptions import ClientException
24 from osmclient.common.exceptions import NotFound
25 import json
26 import logging
27
28
29 class Project(object):
30 def __init__(self, http=None, client=None):
31 self._http = http
32 self._client = client
33 self._logger = logging.getLogger("osmclient")
34 self._apiName = "/admin"
35 self._apiVersion = "/v1"
36 self._apiResource = "/projects"
37 self._apiBase = "{}{}{}".format(
38 self._apiName, self._apiVersion, self._apiResource
39 )
40
41 def create(self, name, project):
42 """Creates a new OSM project"""
43 self._logger.debug("")
44 self._client.get_token()
45 http_code, resp = self._http.post_cmd(
46 endpoint=self._apiBase, postfields_dict=project, skip_query_admin=True
47 )
48 # print('HTTP CODE: {}'.format(http_code))
49 # print('RESP: {}'.format(resp))
50 # if http_code in (200, 201, 202, 204):
51 if resp:
52 resp = json.loads(resp)
53 if not resp or "id" not in resp:
54 raise ClientException("unexpected response from server - {}".format(resp))
55 print(resp["id"])
56 # else:
57 # msg = ""
58 # if resp:
59 # try:
60 # msg = json.loads(resp)
61 # except ValueError:
62 # msg = resp
63 # raise ClientException("failed to create project {} - {}".format(name, msg))
64
65 def update(self, project, project_changes):
66 """Updates an OSM project identified by name"""
67 self._logger.debug("")
68 self._client.get_token()
69 proj = self.get(project)
70 http_code, resp = self._http.patch_cmd(
71 endpoint="{}/{}".format(self._apiBase, proj["_id"]),
72 postfields_dict=project_changes,
73 skip_query_admin=True,
74 )
75 # print('HTTP CODE: {}'.format(http_code))
76 # print('RESP: {}'.format(resp))
77 if http_code in (200, 201, 202):
78 if resp:
79 resp = json.loads(resp)
80 if not resp or "id" not in resp:
81 raise ClientException(
82 "unexpected response from server - {}".format(resp)
83 )
84 print(resp["id"])
85 elif http_code == 204:
86 print("Updated")
87 # else:
88 # msg = ""
89 # if resp:
90 # try:
91 # msg = json.loads(resp)
92 # except ValueError:
93 # msg = resp
94 # raise ClientException("failed to update project {} - {}".format(project, msg))
95
96 def delete(self, name, force=False):
97 """Deletes an OSM project identified by name"""
98 self._logger.debug("")
99 self._client.get_token()
100 project = self.get(name)
101 querystring = ""
102 if force:
103 querystring = "?FORCE=True"
104 http_code, resp = self._http.delete_cmd(
105 "{}/{}{}".format(self._apiBase, project["_id"], querystring),
106 skip_query_admin=True,
107 )
108 # print('HTTP CODE: {}'.format(http_code))
109 # print('RESP: {}'.format(resp))
110 if http_code == 202:
111 print("Deletion in progress")
112 elif http_code == 204:
113 print("Deleted")
114 elif resp and "result" in resp:
115 print("Deleted")
116 else:
117 msg = resp or ""
118 # if resp:
119 # try:
120 # msg = json.loads(resp)
121 # except ValueError:
122 # msg = resp
123 raise ClientException("failed to delete project {} - {}".format(name, msg))
124
125 def list(self, filter=None):
126 """Returns the list of OSM projects"""
127 self._logger.debug("")
128 self._client.get_token()
129 filter_string = ""
130 if filter:
131 filter_string = "?{}".format(filter)
132 _, resp = self._http.get2_cmd(
133 "{}{}".format(self._apiBase, filter_string), skip_query_admin=True
134 )
135 # print('RESP: {}'.format(resp))
136 if resp:
137 return json.loads(resp)
138 return list()
139
140 def get(self, name):
141 """Returns a specific OSM project based on name or id"""
142 self._logger.debug("")
143 self._client.get_token()
144 if utils.validate_uuid4(name):
145 for proj in self.list():
146 if name == proj["_id"]:
147 return proj
148 else:
149 for proj in self.list():
150 if name == proj["name"]:
151 return proj
152 raise NotFound("Project {} not found".format(name))