
    !                         S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKJr  SSKJ	r	  SSKJ
r
  SS	KJr  SS
KJr  SSKJr  SrSrSrSrS rS rS rS rS rS rS rSS jr        SS jrg)a4  Generalized Apigee Management API request handler.

The Apigee Management APIs were designed before One Platform, and include some
design decisions incompatible with apitools (see b/151099218). So the gcloud
apigee surface must make its own HTTPS requests instead of relying on an
apitools-generated client.
    )absolute_import)division)unicode_literalsN)defaults)errors)resource_args)
properties)requests)urllibzapigee.googleapis.comz%s-apigee.googleapis.comerrormessagec                     [         R                  " 5       nU HU  n[        R                  U   nUR                  S-   nXP;  d  X   c   [
        R                  " UR                  5      eX   X$'   MW     U$ )a>  Returns an OrderedDict uniquely identifying the resource to be accessed.

Args:
  identifiers: a collection that maps entity type names to identifiers.
  entity_path: a list of entity type names from least to most specific.

Raises:
  MissingIdentifierError: an entry in entity_path is missing from
    `identifiers`.
Id)collectionsOrderedDictr   ENTITIESpluralr   MissingIdentifierErrorsingular)identifiersentity_pathresource_identifierentity_nameentityid_keys         0lib/googlecloudsdk/command_lib/apigee/request.py_ResourceIdentifierr   ,   sr     $//1 k##K0F]]T!F K$7$?))&//::"-"5 ! 
    c                     [         R                  " 5       R                  XX#SS9nUR                  nUR                  nUR
                  nXVU4$ )zHReturns HTTP status, reason, and response body for a given HTTP request.T)dataheadersstream)r
   
GetSessionrequeststatus_codereasoncontent)urlmethodbodyr!   responsestatusr&   r    s           r   _Communicater-   B   sQ      "**d + <(&??&			$		r   c                 r    [        U [        5      (       d!  [        U S5      (       a  U R                  5       n U $ )zReturns decoded string.

Args:
  response: the raw string or bytes of JSON data

Raises:
  ValueError: failure to load/decode JSON data
decode)
isinstancestrhasattrr/   )r+   s    r   _DecodeResponser3   L   s.     
Hc	"	"wx'B'B H	/r   c                     U =(       d    US   $ )z)Gets resource type from the inputed data. )entity_collectionr   s     r   _GetResourceTyper8   \   s    		-k"o-r   c                     [         R                  " U R                  5        VVs/ s H  u  pUR                  U4PM     snn5      $ s  snnf )z*Builds error identifier from inputed data.)r   r   itemsr   )r   keyvalues      r   _BuildErrorIdentifierr=   a   sF    		 	 .A.G.G.I".I
s||U.I" 
  "s   A
c                     [         R                  " U 5      n[        U;   a=  [        U[           [        5      (       a!  [
        U[           ;   a  U[           [
           $ g)zHExtracts error message from response, returns None if message not found.N)jsonloadsERROR_FIELDr0   dictMESSAGE_FIELD)r+   json_responses     r   _ExtractErrorMessagerE   h   sO    **X&-M!jK 
' '{!;;%m44	r   c                 D    [         R                  " U 5      n[        U5      $ )z2Returns the Apigee host based on the organization.)r   GetOrganizationLocation_GetApigeeHostByLocation)organizationlocations     r   _GetApigeeHostByOrganizationrK   r   s    --l;(	!(	++r   c                 @    U b  U S:X  d  U (       d  [         $ [        U -  $ )z.Returns the Apigee host based on the location.global)APIGEE_GLOBAL_HOSTAPIGEE_LEP_HOST)rJ   s    r   rH   rH   x   s"    X-X	8	##r   c
           	         0 n
U(       a  XzS'   U(       a  XZS'   [        X5      nS/nUR                  5        H2  u  pXR                  [        R                  R                  U5      /-  nM4     U(       aK  [        R                  U   R                  nUR                  [        R                  R                  U5      5        U(       a  [        R                  R                  U5      OSn[        R                  R                  R                  R                  5       nU	(       a  Sn[        U	5      nO^U(       a8  [        R                  R!                  U5      nUR"                  nUR$                  nOSnU R'                  SS5      n[)        U5      nSR+                  U5      nU(       a  US	   S
:X  a  UU-  nSnU(       a  Un[        R                  R-                  UUUSUS45      n[/        UX6U
5      u  nnnUS:  at  [1        X!5      nUS:X  a  [2        R4                  nO'US;   a  [2        R6                  nO[2        R8                  n[;        U5      n [=        [?        U5      5      nU" UUUUUUS9eUc$   [?        U5      n[B        RD                  " U5      nU$ U$ ! [@         a    Sn NBf = f! [@         a4  n[1        X!5      n[;        U5      n[2        RF                  " UUUU5      eSnAff = f)af  Makes a request to the Apigee API and returns the response.

Args:
  identifiers: a collection that maps entity type names to identifiers.
  entity_path: a list of entity type names from least to most specific.
  entity_collection: if provided, the final entity type; the request will not
    be specific as to which entity of that type is being referenced.
  method: an HTTP method string specifying what to do with the accessed
    entity. If the method begins with a colon, it will be interpreted as a
    Cloud custom method (https://cloud.google.com/apis/design/custom_methods)
    and appended to the request URL with the POST HTTP method.
  query_params: any extra query parameters to be sent in the request.
  accept_mimetype: the mimetype to expect in the response body. If not
    provided, the response will be parsed as JSON.
  body: data to send in the request body.
  body_mimetype: the mimetype of the body data, if not JSON.
  method_override: the HTTP method to use for the request, when method starts
    with a colon.
  location: the location of the apigee organization.

Returns:
  an object containing the API's response. If accept_mimetype was set, this
    will be raw bytes. Otherwise, it will be a parsed JSON object.

Raises:
  MissingIdentifierError: an entry in entity_path is missing from
    `identifiers`.
  RequestError: if the request itself fails.
zContent-TypeAcceptv1 httpsorganizationsIdN/r   :POSTi  i  )i  i  )	user_help)$r   r:   r   r   parsequoter   r   append	urlencoder	   VALUESapi_endpoint_overridesapigeeGetrH   urlparseschemenetlocgetrK   join
urlunparser-   r8   r   EntityNotFoundErrorUnauthorizedRequestErrorRequestErrorr=   rE   r3   
ValueErrorr?   r@   ResponseNotJSONError) r   r   r7   r)   query_paramsaccept_mimetyper*   body_mimetypemethod_overriderJ   r!   r   url_path_elementsr;   r<   collection_namequery_stringendpoint_overriderc   hostendpointrI   url_pathr(   r,   r&   r+   resource_typeexception_classerror_identifierrY   r   s                                    r   ResponseToApiRequestr{      s   N '	+N'H+KEf'--/jc**fll&8&8&?@@ 0#,,->?FFOV\\//@A9E''52, ''>>EEIIKF#H-D||$$%67H__F??DF??#4d;L'5DXX'((q	S HFfx\2 NO#)#vWE&&(s]$%6DM}22o	:	77o++o,-@A&x'@Ai -)96 (iA A 2 *hH%h 
//!  i  2&'8Fm./BC''}>N(02 22s*   J 1!J( J%$J%(
K&2/K!!K&)N)NGETNNNzapplication/jsonNN)__doc__
__future__r   r   r   r   r?   !googlecloudsdk.command_lib.apigeer   r   r   googlecloudsdk.corer	   googlecloudsdk.core.credentialsr
   	six.movesr   rN   rO   rA   rC   r   r-   r3   r8   r=   rE   rK   rH   r{   r6   r   r   <module>r      s    '  '   6 4 ; * 4  - ,, .
,$ ,0 %&*)-"'9)-"&lr   