使用Alfresco webservice上传文档

来源:互联网 发布:中控矩阵一体机 编辑:程序博客网 时间:2024/05/01 20:52

Alfresco发布了一组web服务的api,用以支持客户端的调用,这里总结一下ContentService的使用来处理文档上传。

一、条件

1.正确配置Alfresco端

2.测试Alfresco webservice工作正常

利用Alfresco自带的测试用例可进行测试。

二、步骤

1.相关Java包列表

2.封装的核心类

a.DocumentService.java

package org.alfresco.egensource.oa;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.alfresco.webservice.administration.UserDetails;

public interface DocumentService {

    
public void write(DocumentInfo docInfo) throws Exception;
    
    
public void deleteUser(ServletRequest request, ServletResponse response) throws Exception;
}

b.DocumentServiceImpl.java

package org.alfresco.egensource.oa;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.alfresco.webservice.administration.AdministrationServiceSoapBindingStub;
import org.alfresco.webservice.administration.NewUserDetails;
import org.alfresco.webservice.administration.UserDetails;
import org.alfresco.webservice.content.Content;
import org.alfresco.webservice.content.ContentServiceSoapBindingStub;
import org.alfresco.webservice.repository.UpdateResult;
import org.alfresco.webservice.types.CML;
import org.alfresco.webservice.types.CMLCreate;
import org.alfresco.webservice.types.ContentFormat;
import org.alfresco.webservice.types.NamedValue;
import org.alfresco.webservice.types.Node;
import org.alfresco.webservice.types.ParentReference;
import org.alfresco.webservice.types.Predicate;
import org.alfresco.webservice.types.Reference;
import org.alfresco.webservice.types.Store;
import org.alfresco.webservice.util.AuthenticationUtils;
import org.alfresco.webservice.util.Constants;
import org.alfresco.webservice.util.ContentUtils;
import org.alfresco.webservice.util.Utils;
import org.alfresco.webservice.util.WebServiceFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import eu.medsea.util.MimeUtil;

public class DocumentServiceImpl implements DocumentService {
    
private static Log logger = LogFactory.getLog(DocumentServiceImpl.class);

    
private static final String USERNAME = "admin";
    
private static final String PASSWORD = "admin";
    
/** The type of the association we are creating to the new content */
    
private static final String ASSOC_CONTAINS = "{http://www.alfresco.org/model/content/1.0}contains";

    
public static Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
    
public static final String COMPANY_PATH = "/app:company_home";

    
public void write(DocumentInfo docInfo) throws Exception {
        
// Start the session
        logger.info("Start Session");
        String pathname 
= docInfo.getPathName();

        AuthenticationUtils.startSession(USERNAME, PASSWORD);

        String folderName 
= docInfo.getFolderName();
        Reference folder 
= new Reference(STORE, null, pathname + "/cm:" + folderName);
        
try {
            WebServiceFactory.getRepositoryService().get(
new Predicate(new Reference[] { folder }, STORE, null));
        }
 catch (Exception e) {
            logger.info(
"Create parent reference to company home");
            ParentReference parentReference 
= new ParentReference(STORE, null, pathname, Constants.ASSOC_CONTAINS, Constants.createQNameString(
                    Constants.NAMESPACE_CONTENT_MODEL, folderName));

            
// Create folder
            NamedValue[] properties = new NamedValue[] { Utils.createNamedValue(Constants.PROP_NAME, folderName) };
            CMLCreate create 
= new CMLCreate("1", parentReference, nullnullnull, Constants.TYPE_FOLDER, properties);
            CML cml 
= new CML();
            cml.setCreate(
new CMLCreate[] { create });
            UpdateResult[] results 
= WebServiceFactory.getRepositoryService().update(cml);
        }


        File file 
= docInfo.getFile();
        
if (file != null && file.exists() && file.isFile()) {

            
// Get the content service
            ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
            Reference reference 
= createNewContent(contentService, pathname, folderName, file);
            logger.info(reference.toString());
        }
 else {
            logger.error(
"file not found!");
        }

        
// End the session
        AuthenticationUtils.endSession();
        logger.info(
"End Session");
    }


    
public void deleteUsers(String[] userNames) throws Exception {
        AuthenticationUtils.startSession(USERNAME, PASSWORD);
        
if (userNames.length == 0{
            logger.error(
"no usernames!");
            
return;
        }

        
try {
            AdministrationServiceSoapBindingStub administrationService 
= WebServiceFactory.getAdministrationService();
            administrationService.deleteUsers(userNames);
        }
 catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
 finally {
            AuthenticationUtils.endSession();
        }

    }


    
public UserDetails[] createUser(String userName) throws Exception {
        UserDetails user 
= getUser(userName);
        
if (user != null{
            logger.info(userName 
+ " exists!");
            
return new UserDetails[]{user};
        }

        
        AuthenticationUtils.startSession(USERNAME, PASSWORD);
        
try {
            String uuid 
= "";
            
try {
                Reference folder 
= new Reference(STORE, null"/app:company_home/app:user_homes" + "/cm:" + userName);
                Node[] node 
= WebServiceFactory.getRepositoryService().get(new Predicate(new Reference[] { folder }, STORE, null));
                uuid 
= node[0].getReference().getUuid();
            }
 catch (Exception e) {
                ParentReference parentReference 
= new ParentReference(STORE, null"/app:company_home/app:user_homes", Constants.ASSOC_CONTAINS, Constants.createQNameString(
                        Constants.NAMESPACE_CONTENT_MODEL, userName));

                
// Create folder
                NamedValue[] properties = new NamedValue[] { Utils.createNamedValue(Constants.PROP_NAME, userName) };
                CMLCreate create 
= new CMLCreate("1", parentReference, nullnullnull, Constants.TYPE_FOLDER, properties);
                CML cml 
= new CML();
                cml.setCreate(
new CMLCreate[] { create });
                UpdateResult[] results 
= WebServiceFactory.getRepositoryService().update(cml);
                uuid 
= results[0].getDestination().getUuid();
            }

            NamedValue[] properties 
= createPersonProperties(STORE.getScheme() + "://" + STORE.getAddress() + "/" +uuid, userName, nullnullnullnull);
            NewUserDetails newUser 
= new NewUserDetails(userName, userName, properties);
            NewUserDetails[] newUsers 
= new NewUserDetails[]{newUser};
            AdministrationServiceSoapBindingStub administrationService 
= WebServiceFactory.getAdministrationService();
            
return administrationService.createUsers(newUsers);
        }
 catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
 finally {
            AuthenticationUtils.endSession();
        }

        
return null;
    }


    
public UserDetails getUser(String userName) throws Exception {
        AuthenticationUtils.startSession(USERNAME, PASSWORD);
        
try {
            AdministrationServiceSoapBindingStub administrationService 
= WebServiceFactory.getAdministrationService();
            
return administrationService.getUser(userName);
        }
 catch (Exception e) {
            logger.info(e.getMessage());
        }
 finally {
            AuthenticationUtils.endSession();
        }

        
return null;
    }


    
/**
     * 创建文档
     * 
     * 
@param contentService
     * 
@param folderName
     *            文件夹
     * 
@param file
     *            文档
     * 
@return a reference to the created content node
     * 
@throws Exception
     
*/

    
public static Reference createNewContent(ContentServiceSoapBindingStub contentService, String pathname, String folderName, File file) throws Exception {
        ParentReference parentReference 
= new ParentReference(STORE, null, pathname + "/cm:" + folderName, ASSOC_CONTAINS, ASSOC_CONTAINS);

        String fileName 
= file.getName();
        InputStream is 
= new FileInputStream(file);
        
byte[] bytes = ContentUtils.convertToByteArray(is);
        is.close();
        String mimeType 
= MimeUtil.getMimeType(file.getCanonicalPath());
        logger.debug(mimeType);
        ContentFormat contentFormat 
= new ContentFormat(mimeType, "UTF-8");

        SimpleDateFormat sdf 
= new SimpleDateFormat("yyyyMMddHHmmss");
        NamedValue[] properties 
= new NamedValue[] { Utils.createNamedValue(Constants.PROP_NAME, sdf.format(new Date()) + "_" + fileName) };
        CMLCreate create 
= new CMLCreate("1", parentReference, nullnullnull, Constants.TYPE_CONTENT, properties);
        CML cml 
= new CML();
        cml.setCreate(
new CMLCreate[] { create });
        UpdateResult[] result 
= WebServiceFactory.getRepositoryService().update(cml);

        Reference newContentNode 
= result[0].getDestination();
        Content content 
= contentService.write(newContentNode, Constants.PROP_CONTENT, bytes, contentFormat);

        
// Get a reference to the newly created content
        return content.getNode();
    }


    
private static NamedValue[] createPersonProperties(String homeFolder, String firstName, String middleName, String lastName, String email, String orgId) {
        
// Create the new user objects
        return new NamedValue[] new NamedValue(Constants.PROP_USER_HOMEFOLDER, false, homeFolder, null),
                
new NamedValue(Constants.PROP_USER_FIRSTNAME, false, firstName, null), new NamedValue(Constants.PROP_USER_MIDDLENAME, false, middleName, null),
                
new NamedValue(Constants.PROP_USER_LASTNAME, false, lastName, null), new NamedValue(Constants.PROP_USER_EMAIL, false, email, null),
                
new NamedValue(Constants.PROP_USER_ORGID, false, orgId, null) }
;
    }


    
/**
     * 创建内容
     * 
     * 
@param contentService
     *            the content web service
     * 
@param folderName
     *            文件夹
     * 
@param name
     *            内容名称
     * 
@param contentString
     *            内容
     * 
@return a reference to the created content node
     * 
@throws Exception
     
*/

    
public static Reference createNewContent(ContentServiceSoapBindingStub contentService, String pathname, String folderName, String name, String contentString)
            
throws Exception {
        ParentReference parentReference 
= new ParentReference(STORE, null, pathname + "/cm:" + folderName, ASSOC_CONTAINS, ASSOC_CONTAINS);

        
// Define the content format for the content we are adding
        ContentFormat contentFormat = new ContentFormat("text/plain""UTF-8");

        SimpleDateFormat sdf 
= new SimpleDateFormat("yyyyMMddHHmmss");
        NamedValue[] properties 
= new NamedValue[] { Utils.createNamedValue(Constants.PROP_NAME, sdf.format(new Date()) + "_" + name) };
        CMLCreate create 
= new CMLCreate("1", parentReference, nullnullnull, Constants.TYPE_CONTENT, properties);
        CML cml 
= new CML();
        cml.setCreate(
new CMLCreate[] { create });
        UpdateResult[] result 
= WebServiceFactory.getRepositoryService().update(cml);

        Reference newContentNode 
= result[0].getDestination();
        Content content 
= contentService.write(newContentNode, Constants.PROP_CONTENT, contentString.getBytes(), contentFormat);

        
// Get a reference to the newly created content
        return content.getNode();
    }


    
public void deleteUser(String userName, String ticket) throws Exception {
        
// TODO Auto-generated method stub
        String surl = properties.getProperty("repository.user");
        URL url 
= new URL(surl);
        URLConnection uc 
= url.openConnection();
        uc.setDoInput(
true);
        uc.setDoOutput(
true);
        OutputStream os 
= uc.getOutputStream();
        String parameter 
= "?uname=".concat(userName).concat("&ticket=").concat(ticket);
        os.write(parameter.getBytes(
"UTF-8"));
        InputStream is 
= uc.getInputStream();
        
byte[] b = new byte[is.available()];
        is.read(b);
        is.close();
        os.close();
        String result 
= new String(b, "UTF-8");
        logger.info(
"result: " + result);
    }


    
static Properties properties = new Properties();
    
    
static {
        
try {
            properties.load(DocumentServiceImpl.
class.getClassLoader().getResourceAsStream("alfresco/webserviceclient.properties"));
        }
 catch (IOException e) {
            e.printStackTrace();
        }

    }


    
public void deleteUser(ServletRequest request, ServletResponse response) throws Exception {
        
// TODO Auto-generated method stub
        HttpServletRequest resq = (HttpServletRequest) request;
        HttpServletResponse resp 
= (HttpServletResponse) response;
        
        String userName 
= resq.getParameter("uname");
        
        String surl 
= properties.getProperty("repository.user");
        resp.sendRedirect(surl
+"?uname="+userName);
    }


    
}

 

c.DocumentFactory.java

package org.alfresco.egensource.oa;

public class DocumentFactory {

    
private static DocumentService documentService;

    
static {
        documentService 
= new DocumentServiceImpl();
    }

    
    
public static DocumentService getDocumentService() {
        
return documentService;
    }

    
}

d.DocumentInfo.java

package org.alfresco.egensource.oa;

import java.io.File;

public class DocumentInfo implements java.io.Serializable {

    
/**
     * 
     
*/

    
private static final long serialVersionUID = 1L;
    
protected String pathName;
    
protected String folderName;
    
protected File file;

    
public DocumentInfo() {
        pathName 
= "/app:company_home";
        folderName 
= "sample_folder";
    }


    
public DocumentInfo(File file) {
        
new DocumentInfo("sample_folder", file);
    }


    
public DocumentInfo(String folderName, File file) {
        
new DocumentInfo("/app:company_home", folderName, file);
    }


    
public DocumentInfo(String pathName, String folderName, File file) {
        
this.pathName = pathName;
        
this.folderName = folderName;
        
this.file = file;
    }


    
public String getPathName() {
        
return pathName;
    }


    
public void setPathName(String pathName) {
        
this.pathName = pathName;
    }


    
public String getFolderName() {
        
return folderName;
    }


    
public void setFolderName(String folderName) {
        
this.folderName = folderName;
    }


    
public File getFile() {
        
return file;
    }


    
public void setFile(File file) {
        
this.file = file;
    }


    @Override
    
public String toString() {
        StringBuffer sb 
= new StringBuffer();
        
return sb.append("pathName:").append(this.pathName).append("folderName:").append(this.folderName).append(" fileName: ").append(
                ((file 
!= null? file.getName() : "")).toString();
    }


}

 

三、测试 

1.配置文件设定

webserviceclient.properties

repository.location = http://localhost:8080/alfresco/api

repository.user 
=http://localhost:8080/alfresco/faces/UserOAInterface

 

2.测试类

package org.alfresco.egensource.oa.test;

import java.io.File;

import junit.framework.TestCase;

import org.alfresco.egensource.oa.DocumentFactory;
import org.alfresco.egensource.oa.DocumentInfo;
import org.alfresco.egensource.oa.DocumentService;


public class OATestCase extends TestCase {

    
public OATestCase() {
        
// TODO Auto-generated constructor stub
    }


    
public OATestCase(String name) {
        
super(name);
        
// TODO Auto-generated constructor stub
    }


    @Override
    
protected void setUp() throws Exception {
        
// TODO Auto-generated method stub
        super.setUp();
        
    }


    @Override
    
protected void tearDown() throws Exception {
        
// TODO Auto-generated method stub
        super.tearDown();
    }


    
public void testWrite() throws Exception {
        DocumentService service 
= DocumentFactory.getDocumentService();
        DocumentInfo docInfo 
= new DocumentInfo();
        docInfo.setPathName(
"/app:company_home/app:user_homes");
        docInfo.setFolderName(
"阿里妈妈");
        
//        File file = new File("E:/Docuements/Aa718190.dd8ead89-f318-4298-807e-9d946884395b(zh-cn,VS.90).gif");
        File file = new File("E:/Docuements/Egensource公司通讯录.xls");
//        File file = new File("E:/Docuements/appfuse-architecture.ppt");
//        File file = new File("nofile");
        docInfo.setFile(file);
        service.write(docInfo);
    }

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        
// TODO Auto-generated method stub

    }


}

原创粉丝点击