Technology Blogs by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
Former Member
0 Kudos

Introduction

In most of the enterprise portal applications, we may come across a requirement of uploading a file or an image from one part of the application and later access these files or images from the other part of the same application or from a different application. This requires the uploaded files to be stored somewhere. One of the various possible solutions is to maintain these files in the Microsoft SharePoint server. The Microsoft SharePoint server provides couple of standard web services to achieve this. In this article, I have tried to explain the details of the standard web services to be used and step by step procedure to consume them in Web Dynpro Java application.

Prerequisites

  • Microsoft SharePoint server is available and a site-collection/workspace is created in the server for maintaining the documents.
  • A group of users or a generic user id is given the full permission (read, write and delete) on the site collection. In other words assigned as site owner to the above created site collection.
  • The type of authentication in SharePoint system should be set as HTTP basic authentication instead of default Microsoft specific setting.
  • The standard web services dws.asmx, copy.asmx and lists.asmx are downloaded from the SharePoint server as explained later.
  • A Web Dynpro Java application is created with the UIs to allow the user to upload and download files. Adaptive web service model is created for the dws.asmx and copy.asmx web services. Lists.asmx cannot be used as Adaptive web service as explained later, so it can be consumed in an EJB DC and this EJB can be used in WDJ application as an Enterprise Java Bean Model.

 

Step by Step Solution

Downloading the web services provided by the SharePoint server

If the URL for the SharePoint server is http://<Host Name>:<Port>/sites/shp/, the wsdl file can be downloaded by using the below mentioned links.

Shared Documents is the default folder available in the site collection. DWS.asmx web service can be used to create and delete folder and subfolders under the document library (Shared Documents). Copy.asmx can be used to upload and download files and Lists.asmx can be used to delete a file.

Creating the Folder structure under the Document Library/Shared Documents

As mentioned earlier, DWS.asmx will be used for this purpose. Below are the details of the method in DWS that will be used to create a folder/subfolder.

  • Method Name: CreateFolder
  • Input Parameter: url (String). Example:  “Shared Documents/Test Folder”, to create a folder named Test Folder under the Document library/Shared Documents and  “Shared Documents/Test Folder/Sub Folder”, to create a subfolder named Sub Folder under the folder named Test Folder.
  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.
  • Return: On successful creation of the folder/sub-folder, this will return an empty tag. In case of error, the Result tag will hold the error message.

Write the below mentioned code in the method that will be called to create a folder with the given name, assuming the user enters even the path under which the folder has to created as explained earlier.

SPDWSModel model = new SPDWSModel();

Request_CreateFolder request = new Request_CreateFolder(model);

try{

     CreateFolder createFolder = new CreateFolder(model);

     request.setCreateFolder (createFolder);

     createFolder.setUrl(<Folder Path/Folder Name>);

     request.wdSetInvocationModifier(new IWDWSInvocationModifier(){

          public void doModifyInvocation(final Object port) {

               if (port instanceof Stub) {

                    final Stub stub = (Stub)port;

                    stub._setProperty(Stub.USERNAME_PROPERTY, <User Id>);

                    stub._setProperty(Stub.PASSWORD_PROPERTY, <Password>);

               }

               else if (port instanceof DInterfaceInvoker) {

                    final DInterfaceInvoker invoker = (DInterfaceInvoker)port;

                    invoker.setProperty(Stub.USERNAME_PROPERTY, <User Id>);

                    invoker.setProperty(Stub.PASSWORD_PROPERTY, <Password> );

               }

               else throw new RuntimeException("User not autherized");

          }

          public void doModifyAfterInvocation() {}

     });    

     request.execute();

     if(request.getResponse() != null){

          String result = request.getResponse().getCreateFolderResponse().getCreateFolderResult();

          if(null != result){

               wdComponentAPI.getMessageManager().reportSuccess("Folder Created Successfully");

          }

          else{

               wdComponentAPI.getMessageManager().reportException("Folder not Created");

          }

     }

}

catch (WDWSModelExecuteException e) {

     wdComponentAPI.getMessageManager().reportException(e.toString());

}

Similarly DeleteFolder method can be used to delete the folder/sub-folder. Below are the details of the method.

  • Method Name: DeleteFolder
  • Input Parameter: url (String). Example:  “Shared Documents/Test Folder”, to delete a folder named Test Folder under the Document library/Shared Documents folder.
  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.
  • Return: On successful deletion of the folder/sub-folder, this will return an empty <Result/> tag. In case of error, the Result tag will hold the error message. 

Upload a file into the target folder in the Site collection

As mentioned earlier copy.asmx web service will be used for this purpose. Below are the details of the method in Copy that will be used to upload a file into the target folder.

  • Method Name: CopyIntoItems
  • Input Parameters:
    1. SourceUrl (String): Absolute source URL, of the document to be copied. Example: “http://null”, in case the file is uploaded from the local system. In our case this should always be “http://null”. In case of copying a file from one folder in share point to another it will be the absolute URL of the file.
    2. DestinationUrls (Strings): One or more absolute URLs, specifying the destination location or locations, for the copied document. Example: “http://<Host Name>:<Port>/sites/shp/Shared Documents/Test Folder/Test.txt”, if a file named “Test.txt” is being uploaded into a folder named “Test Folder”, placed under Shared Documents(Document Library).
    3. Stream (array of bytes): The byte array representation of the file has to be passed through this.
    4. Fields (array of FieldInformation) (Optional): An array of FieldInformation objects that define the optionally assigned values to one or more fields, associated with the copied document.
  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.

Write the below mentioned code in the method that will be called to upload the selected file with the given name, assuming the user enters even the path under which the file has to uploaded into as explained earlier.

IWDResource resource = wdContext.currentContextElement().getVa_Resource();

String destinationUrl = "http://<Host Name>:<Port>/sites/shp/";

String sourceUrl = "http://null";

SPCopyModel model = new SPCopyModel();

Request_CopyIntoItems request = new Request_CopyIntoItems(model);

try{

     CopyIntoItems copyItem = new CopyIntoItems(model);      

     copyItem.setSourceUrl(sourceUrl); //Populating the source url      

     DestinationUrlCollection destUrl = new DestinationUrlCollection(model);

     String_Item urlString = new String_Item(model);

     urlString.setItem(destinationUrl + <Folder Path> + resource.getResourceName());      

     destUrl.addString(urlString);

     copyItem.setDestinationUrls(destUrl); //Populating the destination url

     FieldInformationCollection fieldCollection = new FieldInformationCollection(model);      

     copyItem.setFields(fieldCollection); //Populating the optional field info

     request.setCopyIntoItems(copyItem);

     InputStream inputStream = resource.read(false);

     int noOfBytes = inputStream.available();

     byte[] byteArray = new byte[noOfBytes];

     inputStream.read(byteArray, 0, noOfBytes);

     copyItem.setStream(byteArray); //Populating the stream

     request.wdSetInvocationModifier(new IWDWSInvocationModifier(){    

          public void doModifyInvocation(final Object port) {    

               if ( port instanceof Stub ) {    

                    final Stub stub = (Stub)port;    

                    stub._setProperty(Stub.USERNAME_PROPERTY, <User Id>);    

                    stub._setProperty(Stub.PASSWORD_PROPERTY, <Password>);    

               }

               else if (port instanceof DInterfaceInvoker) {    

                    final DInterfaceInvoker invoker = (DInterfaceInvoker)port;    

                    invoker.setProperty(Stub.USERNAME_PROPERTY, User Id);    

                    invoker.setProperty(Stub.PASSWORD_PROPERTY, Password);           

               }

               else     throw new RuntimeException("User not autherized");    

          }

          public void doModifyAfterInvocation() {}      

     });

     request.execute();

     if(request.getResponse() != null){

          CopyResult copyResult = (CopyResult) request.getResponse().getCopyIntoItemsResponse().getResults().getCopyResult().get(0);

          String errorCode = copyResult.getErrorCode();    

          String returnDestUrl = copyResult.getDestinationUrl();    

          String message = copyResult.getErrorMessage();    

          if("Success".equalsIgnoreCase(errorCode)){    

               wdComponentAPI.getMessageManager().reportSuccess("File Uploaded Successfully.");    

          }    

          else{

               wdComponentAPI.getMessageManager().reportException("File not Uploaded.");    

          }

     }

}

catch (Exception e) {      

     wdComponentAPI.getMessageManager().reportException(e.toString());

}

Downloading a file from a specific folder path in Site Collection

As mentioned earlier copy.asmx web service will be used for this purpose. Below are the details of the method in Copy that will be used to download a file from the folder path in site collection.

  • Method Name: GetItem
  • Input Parameter:
    1. Url (String): Absolute source URL of the document that is to be retrieved. Example: “http://<Host Name>:<Port>/sites/shp/Shared Documents/Test Folder/Test.txt”, in case the file named “Test.txt” to be downloaded from the folder named “Test Folder”, placed under Shared Documents(Document Library).
  • Output Parameters:
    1. Stream (array of bytes): The byte array representation of the file retrieved from the folder in site collection.
    2. Fields: An array of FieldInformation objects, that represent the fields and the corresponding field values that can be copied from the retrieved document.
  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.

Write the below mentioned code in the method that will be called to download a file with the given name, assuming the user enters even the path under which the file is stored as explained earlier.

String destinationUrl = "http://<Host Name>:<Port>/sites/shp/";

SPCopyModel model = new SPCopyModel();

Request_GetItem request = new Request_GetItem(model);

try{

     GetItem getItem = new GetItem(model);

     request.setGetItem(getItem);

     getItem.setUrl(destinationUrl + <Folder Path> + <FileName>);

     request.wdSetInvocationModifier(new IWDWSInvocationModifier(){    

          public void doModifyInvocation(final Object port) {    

               if ( port instanceof Stub ) {    

                    final Stub stub = (Stub)port;    

                    stub._setProperty(Stub.USERNAME_PROPERTY, <User Id>);    

                    stub._setProperty(Stub.PASSWORD_PROPERTY, <Password>);        

               }    

               else if (port instanceof DInterfaceInvoker) {    

                    final DInterfaceInvoker invoker = (DInterfaceInvoker)port;    

                    invoker.setProperty(Stub.USERNAME_PROPERTY, <User Id>);    

                    invoker.setProperty(Stub.PASSWORD_PROPERTY, <Password>);           

               }    

               else     throw new RuntimeException("User not autherized");    

          }

          public void doModifyAfterInvocation() {}        

     });

     request.execute();

     if(request.getResponse() != null){

          byte [] byteArray = request.getResponse().getGetItemResponse().getStream();    

          IWDResource resource = null;    

          WDWebResourceType resourceType = null;

          resourceType = WDWebResourceType.getWebResourceType( <ContentType>, <File Extension in Uppercase>);

          resource = WDResourceFactory.createResource(byteArray, <File Name>, resourceType);

     }

     if(null != resource){

          resource.download();

     }

     else{

          wdComponentAPI.getMessageManager().reportException("File was not downloaded.");

     }

}

catch (WDWSModelExecuteException e) {

     wdComponentAPI.getMessageManager().reportException(e.toString());

}

Deleting a file from a specific folder path in Site Collection

As mentioned earlier lists.asmx web service will be used for this purpose. Below are the details of the method in lists that will be used to delete a file from the folder path in site collection.

  • Method Name: UpdateListItems
  • Input Parameter:
    1. listName (String): Should always be set as “Shared Documents”.
    2. Updates (complex XML tag):

               Example:

                    <Batch OnError="Continue" PreCalc="TRUE" ListVersion="0" ViewName="">

                         <Method ID="1" Cmd="Delete">

                              <Field Name="ID">3</Field>     

                              <Field Name="FileRef">http://Host Name:Port/sites/shp/Shared Documents/File.txt</Field>

                          </Method>

                    </Batch>

The above mentioned complex XML tag has to be passed to delete a file named File.txt (assuming the Item Id of this file is 3), placed directly under the Shared Documents folder. Item id is an unique id defined for each document stored in the site collection.

  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.

Since this web service is expecting a complex XML tag, it will be represented by ANY tag in the WSDL file. As we know WSDL files with ANY tags cannot be consumed in CE 7.1 and lower versions of NWDS. In CE 7.2 ANY tag is supported, but, we cannot pass the attributes and their values for the XML tags as shown in the above example. For this reason, this web service is consumed in EJB DC and the EJB is consumed in WDJ application as Enterprise Java Bean Model. For more information on consuming web services in EJB refer this SDN Blog Consuming WSDL file in EJB.

Before executing the method to delete a file, we need to know the Item id of the file to be deleted. This can be extracted by executing the GetListItems method, provided by the same web service. Below are the details of the GetListItems method, in lists web service.

  • Method Name: GetListItems
  • Input Parameter:
    1. listName (String): Should always be set as “Shared Documents”.
    2. queryOptions (complex XML tag).

               Example:

                    <QueryOptions>

                         <Folder>

                              http://Host Name:Port/sites/shp/Shared Documents/

                         </Folder>     

                    </QueryOptions>

The above mentioned complex XML tag has to be passed to fetch the list of files defined under the folder Shared Documents. From the list returned, we have to extract the Item Id of the file to be deleted.

  • Return: Returns the complex XML tag, which includes the list of files under the given folder path.

          Example:

               <listitems>

                    <z:row ows_LinkFilename="File1.txt" ows_Created="2012-01-18T03:41:09Z" ows_ID="3" ows_owshiddenversion="3" />

                    <z:row ows_LinkFilename="File2.txt" ows_Created="2012-02-18T17:15:58Z" ows_ID="4" ows_owshiddenversion="2" />

               </listitems>

               The attribute ows_ID, represents the Item Id, for the file with name represented by the attribute ows_LinkFilename.

  • Invocation Parameters: The user id and password, which is granted full permission on the site collection has to be passed.

Below mentioned lines of code can be used in EJB to execute the lists web service calling the GetListItems method to extract the Item id of the file.

String itemId = null;

try{

     URL wsdlLocation = new URL("http://<Host Name>:<Port>/sites/shp/_vti_bin/lists.asmx?wsdl");    

     Lists lists = new Lists(wsdlLocation, new QName("http://schemas.microsoft.com/sharepoint/soap/","Lists"));      

     ListsSoap listsSoapVi = lists.getListsSoap();      

     ((BindingProvider)listsSoapVi).getRequestContext().put(BindingProvider.USERNAME_PROPERTY , <UserId>);   

     ((BindingProvider)listsSoapVi).getRequestContext(). put(BindingProvider.PASSWORD_PROPERTY ,  <Password>);        

     QueryOptions queryOptions = new QueryOptions();      

     //Creating the complex XML Tag structure “QueryOptions”    

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    

     DocumentBuilder db = dbf.newDocumentBuilder();    

     Document dom = db.newDocument();    

     Element queryOptionsElement = dom.createElement("QueryOptions");    

     Element folderElement = dom.createElement("Folder");    

     folderElement.appendChild(dom.createTextNode("http://<Host Name>:<Port>/sites/shp/" + <Parent Folder Name>));

     queryOptionsElement.appendChild(folderElement);        

     queryOptions.getContent().add(queryOptionsElement);

     Query query = new Query();    

     ViewFields viewFields = new ViewFields();    

     GetListItemsResult result = listsSoapVi.getListItems("Shared Documents", "", query, viewFields, "", queryOptions, "");    

     List<Object> itemsList = result.getContent();      

     //Extracting the ItemId of the file to be deleted    

     if(itemsList!= null && itemsList.size() > 0){    

          Element element = (Element) itemsList.get(0);    

          NodeList nodeList = element.getElementsByTagName("z:row");    

          String itemName = "";

          int noOfItems = nodeList.getLength();    

          for (int index = 0; index < noOfItems; index++) {    

               element = (Element) nodeList.item(index);    

               itemName = element.getAttribute("ows_LinkFilename");    

               if(null != itemName && itemName.equals()){    

                    itemId = element.getAttribute("ows_ID");    

                    break;    

               }       

          }    

     }

}

catch (Exception e) {

     e.printStackTrace();

}

return itemId;

Write the below mentioned code in the EJB method that will be called to delete a file with the given name, assuming the user enters even the path under which the file is stored as explained earlier.

String itemId = this.getListItems(<File Name>, <Parent Folder Path>);

try{

     URL wsdlLocation = new URL("http://<Host Name><Port>/sites/shp/_vti_bin/lists.asmx?wsdl");

     Lists lists = new Lists(wsdlLocation, new QName("http://schemas.microsoft.com/sharepoint/soap/","Lists"));

     ListsSoap listsSoapVi = lists.getListsSoap();        

     ((BindingProvider)listsSoapVi).getRequestContext(). put(BindingProvider.USERNAME_PROPERTY ,  <UserId>);   

     ((BindingProvider)listsSoapVi).getRequestContext(). put(BindingProvider.PASSWORD_PROPERTY ,  <Password>);            

     Updates updates = new Updates();

     //Creating the complex XML Tag structure "Batch"

     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    

     DocumentBuilder db = dbf.newDocumentBuilder();    

     Document dom = db.newDocument();    

     Element batchElement = dom.createElement("Batch");    

     batchElement.setAttribute("OnError" , "Continue");    

     batchElement.setAttribute("PreCalc","TRUE");      

     batchElement.setAttribute("ListVersion","0");    

     batchElement.setAttribute("ViewName", "");        

     Element methodElement = dom.createElement("Method");    

     methodElement.setAttribute("ID", "1");    

     methodElement.setAttribute("Cmd", "Delete");        

     Element fieldElement = dom.createElement("Field");    

     fieldElement.setAttribute("Name", "ID");    

     fieldElement.appendChild(dom.createTextNode(itemId));    

     methodElement.appendChild(fieldElement);        

     fieldElement = dom.createElement("Field");    

     fieldElement.setAttribute("Name", "FileRef");    

     fieldElement.appendChild(dom.createTextNode());    

     methodElement.appendChild(fieldElement);    

     batchElement.appendChild(methodElement);      

     dom.appendChild(batchElement);        

     updates.getContent().add(batchElement);        

     UpdateListItemsResult uListItemsResult = listsSoapVi.updateListItems("Shared Documents", updates);   

}

catch (Exception e) {

     e.printStackTrace();

}

Conclusion

In this way we can create and maintain a shared repository of documents in Microsoft SharePoint server from a web Dynpro java application. Files can be uploaded into any folder/subfolder in the shared repository and can be downloaded from. The uploaded files can also be deleted, if required. Versioning of files is also possible in SharePoint. Perquisite for this is to enable versioning for the Document Library (Settings --> Document library settings --> Version setting --> Set either create major versioning or minor versioning). Once this setting is done, uploading the same file/a file with same name will create a new version and download will always fetch the latest version. GetVersions method of Versions.asmx web service can be used to fetch the version history of a particular file.

Labels in this area