Jackrabbit 文件上传下载

1. 在配置文件config.properties中: file.rmi=http://localhost:7000/rmi

2. 下载 jackrabbit-standalone-2.10.1.jar,打开服务:java -jar jackrabbit-standalone-2.10.1.jar --port 7000

3. 

public class JackRabbitFileServiceImpl implements FileService {

    private static Repository repository;

    public static Session initSession(){  
        Session session=null;
        if(null==repository){
            try {
                repository =  new URLRemoteRepository(ReadConfig.getValue("file.rmi"));
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            session=repository.login(new SimpleCredentials("admin","admin".toCharArray()));
        } catch (LoginException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RepositoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return session;
    }
    
    @Override
    public String save(InputStream is, long filesize) {
        String fileId=KeyProvider.getPrimaryKey();
        try{
            Session session=initSession();
            Node root = session.getRootNode();
            String mimeType = "application/octet-stream";
            Node fileNode = root.addNode(fileId, "nt:file");

            Node resNode = fileNode.addNode("jcr:content", "nt:resource");
            resNode.setProperty("jcr:mimeType", mimeType);
            resNode.setProperty("jcr:encoding", "");
            resNode.setProperty("jcr:data", is);

            Calendar lastModified = Calendar.getInstance();
            resNode.setProperty("jcr:lastModified", lastModified);

            session.save();
            is.close();
            session.logout();
        }catch(Exception e){
            e.printStackTrace();
        }
        return fileId;
    }

    @Override
    public InputStream getFileById(String fileId) {
        InputStream is=null;
        try{
            Session session=initSession();
            Node root = session.getRootNode();
            if(root!=null){
                NodeIterator filenodes = root.getNodes(fileId);
                while (filenodes.hasNext()) {
    
                    Node n = filenodes.nextNode();
                    NodeIterator ni1 = n.getNodes();
                    while (ni1.hasNext()) {
    
                        Node n1 = ni1.nextNode();
    
                        if (n1.getName().equals("jcr:content")) {
                            is = n1.getProperty("jcr:data")
                                    .getStream();
                        }
                    }
                }
            }
            session.logout();
        }catch(Exception e){
            e.printStackTrace();
        }
        return is;
    }
    
}

 



posted @ 2015-06-02 11:37  吹小号的程序猿  阅读(2056)  评论(0编辑  收藏  举报