In this case, we are querying against the accounts service, and it returns data in a .csv type format. We will then re-format this according to our own needs (pipelined function.)
FUNCTION FETCH_EMAILS(AUTH_TOKEN_IN IN VARCHAR2) RETURN CLOB IS
/***
** Function: FETCH_EMAILS
** Params: AUTH_TOKEN_IN = Authorization token used for API call.
** Returns: A CLOB formatted in the fashion of a .csv.
** Description: Uses an XML POST request to Google reports API to get back all emails (and
** assorted settings) in .csv format.
***/
--declare variables
L_REQUEST UTL_HTTP.REQ;
L_RESPONSE UTL_HTTP.RESP;
V_REQUEST_BODY VARCHAR2(4000);
V_RESP_CLOB CLOB;
STRING_CHECK VARCHAR2(32767);
V_MESSAGE VARCHAR2(4000);
PAGE_STRING VARCHAR2(4000);
PAGE_NUMBER NUMBER;
BEGIN
IF (SUBSTR(AUTH_TOKEN_IN, 1, 5) != 'Error')
THEN
--Open CLOB
DBMS_LOB.CREATETEMPORARY(V_RESP_CLOB, TRUE);
DBMS_LOB.OPEN(V_RESP_CLOB, DBMS_LOB.LOB_READWRITE);
--Get the number of pages needed
PAGE_NUMBER := ROUND(GET_ACCOUNT_NUM(AUTH_TOKEN_IN) / 10000) + 1;
FOR I IN 1 .. PAGE_NUMBER
LOOP
--Make a string for the current page of the request.
PAGE_STRING := '<page>' || I || '</page>';
--Format the request body into proper rest protocol.
V_REQUEST_BODY := q'|<?xml version="1.0" encoding="UTF-8"?>
<rest xmlns="google:accounts:rest:protocol"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<type>Report</type>
<token>|' || AUTH_TOKEN_IN ||
'</token>
<domain>' || V_DOMAIN ||
'</domain>
<date>' || V_DATE || '</date>' || PAGE_STRING ||
'<reportType>daily</reportType>
<reportName>accounts</reportName>
</rest>';
L_REQUEST := UTL_HTTP.BEGIN_REQUEST('https://www.google.com/hosted/services/v1.0/reports/ReportingData'
,'POST'
,'HTTP/1.1');
-- request headers setup
UTL_HTTP.SET_HEADER(L_REQUEST, 'Content-Type', 'application/x-www-form-urlencoded');
UTL_HTTP.SET_HEADER(L_REQUEST, 'Content-Length', LENGTH(V_REQUEST_BODY));
-- end of request headers setup
-- write out the request body
UTL_HTTP.WRITE_TEXT(L_REQUEST, V_REQUEST_BODY);
-- request/get the response
L_RESPONSE := UTL_HTTP.GET_RESPONSE(R => L_REQUEST);
--Loop to read response until we reach 'end of body', in which case we are done.
BEGIN
LOOP
UTL_HTTP.READ_TEXT(L_RESPONSE, STRING_CHECK);
DBMS_LOB.WRITEAPPEND(V_RESP_CLOB, LENGTH(STRING_CHECK), STRING_CHECK);
END LOOP;
UTL_HTTP.END_RESPONSE(R => L_RESPONSE);
EXCEPTION
WHEN UTL_HTTP.END_OF_BODY THEN
NULL;
END;
UTL_HTTP.END_RESPONSE(R => L_RESPONSE);
END LOOP;
ELSE
V_MESSAGE := 'There was an error in fetching authentication token: ' || AUTH_TOKEN_IN;
RDSPRD.RDS_MAIL.MAIL(ADMIN_EMAIL, ADMIN_EMAIL, 'ERROR: Google Report Tools@' || ADMIN_SERVER, V_MESSAGE);
END IF;
--Need to replace all the header rows (1 per page) with a blank so that pipelined function doesn't output them.
RETURN REGEXP_REPLACE(V_RESP_CLOB, '^date.*' || CHR(10), '', MODIFIER => 'm');
END;
No comments:
Post a Comment