>From 264ce4ce3c44220d3a954d861c91b1f3d7ea2397 Mon Sep 17 00:00:00 2001
From: Abhishek Koneru <akoneru@redhat.com>
Date: Thu, 19 Jun 2014 00:10:13 -0400
Subject: [PATCH] Added methods for providing file input for profile request.

Added new methods to allow user to provide file input to perform
operations like create profile/modify profile.
The supported file formats a re xml and json.
---
 base/common/python/pki/__init__.py |   4 +-
 base/common/python/pki/profile.py  | 111 ++++++++++++++++++++++++++++++++-----
 2 files changed, 100 insertions(+), 15 deletions(-)

diff --git a/base/common/python/pki/__init__.py b/base/common/python/pki/__init__.py
index e9b726cf763785b4a700ef314ff27774b13aba40..891d6ea6364b037f132ff3754b73b372c638b0f7 100644
--- a/base/common/python/pki/__init__.py
+++ b/base/common/python/pki/__init__.py
@@ -168,7 +168,7 @@ class PKIException(Exception, ResourceMessage):
         ret = cls(json_value['Message'], json_value['Code'],
                   json_value['ClassName'])
         for attr in json_value['Attributes']['Attribute']:
-            print(str(attr))
+            print str(attr)
             ret.add_attribute(attr["name"], attr["value"])
         return ret
 
@@ -299,7 +299,7 @@ class PropertyFile(object):
     def show(self):
         """ Show contents of property file."""
         for line in self.lines:
-            print(line)
+            print line
 
     def insert_line(self, index, line):
         """ Insert line in property file """
diff --git a/base/common/python/pki/profile.py b/base/common/python/pki/profile.py
index 4f08ee5ba9527855f63b2785c32f9aaddc8d1289..eafd27515a792eef43dd83b007f77b55fb266967 100644
--- a/base/common/python/pki/profile.py
+++ b/base/common/python/pki/profile.py
@@ -7,6 +7,7 @@ Created on May 13,, 2014
 
 import json
 import types
+from lxml import etree
 
 import pki
 import pki.client as client
@@ -995,31 +996,98 @@ class ProfileClient(object):
         """
         return self._modify_profile_state(profile_id, 'disable')
 
+    def _send_profile_request(self, profile_data, operation):
+
+        if profile_data is None:
+            raise ValueError("No ProfileData specified")
+
+        if operation not in ['create', 'modify']:
+            raise ValueError("Invalid operation specified: " + str(operation))
+
+        profile_object = json.dumps(profile_data, cls=encoder.CustomTypeEncoder,
+                                    sort_keys=True)
+        r = None
+        if operation == 'create':
+            r = self._post(self.profiles_url, profile_object)
+        else:
+            if profile_data.profile_id is None:
+                raise ValueError("Profile Id is not specified.")
+            url = self.profiles_url + '/' + str(profile_data.profile_id)
+            r = self._put(url, profile_object)
+
+        return Profile.from_json(r.json())
+
+    @pki.handle_exceptions()
     def create_profile(self, profile_data):
         """
         Create a new profile for the given ProfileData object.
         """
-        if profile_data is None:
-            raise ValueError("No ProfileData specified")
-
-        profile_object = json.dumps(profile_data, cls=encoder.CustomTypeEncoder,
-                                    sort_keys=True)
-        r = self._post(self.profiles_url, profile_object)
-        return Profile.from_json(r.json())
+        return self._send_profile_request(profile_data, 'create')
 
+    @pki.handle_exceptions()
     def modify_profile(self, profile_data):
         """
         Modify an existing profile.
         """
-        if profile_data is None:
-            raise ValueError("No ProfileData specified")
+        return self._send_profile_request(profile_data, 'modify')
+
+    def _send_request_in_file(self, path_to_file, data_format, operation):
+
+        if path_to_file is None:
+            raise ValueError("File path must be specified.")
+
+        if data_format not in ['xml', 'json']:
+            raise ValueError("Unsupported data type: " + str(data_format))
+
+        if operation not in ['create', 'modify']:
+            raise ValueError("Invalid operation specified: " + str(operation))
+
+        data = None
+        with open(path_to_file) as input_file:
+            data = input_file.read()
+
+        if data_format == 'xml':
+            self.headers['Content-type'] = 'application/xml'
+
+        r = None
+        # Sending the data to the server.
+        if operation == 'create':
+            r = self._post(self.profiles_url, data)
+        else:
+            profile_id = None
+            if data_format == 'xml':
+                profile_id = etree.fromstring(data).get('id')
+            else:
+                profile_id = json.loads(data)['id']
+
+            if profile_id is None:
+                raise ValueError('Profile Id is not specified.')
+            url = self.profiles_url + '/' + profile_id
+            r = self._put(url, data)
+
+        # Reset the Content-type header to json(As used by other methods).
+        if data_format == 'xml':
+            self.headers['Content-type'] = 'application/json'
 
-        url = self.profiles_url + '/' + str(profile_data.profile_id)
-        profile_object = json.dumps(profile_data, cls=encoder.CustomTypeEncoder,
-                                    sort_keys=True)
-        r = self._put(url, profile_object)
         return Profile.from_json(r.json())
 
+    @pki.handle_exceptions()
+    def create_profile_using_file_input(self, path_to_file, data_format="xml"):
+        """
+        Create a new profile from a profile object stored in a file.
+        Acceptable data formats - json, xml.
+        """
+        return self._send_request_in_file(path_to_file, data_format, 'create')
+
+    @pki.handle_exceptions()
+    def modify_profile_using_file_input(self, path_to_file, data_format="xml"):
+        """
+        Modify a profile from a profile object stored in a file.
+        Acceptable data formats - json, xml.
+        """
+        return self._send_request_in_file(path_to_file, data_format, 'modify')
+
+    @pki.handle_exceptions()
     def delete_profile(self, profile_id):
         """
         Delete a profile.
@@ -1185,6 +1253,23 @@ def main():
     # pylint: disable-msg=W0703
     except Exception as e:
         print str(e)
+    print
+
+    # Creating a profile from file
+    print('Creating a profile using file input.')
+    print('------------------------------------')
+    original = profile_client.create_profile_using_file_input(
+        '/tmp/original.xml')
+    print(original)
+    print
+
+    # Modifying a profile from file
+    print('Modifying a profile using file input.')
+    print('------------------------------------')
+    modified = profile_client.modify_profile_using_file_input(
+        '/tmp/modified.xml')
+    print(modified)
+    print
 
 
 if __name__ == "__main__":
-- 
1.8.5.3

