Upload file to Microsoft Office Sharepoint Server 2007

Microsoft Office Sharepoint Server 2007 (aka MOSS2007) provides a web services catalog in order to perform a large collection of operations on it. Morever, if enabled, WebDAV access is available.

The obvious way to upload a file to MOSS Shared Documents is the use of WebDAV protocol, however Microsoft includes a web service to perform this operation additionally. Below, both methods are shown.

Using WebDAV protocol

Required libraries: commons-httpclient-3.1.jar, commons-codec-1.3.jar, commons-logging-1.1.1.jar, log4j-1.2.15.jar, slf4j-api-1.5.6.jar, slf4j-log4j12-1.5.6.jar, jackrabbit-webdav-1.4.jar

import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;

public class UploadFileMOSSWebDAV {

  // Proxy parameters
  static String proxyHost = "proxy.server.com";
  static Integer proxyPort = 80;
  static String proxyUser = "user";
  static String proxyPass = "pass";

  // Sharepoint parameters
  static String sharepointUser = "user";
  static String sharepointPass = "pass";
  static String sharepointDomain = "DOMAIN";

  // Shared Documents folder root
  static String sharedDocumentsRoot = "http://sharepoint.server.com/sites/IdSite/Shared Documents/";

  /**
   * Note: Setting credentials with AuthScope.ANY authentication scope (null value for host and/or realm) is
   * highly discouraged in production applications.
   * @param args
   * @throws Exception
   */
  public static void main(String... args) throws Exception {

    // HTTP client with authentication enabled
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);

    // Proxy configuration
    client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getState().setProxyCredentials(AuthScope.ANY,
          new UsernamePasswordCredentials(proxyUser, proxyPass));

    // Sharepoint authentication
    Credentials defaultcreds =
          new NTCredentials(sharepointUser, sharepointPass, "localhost", sharepointDomain);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);

    // Upload local file test.txt to sharedDocumentsRoot/SomeFolder/test.txt
    PutMethod method = new PutMethod(sharedDocumentsRoot + "SomeFolder/test.txt");
    RequestEntity requestEntity =
            new InputStreamRequestEntity(new FileInputStream(new File("c:/temp/test.txt")));
    method.setRequestEntity(requestEntity);
    client.executeMethod(method);
    System.out.println(method.getStatusCode() + " "+ method.getStatusText());  

  }

}

 Using MOSS Copy web service

Required libraries: commons-httpclient-3.1.jar, commons-codec-1.3.jar, commons-logging-1.1.1.jar, log4j-1.2.15.jar, activation-1.1.1.jar, saaj-api-1.3.jar, saaj-impl-1.3.2.jar, spring-core-2.5.6.jar, spring-context-2.5.6.jar, spring-beans-2.5.6.jar, spring-oxm-1.5.6.jar, spring-ws-core-1.5.6.jar, spring-xml-1.5.6.jar, xmlbeans tool

Resources: Getting started with Sharepoint Web Services

1. Retrieve WSDL from Sharepoint

WSDL for Copy web service can be found at http://sharepoint.server.com/sites/IdSite/_vti_bin/Copy.asmx?WSDL

2. Extract XSD from WSDL

Extract “s:schema” node from WSDL and include namespaces on root element


<s>
[...]
</s>

 Note. “:” replaced by “_” for visualization.

3. Generate XMLBeans objects for marshal

Use XMLBeans Ant Task to generate Java objects in order to perform marshalling and unmarshalling operations from XML

4. Web service client

import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NTCredentials;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.util.Base64;
import org.springframework.oxm.xmlbeans.XmlBeansMarshaller;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import org.springframework.ws.transport.http.CommonsHttpMessageSender;

import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument;
import com.microsoft.schemas.sharepoint.soap.DestinationUrlCollection;
import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument.CopyIntoItems;

public class UploadFileMOSSWS extends WebServiceGatewaySupport {

  // Proxy parameters
  static String proxyHost = "proxy.server.com";
  static Integer proxyPort = 80;
  static String proxyUser = "user";
  static String proxyPass = "pass";

  // Sharepoint parameters
  static String sharepointUser = "user";
  static String sharepointPass = "pass";
  static String sharepointDomain = "DOMAIN";

  // Shared Documents folder root
  static String sharedDocumentsRoot = "http://sharepoint.server.com/sites/IdSite/Shared Documents/";

  // WS Uri
  static String defaultWSUri = "http://sharepoint.server.com/sites/IdSite/_vti_bin/Copy.asmx";

  /**
   * Note: Setting credentials with AuthScope.ANY authentication scope (null value for host and/or realm) is
   * highly discouraged in production applications.
   * @param args
   * @throws Exception
   */
  public static void main(String... args) throws Exception {

    // XMLBeans request object
    CopyIntoItemsDocument request = CopyIntoItemsDocument.Factory.newInstance();
    CopyIntoItems cii = request.addNewCopyIntoItems();
    DestinationUrlCollection duc = DestinationUrlCollection.Factory.newInstance();
    duc.addNewString().setStringValue(sharedDocumentsRoot + "SomeFolder/test.txt");
    cii.setDestinationUrls(duc);
    cii.addNewFields().addNewFieldInformation();

    // Sample file
    String fileContent = "";
    FileInputStream fis = new FileInputStream(new File("c:/temp/test.txt"));
    while (fis.available() > 0) {
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fileContent = fileContent + new String(buffer);
    }
    cii.setStream(Base64.encode(fileContent.getBytes()));

    // MOSS WS Copy File invocation with SOAP Action CopyIntoItems
    System.out.println(new UploadFileMOSSWS().
        callWs(request, "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems"));

  }

  /**
   * Generic Spring WS Client
   * @param input
   * @param soapAction
   * @return
   */
  private XmlObject callWs(XmlObject input, String soapAction) {

    XmlObject result = null;

    // WS Client
    WebServiceTemplate wst = getWebServiceTemplate();
    XmlBeansMarshaller marshaller = new XmlBeansMarshaller();
    wst.setMarshaller(marshaller);
    wst.setUnmarshaller(marshaller);
    wst.setDefaultUri(defaultWSUri);

    // HTTP Client configuration
    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    client.getHostConfiguration().setProxy(proxyHost, proxyPort);
    client.getState().setProxyCredentials(AuthScope.ANY,
          new UsernamePasswordCredentials(proxyUser, proxyPass));
    Credentials defaultcreds =
          new NTCredentials(sharepointUser, sharepointPass, "localhost", sharepointDomain);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    CommonsHttpMessageSender messageSender = new CommonsHttpMessageSender(client);
    wst.setMessageSender(messageSender);

    // WS invocation with SOAP Action
    result = (XmlObject)wst.marshalSendAndReceive(input, new SoapActionCallback(soapAction));

    return result;

    }

}

20 comentarios en “Upload file to Microsoft Office Sharepoint Server 2007

  1. Pingback: capitanfuturo: Upload di file su Sharepoint 2010 + IIS 7 + NTLM con Java | Gestione Documenti

  2. Can any one tell me the below details:
    Hostname: ..?
    Domain Name: ..?
    And I am getting below error…

    HTTP/1.1 404 Not found

    Please help I am trying to Automate the file upload to SharePoint via Java…
    Or suggest me any tools for this…

  3. I am unable to import the following classes using these jar files

    import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument;
    import com.microsoft.schemas.sharepoint.soap.DestinationUrlCollection;
    import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument.CopyIntoItems;

    Could you please assist in fixing the same.. i couldn see these classes in jars

  4. Ananth,

    “Use XMLBeans Ant Task to generate Java objects in order to perform marshalling and unmarshalling operations from XML”.

    This classes are generated from WSDL.

    Regards

    • how can generate this package .I was tried kindly give some steps

      import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument;
      import com.microsoft.schemas.sharepoint.soap.DestinationUrlCollection;
      import com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument.CopyIntoItems;

      Regards,
      Silambarasan

  5. Hi, thanks a lot for quick response.. i generated classes from WSDL using axis2.. could you give me some information on how you generated these classes from WSDL???

      • i just went thru this client generation and i was able to generate the code successfully… but i am facing this run time error..

        Could you please let me know why am i facing this

        Exception in thread “main” java.lang.ExceptionInInitializerError
        at com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument$Factory.newInstance(CopyIntoItemsDocument.java:182)
        at UploadFileMOSSWS.main(UploadFileMOSSWS.java:52)
        Caused by: java.lang.RuntimeException: Cannot load SchemaTypeSystem. Unable to load class with name schemaorg_apache_xmlbeans.system.s171492E8FF1E87432B0037989D859B75.TypeSystemHolder. Make sure the generated binary files are on the classpath.
        at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:783)
        at com.microsoft.schemas.sharepoint.soap.CopyIntoItemsDocument.(CopyIntoItemsDocument.java:20)
        … 2 more
        Caused by: java.lang.ClassNotFoundException: schemaorg_apache_xmlbeans.system.s171492E8FF1E87432B0037989D859B75.TypeSystemHolder
        at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
        at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:769)
        … 3 more

  6. i have set my class path to

    D:\New folder\xmlbeans-2.5.0\lib;D:\New folder\xmlbeans-2.5.0\lib\xbean.jar;D:\New folder\xmlbeans-2.5.0\lib\jsr173_1.0_api.jar;D:\New folder\xmlbeans-2.5.0\lib\xmlbeans-2.3.0.jar;
    still facing the same error.. Any idea why its happening so..

  7. i got thru wid authentication.. could you tell me whats the cause of tis error- Value does not fall within the expected range.

    Thank you very much for the assistance…

  8. Hi,

    I’m using WebDAV protocol, my host/user/password,… are Ok. (I have my static String sharepointDomain = “”; becaune my sharepoint has not domain).

    Morover, i’ve always the same error : ” 401 unauthorized “. I searched all forums but nothing…

    Someone can help me pls?

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s