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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
6 | |
5 | |
5 | |
5 | |
5 | |
4 | |
4 | |
4 | |
3 | |
3 |