Skip to Content

Overview:

Here we will see

  • Using SAP-PI UDF (Java), we consume SharePoint REST to write a File into SharePoint.
  • A business requirement, where employee’s pending item counts need to be updated in SharePoint in file format.
  • Employee’s Pending Count will be fetched from one system’s REST service and resulted string will be posted into a file format in SharePoint.
  • Fetching Employee’s Pending Count via respective REST service will be handled in separate UDF-1 and its result will be supplied to this SharePoint UDF-2.
  • Here we focus on java coding of “SharePoint UDF-2”
  • To access SharePoint, we need to fetch AccessToken first which can be get by following link help:

 

JavaCode to Create a file in SharePoint:

  • Here we try to write a constant string into SharePoint in FileFormat
  • This constant string can be replaced by desired strings like employee’s pendingCount data as described in Overview section
  • AccessToken required for SharePoint authentication which can be found from above mentioned link.
/*
  Sharepoint REST details to create a file:
  url: http://<siteUrl>/_api/web/GetFolderByServerRelativeUrl('/<FolderName>')/Files/add(url='<fileName>',overwrite=true)
  method: POST
  headers:
      Authorization: "Bearer " + accessToken			
  body: "Contents of file"
*/

  //Frame Sharepoint REST URL to create a File
  String siteURL = "https://<host>/<siteURL_path>";	//here <siteURL_path> is '/teams/SPdev/AlertsCount'	
  String wsUrl = siteUrl + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files/add(url='File1.txt',overwrite=true)";	

  //Data to be written in File			
  String request = "Create a File with raw string !!!";
				
  //Create HttpURLConnection
  URL url = new URL(wsUrl);
  URLConnection connection = url.openConnection();
  HttpURLConnection httpConn = (HttpURLConnection) connection;
			
  //Set Header
  httpConn.setDoOutput(true);
  httpConn.setDoInput(true);	
  httpConn.setRequestMethod("POST");				
  httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);

  //Send Request
  DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream ());
  wr.writeBytes(request);
  wr.flush();
  wr.close();
				
  //Read the response.
  String responseStr = "";
  if (httpConn.getResponseCode() == 200) {
    responseStr = "File has been written successfully. ResponseCode: "+ httpConn.getResponseCode();
  }else{
    responseStr += "Error while writing file, ResponseCode: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage();
  }	
  
  //System.out.println(httpResponseStr);	//Print response
	

 

Testing Status in SharePoint:

 

 

Blog updated on 24-Jul2018 with following contents:

Lets see how we can read files present in some specific folder in SharePoint.

Here, in following examples, we will read files from default folder ‘Documents’ which while accessing referred as ‘Shared Documents’.

[1] JavaCode to retrieve all files of a folder from SharePoint:

/*
Sharepoint REST details to retrieve all of the files in a folder
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files
method: GET
headers:
    Authorization: "Bearer " + accessToken
    accept: "application/json;odata=verbose" or "application/atom+xml"
*/
try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<siteURL_path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
   httpConn.setRequestProperty("accept", "application/json;odata=verbose"); //To get response in JSON
   //httpConn.setRequestProperty("accept", "application/atom+xml");         //To get response in XML
   
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 

[2] JavaCode to retrieve a specific file from SharePoint:

/*
Sharepoint REST details to retrieve a specific file
url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files('file name')/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken
*/

try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/Files('XYZ.txt')/$value";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
  
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 

[3] JavaCode to retrieve a specific file from SharePoint when you know file’s URL:

/*
Sharepoint REST details to retrieve a file with its URL
url: http://site url/_api/web/GetFileByServerRelativeUrl('/Folder Name/file name')/$value
method: GET
headers:
    Authorization: "Bearer " + accessToken
*/

try {		
   //Frame SharePoint siteURL			
   String siteURL = "https://<host>/<siteURL_path>";
		
   //Frame SharePoint URL to retrieve all of the files in a folder
   //URL-Type-1
   String wsUrl = siteURL + "/_api/web/GetFileByServerRelativeUrl('/<siteURL_path>/Shared%20Documents/XYZ.txt')/$value";

   //URL-Type-2
   //String wsUrl = siteURL + "/_api/Web/GetFileByServerRelativePath(decodedurl='/<siteURL_path>/Shared%20Documents/XYZ.txt')/$value";
	
   //Create HttpURLConnection
   URL url = new URL(wsUrl);
   URLConnection connection = url.openConnection();
   HttpURLConnection httpConn = (HttpURLConnection) connection;
						
   //Set Header		
   httpConn.setRequestMethod("GET");				
   httpConn.setRequestProperty("Authorization", "Bearer " + accessToken);
  
   //Read the response
   String httpResponseStr = "";
   InputStreamReader isr = null;
   if (httpConn.getResponseCode() == 200) {
     isr = new InputStreamReader(httpConn.getInputStream());
   } else {
     isr = new InputStreamReader(httpConn.getErrorStream());
   }		
   BufferedReader in = new BufferedReader(isr); 	 		
   String strLine = "";
   while ((strLine = in.readLine()) != null) {
     httpResponseStr = httpResponseStr + strLine;
   }
   //System.out.println(httpResponseStr);	//Print response
} catch (Exception e) {
   //System.out.println("Error while reading file: " + e.getMessage());
}		

 

To report this post you need to login first.

6 Comments

You must be Logged on to comment or reply to a post.

    1. Dilip Kumar KrishnaDev Pandey Post author

      Dear Former Member

      Sorry for delayed response, I was too much busy in my current project….

      This is working in PI 7.1 and PO 7.5.

      But I’ve not tried this in XI version, it should work because this is UDF logic to call REST service with POST method, jre1.4 too is supported with this piece of code.

       

      Thanks & Regards

      Dilip

       

      (0) 
  1. Antony FERMINUS

    Hi Dilip,

    Thanks for the blog.

    I get error HTTP ResponseCode: 404 Not Found.

    I have the token. The url is also correct. I use PO 7.5.

    Is it a kind of permission issue to upload the file?

     

    regards,

    Antony.

    (0) 
  2. vinay mittal

    Hi Guys ,

     

    I am stuck!, First of all thanks Dilip for such a wonderful blog. I am able to get the access token  by the client id/secret etc.

    I am calling this API 

    https://xxxx.sharepoint.com/_api/web/GetFileByServerRelativeUrl('/sites/hub/dept/COTraining/Wisam/Shared%20Documents/BushfireAreas.txt‘)/$value to read the file but it says File doesnt exist!

     

    am I doing some mistake in the url creation? Authentication works fine as i was getting a 200 OK on this dummy API request

    https://<sitename&gt;.sharepoint.com/_api/web?$select=Title

     

    Do i need to add some special permissions to the target sharepoint team site?

     

     

    (0) 
    1. Dilip Kumar KrishnaDeo Pandey Post author

      Hi,

      • Please cross verify if folder ‘Documents’ has same file in SharePoint.
      • As per your error, seems to be file not present at same location.
      • And no extra permission required, as your code is able to view the Folder.
      • And I am updating this blog too with File Read info for others benefit…….

       

      Thanks & Regards,

      Dilip

      (0) 

Leave a Reply