代码示例
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.core.RepositoryImpl;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.apache.log4j.Logger;
import javax.jcr.*;
import java.net.URL;
public class FiveHop {
private static final Logger LOGGER = Logger.getLogger(FiveHop.class);
/***
* 获取Repository,有两种方法。
* 方法一:使用工具类JcrUtils.getRepository()
* 方法二:使用方法RepositoryConfig.create(xml, dir);
*
* 结果:
* 1:使用方法一会在工作空间中生成文件夹jackrabbit。在该文件夹中会有目配置文件和数据信息。
* 2:使用方法二时会按照{xml}文件在目录{dir}中生成文件仓库
* 说明:
* 1:当第一次初始化时Jackrabbit repository将初始化一个用户,该用户的用户名是admin,密码是admin
* @param type
* @param dataDir
* @return
* @throws RepositoryException
*/
public Repository getRepository(int type,String dataDir) throws RepositoryException {
Repository repository = null;
if(type == 1){
repository = JcrUtils.getRepository();
}else if(type == 2){
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource("rep_configuration.xml");
LOGGER.info("配置文件路径:"+url.getPath());
String xml = url.getPath();
String dir = dataDir;
RepositoryConfig config = RepositoryConfig.create(xml, dir);
repository = RepositoryImpl.create(config);
}else{
throw new RuntimeException("非支持的类型,请纠正参数或者扩展代码");
}
return repository;
}
public Session doLogin(Repository repository,String userName,String password ) throws RepositoryException {
Session session = repository.login(
new SimpleCredentials(userName, password.toCharArray()));
return session;
}
public static void main(String[] args) throws RepositoryException {
FiveHop fiveHop = new FiveHop();
Repository repository = fiveHop.getRepository(1,"");
Session session = fiveHop.doLogin(repository,"admin","admin");
//获取该会话的根节点
Node root = session.getRootNode();
//在该根节点中增加两个子节点,注意没调用保存方法前,数据都保存在会话中,没有持久化。
Node hello = root.addNode("hello");
Node world = hello.addNode("world");
world.setProperty("message", "Hello, World!");
//数据持久化
session.save();
//精确查找文件节点
Node node = root.getNode("hello/world");
//打印节点路径,使用方法getPath;
LOGGER.info(node.getPath());
//打印节点属性
LOGGER.info(node.getProperty("message").getString());
//删除子节点hello
root.getNode("hello").remove();
//手动持久化
session.save();
//判断节点是否存在,如果使用 root.getNode("hello");会报异常,所以换成下面的方法
node = JcrUtils.getNodeIfExists(root,"hello");
if(node == null){
LOGGER.info("节点hello已经被删除");
}else{
LOGGER.error("节点hello没有被删除");
}
//在该根节点中增加两个子节点,注意没调用保存方法前,数据都保存在会话中,没有持久化。
Node hello2 = root.addNode("hello2");
Node world2 = hello2.addNode("world2");
world2.setProperty("message", "Hello, World!");
//数据持久化
session.save();
}
}
参考资料
官方示例1http://jackrabbit.apache.org/jcr/first-hops.html