MSWord API Developer Workshop 161204 Code Handouts

Embed Size (px)

Citation preview

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    1/26

    Gemini API Developer Workshop 1 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    Load login URL, Login,password data

    Instansiate theConnection

    Establish theconnetion

    Encode Username &Password

    ProcessResponse

    GEMINIAPIAUTHENTICATION &

    GEMINIAPIAUTHORIZATION

    LoginSuccessfull

    IncorrectPassword

    Change PasswordForced

    SMAUTHREASON

    4001 & 4002Unknown

    User4001 & NONE

    UserDisabled Password ExpiryWarning

    SMAUTHREASON'

    2001 &

    2002None 18

    PasswordExpired Immediate PasswordChange Required

    Maximum Failed Number of

    Login Attempts Exceeded1NONE 7

    19 20 24

    1. Login API Client (Java)

    1.1 Login API Client Activity Diagram

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    2/26

    Gemini API Developer Workshop 2 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    1.2 Load Configuration Files

    /*** Loads the properties that configure an API client.

    * @param fileName The name of the file that contains the properties.

    */

    public void loadFile(String fileName)throws Exception

    {

    try

    {

    // Create a FileInputStream object to read the property file that stores

    // the URLs for API, the URL of the XML request Schema and optionally the

    // Gemini API username and password.

    FileInputStream fin = new FileInputStream(fileName);

    // Instantiate the Properties object that stores the key value pair

    Properties config = new Properties();

    // Loads the properties object with the key value pairs in the property// file

    config.load(fin);

    // Close the file

    fin.close();

    }

    catch(Exception e)

    {

    throw e;

    }

    }1.3 Instantiate the Connection

    /**

    * Initialises the HTTPS connection for the client. The username* and password are encoded and passed to the web server for authentication

    * and authorization.

    */

    protected void initConnection()

    {

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    3/26

    Gemini API Developer Workshop 3 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    // Gemini expects that the username and password needs to be encoded with

    // the login URL

    String encodedLogin = Base64.base64Encode( username, password );

    // Get the URL fro Login

    String urlStr = property.getProperty( "login.url" );

    try{

    // Create the URL object for the login URL

    url = new URL( urlStr.trim());

    }

    catch( MalformedURLException e )

    {

    throw new ApiClientException( "Improper URL: " + urlStr );

    }

    // Open the connection to the URL

    conn = (HttpURLConnection)url.openConnection();

    // Set the request method to POST

    httpConn.setRequestMethod( POST );

    // Set the connection not to use the cacheconn.setUseCaches( false );

    // A URL connection can be used for input and/or output. Set the DoInput flag

    // to true if you intend to use the URL connection for input

    conn.setDoOutput( true );

    // A URL connection can be used for input and/or output. Set the DoOutput flag

    // to true if you intend to use the URL connection for output

    conn.setDoInput( true );

    // Set the Authorization request header with the encoded value of the username

    // and password

    conn.setRequestProperty( "Authorization", encodedLogin );

    //Set the Connection request header with the value Keep_Alive for establishing

    // a persistent connection

    conn.setRequestProperty( "Connection", "Keep-Alive" );

    //Set the Cookie request header with the value SMCHALLENGE=YES for notifying

    // Gemini that its a request for Login

    conn.setRequestProperty( "Cookie", "SMCHALLENGE=YES" );

    }

    Create the URL & Openthe connection

    Encode Username &

    Password & load

    login URL

    Initialise the HTTP

    request

    Set the HTTP RequestHeaders

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    4/26

    Gemini API Developer Workshop 4 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    1.4 Establish the Connection

    /**

    * Login to siteminder. Note that no input xml needs to be passed

    * to the web server and no information other than headers is

    * expected.

    */

    private void login()

    {

    try

    {

    conn.connect();

    }

    catch( IOException e )

    {

    throw new ApiClientException( "Unable to login: " + e.getMessage() );}

    }1.5 Process Response

    /**

    * Processes the response of API invocation.

    */

    protected void processResponse()

    {

    //remove earlier cookie info

    resetCookieInfo();

    //process response and create the cookie

    int count = 1;String key = null;

    boolean added = false;

    // Get the HTTP response headers key by using a counter variable

    while( (key = conn.getHeaderFieldKey( count )) != null)

    {

    Connect to the

    server

    Reset the earlier

    cookies info

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    5/26

    Gemini API Developer Workshop 5 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    // Get the corresponding value for the header key

    String value = conn.getHeaderField( count );

    if( key.equalsIgnoreCase( "Set-Cookie" ) )

    {

    // Check the response headers for Authentication/ Authorization

    boolean failed = getSecurityCheckStatus( key, value );// If the Authentication is failed reset the cookies and throw

    // an exception

    if( failed )

    {

    // Reset the Cookie

    resetCookieInfo();

    // Throw an exception

    throw new ApiClientException( "Failed security check." );

    }

    // Store the cookies so that it has to send with the

    // next request

    setCookieInfo( key, value );

    }

    // Increment the count of the headers read from the responsecount++;

    }

    }

    Read all the headers and

    store them in a data

    structure, as they need to

    be sent with the next API

    Call

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    6/26

    Gemini API Developer Workshop 6 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    1.6 Security Check

    /**

    * Checks the authentication / authorization status for the API invocation.

    * Once the API has been invoked, the response indicates whether or not the

    * call succeeded. Processes the HTTP(S) response headers to get this information* @param key The cookie key

    * @param value The cookie value that will be checked.

    * @return Falure status. true indicates successful security check.

    */

    private boolean getSecurityCheckStatus( String key, String value )

    {

    boolean failed = false;

    if( value.indexOf( "GEMINIAPIAUTHENTICATION=2001" ) != -1 )

    {

    //Successful Authentication

    failed = false;

    }

    if( value.indexOf( "GEMINIAPIAUTHORIZATION=2002" ) != -1 )

    {

    //Successful Authorization

    failed = false;

    }

    if( value.indexOf( "GEMINIAPIAUTHENTICATION=4001" ) != -1 )

    {

    //Authentication Failed

    failed = true;

    }

    if( value.indexOf( "GEMINIAPIAUTHORIZATION=4002" ) != -1 )

    {

    //Authorization Failed

    failed = true;

    }

    return failed;

    }1.7 Check Reason for Login Failure/*** Checks the reason for authentication / authorization failure for the

    * API invocation.

    *

    * @param key The cookie string that contains the "LOCATION" keyword.

    * @param value The cookie string that contains the value for "LOCATION."

    *

    Check value of the HTTP

    Set-Cookie header

    GEMINIAPIAUTHENTICATION

    &GEMINIAPIAUTHORIZATION

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    7/26

    Gemini API Developer Workshop 7 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    * @return The resason for failure.

    */

    private String checkReason( String key, String value )

    {

    String reason = "UNKNOWN";

    if( key.equalsIgnoreCase( "LOCATION" ) ){

    if( value.indexOf( "SMAUTHREASON=1")!=-1)

    {

    reason = "User must change password";

    }

    else if( value.indexOf( "SMAUTHREASON=2" )!=-1 )

    {

    reason = "Invalid session";

    }

    else if( value.indexOf( "SMAUTHREASON=3" )!=-1 )

    {

    reason = "Revoked session";

    }

    else if( value.indexOf( "SMAUTHREASON=4" )!=-1 )

    {

    reason = "Expired session";}

    else if( value.indexOf( "SMAUTHREASON=6" )!=-1 )

    {

    reason = "Unknown user";

    }

    else if( value.indexOf( "SMAUTHREASON=7" )!=-1 )

    {

    reason = "User disabled";

    }

    else if( value.indexOf( "SMAUTHREASON=8" )!=-1 )

    {

    reason = "Invalid session ID";

    }

    else if( value.indexOf( "SMAUTHREASON=18" )!=-1 )

    {

    reason = "Password expiry warning";

    }

    else if( value.indexOf( "SMAUTHREASON=19" )!=-1 )

    {

    reason = "Password expired";

    }

    else if( value.indexOf( "SMAUTHREASON=20" )!=-1 )

    Check value of the

    HTTP LOCATION header

    for the value ofSMAUTHREASON

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    8/26

    Gemini API Developer Workshop 8 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    {

    reason = "Immediate password change required";

    }

    else if( value.indexOf( "SMAUTHREASON=24" )!=-1 )

    {

    reason = "Max failed login attempts exceeded";

    }}

    return reason;

    }

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    9/26

    Gemini API Developer Workshop 9 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    2.0 Login API Client (VB)

    Called when the login button is clicked and invokes the function that logs on to GeminiPrivate Sub cmdOK_Click()

    Declare the clsAPI that handles the invoking of the API

    Dim objAPIClass As clsAPI

    Dim bolLoginRetval As Boolean

    Dim strUserID As String

    Dim strPassword As String

    On Error GoTo LabelErr

    Create the class module clsAPISet objAPIClass = New clsAPI

    Get the User Name and Password from the form strUserID = Trim(txtUserName.Text)

    strPassword = Trim(txtPassword.Text)

    Call the doLogin functionbolLoginRetval = objAPIClass.doLogin(strUserID, strPassword)

    If login is successful hide the login form and display the View Renomination details

    form

    If bolLoginRetval = True Then

    'Login is successful. Load frmXMHTTP

    Me.Hide

    'frmInvokeAPI.Show

    frmViewrenomination.Show

    End If

    Exit Sub

    If login fails display the error messageLabelErr:MsgBox "Login Form -- " + Err.Description

    End Sub

    Create the object

    of the classmoduleclsAPI

    Declare thevariables

    Call the function

    that does thelogin

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    10/26

    Gemini API Developer Workshop 10 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    2.1 Establishing Connection & Invoking Login API

    'Get the API Login URL, user id and password from the property file

    'Login to the URL using the XMLHTTP object

    'Check the return status code. If the login process is successful then return true elsereturn false

    Public Function doLogin(pi_userid As String, pi_password As String) As Boolean

    Declare MSXML.XMLHTTPRequest which would be used to send the login request to GeminiDim objXMLHTTP As MSXML.XMLHTTPRequest

    Dim strLoginURLString As String

    Dim strUserID As String

    Dim strPassword As String

    Dim strRetval As Boolean

    Dim bolSucFlag As Boolean

    Dim intFileNum As Integer

    Dim strDataLine As String

    On Error GoTo LocalErr

    'Get the login URL from the file

    intFileNum = FreeFile

    Open App.Path + "\APIURLs.config" For Input As intFileNum

    Do While EOF(intFileNum) = False

    Line Input #intFileNum, strDataLine

    Loop through till you find the API Login URL

    If InStr(1, strDataLine, "APILOGINURL") 0 Then

    strLoginURLString = Mid(strDataLine, 13)

    End If

    Loop

    Close the fileClose #intFileNum

    Display error message is the Login URL is not foundIf Trim(strLoginURLString) = "" Then

    MsgBox "Login URL not found", vbCritical, "Login URL not found"

    End

    End If

    Declare thevariables

    Load the Login URL

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    11/26

    Gemini API Developer Workshop 11 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    strUserID = pi_userid

    strPassword = pi_password

    bolSucFlag = False

    Create MSXML.XMLHTTPRequestSet objXMLHTTP = New MSXML.XMLHTTPRequest

    Open the connection with the parameters

    POST: The HTTP method used

    strLoginURLString: The Login URL

    Flase: To set the call is synchronous

    strUserID: The User Id

    strPassword: The Password

    objXMLHTTP.open "POST", strLoginURLString, False, strUserID, strPassword

    Send the requestobjXMLHTTP.send

    ' Check the status of authentication/authorization

    ' Get the handle to the headers through objXMLHTTP.getAllResponseHeaders and get the

    ' value of GEMINIAPIAUTHENTICATION & GEMINIAPIAUTHORIZATION

    If InStr(1, objXMLHTTP.getAllResponseHeaders, "GEMINIAPIAUTHENTICATION=2001") 0 Then

    'MsgBox "Authentication Successful"

    bolSucFlag = True

    End If

    If InStr(1, objXMLHTTP.getAllResponseHeaders, "GEMINIAPIAUTHORIZATION=2002") 0 Then

    'MsgBox "Authorization Successful"

    bolSucFlag = True

    End If

    If InStr(1, objXMLHTTP.getAllResponseHeaders, "GEMINIAPIAUTHENTICATION=4001") 0 Then

    MsgBox "Authentication Failure", vbCritical, "Error"

    bolSucFlag = False

    End If

    If InStr(1, objXMLHTTP.getAllResponseHeaders, "GEMINIAPIAUTHORIZATION=4002") 0 Then

    MsgBox "Authorization Failure", vbCritical, "Error"bolSucFlag = False

    End If

    Create the

    object ofXMLHTTPRequest

    Open the connection

    and send the

    request

    Check value of

    GEMINIAPIAUTHENTICATION

    &

    GEMINIAPIAUTHORIZATION

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    12/26

    Gemini API Developer Workshop 12 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    ' In case of authentication/authorization failure, the LOCATION header

    ' key needs to be checked to obtain supplimentary information

    If (bolSucFlag = False And InStr(1, objXMLHTTP.getAllResponseHeaders, "LOCATION") 0)

    Then

    If InStr(1, objXMLHTTP.getAllResponseHeaders, "SMAUTHREASON=1") 0 Then

    MsgBox "User must change password"End If

    End If

    'Similar checks must be done for other SMAUTHREASON values

    doLogin = bolSucFlag

    Set objXMLHTTP = Nothing

    Exit Function

    ' Display the error message

    LocalErr:

    MsgBox Err.Description, vbCritical, "Login Error"

    End Function

    Check value of the

    HTTP LOCATION header

    for the value ofSMAUTHREASON

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    13/26

    Gemini API Developer Workshop 13 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    3.0 Query / Update API Activity Diagram

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    14/26

    Gemini API Developer Workshop 14 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    4.0 View System Status History API (Java)

    4.1 Load the URL

    /**

    * Loads the URL for the System Status History API from the properties object.

    */

    public String getUrl()

    {

    // Get the System Status History API URL from the properties object

    String strSuffix = props.getProperty("systemstatushistory.url");

    // Add the URL to the base URL of the Gemini Server

    return (baseUrl + strSuffix);

    }

    4.2 Get the Input Data and Create the Input Xml

    /**

    * Get the Input data and Create the input XML for the API call.

    */protected void createInputXml()

    {

    // Create the Request XML Root element

    Document document = createDocument("NM_SYS_HSTRY_QRY");

    Element root = (Element)document.getDocumentElement();

    //Create XML elements specific to ShipperBalance

    Element gasDay = (Element)document.createElement("CLNDR_DAY");

    //get data from the data source

    SystemStatusHistoryDataSource source = new SystemStatusHistoryDataSource();

    SystemStatusHistoryData data = (SystedtatusHistoryData)source.getData();

    gasDay.appendChild(document.createTextNode(data.strGasDay));

    root.appendChild(gasDay);

    //Get the input xml as a String from the DOM object

    OutputFormat format = new OutputFormat( document );

    StringWriter stringOut = new StringWriter();

    XMLSerializer serial = new XMLSerializer( stringOut, format );

    try

    {

    Load the URL for

    the System StatusHistoryAPI

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    15/26

    Gemini API Developer Workshop 15 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    serial.asDOMSerializer();

    serial.serialize(document.getDocumentElement());

    }

    catch( IOException e )

    {

    throw new ApiClientException( "Error in serializing input xml:");

    }

    inputXml = stringOut.toString();

    // Append the input xml to StringINPUT. This will add the created xml as a

    // request parameter in the HTTP Request Body

    inputXml = "INPUT=" + inputXml;

    }4.3 Prepare the Cookie

    /**

    * Prepare the cookie used for this API invocation. This cookie is

    * obtained during login and is subsequently updated after each API

    * invocation. This method constructs a comma separated string of the cookie

    */

    protected String prepareCookie(){

    // Setting the request properties on the url connection object

    String cookieValue = "";

    for(int z=0; z

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    16/26

    Gemini API Developer Workshop 16 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    }4.4Initialise the HTTPS URLConnection.

    /*** Initializes the HTTPS URLConnection.

    */

    protected void initConnection()

    {

    // Get the URL fro Login

    String urlStr = getUrl();

    try

    {

    // Create the URL object for the login URL

    url = new URL( urlStr.trim());

    }

    catch( MalformedURLException e )

    {

    throw new ApiClientException( "Improper URL: " + urlStr );

    }

    // Open the connection to the URL

    conn = (HttpURLConnection)url.openConnection();

    // Set the request method to POST

    httpConn.setRequestMethod( POST );

    // Set the connection not to use the cache

    conn.setUseCaches( false );

    // A URL connection can be used for input and/or output. Set the DoInput flag

    // to true if you intend to use the URL connection for input

    conn.setDoOutput( true );

    // A URL connection can be used for input and/or output. Set the DoOutput flag

    // to true if you intend to use the URL connection for output

    conn.setDoInput( true );

    }

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    17/26

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    18/26

    Gemini API Developer Workshop 18 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    {

    throw new ApiClientException( "Error getting response code: ");

    }

    //check response content type

    String contentType = conn.getContentType();

    if( !contentType.equals( "text/xml" ) )

    {

    String responseStr = getResponse();

    write( responseStr, errHtml );

    String msg = "Error: Unexpected Content-type ";

    throw new ApiClientException( msg );

    }

    // Create the Output XML

    createOutputXml();

    }4.6 Create Response XML/**

    * Creates the response xml for the API invocation.*/

    protected void createOutputXml()

    {

    String response = getResponse();

    String filename = this.getClass().getName().toLowerCase() + "res.xml";

    write( response, filename );

    }

    /**

    * Gets the HTTP(S) response for the API invocation.

    */

    protected String getResponse()

    {

    StringBuffer sb = new StringBuffer();

    try

    {

    InputStream is = conn.getInputStream();

    InputStreamReader ins = new InputStreamReader(is);

    BufferedReader br = new BufferedReader( ins );

    String line = null;

    while( (line=br.readLine()) != null )

    If content type is not

    text/xml handle the

    errror

    Get the Input Stream

    of the connection andread the XML

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    19/26

    Gemini API Developer Workshop 19 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    {

    sb.append( line );

    }

    br.close();

    }

    catch( IOException e )

    {

    throw new ApiClientException( "Error: Unable to get response from host");

    }

    return sb.toString();

    }4.7 Process Response Headers/**

    * Processes the response of API invocation.

    */

    protected void processResponse()

    {

    //remove earlier cookie info

    resetCookieInfo();

    //process response and create the cookie

    int count = 1;

    String key = null;

    boolean added = false;

    // Get the HTTP response headers key by using a counter variable

    while( (key = conn.getHeaderFieldKey( count )) != null)

    {

    // Get the corresponding value for the header key

    String value = conn.getHeaderField( count );

    if( key.equalsIgnoreCase( "Set-Cookie" ) )

    {

    // Check the response headers for Authentication/ Authorization

    boolean failed = getSecurityCheckStatus( key, value );// If the Authentication is failed reset the cookies and throw

    // an exception

    if( failed )

    {

    // Reset the Cookie

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    20/26

    Gemini API Developer Workshop 20 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    resetCookieInfo();

    // Throw an exception

    throw new ApiClientException( "Failed security check." );

    }

    // The Application server maintain the client session using the

    // cookie called JSESSIONID. Check if the cookie JSESSIONID is

    // present in the response headers

    if (value.indexOf("JSESSIONID")!=-1 && !added)

    {

    // The variable jSessionId is used to store the value of

    // the JSESSIONID cookie.

    if (jSessionId == null)

    {

    // Client has received the value for the first

    // time

    jSessionId = value;

    }

    else

    {

    // SessionId reassigned

    value = jSessionId;

    }// Store the cookies so that it has to send with the

    // next request

    setCookieInfo( key, value);

    added = true;

    }

    else

    {

    // Store the cookies so that it has to send with the

    // next request

    setCookieInfo( key, value );

    }

    }

    // Increment the count of the headers read from the response

    count++;

    }

    }

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    21/26

    Gemini API Developer Workshop 21 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    5.0 View Renomination Details API (VB)

    5.1 Creating API Request XML

    Dim strXMLContent As String

    Creates the request xml using the values entered by the user send the API request to

    Gemini and receives the response

    Private Sub Submit_Click()

    Dim xmlDoc As New DOMDocument

    Dim strSchemaName As String

    Dim strGasDay As String

    Dim strServiceId As String

    Dim strActivityNumber As String

    Dim objAPIClass As clsAPI

    Dim strAPIName As String

    Dim strInputXML As String

    Dim strAPIRetVal As String

    Dim strUrlstring As String

    Dim Str As String

    Get the data entered by the userstrGasDay = Trim(txtgasday.Text)

    strActivityNumber = Trim(txtActivityNmb.Text)

    strServiceId = Trim(txtServiceId.Text)

    Set the name of the API request Schema

    strSchemaName = "geminiapiviewrenominationdetailsreq"

    Set the URL for View Renomination Details APIstrUrlstring = Trim(urltxt.Text)

    Dim success As Boolean

    Create the View Renominations Request XML

    strXMLContent = "" + strGasDay +

    "" + strServiceId + "" + strActivityNumber +

    ""

    Declare thevariables

    Get the Inputdata

    Create the Input

    XML

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    22/26

    Gemini API Developer Workshop 22 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    Create the clsAPI class moduleSet objAPIClass = New clsAPI

    Append the base URL to View Renominations Details the API URL

    'Get the View Renominations Details URL from the fileintFileNum = FreeFile

    Open App.Path + "\APIURLs.config" For Input As intFileNum

    Do While EOF(intFileNum) = False

    Line Input #intFileNum, strDataLine

    Loop through till you find the API View Renominations URL

    If InStr(1, strDataLine, "APIVIEWRENOMINATIONS") 0 Then

    strUrlstring = Mid(strDataLine, 13)

    End If

    Loop

    Close the fileClose #intFileNum

    strAPIName = strUrlstring

    If strXMLContent "" Then

    Append INPUT= to the API request XML, which will be posted to the URL as a

    Request Parameter

    strInputXML = "INPUT=" & strXMLContent

    Text2.Text = ""

    Else

    errorlbl.Caption = " Input xml not proper..."

    End If

    errorlbl.Caption = "Contacting API server..."

    DoEvents

    Call the API and send the API URL and the API Request XML as parametersstrAPIRetVal = objAPIClass.callAPI(strAPIName, strInputXML)

    DoEvents

    errorlbl.Caption = "Response received !"

    Text2.Text = strAPIRetVal

    Create the

    object of class

    module clsAPI

    Load the View

    Renominations Details

    URL

    Call the function

    that calls theAPI

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    23/26

    Gemini API Developer Workshop 23 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    Response is received hide the form and show the Output form where the details

    will be displayed

    Me.Hide

    frmViewRenominationoutput.Show

    Else

    If there is an error display the error message

    errorlbl.Caption = "Unable to load the XML Content " & strXMLContentEnd If

    Else

    frmViewrenomination.Show

    End If

    End Sub

    5.2 Establishing Connection & Invoking View Renominations Details APIPublic Function callAPI(strAPIName As String, strInputXMLString) As String

    'Get the full URL of the API from the property file

    'Open a connection to this URL using XMLHTTP object

    'Set the content type to "application/x-www-form-urlencoded"

    'Send the input XML

    'Check the status code.

    'If status code is a success then extract the output URL from the response text

    'of the XMLHTTP object and return the value

    'If status code is a failure then return a value of -1

    Dim objXMLHTTP As MSXML.XMLHTTPRequest

    'Dim strAPIName1 As String

    'Dim strInputXMLString1 As String

    On Error GoTo LocalErr

    Set objXMLHTTP = New MSXML.XMLHTTPRequest

    objXMLHTTP.open "POST", strAPIName, False

    objXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

    Handle Response

    Create the XMLHTTPRequest object

    and open the connection. Set the

    request header content-type to

    application/x-www-form-

    urlencoded

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    24/26

    Gemini API Developer Workshop 24 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    Send the Input XML to the server

    objXMLHTTP.send strInputXMLString

    Get the XML response back

    callAPI = objXMLHTTP.responseText

    Set objXMLHTTP = Nothing

    Exit Function

    LocalErr:

    MsgBox Err.Description, vbCritical, "Error"

    End Function

    Send the XML

    request and

    get the XML

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    25/26

    Gemini API Developer Workshop 25 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    6.0 Update Renominations API (Java)

    6.1 Creating Input XML/**

    * Create the input XML for the API call.*/

    protected void createInputXml()

    {

    Document document = createDocument("UPDT_RNM");

    Element root = (Element)document.getDocumentElement();

    //Create XML elements specific to Update Renominations

    Element elgasDay = (Element)document.createElement("GAS_DAY");

    Element elServiceId = (Element)document.createElement("SERVC_ID");

    //get data

    //UpdateRenominationsDataSource source = new UpdateRenominationsDataSource();

    //UpdateRenominationsData data = (UpdateRenominationsData)source.getData();

    hUpdateRenoms=(HashMap)data.hUpdateRenoms;

    if(hUpdateRenoms!=null)

    {alUpdateRenoms=(ArrayList)hUpdateRenoms.get("update_renoms_data");

    gasday=(String)hUpdateRenoms.get("gas_day");

    serviceId=(String)hUpdateRenoms.get("service_id");

    }

    elgasDay.appendChild(document.createTextNode(gasday));

    elServiceId.appendChild(document.createTextNode(serviceId));

    root.appendChild(elgasDay);

    root.appendChild(elServiceId);

    int iSize = alUpdateRenoms.size();

    for(int i=0; i

  • 8/14/2019 MSWord API Developer Workshop 161204 Code Handouts

    26/26

    Gemini API Developer Workshop 26 of 26 Document ReferenceVersion 1

    NGT Confidential Date: 16/12/2004

    String startTime =""+updateRenominationsInfo.getStartTime();

    elStartTime.appendChild(document.createTextNode(startTime));

    elDetail.appendChild(elStartTime);

    Element elRequestedEnergy=(Element)document.createElement("REQ_NRG");

    String requestedEnergy=""+updateRenominationsInfo.getRequestedEnergy();

    elRequestedEnergy.appendChild(document.createTextNode(requestedEnergy));

    elDetail.appendChild(elRequestedEnergy);

    Element elToleranceFlag=(Element)document.createElement("IGNR_TLRNCE");String toleranceFlag=updateRenominationsInfo.getToleranceFlag();

    elToleranceFlag.appendChild(document.createTextNode(toleranceFlag));

    elDetail.appendChild(elToleranceFlag);

    root.appendChild(elDetail);

    }

    //get the input xml

    inputXml = getInputXmlString( document );

    String strName = getClass().getName().toLowerCase();

    write(inputXml, strName + "req.xml" );

    inputXml = "INPUT=" + inputXml;

    }