可以把資源庫理解成一個數據庫,oracle、mysql這些數據庫可以方便地保存一些常規數據,而類似樹狀的數據,例如一個文件夾下包含兩個子文件夾,而子文件夾下又分別有文件,這樣的數據在數據庫中是不好實現存儲的,即使存儲了,也不太直觀,於是採用jcr資源庫來存放數據。
使用步驟:在apache官網下下載jackrabbit-2.8.0的例子
如下是一個簡單的servlet程序,有一些基本的xpath操作jcr方法:
1.TestResjsp.jsp(含有一個簡單的提交按鈕)
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ResServlet">
<input type="submit">
</form>
<%String ico=String.valueOf(request.getAttribute("ico"));
Map map=(Map)request.getAttribute("map");
%>
<input type="text" value=<%= ico%>>
</body>
</html>
2.ResDao(包含各種操作xpath的方法)
package com.bolue.bean;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.version.VersionException;
public class ResDao {
String roleright[] = null;
public ResDao(String _role) {
this.roleright = _role.split(",");
}
public ResDao() {
super();
}
String bas = "bas_";
String nom = "nom_";
String file = "file_";
String ext = "ext_";
String role = "role_";
String reskeyword = "resKeyWord";
String type = "type";
/**
*
* @param jcrSession
* @param path
* @return
*/
public ResVo getRes(Session jcrSession, String path) {
ResVo rv = null;
try {
if (path == null || path.equals("/")) {
Node n = jcrSession.getRootNode();
rv.setName("root");
rv.setIco("/WEB-INF/images/web.jpg");
rv.setTitle("數字資源庫");
rv.setResPath("/");
rv.setParentPath("/");
rv.setDataurl("/ControlPanel?sys=SysManager&func=list");
rv.setMemo("數字資源庫");
} else {
Node node = jcrSession.getNode(path);
if (this.checkrole(node, "r")) {
rv = fillVo(node);
} else {
rv = null;
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
rv = null;
} catch (RepositoryException e) {
e.printStackTrace();
rv = null;
}
return rv;
}
/**
* 訪問系統運行參數
*
* @param jcrSession
* @param path
* @return
*/
public ResVo getConfig(Session jcrSession, String path) {
ResVo rv = null;
try {
Node node = jcrSession.getNode(path);
rv = fillVo(node);
} catch (PathNotFoundException e) {
e.printStackTrace();
rv = null;
} catch (RepositoryException e) {
e.printStackTrace();
rv = null;
}
return rv;
}
public List getConfig(Session jcrSession, String path,String flag) {
Node node=null;
List list=new ArrayList();
ResVo rv = null;
try {
node= jcrSession.getNode(path);
NodeIterator it=node.getNodes();
while(it.hasNext()){
Node nodeOther=(Node)it.next();
rv = fillVo(nodeOther);
list.add(rv);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return list;
}
public ResVo getResLogin(Session jcrSession, String path, String password) {
ResVo userResVo = null;
try {
Node node = jcrSession.getNode(path);
// String role = node.getProperty("role_rw").getString();
userResVo = fillVo(node);
if (((String) userResVo.getBas().get("password")).equals(password)
&& ((String) userResVo.getBas().get("state")).equals("1")) {
} else {
userResVo = null;
}
} catch (PathNotFoundException e) {
e.printStackTrace();
userResVo = null;
} catch (RepositoryException e) {
e.printStackTrace();
userResVo = null;
}
return userResVo;
}
public ResVo getResLoginByName(Session jcrSession, String path) {
ResVo userResVo = null;
try {
Node node = jcrSession.getNode(path);
// String role = node.getProperty("role_rw").getString();
userResVo = fillVo(node);
if (((String) userResVo.getBas().get("state")).equals("1")) {
} else {
userResVo = null;
}
} catch (PathNotFoundException e) {
e.printStackTrace();
userResVo = null;
} catch (RepositoryException e) {
e.printStackTrace();
userResVo = null;
}
return userResVo;
}
/**
*
* @param jcrSession
* @param path
* @return
*/
public boolean hasRes(Session jcrSession, String path) {
boolean flag = false;
try {
flag = jcrSession.getRootNode().hasNode(path);
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return flag;
}
/**
*
* @param jcrSession
* @param path
* @param type
* @param current
* @param offset
* @return
*/
public List getChildrenTree(Session jcrSession, String path, String type,
long current, long offset) {
String xpathcondition = path + "/element(*, nt:unstructured) [@type";
if (type != null && !type.equals("")) {
xpathcondition = xpathcondition + "='" + type + "' and ";
}
String tempstr = "";
for (int i = 0; i < this.roleright.length; i++) {
String _s = this.roleright[i];
if (_s.length() > 0) {
xpathcondition = xpathcondition + "(jcr:contains(role_r,'"
+ this.roleright[i] + "') ";
if (i + 1 < this.roleright.length) {
xpathcondition = xpathcondition + " and ";
}
}
}
xpathcondition = xpathcondition + ")]";
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
Query q = qm.createQuery(xpathcondition, "xpath");
QueryResult result = q.execute();
NodeIterator it = result.getNodes();
if ((current + offset) > it.getSize()) {
offset = it.getSize() - current;
}
if (current > 0) {
it.skip(current);
}
for (long i = 0; i < offset; i++) {
Node n = it.nextNode();
ResVo resvo = new ResVo();
resvo = fillVo(n);
list.add(resvo);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public List search(Session jcrSession, ResVo resVo,long current,long offset,String sortStr) {
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,sortStr);
// xpath = "//res/public//element(*, nt:unstructured) [" +
// "jcr:like(@bas_uploadedbyname,'%%')" +
// " and jcr:like(@bas_author,'%%')" +
// " and jcr:like(@bas_time,'%%')" +
// " and jcr:like(@bas_createTime,'%%')" +
// " and (bas_state='2')"+
// " and ( jcr:like(@nom_category,'rootId%') or jcr:like(@nom_category,'110%') or jcr:like(@nom_category,'111%') or jcr:like(@nom_category,'112%') or jcr:like(@nom_category,'113%') or jcr:like(@nom_category,'114%') or jcr:like(@nom_category,'115%')
or jcr:like(@nom_category,'116%') or jcr:like(@nom_category,'117%') or jcr:like(@nom_category,'118%') or jcr:like(@nom_category,'119%') or jcr:like(@nom_category,'120%') ) and jcr:like(@nom_lib,'/system/lib/tupian%') and type='element' ] order by
@bas_publishTime descending";
// fn:compare(comp1,comp2)
// xpath = "//res/public//element(*, nt:unstructured) [" +
// "(bas_state='2')" +
// " and jcr:like(@bas_time,'%133%') "+
// " and ( jcr:like(@nom_category,'rootId%') or jcr:like(@nom_category,'110%') or jcr:like(@nom_category,'111%') or jcr:like(@nom_category,'112%') or jcr:like(@nom_category,'113%') or jcr:like(@nom_category,'114%') or jcr:like(@nom_category,'115%')
or jcr:like(@nom_category,'116%') or jcr:like(@nom_category,'117%') or jcr:like(@nom_category,'118%') or jcr:like(@nom_category,'119%') or jcr:like(@nom_category,'120%') ) and jcr:like(@nom_lib,'/system/lib/tupian%') and type='element' ] order by
@bas_publishTime descending";
//System.out.println(xpath);
Query q = qm.createQuery(xpath, "xpath");
QueryResult result = q.execute();
NodeIterator it = result.getNodes();
//System.out.println(it.getSize());
long i=0;
while (it.hasNext()) {
it.next();
i=++i;
}
list.add(i);//總數據量
it = qm.createQuery(xpath, "xpath").execute().getNodes();
long m = 0;
it.skip(current);
while(it.hasNext()){
Node n = it.nextNode();
//System.out.println(n.getPath());
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
m=++m;
if(m==offset){
break;
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public List searchFav(Session jcrSession, ResVo resVo,long current,long offset) {
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
Query q = qm.createQuery(xpath, "xpath");
QueryResult result = q.execute();
NodeIterator it = result.getNodes();
//System.out.println(it.getSize());
long i=0;
while (it.hasNext()) {
it.next();
i=++i;
}
list.add(i);//總數據量
it = qm.createQuery(xpath, "xpath").execute().getNodes();
long m = 0;
it.skip(current);
while(it.hasNext()){
Node n = it.nextNode();
//System.out.println(n.getPath());
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
m=++m;
if(m==offset){
break;
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public List search(Session jcrSession, ResVo resVo) {
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
NodeIterator it =null;
it = qm.createQuery(xpath, "xpath").execute().getNodes();
while(it.hasNext()){
Node n = it.nextNode();
ResVo resvo = new ResVo();
resvo = fillVo(n);
list.add(resvo);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public Long getResCount(Session jcrSession, ResVo resVo) {
Long count=0l;
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
NodeIterator it =null;
it = qm.createQuery(xpath, "xpath").execute().getNodes();
count=it.getSize();
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return count;
}
public List searchSort(Session jcrSession, ResVo resVo,String sortStr) {
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,sortStr);
NodeIterator it =null;
it = qm.createQuery(xpath, "xpath").execute().getNodes();
while(it.hasNext()){
Node n = it.nextNode();
ResVo resvo = new ResVo();
resvo = fillVo(n);
list.add(resvo);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
//節點狀態判斷
public List searchNodeState(Session jcrSession, ResVo resVo){
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
NodeIterator it =null;
it = qm.createQuery(xpath, "xpath").execute().getNodes();
while(it.hasNext()){
Node n = it.nextNode();
String editState="";
if(n.hasProperty("bas_editState")){
editState=n.getProperty("bas_editState").getString();
}
list.add(editState);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public Long searchLong(Session jcrSession, ResVo resVo) {
List list = new ArrayList();
Long count=0l;
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
NodeIterator it =null;
it = qm.createQuery(xpath, "xpath").execute().getNodes();
while(it.hasNext()){
it.nextNode();
count++;
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return count;
}
/**
* 如果path指向的資源是set集合類型,那麼返回所有子節點.
*
* @param jcrSession
* @param path
* @param type
* 指定返回類型。如果爲空則返回所有子節點,包含集合和元素
* @return
*/
public List getChildren(Session jcrSession, String path, String type) {
List list = new ArrayList();
try {
Node node = jcrSession.getNode(path);
// if (this.checkrole(node, "r")) {
NodeIterator it = node.getNodes();
while (it.hasNext()) {
Node n = it.nextNode();
if (type != null && !type.equals("")) {
if (n.hasProperty("type")
&& type.equals(n.getProperty("type").getString())
&& this.checkrole(n, "r")) {
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
}
} else {
if (this.checkrole(n, "r")) {
ResVo resvo = new ResVo();
resvo = fillVo(n);
list.add(resvo);
}
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
//用戶的資源數量
public Long getUserChildren(Session jcrSession, String path) {
Long count=0l;
try {
Node node = jcrSession.getNode(path);
NodeIterator it = node.getNodes();
while (it.hasNext()) {
Node n = it.nextNode();
count++;
}
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return count;
}
/**
*
* @param jcrSession
* @param path
* @param type
* @param current
* 當前值
* @param offset
* 偏移量
* @return
*/
public List getChildren(Session jcrSession, String path, String type,long current, long offset) {
List list = new ArrayList();
try {
Node node = jcrSession.getNode(path);
// if (this.checkrole(node, "r")) {
NodeIterator it = node.getNodes();
String size = String.valueOf(it.getSize());
list.add(size);
long m = 0;
it.skip(current);
while(it.hasNext()){
Node n = it.nextNode();
if (type != null && !type.equals("")) {
if (n.hasProperty("type")
&&type.equals(n.getProperty("type").getString())
&& this.checkrole(n, "r")) {
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
}
} else {
if (this.checkrole(n, "r")) {
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
}
}
m=++m;
if(m==offset){
break;
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public ResVo modify(Session jcrSession, ResVo resVo) {
ResVo _resVo = null;
String resPath = resVo.getResPath();
try {
Node node = jcrSession.getNode(resPath);
if (checkrole(node, "rw")) {
_resVo = new ResVo();
fillNode(node, resVo.getBas(), this.bas);
fillNode(node, resVo.getNom(), this.nom);
fillNode(node, resVo.getFile(), this.file);
fillNode(node, resVo.getExt(), this.ext);
fillNode(node, resVo.getRole(), this.role);
node.setProperty("ico", resVo.getIco());
node.setProperty("name", resVo.getName());
node.setProperty("config", resVo.getConfig());
node.setProperty("dataurl", resVo.getDataurl());
node.setProperty("title", resVo.getTitle());
node.setProperty("resKeyWord", resVo.getResKeyWord());
//node.setProperty("time", resVo.getTime());
node.setProperty("memo", resVo.getMemo());
_resVo = fillVo(node);
}
// jcrSession.save();
} catch (PathNotFoundException e) {
_resVo = null;
e.printStackTrace();
} catch (RepositoryException e) {
_resVo = null;
e.printStackTrace();
} catch (Exception e) {
_resVo = null;
e.printStackTrace();
}
return _resVo;
}
public boolean deleted(Session jcrSession, ResVo resVo) {
boolean _flag = false;
try {
Node node = jcrSession.getNode(resVo.getResPath());
if (checkrole(node, "rw")) {
node.remove();
_flag = true;
}
// jcrSession.save();
} catch (PathNotFoundException e) {
e.printStackTrace();
return false;
} catch (RepositoryException e) {
e.printStackTrace();
return false;
}
return _flag;
}
public boolean deletedFile(Session jcrSession, ResVo resVo,String realPath) {
boolean _flag = false;
try {
Node node = jcrSession.getNode(resVo.getResPath());
if(node.hasProperty("bas_state")){
String state = node.getProperty("bas_state").getString();
if("0".equals(state)){
if(node.hasProperty("bas_filepath")){
String filepath = node.getProperty("bas_filepath").getString();
realPath=node.getProperty("bas_filesavepath").getString();
File file = new File(realPath+filepath);
if(file!=null){
file.delete();
}
}
}
}
node.remove();
_flag = true;
// jcrSession.save();
} catch (PathNotFoundException e) {
e.printStackTrace();
return false;
} catch (RepositoryException e) {
e.printStackTrace();
return false;
}
return _flag;
}
public boolean deletedNode(Session jcrSession, ResVo resVo) {
boolean _flag = false;
try {
Node node = jcrSession.getNode(resVo.getResPath());
node.remove();
_flag = true;
// jcrSession.save();
} catch (PathNotFoundException e) {
e.printStackTrace();
return false;
} catch (RepositoryException e) {
e.printStackTrace();
return false;
}
return _flag;
}
public ResVo creat(Session jcrSession, ResVo resVo) {
try {
Node node = jcrSession.getNode(resVo.getResPath());
//String role = node.getProperty("role_rw").getString();
// this.roleright;
String type =resVo.getType();
if("".equals(type)){
type="node";
}
// if (node.hasProperty("type")) {
// type = node.getProperty("type").getString();
// } else {
// type = "node";
// }
if (!(node.hasNode(resVo.getName()))) {
node =node.addNode(resVo.getName());
fillNode(node, resVo.getBas(), this.bas);
fillNode(node, resVo.getNom(), this.nom);
fillNode(node, resVo.getFile(), this.file);
fillNode(node, resVo.getExt(), this.ext);
fillNode(node, resVo.getRole(), this.role);
node.setProperty(this.type, resVo.getType());
node.setProperty("ico", resVo.getIco());
node.setProperty("config", resVo.getConfig());
node.setProperty("dataurl", resVo.getDataurl());
node.setProperty("title", resVo.getTitle());
node.setProperty("resKeyWord", resVo.getResKeyWord());
node.setProperty("time", resVo.getTime());
node.setProperty("memo", resVo.getMemo());
// jcrSession.save();
resVo = fillVo(node);
} else{
resVo = null;
}
} catch (RepositoryException e) {
resVo = null;
e.printStackTrace();
} catch (Exception e) {
resVo = null;
e.printStackTrace();
}
return resVo;
}
public ResVo creatPublic(Session jcrSession, ResVo resVo) {
try {
Node node = jcrSession.getNode(resVo.getResPath());
//String role = node.getProperty("role_rw").getString();
// this.roleright;
String type =resVo.getType();
if("".equals(type)){
type="node";
}
// if (node.hasProperty("type")) {
// type = node.getProperty("type").getString();
// } else {
// type = "node";
// }
//判斷節點是否已存在,存在說明已經發布過了,此處應該修改節點
if (!(node.hasNode(resVo.getName()))) {
node = node.addNode(resVo.getName());
fillNode(node, resVo.getBas(), this.bas);
fillNode(node, resVo.getNom(), this.nom);
fillNode(node, resVo.getFile(), this.file);
fillNode(node, resVo.getExt(), this.ext);
fillNode(node, resVo.getRole(), this.role);
node.setProperty(this.type, resVo.getType());
node.setProperty("ico", resVo.getIco());
node.setProperty("config", resVo.getConfig());
node.setProperty("dataurl", resVo.getDataurl());
node.setProperty("title", resVo.getTitle());
node.setProperty("resKeyWord", resVo.getResKeyWord());
node.setProperty("time", resVo.getTime());
node.setProperty("memo", resVo.getMemo());
// jcrSession.save();
resVo = fillVo(node);
// //修改用戶發佈量
// String p=resVo.getParentPath();
// int index=p.lastIndexOf("/");
// p=p.substring(index+1);
// String userRespath="/system/user/"+p;
// ResVo userVo=getRes(jcrSession,userRespath);
// Hashtable b=userVo.getBas();
// Long publicCount=0l;
// if(b.get("publicCount")!=null){
// publicCount=Long.valueOf((String)b.get("publicCount"));
// publicCount++;
// b.put("publicCount", Long.toString(publicCount));
// userVo.setBas(b);
// modify(jcrSession,userVo);
// }else{
// publicCount++;
// b.put("publicCount", Long.toString(publicCount));
// userVo.setBas(b);
// modify(jcrSession,userVo);
// }
} else {
//重新發布修改公用庫下的節點
String respath=resVo.getResPath()+resVo.getName();
resVo.setResPath(respath);
resVo=modify(jcrSession,resVo);
}
} catch (RepositoryException e) {
resVo = null;
e.printStackTrace();
} catch (Exception e) {
resVo = null;
e.printStackTrace();
}
return resVo;
}
ResVo fillVo(Node node) {
ResVo _resVo = new ResVo();
Hashtable _bas = new Hashtable();
Hashtable _nom = new Hashtable();
Hashtable _ext = new Hashtable();
Hashtable _role = new Hashtable();
Hashtable _file = new Hashtable();
try {
PropertyIterator propertys = node.getProperties();
while (propertys.hasNext()) {
Property property = propertys.nextProperty();
String proname = property.getName();
// System.out.println(proname+" = "+property.getString());
if (proname.startsWith(this.nom)) {
_nom.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.bas)) {
_bas.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.ext)) {
_ext.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.role)) {
_role.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.file)) {
_file.put(filterPrefix(proname), property.getStream());
}
}
_resVo.setBas(_bas);
_resVo.setNom(_nom);
_resVo.setExt(_ext);
_resVo.setRole(_role);
_resVo.setFile(_file);
if (node.hasProperty("ico")) {
_resVo.setIco(node.getProperty("ico").getString());
}
if (node.hasProperty("config")) {
_resVo.setConfig(node.getProperty("config").getString());
}
if (node.hasProperty("dataurl")) {
_resVo.setDataurl(node.getProperty("dataurl").getString());
}
/*
* if (node.hasProperty("r")){
* _resVo.setR(node.getProperty("r").getString()); } if
* (node.hasProperty("rw")){
* _resVo.setRw(node.getProperty("rw").getString()); }
*/
if (node.hasProperty("title")) {
_resVo.setTitle(node.getProperty("title").getString());
}
if (node.hasProperty("time")) {
_resVo.setTime(node.getProperty("time").getString());
}
if (node.hasProperty(this.reskeyword)) {
_resVo.setResKeyWord(node.getProperty(this.reskeyword)
.getString());
}
if (node.hasProperty(this.type)) {
_resVo.setType(node.getProperty(this.type).getString());
}
if (node.hasProperty("memo")) {
_resVo.setMemo(node.getProperty("memo").getString());
}
_resVo.setName(node.getName());
_resVo.setParentPath(node.getParent().getPath());
_resVo.setResPath(node.getPath());
} catch (RepositoryException e) {
e.printStackTrace();
}
return _resVo;
}
ResVo fillVosample(Node node) {
ResVo _resVo = new ResVo();
Hashtable _nom = new Hashtable();
Hashtable _bas = new Hashtable();
Hashtable _role = new Hashtable();
try {
PropertyIterator propertys = node.getProperties();
while (propertys.hasNext()) {
Property property = propertys.nextProperty();
String proname = property.getName();
// System.out.println(proname+" = "+property.getString());
if (proname.startsWith(this.nom)) {
_nom.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.bas)) {
_bas.put(filterPrefix(proname), property.getString());
}
if (proname.startsWith(this.role)) {
_role.put(filterPrefix(proname), property.getString());
}
}
_resVo.setBas(_bas);
_resVo.setNom(_nom);
_resVo.setRole(_role);
if (node.hasProperty("ico")) {
_resVo.setIco(node.getProperty("ico").getString());
}
if (node.hasProperty("config")) {
_resVo.setConfig(node.getProperty("config").getString());
}
if (node.hasProperty("dataurl")) {
_resVo.setDataurl(node.getProperty("dataurl").getString());
}
if (node.hasProperty("title")) {
_resVo.setTitle(node.getProperty("title").getString());
}
if (node.hasProperty("time")) {
//System.out.println(node.getProperty("time").getString()+"aaaaaaaaaa");
_resVo.setTime(node.getProperty("time").getString());
}
if (node.hasProperty(this.reskeyword)) {
_resVo.setResKeyWord(node.getProperty(this.reskeyword)
.getString());
}
if (node.hasProperty(this.type)) {
_resVo.setType(node.getProperty(this.type).getString());
}
if (node.hasProperty("memo")) {
_resVo.setMemo(node.getProperty("memo").getString());
}
_resVo.setName(node.getName());
_resVo.setParentPath(node.getParent().getPath());
_resVo.setResPath(node.getPath());
} catch (RepositoryException e) {
e.printStackTrace();
}
return _resVo;
}
ResVo fillVoSearch(Node node) {
ResVo _resVo = new ResVo();
try {
if (node.hasProperty("ico")) {
_resVo.setIco(node.getProperty("ico").getString());
}
if (node.hasProperty("dataurl")) {
_resVo.setDataurl(node.getProperty("dataurl").getString());
}
if (node.hasProperty("title")) {
_resVo.setTitle(node.getProperty("title").getString());
}
if (node.hasProperty("time")) {
_resVo.setTime(node.getProperty("time").getString());
}
if (node.hasProperty(this.reskeyword)) {
_resVo.setResKeyWord(node.getProperty(this.reskeyword)
.getString());
}
if (node.hasProperty(this.type)) {
_resVo.setType(node.getProperty(this.type).getString());
}
if (node.hasProperty("memo")) {
_resVo.setMemo(node.getProperty("memo").getString());
}
_resVo.setName(node.getName());
_resVo.setParentPath(node.getParent().getPath());
_resVo.setResPath(node.getPath());
} catch (RepositoryException e) {
e.printStackTrace();
}
return _resVo;
}
Node fillNode(Node node, Hashtable values, String prefix)
{
Node _node = node;
if ((values != null) && (values.size() > 0)) {
Iterator iterator = values.keySet().iterator();
while (iterator.hasNext()) {
String obj = (String) iterator.next();
Object v = values.get(obj);
try {
if (prefix.equals(this.file)) {
node.setProperty(prefix + obj, (InputStream) v);
} else {
_node.setProperty(prefix + obj, (String) v);
}
} catch (ValueFormatException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (VersionException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (LockException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (ConstraintViolationException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (RepositoryException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}
return _node;
}
String filterPrefix(String n) {
return n.substring(n.indexOf(95) + 1);
}
boolean checkrole(Node n, String rw) throws ValueFormatException,
PathNotFoundException, RepositoryException {
String role = "";
boolean flag = false;
if(n.hasProperty("role_"+rw)){
role = n.getProperty("role_" + rw).getString();
}
if(role.indexOf("owner")!=-1||role.indexOf("all")!=-1){
flag=true;
}else{
for (int i = 0; i < this.roleright.length; i++) {
if (role.indexOf(this.roleright[i]) > -1) {
flag = true;
break;
}
}
}
return flag;
}
String creatXpath(ResVo resVo,String sortStr) {
Iterator iterator;
String obj;
String xpath = "/"+resVo.getResPath()+"/element(*, nt:unstructured) [";
String temppath = "";
Hashtable _bas = resVo.getBas();
Hashtable _nom = resVo.getNom();
Hashtable _ext = resVo.getExt();
Hashtable _role = resVo.getRole();
if ((_bas != null) && (!(_bas.isEmpty()))) {
iterator = _bas.keySet().iterator();
while (iterator.hasNext()) {
obj = (String) iterator.next();
if("state".equals(obj)){
String statesStr = (String)_bas.get(obj);
if(statesStr!=null&&!"".equals(statesStr.trim())){
String[] states = ((String)_bas.get(obj)).split(",");
temppath+="(";
for(int i= 0;i<states.length;i++){
temppath = temppath +this.bas + obj + "='" + states[i]+"'";
if(i!=states.length-1){
temppath +=" or ";
}
}
temppath+=") and ";
}
}else if("nodeType".equals(obj)){
String nodeTypeStr = (String)_bas.get(obj);
if(nodeTypeStr!=null&&!"".equals(nodeTypeStr.trim())){
if(nodeTypeStr.contains(",")){
String[] nodeTypeStrs = ((String)_bas.get(obj)).split(",");
temppath+="(";
for(int i= 0;i<nodeTypeStrs.length;i++){
temppath = temppath +this.bas + obj + "='" + nodeTypeStrs[i]+"'";
if(i!=nodeTypeStrs.length-1){
temppath +=" or ";
}
}
temppath+=") and ";
}else{
temppath = temppath +this.bas + obj + "='" + nodeTypeStr+"' ) and";
}
}
}
else{
if("".equals((String) _bas.get(obj))){
continue;
}if("isIndex".equals(obj)||"position".equals(obj)){
temppath = temppath + "jcr:like(@"+this.bas + obj + ",'"
+ ((String) _bas.get(obj)) + "') and ";
}else{
temppath = temppath + "jcr:like(@"+this.bas + obj + ",'%"
+ ((String) _bas.get(obj)) + "%') and ";
}
}
}
}
if ((_nom != null) && (!(_nom.isEmpty()))) {
iterator = _nom.keySet().iterator();
while (iterator.hasNext()) {
obj = (String) iterator.next(); // jcr:like(array,'%ar%)
if ((obj.equals("category"))) {
String categoryValue=(String)_nom.get(obj);
if(categoryValue.contains(",")){
categoryValue = categoryValue.replaceAll(" ", " ").trim();
String[] _categoryValue = categoryValue.split(",");
temppath = temppath + "(";
for (int i = 0; i < _categoryValue.length; ++i) {
temppath = temppath + " jcr:like(@nom_category,'%"
+ _categoryValue[i] + "') ";
if (i + 1 < _categoryValue.length)
temppath = temppath + " or ";
else {
temppath = temppath + " ) and ";
}
}
}else{
temppath = temppath + " jcr:like(@nom_category,'"
+ (String) _nom.get(obj) + "%') and ";
}
}
else if (obj.equals("lib")) {
temppath = temppath + " jcr:like(@nom_lib,'"
+ (String) _nom.get(obj) + "%') and ";
} else {
temppath = temppath + this.nom + obj + "='"
+ ((String) _nom.get(obj)) + "' and ";
}
}
}
//sortStr說明爲用戶分頁查詢,需要根據權限查詢
if("user".equals(sortStr)) {
if ((_role != null) && (!(_role.isEmpty()))) {
iterator = _role.keySet().iterator();
while (iterator.hasNext()) {
obj = (String) iterator.next(); // jcr:like(array,'%ar%)
if ((obj.equals("rightrole"))) {
String rightroleValue=(String)_role.get(obj);
if(rightroleValue.contains(",")){
rightroleValue = rightroleValue.replaceAll(" ", " ").trim();
String[] _rightroleValue = rightroleValue.split(",");
temppath = temppath + "(";
for (int i = 0; i < _rightroleValue.length; ++i) {
temppath = temppath + " jcr:contains(@role_rightrole,'"
+ _rightroleValue[i] + "') ";
if (i + 1 < _rightroleValue.length)
temppath = temppath + " or ";
else {
temppath = temppath + " ) and ";
}
}
}else{
temppath = temppath + " jcr:contains(@role_rightrole,'"
+ (String) _role.get(obj) + "') and ";
}
}
}
}
}
if ((_ext != null) && (!(_ext.isEmpty()))) {
iterator = _ext.keySet().iterator();
while (iterator.hasNext()) {
obj = (String) iterator.next();
temppath = temppath + this.ext + obj + "='"
+ ((String) _ext.get(obj)) + "' and ";
}
}
if(resVo.getType() != null){
if(resVo.getType().contains(",")){
String[] str=resVo.getType().split(",");
temppath = temppath + "("+this.type + "='" + str[0] + "' or "+this.type+"='"+str[1]+"') and ";
}
else{
temppath = temppath + this.type + "='" + resVo.getType() + "' and ";
}
}
// if ((resVo.getType() != null) && (!(resVo.getType().equals("")))) {
// temppath = temppath + this.type + "='" + resVo.getType() + "' and ";
// }
if ((resVo.getTitle() != null) && (!(resVo.getTitle().equals("")))) {
//temppath = temppath + "jcr:contains(@title,'" + resVo.getTitle()
temppath = temppath + "jcr:like(@title,'%" + resVo.getTitle()
+ "%') and ";
}
if ((resVo.getName()!= null) && (!(resVo.getName().equals("")))) {
//temppath = temppath + "jcr:contains(@title,'" + resVo.getTitle()
temppath = temppath + "jcr:like(@name,'%" + resVo.getName()
+ "%') and ";
}
if ((resVo.getMemo() != null) && (!(resVo.getMemo().equals("")))) {
temppath = temppath + "jcr:like(@memo,'%" + resVo.getMemo()
+ "%') and ";
}
if ((resVo.getTime() != null) && (!(resVo.getTime().equals("")))) {
temppath = temppath + "jcr:like(@time,'" + resVo.getTime()
+ "%') and ";
}
String keyword = resVo.getResKeyWord();
if ((keyword != null) && (!(keyword.equals("")))) {
keyword = keyword.replaceAll(" ", " ").trim();
String[] _keyword = keyword.split(" ");
temppath = temppath ;
for (int i = 0; i < _keyword.length; ++i) {
temppath = temppath + " jcr:contains(@resKeyWord,'"
+ _keyword[i] + "') ";
if (i + 1 < _keyword.length)
temppath = temppath + " or ";
else {
temppath = temppath;
}
}
}
if (temppath.endsWith("and ")) {
temppath = temppath.substring(0, temppath.lastIndexOf("and "));
}
xpath = xpath + temppath;
// if ((orderby != null) && (!(orderby.equals(""))))
xpath = xpath + "]";
//descending ascending
if(resVo.getResPath().contains("/system/lib")){
xpath=xpath+" order by @bas__positionNum ascending";
}
else{
if(!"".equals(sortStr)&&!"user".equals(sortStr)){
xpath=xpath+" order by @"+sortStr+ " ascending";
}
else{
xpath=xpath+" order by @time descending";
}
}
// else {
// }
System.out.println("xpath = " + xpath);
return xpath;
}
public String createXpathLogn(Session jcrSession,ResVo resVo){
long countLong=0l;
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
//查詢此資源的相關日誌數量
String respath=resVo.resPath.replace("/", "_");
String title=respath+"_"+resVo.getTitle();
String xpathLog = "//log//element(*, nt:unstructured) [jcr:like(@title,'"+title+"')]";
// String xpathLog = "//* [jcr:like(@title,'"+title+"') and type='node']";
// System.out.print(xpathLog+" "+"日誌");
NodeIterator itLog = qm.createQuery(xpathLog, "xpath").execute().getNodes();
while(itLog.hasNext()){
itLog.next();
countLong++;
}
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return Long.toString(countLong);
}
//返回最新的日誌節點
public Node getNewLogNode(Session jcrSession,ResVo resVo){
Node node=null;
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
//查詢此資源的相關日誌數量
String respath=resVo.resPath.replace("/", "_");
String title=respath+"_"+resVo.getTitle();
String xpathLog = "//log//element(*, nt:unstructured) [jcr:like(@title,'"+title+"')]";
//String xpathLog="max(//log/@time)";
NodeIterator itLog = qm.createQuery(xpathLog, "xpath").execute().getNodes();
while(itLog.hasNext()){
node=(Node)itLog.next();
}
} catch (PathNotFoundException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
return node;
}
public List searchW(Session jcrSession, ResVo resVo,long current,long offset) {
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
String xpath = this.creatXpath(resVo,"");
Query q = qm.createQuery(xpath, "xpath");
QueryResult result = q.execute();
NodeIterator it = result.getNodes();
long i=0;
while (it.hasNext()) {
it.next();
i=++i;
}
list.add(i);//總數據量
it = qm.createQuery(xpath, "xpath").execute().getNodes();
long m = 0;
//it.skip(current);
while(it.hasNext()){
Node n = it.nextNode();
//System.out.println(n.getPath());
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
m=++m;
if(m==offset){
break;
}
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
//根據指定xpath查詢數據
public List searchByXpath(Session jcrSession,String xpath){
List list = new ArrayList();
try {
QueryManager qm = jcrSession.getWorkspace().getQueryManager();
Query q = qm.createQuery(xpath, "xpath");
QueryResult result = q.execute();
NodeIterator it = result.getNodes();
long i=0;
while (it.hasNext()) {
it.next();
i=++i;
}
list.add(i);//總數據量
it = qm.createQuery(xpath, "xpath").execute().getNodes();
long m = 0;
//it.skip(current);
while(it.hasNext()){
Node n = it.nextNode();
//System.out.println(n.getPath());
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
public List getChildrenW(Session jcrSession, String path, String type) {
List list = new ArrayList();
try {
Node node = jcrSession.getNode(path);
// if (this.checkrole(node, "r")) {
NodeIterator it = node.getNodes();
while (it.hasNext()) {
Node n = it.nextNode();
ResVo resvo = new ResVo();
resvo = fillVosample(n);
list.add(resvo);
}
} catch (PathNotFoundException e) {
e.printStackTrace();
list = null;
} catch (RepositoryException e) {
e.printStackTrace();
list = null;
}
return list;
}
/**
* 修改密碼
* @param jcrSession
* @param resVo
* @return
*/
public ResVo modifyPwd(Session jcrSession, ResVo resVo) {
ResVo _resVo = null;
String resPath = resVo.getResPath();
try {
Node node = jcrSession.getNode(resPath);
if (checkrole(node, "rw")) {
_resVo = new ResVo();
fillNode(node, resVo.getBas(), this.bas);
fillNode(node, resVo.getNom(), this.nom);
fillNode(node, resVo.getFile(), this.file);
fillNode(node, resVo.getExt(), this.ext);
fillNode(node, resVo.getRole(), this.role);
node.setProperty("ico", resVo.getIco());
node.setProperty("config", resVo.getConfig());
node.setProperty("dataurl", resVo.getDataurl());
node.setProperty("title", resVo.getTitle());
node.setProperty("resKeyWord", resVo.getResKeyWord());
// node.setProperty("time", resVo.getTime());
node.setProperty("memo", resVo.getMemo());
_resVo = fillVo(node);
}
// jcrSession.save();
} catch (PathNotFoundException e) {
_resVo = null;
e.printStackTrace();
} catch (RepositoryException e) {
_resVo = null;
e.printStackTrace();
} catch (Exception e) {
_resVo = null;
e.printStackTrace();
}
return _resVo;
}
}
3.ResServlet.java(調用ResDao裏面的方法實現檢索)
package sevlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.LoginException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.map.HashedMap;
import test.Connection;
import test.ResDao;
import test.ResVo;
/**
* Servlet implementation class ResServlet
*/
public class ResServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ResServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("111111111111111111");
ResDao resDao = new ResDao();
Session jcrSession = null;
Node node = null;
String resPath = null;
try {
jcrSession = Connection.getConn();// 連接jcr
ResVo rv = new ResVo();
// 創建
/*
* rv.setName("afterService");//設置ResVo的值 rv.setTitle("售後服務");
* rv.setParentPath("/"); rv.setResPath("/system");
* rv.setMemo("售後服務");
* rv.setIco("/WEB-INF/images/afterService.png");
* resDao.creat(jcrSession, rv);//創建
*/
// 得到某個指定節點的某個屬性值
/*
* node = jcrSession.getNode("/system/afterService");//
* 找到system/afterService下的節點 resPath =
* node.getProperty("ico").getString();// 得到node的ico屬性
*/
// 把node節點轉爲resVo對象
// rv = resDao.fillVosample(node);// 把node節點轉換爲 resVo對象
// 修改某個resVo的值
// rv.setIco("/WEB-INF/images/afterService.png");//設置ico的值
// resDao.modify(jcrSession, rv);//修改ico的值
// 1.指定路徑節點查詢
/*
* Node pointPath = jcrSession.getNode("/system"); resPath =
* pointPath.getName();
*/
// 2.指定路徑節點子節點查詢
// 查詢 /menu 路徑下的所有節點
/*node = jcrSession.getNode("/menu");// 指定路徑爲:/menu
NodeIterator iterator = node.getNodes();
while (iterator.hasNext()) {
Node nodes = iterator.nextNode();
System.out.println("指定路徑的子節點名稱是: " + nodes.getName() + ",指定路徑的子節點的路徑是:" + nodes.getPath());
}*/
// 3.指定路徑節點子節點樹查詢
/*node = jcrSession.getRootNode();
NodeIterator it =
node.getNodes();
while(it.hasNext()){
Node childPath = it.nextNode();
System.out.println("指定節點的子節點: -"+childPath.getName());
NodeIterator its = childPath.getNodes();
while(its.hasNext()){
Node nn = its.nextNode();
System.out.println("指定節點的子節點下的子節點: --"+nn.getName());
}
}*/
// 4.指定節點父節點查詢(查詢父節點的名稱和路徑)
/*node = jcrSession.getNode("/menu/system");
String parentNode = node.getParent().getName();// 得到父節點的名稱
String parentPath = node.getParent().getPath();// 得到父節點的路徑
System.out.println("parentNode is : " + parentNode
+ ",parentPath is : " + parentPath);*/
// 5.指定節點路徑新增節點
/*node = jcrSession.getNode("/menu");
node.addNode("function");
jcrSession.save();//保存(很重要的步驟) */
// 6.指定節點路徑刪除節點
/*node = jcrSession.getNode("/system");
rv =resDao.fillVosample(node);
boolean s = resDao.deletedNode(jcrSession, rv);
System.out.println("刪除了? "+s);*/
// 7.指定節點路徑修改節點
node = jcrSession.getNode("/menu/function");
node.setProperty("name", "功能菜單");
// 跳轉頁面
/*
* request.setAttribute("ico", resPath);
* request.getRequestDispatcher
* ("/TestResjsp.jsp").forward(request,response);
*/
} catch (LoginException e) {
e.printStackTrace();
} catch (RepositoryException e) {
e.printStackTrace();
}
}
}