title: saving file in alfresco with Version and Download the latest version
body: <p>I work with alfresco Community 4.0 and I used this jar <strong>alfresco-web-service-client-4.0.d.jar</strong></p>
  
  <p>using this code I can save my test.pdf file in alfresco :</p>
  
  <pre><code>File file = new File("C:/test.pdf");
  
    saveAttachement(file,"test.pdf", "/app:company_home/cm:MyFolder",
                          "admin", "admin")
  
  
  
                           public String saveAttachement(File file, String name, String folderName, String userName, String pwd)
          throws Exception {
  
  
          byte[] contentByte = IOUtils.toByteArray(new FileInputStream(file));
  
          // Start the session
          AuthenticationUtils.startSession(userName, pwd);
  
          try {
              // Create a reference to the parent where we want to create content
              Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
              ParentReference companyHomeParent = new ParentReference(storeRef, null, folderName, Constants.ASSOC_CONTAINS, null);
  
              // Assign name
              companyHomeParent.setChildName("cm:" + name);
  
              // Construct CML statement to create content node
              // Note: Assign "1" as a local id, so we can refer to it in subsequent
              //       CML statements within the same CML block
              NamedValue[] contentProps = new NamedValue[1];
              contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);
  
              CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_CONTENT, contentProps);
  
              // Construct CML statement to add titled aspect
              NamedValue[] titledProps = new NamedValue[2];
              titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, name);
              titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, name);
  
              CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");
  
              // Construct CML Block
              CML cml = new CML();
              cml.setCreate(new CMLCreate[] { create });
              cml.setAddAspect(new CMLAddAspect[] { addAspect });
  
              // Issue CML statement via Repository Web Service and retrieve result
              // Note: Batching of multiple statements into a single web call
              UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
              Reference content = result[0].getDestination();
  
              // Write some content
              ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
  
              //String text = "The quick brown fox jumps over the lazy dog";
              ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
              Content contentRef = contentService.write(content, Constants.PROP_CONTENT, contentByte, contentFormat);
              System.out.println("Document are created successfully. UID:= " + content.getUuid());
  
              return content.getUuid();
          } catch (Throwable e) {
              System.out.println(e.toString());
          } finally {
              // End the session
              AuthenticationUtils.endSession();
  
              //System.exit(0);
          }
  
          return null;
      }
  </code></pre>
  
  <p>after saving this file in alfresco I have this id <code>d7633eff-8595-4d6c-8c18-a29a656607ba</code></p>
  
  <p>it will be used later to download this file</p>
  
  <p>This is the download code :</p>
  
  <pre><code>ContentResult contentResult = getContentsById("d7633eff-8595-4d6c-8c18-a29a656607ba", "admin", "admin");
  
  
         public ContentResult getContentsById(String contentId, String userName, String pwd)
          throws Exception {
          ContentResult contentResult = new ContentResult();
  
          // Start the session
          AuthenticationUtils.startSession(userName, pwd);
  
          try {
              Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
              ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
  
              Reference contentReference = new Reference(storeRef, contentId, null);
              Content[] readResult = null;
  
              try {
                  readResult = contentService.read(new Predicate(new Reference[] { contentReference }, storeRef, null), Constants.PROP_CONTENT);
              } catch (ContentFault e) {
                  e.printStackTrace();
              } catch (RemoteException e) {
                  e.printStackTrace();
              }
  
              if ((readResult != null) &amp;&amp; (readResult[0] != null)) {
                  Content content = readResult[0];
                  ContentFormat cnf = content.getFormat();
                  Reference ref = content.getNode();
  
                  String[] splitedUrl = content.getUrl().split("/");
                  String name = splitedUrl[splitedUrl.length - 1];
  
                  InputStream is = ContentUtils.getContentAsInputStream(content);
                  byte[] contentByte = ConvertUtil.convertInputStreamToByte(is);
  
                  contentResult.setName(name);
                  contentResult.setMimetype(cnf.getMimetype());
                  contentResult.setId(ref.getUuid());
                  contentResult.setUrl(content.getUrl());
                  contentResult.setPath(ref.getPath());
                  contentResult.setContentByte(contentByte);
                  System.out.println(" document has been retrieved");
              }
          } catch (Exception e) {
              System.out.println(e.toString());
          } finally {
              // End the session
              AuthenticationUtils.endSession();
  
              // System.exit(0);
          }
  
          return contentResult;
      }
  </code></pre>
  
  <p>currently I change the <strong>test.pdf</strong>  file content  without changing the file name
          and I put it in another location in the disc.</p>
  
  <p>This is the new file location.</p>
  
  <p><strong>C:/version/test.pdf</strong></p>
  
  <p>So in the disk I have two files with the same name but with different content.</p>
  
  <p>my goal is to save the new file in alfresco but using versioning.</p>
  
  <p>in my opinion I must use the old id  which is saving in alfresco : <strong>d7633eff-8595-4d6c-8c18-a29a656607ba</strong></p>
  
  <p>so I should develop a method that takes as a parameter the new file and the old id</p>
  
  <p>like this </p>
  
  <pre><code> File file = new File("C:/version/test.pdf");
  
    saveWithVersionAttachement(file,"d7633eff-8595-4d6c-8c18-a29a656607ba","test.pdf", "/app:company_home/cm:MyFolder",
                          "admin", "admin",)
  
  
  
                           public String saveWithVersionAttachement(File file,String oldId, String name, String folderName, String userName, String pwd)
          throws Exception {
   .............
   .............
  </code></pre>
  
  <p>in my opinion this method must save the new file in alfresco like this test_2.pdf or test_v2.pdf ..</p>
  
  <p>so the two files are saved in alfresco and having the same id </p>
  
  <p>and in the download method  I want to have the latest version.</p>
  
  <p>so I must change the method <code>getContentById ("d7633eff-8595-4d6c-8c18-a29a656607ba", "admin", "admin");</code> </p>
  
  <p>in order to return the latest version which is <strong>test_2.pdf or test_v2.pdf ...</strong></p>
  
  <p>I tried unsuccessfully to work with OpenCMIS using <strong>alfresco-OpenCMIS-extension-0.7.jar</strong> </p>
  
  <p>I added this lines in <strong>Alfresco\tomcat\webapps\alfresco\WEB-INF\classes\alfresco\model\contentModel.xml</strong> </p>
  
  <pre><code>&lt;mandatory-aspects&gt;
  &lt;aspect&gt;cm:versionable&lt;/aspect&gt;
  &lt;/mandatory-aspects&gt;
  </code></pre>
  
  <p>also I added   this line <code>version.store.enableAutoVersioning=true</code></p>
  
  <p>in <strong>Alfresco\tomcat\shared\classes\alfresco-global.properties</strong></p>
  
  <p>is there anyone who can help me to solve my problem</p>
  
  <p><strong>UPDATED :</strong></p>
  
  <p><strong>I work with CMIS :</strong></p>
  
  <p>I try with this code :</p>
  
  <pre><code>import java.io.ByteArrayInputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.Reader;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  
  import org.apache.chemistry.opencmis.client.api.Document;
  import org.apache.chemistry.opencmis.client.api.Repository;
  import org.apache.chemistry.opencmis.client.api.Session;
  import org.apache.chemistry.opencmis.client.api.SessionFactory;
  import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
  import org.apache.chemistry.opencmis.commons.SessionParameter;
  import org.apache.chemistry.opencmis.commons.data.ContentStream;
  import org.apache.chemistry.opencmis.commons.enums.BindingType;
  import org.apache.commons.io.IOUtils;
  
  
       public void saveVersioning(File file, String filename, String userName, String pwd, String docId)
              throws Exception {
  
              SessionFactory factory = SessionFactoryImpl.newInstance();
              Map&lt;String, String&gt; parameters = new HashMap&lt;String, String&gt;();
  
              // User credentials.
              parameters.put(SessionParameter.USER,userName);
              parameters.put(SessionParameter.PASSWORD, pwd);
  
              // Connection settings.
              parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
              parameters.put(SessionParameter.ATOMPUB_URL, "http://localhost:9080/alfresco/service/cmis"); // URL to your CMIS server.
              parameters.put(SessionParameter.AUTH_HTTP_BASIC, "true" );
  
              // Create session.
              // Alfresco only provides one repository.
              Repository repository = factory.getRepositories(parameters).get(0);
  
              Session session = repository.createSession();
  
               // Get the contents of the file
              Document doc = (Document) session.getObject(docId);
              ContentStream contentStream = doc.getContentStream(); // returns null if the document has no content
              if (contentStream != null) {
  
  
                      String mimetype = "text/plain; charset=UTF-8";
                      String content = "";
  
                      if (contentStream != null) {
                          filename = contentStream.getFileName();
                          mimetype = contentStream.getMimeType();
                          content = getContentAsString(contentStream);
                          System.out.println("file name "+filename);
                          System.out.println("minetype "+mimetype);
                          System.out.println("content "+content);
                      }
  
  
                      byte[] buf = IOUtils.toByteArray(new FileInputStream(file));
                      ByteArrayInputStream input = new ByteArrayInputStream(buf);
  
                      contentStream = session.getObjectFactory().createContentStream(
                              filename, buf.length, mimetype, input);
  
  
  
                      System.out.println("Document version history");
                      {
                          List&lt;Document&gt; versions = doc.getAllVersions();
                          for (Document version : versions) {
                              System.out.println("\tname: " + version.getName());
                              System.out.println("\tversion label: " + version.getVersionLabel());
                              System.out.println("\tversion series id: " + version.getVersionSeriesId());
                              System.out.println("\tchecked out by: "
                                      + version.getVersionSeriesCheckedOutBy());
                              System.out.println("\tchecked out id: "
                                      + version.getVersionSeriesCheckedOutId());
                              System.out.println("\tmajor version: " + version.isMajorVersion());
                              System.out.println("\tlatest version: " + version.isLatestVersion());
                              System.out.println("\tlatest major version: " + version.isLatestMajorVersion());
                              System.out.println("\tcheckin comment: " + version.getCheckinComment());
                              System.out.println("\tcontent length: " + version.getContentStreamLength()
                                      + "\n");
                          }
                      }
                  }
  
  
  
          }
  
  
  
      private static String getContentAsString(ContentStream stream) throws IOException {
          StringBuilder sb = new StringBuilder();
          Reader reader = new InputStreamReader(stream.getStream(), "UTF-8");
  
          try {
              final char[] buffer = new char[4 * 1024];
              int b;
              while (true) {
                  b = reader.read(buffer, 0, buffer.length);
                  if (b &gt; 0) {
                      sb.append(buffer, 0, b);
                  } else if (b == -1) {
                      break;
                  }
              }
          } finally {
              reader.close();
          }
  
          return sb.toString();
      }
  </code></pre>
  
  <p>I call this fonction using this code :</p>
  
  <pre><code>File file = new File("C:/version/test.pdf");
  
  saveVersioning(file, "test.pdf","admin","admin","d7633eff-8595-4d6c-8c18-a29a656607ba");
  </code></pre>
  
  <p>I used this jar :</p>
  
  <pre><code>chemistry-opencmis-client-api-0.13.0.jar
  chemistry-opencmis-client-bindings-0.13.0.jar
  chemistry-opencmis-client-impl-0.13.0.jar
  chemistry-opencmis-commons-api-0.13.0.jar
  chemistry-opencmis-commons-impl-0.13.0.jar
  commons-io-1.4.jar
  slf4j-api-1.7.5.jar
  stax2-api-3.1.4.jar
  woodstox-core-asl-4.4.0.jar
  </code></pre>
  
  <p>but when I try to test  I have this error :</p>
  
  <pre><code>Caused by: java.lang.NoClassDefFoundError: org/apache/chemistry/opencmis/client/api/SessionFactory
  .............
  ............
  Caused by: java.lang.ClassNotFoundException: org.apache.chemistry.opencmis.client.api.SessionFactory
      at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
      at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
      ... 124 more
  </code></pre>