You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@chemistry.apache.org by fm...@apache.org on 2012/02/25 14:43:34 UTC

svn commit: r1293600 [8/9] - in /chemistry/opencmis/branches/android: ./ chemistry-opencmis-client/chemistry-opencmis-client-bindings/ chemistry-opencmis-client/chemistry-opencmis-client-bindings/src/main/java/org/apache/chemistry/opencmis/client/bindi...

Modified: chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/main/java/org/apache/chemistry/opencmis/util/specexamples/Main.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/main/java/org/apache/chemistry/opencmis/util/specexamples/Main.java?rev=1293600&r1=1293599&r2=1293600&view=diff
==============================================================================
--- chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/main/java/org/apache/chemistry/opencmis/util/specexamples/Main.java (original)
+++ chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/main/java/org/apache/chemistry/opencmis/util/specexamples/Main.java Sat Feb 25 13:43:31 2012
@@ -1,630 +1,630 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.chemistry.opencmis.util.specexamples;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.apache.chemistry.opencmis.client.bindings.CmisBindingFactory;
-import org.apache.chemistry.opencmis.commons.PropertyIds;
-import org.apache.chemistry.opencmis.commons.SessionParameter;
-import org.apache.chemistry.opencmis.commons.data.Ace;
-import org.apache.chemistry.opencmis.commons.data.Acl;
-import org.apache.chemistry.opencmis.commons.data.CmisExtensionElement;
-import org.apache.chemistry.opencmis.commons.data.ContentStream;
-import org.apache.chemistry.opencmis.commons.data.ExtensionsData;
-import org.apache.chemistry.opencmis.commons.data.ObjectInFolderData;
-import org.apache.chemistry.opencmis.commons.data.ObjectInFolderList;
-import org.apache.chemistry.opencmis.commons.data.Properties;
-import org.apache.chemistry.opencmis.commons.data.PropertyData;
-import org.apache.chemistry.opencmis.commons.data.RepositoryInfo;
-import org.apache.chemistry.opencmis.commons.enums.AclPropagation;
-import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
-import org.apache.chemistry.opencmis.commons.enums.BindingType;
-import org.apache.chemistry.opencmis.commons.enums.IncludeRelationships;
-import org.apache.chemistry.opencmis.commons.enums.VersioningState;
-import org.apache.chemistry.opencmis.commons.impl.dataobjects.BindingsObjectFactoryImpl;
-import org.apache.chemistry.opencmis.commons.impl.dataobjects.CmisExtensionElementImpl;
-import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
-import org.apache.chemistry.opencmis.commons.impl.dataobjects.ExtensionDataImpl;
-import org.apache.chemistry.opencmis.commons.spi.AclService;
-import org.apache.chemistry.opencmis.commons.spi.BindingsObjectFactory;
-import org.apache.chemistry.opencmis.commons.spi.CmisBinding;
-import org.apache.chemistry.opencmis.commons.spi.DiscoveryService;
-import org.apache.chemistry.opencmis.commons.spi.Holder;
-import org.apache.chemistry.opencmis.commons.spi.MultiFilingService;
-import org.apache.chemistry.opencmis.commons.spi.NavigationService;
-import org.apache.chemistry.opencmis.commons.spi.ObjectService;
-import org.apache.chemistry.opencmis.commons.spi.RepositoryService;
-import org.apache.chemistry.opencmis.commons.spi.VersioningService;
-import org.apache.commons.io.filefilter.WildcardFileFilter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-public class Main {
-
-    private static final Log LOG = LogFactory.getLog(Main.class.getName());
-    private static final BigInteger TYPE_DEPTH_ALL = BigInteger.valueOf(-1);
-    private static final BigInteger MAX_ITEMS = null;
-    private static final BigInteger SKIP_COUNT = BigInteger.valueOf(0);
-    private static final String TOPLEVEL_TYPE = "DocumentTopLevel";
-    private static final String VERSIONED_TYPE = "VersionableType";
-    private static String LOGDIR = System.getProperty("java.io.tmpdir");// + File.separator;
-    private String targetDir = System.getProperty("java.io.tmpdir");// + File.separator;
-
-    private BindingsObjectFactory objFactory = new BindingsObjectFactoryImpl();
-    private BindingType bindingType;
-    private String rootFolderId;
-    private String repositoryId;
-    private ObjectService objSvc;
-    private NavigationService navSvc;
-    private RepositoryService repSvc;
-    private VersioningService verSvc;
-    private MultiFilingService multiSvc;
-    private DiscoveryService discSvc;
-    private AclService aclSvc;
-
-    private static final String[] URLS = {"http://de05189:8080/inmemory/atom", 
-            "http://de05189:8080/inmemory/services", 
-            "http://de05189:8080/inmemory/browser"};
-    private static final BindingType[] BINDINGS = {BindingType.ATOMPUB, BindingType.WEBSERVICES, BindingType.BROWSER};
-
-    public Main() {
-    }
-
-    public void runAllBindings() {
-      for (int i = 0; i < BINDINGS.length; i++) {
-            bindingType = BINDINGS[i];
-            init(URLS[i], BINDINGS[i]);
-            run();
-        }
-        
-    }
-    
-    public void run() {
-        LOG.debug("Generating spec examples for Binding: " + bindingType.value());
-        // Repository Service:
-        getRepositories();
-
-        repositoryId = "A1";
-        getRepositoryInfo();
-
-        getTypeDefinition("cmis:folder");
-        
-        String docId = getTestDocId();
-        String folderId = getTestFolderId();
-
-        getTypeChildren(TOPLEVEL_TYPE);
-
-        // Navigation Service:
-        getChildren(folderId);
-        getDescendants(folderId);
-
-        // Object Service:
-        getObject(docId);
-        getAcl(docId);
-        String id1 = createDocument("SampleDocument", TOPLEVEL_TYPE, rootFolderId, VersioningState.NONE);
-        updateProperties(id1, PropertyIds.NAME, "RenamedDocument");
-        getAllowableActions(id1);
-        
-        deleteObject(id1);
-
-        // Discovery Service:
-        doQuery();
-
-        // Versioning Service
-        String id2 = prepareVersionSeries("VersionedDocument", VERSIONED_TYPE, rootFolderId);
-        checkOut(id2);
-        checkIn(id2, true, "final version in series");
-        getAllVersions(id2);
-
-        // delete all generated objects
-        String[] ids = {id2};
-        
-        cleanup(ids);
-
-        // collect all captured files and store them in a ZIP file
-        String dirs[] = {BindingType.ATOMPUB.value(), BindingType.WEBSERVICES.value(), BindingType.BROWSER.value() };        
-        createZipFile("CMIS-Spec-Examples.zip", dirs);
-    }
-
-    private void init(String url, BindingType bindingType) {
-        LOG.debug("Initializing connection to InMemory server: ");
-        LOG.debug("   Binding: " + bindingType.value());
-        LOG.debug("   URL: " + url);
-
-        Map<String, String> parameters = new HashMap<String, String>();
-        parameters.put(SessionParameter.USER, "admin");
-        parameters.put(SessionParameter.PASSWORD, "admin");
-
-        parameters.put(SessionParameter.BINDING_TYPE, bindingType.value());
-
-        // get factory and create binding
-        CmisBindingFactory factory = CmisBindingFactory.newInstance();
-        CmisBinding binding = null;
-        
-        if (bindingType == BindingType.ATOMPUB)  {
-            parameters.put(SessionParameter.ATOMPUB_URL, url);
-            binding = factory.createCmisAtomPubBinding(parameters);
-        } else if (bindingType == BindingType.WEBSERVICES) {
-            parameters.put(SessionParameter.WEBSERVICES_ACL_SERVICE, url + "/ACLService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_DISCOVERY_SERVICE,  url + "/DiscoveryService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_MULTIFILING_SERVICE,  url + "/MultiFilingService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_NAVIGATION_SERVICE,  url + "/NavigationService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_OBJECT_SERVICE,  url + "/ObjectService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_POLICY_SERVICE,  url + "/PolicyService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_RELATIONSHIP_SERVICE,  url + "/RelatinshipService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_REPOSITORY_SERVICE,  url + "/RepositoryService?wsdl");
-            parameters.put(SessionParameter.WEBSERVICES_VERSIONING_SERVICE,  url + "/VersioningService?wsdl");
-            binding = factory.createCmisWebServicesBinding(parameters);            
-        } else if (bindingType == BindingType.BROWSER) {
-            parameters.put(SessionParameter.BROWSER_URL, url); 
-            binding = factory.createCmisBrowserBinding(parameters);            
-        } else {
-            LOG.error("Unknown binding type: " + bindingType.value());
-            return;
-        }
-        objFactory = binding.getObjectFactory();
-        repSvc = binding.getRepositoryService();
-        objSvc = binding.getObjectService();
-        navSvc = binding.getNavigationService();
-        verSvc = binding.getVersioningService();
-        multiSvc = binding.getMultiFilingService();
-        discSvc = binding.getDiscoveryService();
-        aclSvc = binding.getAclService();
-        
-        // create a folder where target files will be stored:
-        targetDir = bindingType.value();
-        File in = new File(targetDir);
-        boolean ok = in.mkdir();
-        
-        LOG.debug("creating target directory for files: " + ok);
-        LOG.debug("Initializing done. ");
-    }
-
-    private void getRepositories() {
-        LOG.debug("getRepositories()");
-        List<RepositoryInfo> repositories = repSvc.getRepositoryInfos(null);
-        this.repositoryId = repositories.get(0).getId();
-        renameFiles("getRepositoryInfos");
-        LOG.debug("getRepositoryInfo() done.");
-    }
-
-    private void getRepositoryInfo() {
-        LOG.debug("getting repository info for repository " + repositoryId);
-        // Because the browser binding silently retrieves all repositories on the first request we call it twice
-        // and use a dummy extension data element to prevent caching
-        RepositoryInfo repoInfo = repSvc.getRepositoryInfo(repositoryId, null);
-        if (bindingType.equals(BindingType.BROWSER)) {
-            ExtensionDataImpl dummyExt = new ExtensionDataImpl();
-            List<CmisExtensionElement> extList = new ArrayList<CmisExtensionElement>() {{ add(new CmisExtensionElementImpl("foo", "foo", null, "bar")); }};
-            dummyExt.setExtensions(extList);
-            repoInfo = repSvc.getRepositoryInfo(repositoryId, dummyExt);
-        }
-        LOG.debug("repository id is: " + repoInfo.getId());
-        rootFolderId = repoInfo.getRootFolderId();
-        LOG.debug("root folder id is: " + repoInfo.getRootFolderId());
-        renameFiles("getRepositoryInfo");
-        LOG.debug("getRepositoryInfo() done.");
-    }
-
-    private void getObject(String objectId) {
-        LOG.debug("getObject " + objectId);
-        objSvc.getObject(repositoryId, objectId, "*", false /* includeAllowableActions */,
-                IncludeRelationships.NONE /* includeRelationships */, null /* renditionFilter */,
-                false /* includePolicyIds */, false /* includeAcl */, null);
-        renameFiles("getObject");
-        LOG.debug("getObject() done.");
-    }
-
-    private void getChildren(String folderId) {
-        LOG.debug("getChildren " + folderId);
-        navSvc.getChildren(repositoryId, folderId, "*", null /* orderBy */, false /* includeAllowableActions */,
-                IncludeRelationships.NONE, null /* renditionFilter */, true /* includePathSegment */, MAX_ITEMS,
-                SKIP_COUNT, null);
-        renameFiles("getChildren");
-        LOG.debug("getChildren() done.");
-    }
-
-    private void getDescendants(String folderId) {
-        final BigInteger DEPTH = BigInteger.valueOf(3);
-        LOG.debug("getDescendants " + folderId);
-        navSvc.getDescendants(repositoryId, folderId, DEPTH, "*", false /* includeAllowableActions */,
-                IncludeRelationships.NONE, null /* renditionFilter */, true /* includePathSegment */, null);
-        renameFiles("getDescendants");
-        LOG.debug("getDescendants() done.");
-    }
-
-    private void doQuery() {
-        LOG.debug("doQuery ");
-        String statement = "SELECT * from cmis:document WHERE IN_FOLDER('" + rootFolderId + "')";
-        discSvc.query(repositoryId, statement, false /* searchAllVersions */, false /* includeAllowableActions */,
-                IncludeRelationships.NONE, null, MAX_ITEMS, SKIP_COUNT, null);
-        renameFiles("doQuery");
-        LOG.debug("doQuery() done.");
-    }
-
-    private void getTypeChildren(String typeId) {
-        LOG.debug("getTypeChildren " + typeId);
-        repSvc.getTypeChildren(repositoryId, typeId, true /* includePropertyDefinitions */, MAX_ITEMS, SKIP_COUNT, null);
-        renameFiles("getTypeChildren");
-        LOG.debug("getTypeChildren() done.");
-    }
-
-    private String createDocument(String name, String typeId, String folderId, VersioningState versioningState) {
-        LOG.debug("createDocument " + typeId);
-
-        String id = createDocumentIntern(name, typeId, folderId, versioningState);
-        renameFiles("createDocument");
-        LOG.debug("createDocument() done.");
-
-        return id;
-    }
-
-    private String createDocumentIntern(String name, String typeId, String folderId, VersioningState versioningState) {
-        ContentStream contentStream = null;
-        List<String> policies = null;
-        Acl addACEs = null;
-        Acl removeACEs = null;
-        ExtensionsData extension = null;
-
-        List<PropertyData<?>> properties = new ArrayList<PropertyData<?>>();
-        properties.add(objFactory.createPropertyIdData(PropertyIds.NAME, name));
-        properties.add(objFactory.createPropertyIdData(PropertyIds.OBJECT_TYPE_ID, typeId));
-        Properties props = objFactory.createPropertiesData(properties);
-
-        contentStream = createContent();
-
-        String id = null;
-        id = objSvc.createDocument(repositoryId, props, folderId, contentStream, versioningState, policies, addACEs,
-                removeACEs, extension);
-        return id;
-    }
-
-    private ContentStream createContent() {
-        ContentStreamImpl content = new ContentStreamImpl();
-        content.setFileName("data.txt");
-        content.setMimeType("text/plain");
-        int len = 32 * 1024;
-        byte[] b = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x0c, 0x0a,
-                0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x0c, 0x0a }; // 32
-        // Bytes
-        ByteArrayOutputStream ba = new ByteArrayOutputStream(len);
-        try {
-            for (int i = 0; i < 1024; i++) {
-                ba.write(b);
-            }
-        } catch (IOException e) {
-            throw new RuntimeException("Failed to fill content stream with data", e);
-        }
-        content.setStream(new ByteArrayInputStream(ba.toByteArray()));
-        content.setLength(BigInteger.valueOf(len));
-        return content;
-    }
-
-    private void updateProperties(String id, String propertyId, String propertyValue) {
-        LOG.debug("updateProperties " + id);
-        List<PropertyData<?>> properties = new ArrayList<PropertyData<?>>();
-        properties.add(objFactory.createPropertyStringData(propertyId, propertyValue));
-        Properties newProps = objFactory.createPropertiesData(properties);
-
-        Holder<String> idHolder = new Holder<String>(id);
-        Holder<String> changeTokenHolder = new Holder<String>();
-        objSvc.updateProperties(repositoryId, idHolder, changeTokenHolder, newProps, null);
-        renameFiles("updateProperties");
-        LOG.debug("updateProperties() done.");
-    }
-
-    private void deleteObject(String id) {
-        LOG.debug("deleteObject " + id);
-        objSvc.deleteObject(repositoryId, id, true, null);
-        renameFiles("deleteObject");
-        LOG.debug("deleteObject() done.");
-    }
-
-    private void cleanup (String[] ids) {
-        LOG.debug("cleaning up...");
-        for (String id : ids) {
-            LOG.debug("deleteing object " + id);
-            objSvc.deleteObject(repositoryId, id, true, null);            
-        }
-        LOG.debug("... cleaning up done");
-    }
-    
-    /**
-     * enumerate the children of the root folder and return the id of the first
-     * document
-     * 
-     * @return id of first doc in root folder
-     */
-    private String getTestDocId() {
-        return getTestId(BaseTypeId.CMIS_DOCUMENT);
-    }
-
-    /**
-     * enumerate the children of the root folder and return the id of the first
-     * sub-folder
-     * 
-     * @return id of first doc in root folder
-     */
-    private String getTestFolderId() {
-        return getTestId(BaseTypeId.CMIS_FOLDER);
-    }
-
-    private String getTestId(BaseTypeId baseTypeId) {
-        LOG.debug("getTestDocId()");
-        ObjectInFolderList result = navSvc.getChildren(repositoryId, rootFolderId, "*", null, false,
-                IncludeRelationships.NONE, null, true, MAX_ITEMS, SKIP_COUNT, null);
-
-        List<ObjectInFolderData> children = result.getObjects();
-        LOG.debug(" found " + children.size() + " folders in getChildren()");
-        for (ObjectInFolderData child : children) {
-            if (baseTypeId.equals(child.getObject().getBaseTypeId()))
-                return child.getObject().getId();
-        }
-        return null;
-    }
-
-    private String prepareVersionSeries(String name, String typeId, String folderId) {
-        String id = createDocumentIntern(name, typeId, folderId, VersioningState.MAJOR);
-        Holder<Boolean> contentCopied = new Holder<Boolean>();
-        Holder<String> idHolder = new Holder<String>(id);
-
-        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
-        String checkinComment = "Checkin V2.0";
-        verSvc.checkIn(repositoryId, idHolder, true /*major*/, null /*properties*/, null /*content*/,
-                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
-
-        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
-        checkinComment = "Checkin V2.1";
-        verSvc.checkIn(repositoryId, idHolder, false /*major*/, null /*properties*/, null /*content*/,
-                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
-        
-        return idHolder.getValue();
-    }
-    
-    private void checkOut(String id) {
-        LOG.debug("checkOut()");        
-        Holder<String> idHolder = new Holder<String>(id);
-        Holder<Boolean> contentCopied = new Holder<Boolean>(true);
-        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
-        renameFiles("checkOut");
-        LOG.debug("checkOut done.");
-    }
-
-    private void checkIn(String id, boolean major, String checkinComment) {
-        LOG.debug("checkIn()");        
-        Holder<String> idHolder = new Holder<String>(id);
-        verSvc.checkIn(repositoryId, idHolder, major /*major*/, null /*properties*/, null /*content*/,
-                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
-        renameFiles("checkIn");
-        LOG.debug("checkIn done.");
-    }
-
-    private void getAllVersions(String id) {
-        LOG.debug("getAllVersions()");     
-        verSvc.getAllVersions(repositoryId, id/* object id */, id/* series id */, "*"/* filter */,
-                false /* includeAllowableActions */, null /* extension */);
-        renameFiles("getAllVersions");
-        LOG.debug("getAllVersions done.");
-    }
-    
-    private void getAcl(String objectId) {
-        LOG.debug("getting Acl() " + objectId);
-
-        // get old ACL first:
-        Acl oldAcl = aclSvc.getAcl(repositoryId, objectId, true, null);
-
-        // create a new ACL for the test doc
-        List<Ace> aces = new ArrayList<Ace>();
-        aces.add(objFactory.createAccessControlEntry("Alice", Collections.singletonList("cmis:read")));
-        aces.add(objFactory.createAccessControlEntry("Bob", Collections.singletonList("cmis:write")));
-        aces.add(objFactory.createAccessControlEntry("admin", Collections.singletonList("cmis:all")));
-        Acl acl = objFactory.createAccessControlList(aces);
-
-        // add the new ACL and remove the old one
-        aclSvc.applyAcl(repositoryId, objectId, acl, oldAcl, AclPropagation.OBJECTONLY, null);
-            
-        aclSvc.getAcl(repositoryId, objectId, true, null);
-        renameFiles("getAcl");
-        LOG.debug("getting Acl() done.");
-    }
-
-    private void getTypeDefinition(String typeId) {
-        LOG.debug("getTypeDefinition " + typeId);
-        repSvc.getTypeDefinition(repositoryId, typeId, null);
-        renameFiles("getTypeDefinition");
-        LOG.debug("getTypeDefinition() done.");
-    }
-
-    private void getTypeDescendants(String typeId) {
-        LOG.debug("getTypeDescendants " + typeId);
-        repSvc.getTypeDescendants(repositoryId, typeId, TYPE_DEPTH_ALL, true /* includePropertyDefinitions */, null);
-        renameFiles("getTypeDescendants");
-        LOG.debug("getTypeDescendants() done.");
-    }
-
-    private void getAllowableActions(String objectId) {
-        LOG.debug("getAllowableActions " + objectId);
-        objSvc.getAllowableActions(repositoryId, objectId, null);
-        renameFiles("getAllowableActions");
-        LOG.debug("getAllowableActions() done.");
-    }
-
-    private void renameFiles(String name) {
-        String fileNameInReq = findLastFile(LOGDIR, "*-request.log");
-        String fileNameInResp = findLastFile(LOGDIR, "*-response.log");
-        if (null == fileNameInReq) {
-            LOG.error("Failed to find captured request file for " + name);
-            return;
-        }
-        if (null == fileNameInResp) {
-            LOG.error("Failed to find captured response file for " + name);
-            return;
-        }
-        File in = new File(fileNameInReq);
-        File out = new File(targetDir + File.separator + name + "-request.log");
-        if (out.exists())
-            out.delete();
-        boolean ok = in.renameTo(out);
-        if (ok)
-            LOG.debug("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " succeeded.");
-        else
-            LOG.warn("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " failed.");
-
-        in = new File(fileNameInResp);
-        out = new File(targetDir + File.separator + name + "-response.log");
-        if (out.exists())
-            out.delete();
-        ok = in.renameTo(out);
-        if (ok)
-            LOG.debug("Renaming file " + in.getAbsolutePath() + "to " + out.getAbsolutePath() + " succeeded.");
-        else
-            LOG.warn("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " failed.");
-    }
-    
-    private void createZipFile(String zipFileName, String[] dirs) {
-        
-        File out = new File(zipFileName);
-        if (out.exists())
-            out.delete();
-        
-        FileOutputStream fout = null;
-        ZipOutputStream zout =null;
-        try {
-            fout = new FileOutputStream(zipFileName);
-            zout = new ZipOutputStream(fout);
-            for (String dir: dirs) {
-                File dirToZip = new File(dir);
-                addDirectory(zout, dir, dirToZip);
-            }
-        } catch (Exception e) {
-            LOG.error("Creating ZIP file failed: " + e);
-        } finally {
-            try {
-                if (zout != null)
-                    zout.close();
-                if (fout != null)
-                    fout.close();
-            } catch (IOException e) {
-                LOG.error(e);
-            }
-        }
-    }
-    
-    private static void addDirectory(ZipOutputStream zout, String prefix, File sourceDir) throws IOException {
-        
-        File[] files = sourceDir.listFiles();
-        LOG.debug("Create Zip, adding directory " + sourceDir.getName());
-               
-        if (null != files) {
-            for(int i=0; i < files.length; i++)
-            {
-                if(files[i].isDirectory())
-                {
-                    addDirectory(zout, prefix + File.separator + files[i].getName(), files[i]);
-                } else {
-                    LOG.debug("Create Zip, adding file " + files[i].getName());
-                    byte[] buffer = new byte[65536];
-                    FileInputStream fin = new FileInputStream(files[i]);
-                    String zipEntryName = prefix + File.separator + files[i].getName();
-                    LOG.debug("   adding entry " + zipEntryName);
-                    zout.putNextEntry(new ZipEntry(zipEntryName));
-
-                    int length;
-                    while((length = fin.read(buffer)) > 0)
-                    {
-                        zout.write(buffer, 0, length);
-                    }
-
-                    zout.closeEntry();
-                    fin.close();
-                }
-            }      
-        }
-    }
-    
-    public static void clean() {
-        LOG.debug("Cleaning generated and captured request and response logs...");
-        
-        cleanFilesWithFilter(LOGDIR, "*-request.log");
-        cleanFilesWithFilter(LOGDIR, "*-response.log");
-        for (int i = 0; i < BINDINGS.length; i++) {
-            String dir = BINDINGS[i].value();
-            
-            cleanFilesWithFilter(dir, "*-request.log");
-            cleanFilesWithFilter(dir, "*-response.log");
-
-            File dirToDelete = new File (dir);
-            boolean ok = dirToDelete.delete();
-            if (ok)
-                LOG.debug("Deleting dir " + dirToDelete.getAbsolutePath() + " succeeded.");
-            else
-                LOG.warn("Deleting dir " + dirToDelete.getAbsolutePath() + " failed.");
-        }
-        LOG.debug("... done.");        
-    }
-    
-    private static void cleanFilesWithFilter(String directoryPath, String wildcardFilter) {
-        File dir = new File(directoryPath);
-        FileFilter fileFilter = new WildcardFileFilter(wildcardFilter);
-        File[] files = dir.listFiles(fileFilter);
-        if (files != null)
-            for (int i = 0; i < files.length; i++) {
-                boolean ok = files[i].delete();
-                LOG.debug("Deleting file: " + files[i] + ", success: " + ok);
-            }        
-    }
-    
-    private static String findLastFile(String directoryPath, String wildcardFilter) {
-        File dir = new File(directoryPath);
-        FileFilter fileFilter = new WildcardFileFilter(wildcardFilter);
-        File[] files = dir.listFiles(fileFilter);
-        if (files.length == 0)
-            return null;
-        else
-            return files[files.length-1].getAbsolutePath();
-    }
-
-    public static void main(String[] args) {
-        if (args.length > 0 && args[0].equals("-clean")) {
-            LOG.debug("Cleaning up generated files...");
-            Main.clean();
-            LOG.debug("... cleaning up done.");
-        } else {
-            LOG.debug("Starting generating spec examples...");
-            Main main = new Main();
-            main.runAllBindings();
-            LOG.debug("... finished generating spec examples.");
-        }
-    }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.chemistry.opencmis.util.specexamples;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.chemistry.opencmis.client.bindings.CmisBindingFactory;
+import org.apache.chemistry.opencmis.commons.PropertyIds;
+import org.apache.chemistry.opencmis.commons.SessionParameter;
+import org.apache.chemistry.opencmis.commons.data.Ace;
+import org.apache.chemistry.opencmis.commons.data.Acl;
+import org.apache.chemistry.opencmis.commons.data.CmisExtensionElement;
+import org.apache.chemistry.opencmis.commons.data.ContentStream;
+import org.apache.chemistry.opencmis.commons.data.ExtensionsData;
+import org.apache.chemistry.opencmis.commons.data.ObjectInFolderData;
+import org.apache.chemistry.opencmis.commons.data.ObjectInFolderList;
+import org.apache.chemistry.opencmis.commons.data.Properties;
+import org.apache.chemistry.opencmis.commons.data.PropertyData;
+import org.apache.chemistry.opencmis.commons.data.RepositoryInfo;
+import org.apache.chemistry.opencmis.commons.enums.AclPropagation;
+import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
+import org.apache.chemistry.opencmis.commons.enums.BindingType;
+import org.apache.chemistry.opencmis.commons.enums.IncludeRelationships;
+import org.apache.chemistry.opencmis.commons.enums.VersioningState;
+import org.apache.chemistry.opencmis.commons.impl.dataobjects.BindingsObjectFactoryImpl;
+import org.apache.chemistry.opencmis.commons.impl.dataobjects.CmisExtensionElementImpl;
+import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl;
+import org.apache.chemistry.opencmis.commons.impl.dataobjects.ExtensionDataImpl;
+import org.apache.chemistry.opencmis.commons.spi.AclService;
+import org.apache.chemistry.opencmis.commons.spi.BindingsObjectFactory;
+import org.apache.chemistry.opencmis.commons.spi.CmisBinding;
+import org.apache.chemistry.opencmis.commons.spi.DiscoveryService;
+import org.apache.chemistry.opencmis.commons.spi.Holder;
+import org.apache.chemistry.opencmis.commons.spi.MultiFilingService;
+import org.apache.chemistry.opencmis.commons.spi.NavigationService;
+import org.apache.chemistry.opencmis.commons.spi.ObjectService;
+import org.apache.chemistry.opencmis.commons.spi.RepositoryService;
+import org.apache.chemistry.opencmis.commons.spi.VersioningService;
+import org.apache.commons.io.filefilter.WildcardFileFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Main {
+
+    private static final Logger LOG = LoggerFactory.getLogger(Main.class.getName());
+    private static final BigInteger TYPE_DEPTH_ALL = BigInteger.valueOf(-1);
+    private static final BigInteger MAX_ITEMS = null;
+    private static final BigInteger SKIP_COUNT = BigInteger.valueOf(0);
+    private static final String TOPLEVEL_TYPE = "DocumentTopLevel";
+    private static final String VERSIONED_TYPE = "VersionableType";
+    private static String LOGDIR = System.getProperty("java.io.tmpdir");// + File.separator;
+    private String targetDir = System.getProperty("java.io.tmpdir");// + File.separator;
+
+    private BindingsObjectFactory objFactory = new BindingsObjectFactoryImpl();
+    private BindingType bindingType;
+    private String rootFolderId;
+    private String repositoryId;
+    private ObjectService objSvc;
+    private NavigationService navSvc;
+    private RepositoryService repSvc;
+    private VersioningService verSvc;
+    private MultiFilingService multiSvc;
+    private DiscoveryService discSvc;
+    private AclService aclSvc;
+
+    private static final String[] URLS = {"http://de05189:8080/inmemory/atom", 
+            "http://de05189:8080/inmemory/services", 
+            "http://de05189:8080/inmemory/browser"};
+    private static final BindingType[] BINDINGS = {BindingType.ATOMPUB, BindingType.WEBSERVICES, BindingType.BROWSER};
+
+    public Main() {
+    }
+
+    public void runAllBindings() {
+      for (int i = 0; i < BINDINGS.length; i++) {
+            bindingType = BINDINGS[i];
+            init(URLS[i], BINDINGS[i]);
+            run();
+        }
+        
+    }
+    
+    public void run() {
+        LOG.debug("Generating spec examples for Binding: " + bindingType.value());
+        // Repository Service:
+        getRepositories();
+
+        repositoryId = "A1";
+        getRepositoryInfo();
+
+        getTypeDefinition("cmis:folder");
+        
+        String docId = getTestDocId();
+        String folderId = getTestFolderId();
+
+        getTypeChildren(TOPLEVEL_TYPE);
+
+        // Navigation Service:
+        getChildren(folderId);
+        getDescendants(folderId);
+
+        // Object Service:
+        getObject(docId);
+        getAcl(docId);
+        String id1 = createDocument("SampleDocument", TOPLEVEL_TYPE, rootFolderId, VersioningState.NONE);
+        updateProperties(id1, PropertyIds.NAME, "RenamedDocument");
+        getAllowableActions(id1);
+        
+        deleteObject(id1);
+
+        // Discovery Service:
+        doQuery();
+
+        // Versioning Service
+        String id2 = prepareVersionSeries("VersionedDocument", VERSIONED_TYPE, rootFolderId);
+        checkOut(id2);
+        checkIn(id2, true, "final version in series");
+        getAllVersions(id2);
+
+        // delete all generated objects
+        String[] ids = {id2};
+        
+        cleanup(ids);
+
+        // collect all captured files and store them in a ZIP file
+        String dirs[] = {BindingType.ATOMPUB.value(), BindingType.WEBSERVICES.value(), BindingType.BROWSER.value() };        
+        createZipFile("CMIS-Spec-Examples.zip", dirs);
+    }
+
+    private void init(String url, BindingType bindingType) {
+        LOG.debug("Initializing connection to InMemory server: ");
+        LOG.debug("   Binding: " + bindingType.value());
+        LOG.debug("   URL: " + url);
+
+        Map<String, String> parameters = new HashMap<String, String>();
+        parameters.put(SessionParameter.USER, "admin");
+        parameters.put(SessionParameter.PASSWORD, "admin");
+
+        parameters.put(SessionParameter.BINDING_TYPE, bindingType.value());
+
+        // get factory and create binding
+        CmisBindingFactory factory = CmisBindingFactory.newInstance();
+        CmisBinding binding = null;
+        
+        if (bindingType == BindingType.ATOMPUB)  {
+            parameters.put(SessionParameter.ATOMPUB_URL, url);
+            binding = factory.createCmisAtomPubBinding(parameters);
+        } else if (bindingType == BindingType.WEBSERVICES) {
+            parameters.put(SessionParameter.WEBSERVICES_ACL_SERVICE, url + "/ACLService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_DISCOVERY_SERVICE,  url + "/DiscoveryService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_MULTIFILING_SERVICE,  url + "/MultiFilingService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_NAVIGATION_SERVICE,  url + "/NavigationService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_OBJECT_SERVICE,  url + "/ObjectService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_POLICY_SERVICE,  url + "/PolicyService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_RELATIONSHIP_SERVICE,  url + "/RelatinshipService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_REPOSITORY_SERVICE,  url + "/RepositoryService?wsdl");
+            parameters.put(SessionParameter.WEBSERVICES_VERSIONING_SERVICE,  url + "/VersioningService?wsdl");
+            binding = factory.createCmisWebServicesBinding(parameters);            
+        } else if (bindingType == BindingType.BROWSER) {
+            parameters.put(SessionParameter.BROWSER_URL, url); 
+            binding = factory.createCmisBrowserBinding(parameters);            
+        } else {
+            LOG.error("Unknown binding type: " + bindingType.value());
+            return;
+        }
+        objFactory = binding.getObjectFactory();
+        repSvc = binding.getRepositoryService();
+        objSvc = binding.getObjectService();
+        navSvc = binding.getNavigationService();
+        verSvc = binding.getVersioningService();
+        multiSvc = binding.getMultiFilingService();
+        discSvc = binding.getDiscoveryService();
+        aclSvc = binding.getAclService();
+        
+        // create a folder where target files will be stored:
+        targetDir = bindingType.value();
+        File in = new File(targetDir);
+        boolean ok = in.mkdir();
+        
+        LOG.debug("creating target directory for files: " + ok);
+        LOG.debug("Initializing done. ");
+    }
+
+    private void getRepositories() {
+        LOG.debug("getRepositories()");
+        List<RepositoryInfo> repositories = repSvc.getRepositoryInfos(null);
+        this.repositoryId = repositories.get(0).getId();
+        renameFiles("getRepositoryInfos");
+        LOG.debug("getRepositoryInfo() done.");
+    }
+
+    private void getRepositoryInfo() {
+        LOG.debug("getting repository info for repository " + repositoryId);
+        // Because the browser binding silently retrieves all repositories on the first request we call it twice
+        // and use a dummy extension data element to prevent caching
+        RepositoryInfo repoInfo = repSvc.getRepositoryInfo(repositoryId, null);
+        if (bindingType.equals(BindingType.BROWSER)) {
+            ExtensionDataImpl dummyExt = new ExtensionDataImpl();
+            List<CmisExtensionElement> extList = new ArrayList<CmisExtensionElement>() {{ add(new CmisExtensionElementImpl("foo", "foo", null, "bar")); }};
+            dummyExt.setExtensions(extList);
+            repoInfo = repSvc.getRepositoryInfo(repositoryId, dummyExt);
+        }
+        LOG.debug("repository id is: " + repoInfo.getId());
+        rootFolderId = repoInfo.getRootFolderId();
+        LOG.debug("root folder id is: " + repoInfo.getRootFolderId());
+        renameFiles("getRepositoryInfo");
+        LOG.debug("getRepositoryInfo() done.");
+    }
+
+    private void getObject(String objectId) {
+        LOG.debug("getObject " + objectId);
+        objSvc.getObject(repositoryId, objectId, "*", false /* includeAllowableActions */,
+                IncludeRelationships.NONE /* includeRelationships */, null /* renditionFilter */,
+                false /* includePolicyIds */, false /* includeAcl */, null);
+        renameFiles("getObject");
+        LOG.debug("getObject() done.");
+    }
+
+    private void getChildren(String folderId) {
+        LOG.debug("getChildren " + folderId);
+        navSvc.getChildren(repositoryId, folderId, "*", null /* orderBy */, false /* includeAllowableActions */,
+                IncludeRelationships.NONE, null /* renditionFilter */, true /* includePathSegment */, MAX_ITEMS,
+                SKIP_COUNT, null);
+        renameFiles("getChildren");
+        LOG.debug("getChildren() done.");
+    }
+
+    private void getDescendants(String folderId) {
+        final BigInteger DEPTH = BigInteger.valueOf(3);
+        LOG.debug("getDescendants " + folderId);
+        navSvc.getDescendants(repositoryId, folderId, DEPTH, "*", false /* includeAllowableActions */,
+                IncludeRelationships.NONE, null /* renditionFilter */, true /* includePathSegment */, null);
+        renameFiles("getDescendants");
+        LOG.debug("getDescendants() done.");
+    }
+
+    private void doQuery() {
+        LOG.debug("doQuery ");
+        String statement = "SELECT * from cmis:document WHERE IN_FOLDER('" + rootFolderId + "')";
+        discSvc.query(repositoryId, statement, false /* searchAllVersions */, false /* includeAllowableActions */,
+                IncludeRelationships.NONE, null, MAX_ITEMS, SKIP_COUNT, null);
+        renameFiles("doQuery");
+        LOG.debug("doQuery() done.");
+    }
+
+    private void getTypeChildren(String typeId) {
+        LOG.debug("getTypeChildren " + typeId);
+        repSvc.getTypeChildren(repositoryId, typeId, true /* includePropertyDefinitions */, MAX_ITEMS, SKIP_COUNT, null);
+        renameFiles("getTypeChildren");
+        LOG.debug("getTypeChildren() done.");
+    }
+
+    private String createDocument(String name, String typeId, String folderId, VersioningState versioningState) {
+        LOG.debug("createDocument " + typeId);
+
+        String id = createDocumentIntern(name, typeId, folderId, versioningState);
+        renameFiles("createDocument");
+        LOG.debug("createDocument() done.");
+
+        return id;
+    }
+
+    private String createDocumentIntern(String name, String typeId, String folderId, VersioningState versioningState) {
+        ContentStream contentStream = null;
+        List<String> policies = null;
+        Acl addACEs = null;
+        Acl removeACEs = null;
+        ExtensionsData extension = null;
+
+        List<PropertyData<?>> properties = new ArrayList<PropertyData<?>>();
+        properties.add(objFactory.createPropertyIdData(PropertyIds.NAME, name));
+        properties.add(objFactory.createPropertyIdData(PropertyIds.OBJECT_TYPE_ID, typeId));
+        Properties props = objFactory.createPropertiesData(properties);
+
+        contentStream = createContent();
+
+        String id = null;
+        id = objSvc.createDocument(repositoryId, props, folderId, contentStream, versioningState, policies, addACEs,
+                removeACEs, extension);
+        return id;
+    }
+
+    private ContentStream createContent() {
+        ContentStreamImpl content = new ContentStreamImpl();
+        content.setFileName("data.txt");
+        content.setMimeType("text/plain");
+        int len = 32 * 1024;
+        byte[] b = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x0c, 0x0a,
+                0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x0c, 0x0a }; // 32
+        // Bytes
+        ByteArrayOutputStream ba = new ByteArrayOutputStream(len);
+        try {
+            for (int i = 0; i < 1024; i++) {
+                ba.write(b);
+            }
+        } catch (IOException e) {
+            throw new RuntimeException("Failed to fill content stream with data", e);
+        }
+        content.setStream(new ByteArrayInputStream(ba.toByteArray()));
+        content.setLength(BigInteger.valueOf(len));
+        return content;
+    }
+
+    private void updateProperties(String id, String propertyId, String propertyValue) {
+        LOG.debug("updateProperties " + id);
+        List<PropertyData<?>> properties = new ArrayList<PropertyData<?>>();
+        properties.add(objFactory.createPropertyStringData(propertyId, propertyValue));
+        Properties newProps = objFactory.createPropertiesData(properties);
+
+        Holder<String> idHolder = new Holder<String>(id);
+        Holder<String> changeTokenHolder = new Holder<String>();
+        objSvc.updateProperties(repositoryId, idHolder, changeTokenHolder, newProps, null);
+        renameFiles("updateProperties");
+        LOG.debug("updateProperties() done.");
+    }
+
+    private void deleteObject(String id) {
+        LOG.debug("deleteObject " + id);
+        objSvc.deleteObject(repositoryId, id, true, null);
+        renameFiles("deleteObject");
+        LOG.debug("deleteObject() done.");
+    }
+
+    private void cleanup (String[] ids) {
+        LOG.debug("cleaning up...");
+        for (String id : ids) {
+            LOG.debug("deleteing object " + id);
+            objSvc.deleteObject(repositoryId, id, true, null);            
+        }
+        LOG.debug("... cleaning up done");
+    }
+    
+    /**
+     * enumerate the children of the root folder and return the id of the first
+     * document
+     * 
+     * @return id of first doc in root folder
+     */
+    private String getTestDocId() {
+        return getTestId(BaseTypeId.CMIS_DOCUMENT);
+    }
+
+    /**
+     * enumerate the children of the root folder and return the id of the first
+     * sub-folder
+     * 
+     * @return id of first doc in root folder
+     */
+    private String getTestFolderId() {
+        return getTestId(BaseTypeId.CMIS_FOLDER);
+    }
+
+    private String getTestId(BaseTypeId baseTypeId) {
+        LOG.debug("getTestDocId()");
+        ObjectInFolderList result = navSvc.getChildren(repositoryId, rootFolderId, "*", null, false,
+                IncludeRelationships.NONE, null, true, MAX_ITEMS, SKIP_COUNT, null);
+
+        List<ObjectInFolderData> children = result.getObjects();
+        LOG.debug(" found " + children.size() + " folders in getChildren()");
+        for (ObjectInFolderData child : children) {
+            if (baseTypeId.equals(child.getObject().getBaseTypeId()))
+                return child.getObject().getId();
+        }
+        return null;
+    }
+
+    private String prepareVersionSeries(String name, String typeId, String folderId) {
+        String id = createDocumentIntern(name, typeId, folderId, VersioningState.MAJOR);
+        Holder<Boolean> contentCopied = new Holder<Boolean>();
+        Holder<String> idHolder = new Holder<String>(id);
+
+        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
+        String checkinComment = "Checkin V2.0";
+        verSvc.checkIn(repositoryId, idHolder, true /*major*/, null /*properties*/, null /*content*/,
+                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
+
+        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
+        checkinComment = "Checkin V2.1";
+        verSvc.checkIn(repositoryId, idHolder, false /*major*/, null /*properties*/, null /*content*/,
+                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
+        
+        return idHolder.getValue();
+    }
+    
+    private void checkOut(String id) {
+        LOG.debug("checkOut()");        
+        Holder<String> idHolder = new Holder<String>(id);
+        Holder<Boolean> contentCopied = new Holder<Boolean>(true);
+        verSvc.checkOut(repositoryId, idHolder, null, contentCopied);
+        renameFiles("checkOut");
+        LOG.debug("checkOut done.");
+    }
+
+    private void checkIn(String id, boolean major, String checkinComment) {
+        LOG.debug("checkIn()");        
+        Holder<String> idHolder = new Holder<String>(id);
+        verSvc.checkIn(repositoryId, idHolder, major /*major*/, null /*properties*/, null /*content*/,
+                checkinComment, null/*policies*/, null/*addAcl*/, null /*removeAcl*/, null /*extension*/);
+        renameFiles("checkIn");
+        LOG.debug("checkIn done.");
+    }
+
+    private void getAllVersions(String id) {
+        LOG.debug("getAllVersions()");     
+        verSvc.getAllVersions(repositoryId, id/* object id */, id/* series id */, "*"/* filter */,
+                false /* includeAllowableActions */, null /* extension */);
+        renameFiles("getAllVersions");
+        LOG.debug("getAllVersions done.");
+    }
+    
+    private void getAcl(String objectId) {
+        LOG.debug("getting Acl() " + objectId);
+
+        // get old ACL first:
+        Acl oldAcl = aclSvc.getAcl(repositoryId, objectId, true, null);
+
+        // create a new ACL for the test doc
+        List<Ace> aces = new ArrayList<Ace>();
+        aces.add(objFactory.createAccessControlEntry("Alice", Collections.singletonList("cmis:read")));
+        aces.add(objFactory.createAccessControlEntry("Bob", Collections.singletonList("cmis:write")));
+        aces.add(objFactory.createAccessControlEntry("admin", Collections.singletonList("cmis:all")));
+        Acl acl = objFactory.createAccessControlList(aces);
+
+        // add the new ACL and remove the old one
+        aclSvc.applyAcl(repositoryId, objectId, acl, oldAcl, AclPropagation.OBJECTONLY, null);
+            
+        aclSvc.getAcl(repositoryId, objectId, true, null);
+        renameFiles("getAcl");
+        LOG.debug("getting Acl() done.");
+    }
+
+    private void getTypeDefinition(String typeId) {
+        LOG.debug("getTypeDefinition " + typeId);
+        repSvc.getTypeDefinition(repositoryId, typeId, null);
+        renameFiles("getTypeDefinition");
+        LOG.debug("getTypeDefinition() done.");
+    }
+
+    private void getTypeDescendants(String typeId) {
+        LOG.debug("getTypeDescendants " + typeId);
+        repSvc.getTypeDescendants(repositoryId, typeId, TYPE_DEPTH_ALL, true /* includePropertyDefinitions */, null);
+        renameFiles("getTypeDescendants");
+        LOG.debug("getTypeDescendants() done.");
+    }
+
+    private void getAllowableActions(String objectId) {
+        LOG.debug("getAllowableActions " + objectId);
+        objSvc.getAllowableActions(repositoryId, objectId, null);
+        renameFiles("getAllowableActions");
+        LOG.debug("getAllowableActions() done.");
+    }
+
+    private void renameFiles(String name) {
+        String fileNameInReq = findLastFile(LOGDIR, "*-request.log");
+        String fileNameInResp = findLastFile(LOGDIR, "*-response.log");
+        if (null == fileNameInReq) {
+            LOG.error("Failed to find captured request file for " + name);
+            return;
+        }
+        if (null == fileNameInResp) {
+            LOG.error("Failed to find captured response file for " + name);
+            return;
+        }
+        File in = new File(fileNameInReq);
+        File out = new File(targetDir + File.separator + name + "-request.log");
+        if (out.exists())
+            out.delete();
+        boolean ok = in.renameTo(out);
+        if (ok)
+            LOG.debug("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " succeeded.");
+        else
+            LOG.warn("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " failed.");
+
+        in = new File(fileNameInResp);
+        out = new File(targetDir + File.separator + name + "-response.log");
+        if (out.exists())
+            out.delete();
+        ok = in.renameTo(out);
+        if (ok)
+            LOG.debug("Renaming file " + in.getAbsolutePath() + "to " + out.getAbsolutePath() + " succeeded.");
+        else
+            LOG.warn("Renaming file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + " failed.");
+    }
+    
+    private void createZipFile(String zipFileName, String[] dirs) {
+        
+        File out = new File(zipFileName);
+        if (out.exists())
+            out.delete();
+        
+        FileOutputStream fout = null;
+        ZipOutputStream zout =null;
+        try {
+            fout = new FileOutputStream(zipFileName);
+            zout = new ZipOutputStream(fout);
+            for (String dir: dirs) {
+                File dirToZip = new File(dir);
+                addDirectory(zout, dir, dirToZip);
+            }
+        } catch (Exception e) {
+            LOG.error("Creating ZIP file failed: " + e);
+        } finally {
+            try {
+                if (zout != null)
+                    zout.close();
+                if (fout != null)
+                    fout.close();
+            } catch (IOException e) {
+                LOG.error(e.toString(), e);
+            }
+        }
+    }
+    
+    private static void addDirectory(ZipOutputStream zout, String prefix, File sourceDir) throws IOException {
+        
+        File[] files = sourceDir.listFiles();
+        LOG.debug("Create Zip, adding directory " + sourceDir.getName());
+               
+        if (null != files) {
+            for(int i=0; i < files.length; i++)
+            {
+                if(files[i].isDirectory())
+                {
+                    addDirectory(zout, prefix + File.separator + files[i].getName(), files[i]);
+                } else {
+                    LOG.debug("Create Zip, adding file " + files[i].getName());
+                    byte[] buffer = new byte[65536];
+                    FileInputStream fin = new FileInputStream(files[i]);
+                    String zipEntryName = prefix + File.separator + files[i].getName();
+                    LOG.debug("   adding entry " + zipEntryName);
+                    zout.putNextEntry(new ZipEntry(zipEntryName));
+
+                    int length;
+                    while((length = fin.read(buffer)) > 0)
+                    {
+                        zout.write(buffer, 0, length);
+                    }
+
+                    zout.closeEntry();
+                    fin.close();
+                }
+            }      
+        }
+    }
+    
+    public static void clean() {
+        LOG.debug("Cleaning generated and captured request and response logs...");
+        
+        cleanFilesWithFilter(LOGDIR, "*-request.log");
+        cleanFilesWithFilter(LOGDIR, "*-response.log");
+        for (int i = 0; i < BINDINGS.length; i++) {
+            String dir = BINDINGS[i].value();
+            
+            cleanFilesWithFilter(dir, "*-request.log");
+            cleanFilesWithFilter(dir, "*-response.log");
+
+            File dirToDelete = new File (dir);
+            boolean ok = dirToDelete.delete();
+            if (ok)
+                LOG.debug("Deleting dir " + dirToDelete.getAbsolutePath() + " succeeded.");
+            else
+                LOG.warn("Deleting dir " + dirToDelete.getAbsolutePath() + " failed.");
+        }
+        LOG.debug("... done.");        
+    }
+    
+    private static void cleanFilesWithFilter(String directoryPath, String wildcardFilter) {
+        File dir = new File(directoryPath);
+        FileFilter fileFilter = new WildcardFileFilter(wildcardFilter);
+        File[] files = dir.listFiles(fileFilter);
+        if (files != null)
+            for (int i = 0; i < files.length; i++) {
+                boolean ok = files[i].delete();
+                LOG.debug("Deleting file: " + files[i] + ", success: " + ok);
+            }        
+    }
+    
+    private static String findLastFile(String directoryPath, String wildcardFilter) {
+        File dir = new File(directoryPath);
+        FileFilter fileFilter = new WildcardFileFilter(wildcardFilter);
+        File[] files = dir.listFiles(fileFilter);
+        if (files.length == 0)
+            return null;
+        else
+            return files[files.length-1].getAbsolutePath();
+    }
+
+    public static void main(String[] args) {
+        if (args.length > 0 && args[0].equals("-clean")) {
+            LOG.debug("Cleaning up generated files...");
+            Main.clean();
+            LOG.debug("... cleaning up done.");
+        } else {
+            LOG.debug("Starting generating spec examples...");
+            Main main = new Main();
+            main.runAllBindings();
+            LOG.debug("... finished generating spec examples.");
+        }
+    }
+}

Modified: chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/test/java/org/apache/chemistry/opencmis/util/content/loremipsum/LoremIpsumTest.java
URL: http://svn.apache.org/viewvc/chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/test/java/org/apache/chemistry/opencmis/util/content/loremipsum/LoremIpsumTest.java?rev=1293600&r1=1293599&r2=1293600&view=diff
==============================================================================
--- chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/test/java/org/apache/chemistry/opencmis/util/content/loremipsum/LoremIpsumTest.java (original)
+++ chemistry/opencmis/branches/android/chemistry-opencmis-test/chemistry-opencmis-test-util/src/test/java/org/apache/chemistry/opencmis/util/content/loremipsum/LoremIpsumTest.java Sat Feb 25 13:43:31 2012
@@ -1,401 +1,397 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.chemistry.opencmis.util.content.loremipsum;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-
-import org.apache.chemistry.opencmis.util.content.loremipsum.LoremIpsum;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class LoremIpsumTest {
-
-    private static final Log LOG = LogFactory.getLog(LoremIpsumTest.class);
-
-    String sample = "One two three four five six. Seven eight nine ten eleven twelve. "
-		+ "\n\n"
-		+ "Thirteen fourteen fifteen sixteen. Seventeen eighteen nineteen twenty.";
-       
-    String dictionary = "a bb ccc dddd eeeee ffffff ggggggg hhhhhhhh iiiiiiiii jjjjjjjjjj kkkkkkkkkkk llllllllllll";
-    LoremIpsum generator = new LoremIpsum(sample, dictionary);
-    
-	@Before
-	public void setUp() throws Exception {
-	    dictionary.split(" ");
-	}
-
-	@After
-	public void tearDown() throws Exception {
-	}
-
-	@Test
-	public void  test_mean() {
-		int[] ia1 = {1, 2, 3, 4};
-        assertEquals(2.5d, LoremIpsum.mean(ia1), 0.01d);
-        int[] ia2 = {6, 6, 4, 4};
-        assertEquals(5.0d, LoremIpsum.mean(ia2), 0.01d);
-	}
-	
-    @Test
-	public void  test_mean_empty() {
-		int[] ia1 = {};
-        assertEquals(0.0d, LoremIpsum.mean(ia1), 0.01d);
-    }
-    
-    @Test
-	public void  test_variance() {
-		double[] ia1 = {6.0d, 6.0d, 4.0d, 4.0d};
-        assertEquals(1.0d, LoremIpsum.variance(ia1), 0.01d);
-        double[] ia2 = {1.0d, 2.0d, 3.0d, 4.0d};
-        assertEquals(1.25d, LoremIpsum.variance(ia2), 0.01d);
-    }
-    
-    @Test
-	public void  test_sigma() {
-		double[] ia1 = {6.0d, 6.0d, 4.0d, 4.0d};
-        double[] ia2 = {1.0d, 2.0d, 3.0d, 4.0d};
-        assertEquals(1.0d, LoremIpsum.sigma(ia1), 0.01d);
-        assertEquals(Math.sqrt(1.25), LoremIpsum.sigma(ia2), 0.01d);
-    }
-    
-    @Test
-	public void  test_sigma_empty() {
-		int[] ia1 = {};
-        assertEquals(0.0d, LoremIpsum.sigma(ia1), 0.01d);
-    }
-    
-    @Test
-	public void test_split_sentences() {
-    	String[] sentences1 = {"Hello", "Hi"};
-    	assertArrayEquals (sentences1, LoremIpsum.splitSentences("Hello. Hi."));
-        String[] sentences2 = {"One two three four five six", 
-                                 "Seven eight nine ten eleven twelve", 
-                                 "Thirteen fourteen fifteen sixteen", 
-                                 "Seventeen eighteen nineteen twenty"}; 
-        assertArrayEquals(sentences2, LoremIpsum.splitSentences(sample));
-    }
-    
-    @Test
-	public void test_split_sentences_empty() {
-    	String[] sentences = {};
-    	assertArrayEquals(sentences, LoremIpsum.splitSentences(""));
-    }
-    
-    @Test
-	public void test_split_sentences_trailing() {
-    	String[] sentences1 = {"Hello", "Hi", "Hello"};    	
-    	assertArrayEquals(sentences1, LoremIpsum.splitSentences("Hello. Hi. Hello"));
-    	String[] sentences2 = {"Hello", "Hi", "Hello"};
-    	assertArrayEquals(sentences2, LoremIpsum.splitSentences("  Hello. Hi. Hello  "));
-        String[] sentences3 = {"Hello", "Hi", "Hello"};
-        assertArrayEquals(sentences3, LoremIpsum.splitSentences("..  Hello... Hi.... Hello  ")); 
-    }
-
-    @Test
-	public void test_split_paragraphs() {
-    	String[] paragraphs = {"One two three four five six. Seven eight nine ten eleven twelve.",
-    			"Thirteen fourteen fifteen sixteen. Seventeen eighteen nineteen twenty."};
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs(sample));
-    }
-    
-    @Test
-	public void test_split_paragraphs_empty() {
-    	String[] paragraphs = {};
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs(""));
-    }
-    
-    @Test
-	public void test_split_paragraphs_trailing() {
-    	String[] paragraphs = {"Hello", "Hi"};
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n\n"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n\n\n\n\n"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\nHello\n\nHi"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\nHello\n\nHi"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\n\nHello\n\nHi"));
-    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\n\n\n\n\nHello\n\nHi"));
-    }
-    
-    @Test
-	public void test_split_words() {
-    	String[] words = {"One", "two", "three", "four"};
-    	assertArrayEquals(words, LoremIpsum.splitWords("One two three four"));    	
-    	assertArrayEquals(words, LoremIpsum.splitWords("  One    two  three  four   ")); 
-    }
-                
-    @Test
-	public void test_split_words_empty() {
-    	String[] words = {};
-    	assertArrayEquals(words, LoremIpsum.splitWords(""));
-	}
-    
-    @Test
-	public void test_choose_closest() {
-    	Integer[] intArray1 ={1,2,3,4};
-        assertEquals(1, LoremIpsum.chooseClosest(intArray1, 1));
-        Integer[] intArray2 ={1,2,3,4};
-        assertEquals(4, LoremIpsum.chooseClosest(intArray2, 4));
-        assertEquals(4, LoremIpsum.chooseClosest(intArray2, 20));
-        assertEquals(1, LoremIpsum.chooseClosest(intArray2, -10));
-        Integer[] intArray3 ={1,4};
-        assertEquals(1, LoremIpsum.chooseClosest(intArray3, 2));
-        assertEquals(4, LoremIpsum.chooseClosest(intArray3, 3));
-        Integer[] intArray4 ={1,3};
-        assertEquals(1, LoremIpsum.chooseClosest(intArray4, 2));
-        Integer[] intArray5 ={3,1};
-        assertEquals(3, LoremIpsum.chooseClosest(intArray5, 2));
-        Integer[] intArray6 ={1};
-        assertEquals(1, LoremIpsum.chooseClosest(intArray6, 200));
-    }
-
-    @Test
-	public void test_sentence_mean() {
-        assertEquals(5.0d, generator.getSentenceMean(), 0.01d);
-	}
-   
-    @Test
-	public void test_paragraph_mean() {
-    	assertEquals(2.0d, generator.getParagraphMean(), 0.01d);
-    }
-        
-    @Test
-	public void test_sentence_sigma() {
-        assertEquals(1.0d, generator.getSentenceSigma(), 0.01d);
-    }
-        
-    @Test
-	public void test_paragraph_sigma() {
-        assertEquals(0.0d, generator.getParagraphSigma(), 0.01d);
-    }
-        
-    @Test
-	public void test_sample() {
-        assertEquals(generator.getSample(), sample);
-    }
-
-    @Test
-	public void test_dictionary() {
-        assertEquals(generator.getDictionary(), dictionary);
-    }
-
-    @Test
-	public void test_set_dictionary() {
-        String newdict = "a b c";
-        generator.setDictionary(newdict);
-        assertEquals(generator.getDictionary(), newdict);
-	}
-    
-    @Test 
-    public void test_init_no_sample() {
-    	doGenerate("");
-    	doGenerate(" ");
-    	doGenerate("\n\n");
-    	doGenerate("  \n\n  ");
-    	doGenerate(" .\n\n .");
-    }
-    
-    private void doGenerate(String text) {
-    	try {
-    		generator = new LoremIpsum(text, dictionary);
-    		generator.generateParagraph(false);
-    		fail("Sample text " + text + " should generate exception.");
-    	} catch (RuntimeException e) {
-    		assertTrue(e.getMessage().contains("Invalid sample text"));
-    	}
-    }
-    
-    @Test 
-    public void test_init_no_dict() {
-    	doGenerateNoDict("");
-    	doGenerateNoDict(" ");
-    	doGenerateNoDict("\n\n");
-    	doGenerateNoDict("  \n\n  ");
-    }
-    
-    private void doGenerateNoDict(String dict) {
-    	try {
-    		generator = new LoremIpsum(sample, dict);
-    		generator.generateParagraph(false);
-    		fail("Dictionary " + dict + " should generate exception.");
-    	} catch (RuntimeException e) {
-    		assertEquals(e.getMessage(), "Invalid dictionary.");
-    	}
-    }
-
-    @Test 
-    public void testGenerate() {
-    	LOG.debug("Generate new text: ");
-    	String newDict = "me you he the One two three four five six Seven eight nine ten eleven twelve "
-       		+ "Thirteen fourteen fifteen sixteen Seventeen eighteen nineteen twenty joe fred some";
-    	String[] newParagraphs = new String[4];
-    	generator.setDictionary(newDict);
-    	for (int i=0; i<newParagraphs.length; i++) {
-    		newParagraphs[i] = generator.generateParagraph(false);
-    		LOG.debug(newParagraphs[i]);
-    		LOG.debug("");
-    	}
-    	assertFalse(newParagraphs[0].equals(newParagraphs[1]));
-    	assertFalse(newParagraphs[0].equals(newParagraphs[2]));
-    	assertFalse(newParagraphs[0].equals(newParagraphs[3]));
-    	assertFalse(newParagraphs[1].equals(newParagraphs[2]));
-    	assertFalse(newParagraphs[1].equals(newParagraphs[3]));
-    	assertFalse(newParagraphs[2].equals(newParagraphs[3]));
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsum() {
-    	LOG.debug("Generate new Lore Ipsum text: ");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String[] newParagraphs = new String[4];
-    	for (int i=0; i<newParagraphs.length; i++) {
-    		newParagraphs[i] = ipsum.generateParagraph(false);
-    		LOG.debug(newParagraphs[i]);
-    		LOG.debug("");
-    		LOG.debug("");
-    	}
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumHtml1() {
-    	LOG.debug("Generate new Lore Ipsum as html paragraphs:");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String output = ipsum.generateParagraphsHtml(2048, true);
-    	LOG.debug(output);
-    	LOG.debug("");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumHtml2() {
-    	LOG.debug("Generate new Lore Ipsum as one html paragraph:");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String output = ipsum.generateOneParagraphHtml(2048, true);
-    	LOG.debug(output);
-    	LOG.debug("");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumHtml3() {
-        LOG.debug("Generate new Lore Ipsum as full html document: ");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String output = ipsum.generateParagraphsFullHtml(2048, true);
-    	LOG.debug(output);
-    	LOG.debug("");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumPlainText() {
-    	LOG.debug("Generate new Lore Ipsum as plain text: ");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String output = ipsum.generateParagraphsPlainText(2048, true);
-    	LOG.debug(output);
-    	LOG.debug("");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumPlainTextFormatted() {
-    	LOG.debug("Generate new Lore Ipsum as plain text with 60 columns: ");
-    	LoremIpsum ipsum = new LoremIpsum();
-    	String output = ipsum.generateParagraphsPlainText(256, 60, false);
-    	LOG.debug(output);
-    	LOG.debug("");
-    }
-        
-    @Test 
-    public void testGenerateLoreIpsumHtml1Writer() throws IOException {
-        LOG.debug("Generate new Lore Ipsum as html paragraphs with PrintWriter:");
-        LoremIpsum ipsum = new LoremIpsum();
-        StringWriter writer = new StringWriter();
-        ipsum.generateParagraphsHtml(writer, 2048, true);
-        LOG.debug(writer.toString());
-        LOG.debug("End Test.");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumHtml2Writer() throws IOException  {
-        LOG.debug("Generate new Lore Ipsum as full html paragraph with PrintWriter:");
-        LoremIpsum ipsum = new LoremIpsum();
-        StringWriter writer = new StringWriter();
-        ipsum.generateParagraphsFullHtml(writer, 2048, true);
-        LOG.debug(writer.toString());
-        LOG.debug("End Test.");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumPlainTextWriter() throws IOException  {
-        LOG.debug("Generate new Lore Ipsum as plain text with PrintWriter: ");
-        LoremIpsum ipsum = new LoremIpsum();
-        StringWriter writer = new StringWriter();
-        ipsum.generateParagraphsPlainText(writer, 2048, true);
-        LOG.debug(writer.toString());
-        LOG.debug("End Test.");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumPlainTextFormattedWriter() throws IOException {
-        LOG.debug("Generate new Lore Ipsum as plain text with 60 columns with PrintWriter: ");
-        LoremIpsum ipsum = new LoremIpsum();
-        StringWriter writer = new StringWriter();
-        ipsum.generateParagraphsPlainText(writer, 256, 60, false);
-        LOG.debug(writer.toString());
-        LOG.debug("End Test.");
-    }
-    
-    @Test 
-    public void testGenerateLoreIpsumGerman() throws Exception {
-    	LOG.debug("Generate new Lore Ipsum Ferry Tale: ");
-    	InputStream is = this.getClass().getResourceAsStream("/HaenselUndGretel.txt");
-    	
-    	// read stream into a string
-    	final char[] buffer = new char[0x10000];
-    	StringBuilder sample = new StringBuilder();
-    	Reader in = new InputStreamReader(is, "ISO-8859-1");
-    	int read;
-    	do {
-    	  read = in.read(buffer, 0, buffer.length);
-    	  if (read>0) {
-    	    sample.append(buffer, 0, read);
-    	  }
-    	} while (read>=0);
-
-    	
-    	LoremIpsum ipsum = new LoremIpsum(sample.toString());
-    	String output = ipsum.generateParagraphsPlainText(4096, 80, false);
-    	LOG.debug(output);
-        LOG.debug("End Test.");
-    }
-    
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.chemistry.opencmis.util.content.loremipsum;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringWriter;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LoremIpsumTest {
+
+    private static final Logger LOG = LoggerFactory.getLogger(LoremIpsumTest.class);
+
+    String sample = "One two three four five six. Seven eight nine ten eleven twelve. "
+		+ "\n\n"
+		+ "Thirteen fourteen fifteen sixteen. Seventeen eighteen nineteen twenty.";
+       
+    String dictionary = "a bb ccc dddd eeeee ffffff ggggggg hhhhhhhh iiiiiiiii jjjjjjjjjj kkkkkkkkkkk llllllllllll";
+    LoremIpsum generator = new LoremIpsum(sample, dictionary);
+    
+	@Before
+	public void setUp() throws Exception {
+	    dictionary.split(" ");
+	}
+
+	@After
+	public void tearDown() throws Exception {
+	}
+
+	@Test
+	public void  test_mean() {
+		int[] ia1 = {1, 2, 3, 4};
+        assertEquals(2.5d, LoremIpsum.mean(ia1), 0.01d);
+        int[] ia2 = {6, 6, 4, 4};
+        assertEquals(5.0d, LoremIpsum.mean(ia2), 0.01d);
+	}
+	
+    @Test
+	public void  test_mean_empty() {
+		int[] ia1 = {};
+        assertEquals(0.0d, LoremIpsum.mean(ia1), 0.01d);
+    }
+    
+    @Test
+	public void  test_variance() {
+		double[] ia1 = {6.0d, 6.0d, 4.0d, 4.0d};
+        assertEquals(1.0d, LoremIpsum.variance(ia1), 0.01d);
+        double[] ia2 = {1.0d, 2.0d, 3.0d, 4.0d};
+        assertEquals(1.25d, LoremIpsum.variance(ia2), 0.01d);
+    }
+    
+    @Test
+	public void  test_sigma() {
+		double[] ia1 = {6.0d, 6.0d, 4.0d, 4.0d};
+        double[] ia2 = {1.0d, 2.0d, 3.0d, 4.0d};
+        assertEquals(1.0d, LoremIpsum.sigma(ia1), 0.01d);
+        assertEquals(Math.sqrt(1.25), LoremIpsum.sigma(ia2), 0.01d);
+    }
+    
+    @Test
+	public void  test_sigma_empty() {
+		int[] ia1 = {};
+        assertEquals(0.0d, LoremIpsum.sigma(ia1), 0.01d);
+    }
+    
+    @Test
+	public void test_split_sentences() {
+    	String[] sentences1 = {"Hello", "Hi"};
+    	assertArrayEquals (sentences1, LoremIpsum.splitSentences("Hello. Hi."));
+        String[] sentences2 = {"One two three four five six", 
+                                 "Seven eight nine ten eleven twelve", 
+                                 "Thirteen fourteen fifteen sixteen", 
+                                 "Seventeen eighteen nineteen twenty"}; 
+        assertArrayEquals(sentences2, LoremIpsum.splitSentences(sample));
+    }
+    
+    @Test
+	public void test_split_sentences_empty() {
+    	String[] sentences = {};
+    	assertArrayEquals(sentences, LoremIpsum.splitSentences(""));
+    }
+    
+    @Test
+	public void test_split_sentences_trailing() {
+    	String[] sentences1 = {"Hello", "Hi", "Hello"};    	
+    	assertArrayEquals(sentences1, LoremIpsum.splitSentences("Hello. Hi. Hello"));
+    	String[] sentences2 = {"Hello", "Hi", "Hello"};
+    	assertArrayEquals(sentences2, LoremIpsum.splitSentences("  Hello. Hi. Hello  "));
+        String[] sentences3 = {"Hello", "Hi", "Hello"};
+        assertArrayEquals(sentences3, LoremIpsum.splitSentences("..  Hello... Hi.... Hello  ")); 
+    }
+
+    @Test
+	public void test_split_paragraphs() {
+    	String[] paragraphs = {"One two three four five six. Seven eight nine ten eleven twelve.",
+    			"Thirteen fourteen fifteen sixteen. Seventeen eighteen nineteen twenty."};
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs(sample));
+    }
+    
+    @Test
+	public void test_split_paragraphs_empty() {
+    	String[] paragraphs = {};
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs(""));
+    }
+    
+    @Test
+	public void test_split_paragraphs_trailing() {
+    	String[] paragraphs = {"Hello", "Hi"};
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n\n"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("Hello\n\nHi\n\n\n\n\n\n"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\nHello\n\nHi"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\nHello\n\nHi"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\n\nHello\n\nHi"));
+    	assertArrayEquals(paragraphs, LoremIpsum.splitParagraphs("\n\n\n\n\n\nHello\n\nHi"));
+    }
+    
+    @Test
+	public void test_split_words() {
+    	String[] words = {"One", "two", "three", "four"};
+    	assertArrayEquals(words, LoremIpsum.splitWords("One two three four"));    	
+    	assertArrayEquals(words, LoremIpsum.splitWords("  One    two  three  four   ")); 
+    }
+                
+    @Test
+	public void test_split_words_empty() {
+    	String[] words = {};
+    	assertArrayEquals(words, LoremIpsum.splitWords(""));
+	}
+    
+    @Test
+	public void test_choose_closest() {
+    	Integer[] intArray1 ={1,2,3,4};
+        assertEquals(1, LoremIpsum.chooseClosest(intArray1, 1));
+        Integer[] intArray2 ={1,2,3,4};
+        assertEquals(4, LoremIpsum.chooseClosest(intArray2, 4));
+        assertEquals(4, LoremIpsum.chooseClosest(intArray2, 20));
+        assertEquals(1, LoremIpsum.chooseClosest(intArray2, -10));
+        Integer[] intArray3 ={1,4};
+        assertEquals(1, LoremIpsum.chooseClosest(intArray3, 2));
+        assertEquals(4, LoremIpsum.chooseClosest(intArray3, 3));
+        Integer[] intArray4 ={1,3};
+        assertEquals(1, LoremIpsum.chooseClosest(intArray4, 2));
+        Integer[] intArray5 ={3,1};
+        assertEquals(3, LoremIpsum.chooseClosest(intArray5, 2));
+        Integer[] intArray6 ={1};
+        assertEquals(1, LoremIpsum.chooseClosest(intArray6, 200));
+    }
+
+    @Test
+	public void test_sentence_mean() {
+        assertEquals(5.0d, generator.getSentenceMean(), 0.01d);
+	}
+   
+    @Test
+	public void test_paragraph_mean() {
+    	assertEquals(2.0d, generator.getParagraphMean(), 0.01d);
+    }
+        
+    @Test
+	public void test_sentence_sigma() {
+        assertEquals(1.0d, generator.getSentenceSigma(), 0.01d);
+    }
+        
+    @Test
+	public void test_paragraph_sigma() {
+        assertEquals(0.0d, generator.getParagraphSigma(), 0.01d);
+    }
+        
+    @Test
+	public void test_sample() {
+        assertEquals(generator.getSample(), sample);
+    }
+
+    @Test
+	public void test_dictionary() {
+        assertEquals(generator.getDictionary(), dictionary);
+    }
+
+    @Test
+	public void test_set_dictionary() {
+        String newdict = "a b c";
+        generator.setDictionary(newdict);
+        assertEquals(generator.getDictionary(), newdict);
+	}
+    
+    @Test 
+    public void test_init_no_sample() {
+    	doGenerate("");
+    	doGenerate(" ");
+    	doGenerate("\n\n");
+    	doGenerate("  \n\n  ");
+    	doGenerate(" .\n\n .");
+    }
+    
+    private void doGenerate(String text) {
+    	try {
+    		generator = new LoremIpsum(text, dictionary);
+    		generator.generateParagraph(false);
+    		fail("Sample text " + text + " should generate exception.");
+    	} catch (RuntimeException e) {
+    		assertTrue(e.getMessage().contains("Invalid sample text"));
+    	}
+    }
+    
+    @Test 
+    public void test_init_no_dict() {
+    	doGenerateNoDict("");
+    	doGenerateNoDict(" ");
+    	doGenerateNoDict("\n\n");
+    	doGenerateNoDict("  \n\n  ");
+    }
+    
+    private void doGenerateNoDict(String dict) {
+    	try {
+    		generator = new LoremIpsum(sample, dict);
+    		generator.generateParagraph(false);
+    		fail("Dictionary " + dict + " should generate exception.");
+    	} catch (RuntimeException e) {
+    		assertEquals(e.getMessage(), "Invalid dictionary.");
+    	}
+    }
+
+    @Test 
+    public void testGenerate() {
+    	LOG.debug("Generate new text: ");
+    	String newDict = "me you he the One two three four five six Seven eight nine ten eleven twelve "
+       		+ "Thirteen fourteen fifteen sixteen Seventeen eighteen nineteen twenty joe fred some";
+    	String[] newParagraphs = new String[4];
+    	generator.setDictionary(newDict);
+    	for (int i=0; i<newParagraphs.length; i++) {
+    		newParagraphs[i] = generator.generateParagraph(false);
+    		LOG.debug(newParagraphs[i]);
+    		LOG.debug("");
+    	}
+    	assertFalse(newParagraphs[0].equals(newParagraphs[1]));
+    	assertFalse(newParagraphs[0].equals(newParagraphs[2]));
+    	assertFalse(newParagraphs[0].equals(newParagraphs[3]));
+    	assertFalse(newParagraphs[1].equals(newParagraphs[2]));
+    	assertFalse(newParagraphs[1].equals(newParagraphs[3]));
+    	assertFalse(newParagraphs[2].equals(newParagraphs[3]));
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsum() {
+    	LOG.debug("Generate new Lore Ipsum text: ");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String[] newParagraphs = new String[4];
+    	for (int i=0; i<newParagraphs.length; i++) {
+    		newParagraphs[i] = ipsum.generateParagraph(false);
+    		LOG.debug(newParagraphs[i]);
+    		LOG.debug("");
+    		LOG.debug("");
+    	}
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumHtml1() {
+    	LOG.debug("Generate new Lore Ipsum as html paragraphs:");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String output = ipsum.generateParagraphsHtml(2048, true);
+    	LOG.debug(output);
+    	LOG.debug("");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumHtml2() {
+    	LOG.debug("Generate new Lore Ipsum as one html paragraph:");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String output = ipsum.generateOneParagraphHtml(2048, true);
+    	LOG.debug(output);
+    	LOG.debug("");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumHtml3() {
+        LOG.debug("Generate new Lore Ipsum as full html document: ");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String output = ipsum.generateParagraphsFullHtml(2048, true);
+    	LOG.debug(output);
+    	LOG.debug("");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumPlainText() {
+    	LOG.debug("Generate new Lore Ipsum as plain text: ");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String output = ipsum.generateParagraphsPlainText(2048, true);
+    	LOG.debug(output);
+    	LOG.debug("");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumPlainTextFormatted() {
+    	LOG.debug("Generate new Lore Ipsum as plain text with 60 columns: ");
+    	LoremIpsum ipsum = new LoremIpsum();
+    	String output = ipsum.generateParagraphsPlainText(256, 60, false);
+    	LOG.debug(output);
+    	LOG.debug("");
+    }
+        
+    @Test 
+    public void testGenerateLoreIpsumHtml1Writer() throws IOException {
+        LOG.debug("Generate new Lore Ipsum as html paragraphs with PrintWriter:");
+        LoremIpsum ipsum = new LoremIpsum();
+        StringWriter writer = new StringWriter();
+        ipsum.generateParagraphsHtml(writer, 2048, true);
+        LOG.debug(writer.toString());
+        LOG.debug("End Test.");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumHtml2Writer() throws IOException  {
+        LOG.debug("Generate new Lore Ipsum as full html paragraph with PrintWriter:");
+        LoremIpsum ipsum = new LoremIpsum();
+        StringWriter writer = new StringWriter();
+        ipsum.generateParagraphsFullHtml(writer, 2048, true);
+        LOG.debug(writer.toString());
+        LOG.debug("End Test.");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumPlainTextWriter() throws IOException  {
+        LOG.debug("Generate new Lore Ipsum as plain text with PrintWriter: ");
+        LoremIpsum ipsum = new LoremIpsum();
+        StringWriter writer = new StringWriter();
+        ipsum.generateParagraphsPlainText(writer, 2048, true);
+        LOG.debug(writer.toString());
+        LOG.debug("End Test.");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumPlainTextFormattedWriter() throws IOException {
+        LOG.debug("Generate new Lore Ipsum as plain text with 60 columns with PrintWriter: ");
+        LoremIpsum ipsum = new LoremIpsum();
+        StringWriter writer = new StringWriter();
+        ipsum.generateParagraphsPlainText(writer, 256, 60, false);
+        LOG.debug(writer.toString());
+        LOG.debug("End Test.");
+    }
+    
+    @Test 
+    public void testGenerateLoreIpsumGerman() throws Exception {
+    	LOG.debug("Generate new Lore Ipsum Ferry Tale: ");
+    	InputStream is = this.getClass().getResourceAsStream("/HaenselUndGretel.txt");
+    	
+    	// read stream into a string
+    	final char[] buffer = new char[0x10000];
+    	StringBuilder sample = new StringBuilder();
+    	Reader in = new InputStreamReader(is, "ISO-8859-1");
+    	int read;
+    	do {
+    	  read = in.read(buffer, 0, buffer.length);
+    	  if (read>0) {
+    	    sample.append(buffer, 0, read);
+    	  }
+    	} while (read>=0);
+
+    	
+    	LoremIpsum ipsum = new LoremIpsum(sample.toString());
+    	String output = ipsum.generateParagraphsPlainText(4096, 80, false);
+    	LOG.debug(output);
+        LOG.debug("End Test.");
+    }
+    
+}

Modified: chemistry/opencmis/branches/android/chemistry-opencmis-workbench/chemistry-opencmis-workbench/pom.xml
URL: http://svn.apache.org/viewvc/chemistry/opencmis/branches/android/chemistry-opencmis-workbench/chemistry-opencmis-workbench/pom.xml?rev=1293600&r1=1293599&r2=1293600&view=diff
==============================================================================
--- chemistry/opencmis/branches/android/chemistry-opencmis-workbench/chemistry-opencmis-workbench/pom.xml (original)
+++ chemistry/opencmis/branches/android/chemistry-opencmis-workbench/chemistry-opencmis-workbench/pom.xml Sat Feb 25 13:43:31 2012
@@ -229,6 +229,11 @@
             <version>1.8.6</version>
         </dependency>
         <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-log4j12</artifactId>
+            <version>1.6.4</version>          
+        </dependency>
+        <dependency>
             <groupId>log4j</groupId>
             <artifactId>log4j</artifactId>
             <version>1.2.16</version>