关闭

毕业设计代码精选2

130人阅读 评论(0) 收藏 举报
package com.nb.org.interceptor;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;
import com.nb.org.domain.Department;
import com.nb.org.domain.Person;
import com.nb.org.service.IDepartmentPermissionService;
import com.nb.org.service.IDepartmentService;
import com.nb.org.service.IPersonService;
import com.nb.org.service.IPositionService;

/*
 * 该拦截器拦截所有rest的请求,验证请求的用户是否有权限请求相应的rest API
 */
public class AuthenticateRestRequestInterceptor implements HandlerInterceptor {

	@Autowired
	private IDepartmentPermissionService departmentPermissionService;

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IPersonService personService;

	@Autowired
	private IPositionService positionService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		JSONObject json = new JSONObject();

		// 获取请求路径(格式:/rest/*)
		String servletPath = request.getServletPath();
		// 根据servletPath获取请求的rest path
		String restPath = getRestPath(servletPath);
		// 获取请求的方法
		String method = request.getMethod();
		// 获取请求头认证信息
		String authorization = request.getHeader("Authorization");
		// 获取请求头中的部门信息
		String departmentName = request.getHeader("departmentName");
		if (departmentName != null) {
			departmentName = new String(Base64.decodeFast(departmentName));
		}
		
		// 判断请求中是否包含用户身份信息
		if (authorization != null && !"".equals(authorization) && authorization.length() > 6) {
			String credential = authorization.substring(6);
			// Base64解码,得到用户名和密码(格式:用户名:密码)
			credential = new String(Base64.decodeFast(credential));
			// 判断解码后的字符串是否包含:
			if (credential.contains(":")) {
				String[] pair = credential.split(":");
				// 调用接口验证用户名密码是否正确,然后再确认是否有相应的权限
				boolean identity = personService.authenticate(pair[0], pair[1]);
				//如果用户名密码验证通过
				if (identity) {
					// 调用接口判断是否有相应的权限
					Person restUser = personService.getPersonByUserName(pair[0]);
					//调用非查询方法时需要提供 要管理的部门名称。查询方法面对所有人员开放。
					if(!method.equals("GET")) {
						if(departmentName == null) {
							json = new JSONObject();
							json.put("code", "2003");
							json.put("result", "failure");
							json.put("reason", "请输入您要管理的部门名称");
							response.setContentType("application/json");
							response.getWriter().write(json.toJSONString());
							return false;
						}
						Department department = departmentService.selectDepByName(departmentName);
						if(department == null) {
							json.put("code", "2004");
							json.put("result", "failure");
							json.put("reason", "您输入的要管理的部门名称不存在");
							response.setContentType("application/json");
							response.getWriter().write(json.toJSONString());
							return false;
						}
						//把操作者登录的部门放进request中
						request.setAttribute("departmentName", department);
						boolean entitled = departmentPermissionService.getDepartmantPermissionRest(department.getId(), restUser.getId()) == 1;
						if (entitled) {
							// 将该用户的信息放入request中
							request.setAttribute("restUser", restUser);
							return true;
						} else { // 您没有此权限进行该操作
							json = new JSONObject();
							json.put("code", "1000");
							json.put("result", "failure");
							json.put("reason", "您没有此权限进行该操作");
							response.setContentType("application/json");
							response.getWriter().write(json.toJSONString());
							return false;
						}
					} else {
						//到此可判断为执行查询方法,不需要权限,只要用户名密码校验通过即可
						return true;
					}
				} else { // 用户名或密码错误
					json = new JSONObject();
					json.put("code", "2000");
					json.put("result", "failure");
					json.put("reason", "用户名或密码错误");
					response.setContentType("application/json");
					response.getWriter().write(json.toJSONString());
					return false;
				}
			} else {
				json = new JSONObject();
				json.put("code", "2001");
				json.put("result", "failure");
				json.put("reason", "身份凭据格式不正确");
				response.setContentType("application/json");
				response.getWriter().write(json.toJSONString());
				return false;
			}

		} else {
			// 如果不包含身份信息,
			json = new JSONObject();
			json.put("code", "2002");
			json.put("result", "failure");
			json.put("reason", "未提供身份凭据");
			response.setContentType("application/json");
			response.getWriter().write(json.toJSONString());
			return false;
		}

	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

	}

	private String getRestPath(String servletPath) {
		String temp = servletPath.substring(6);
		if (temp.contains("/")) {
			int location = temp.indexOf('/');
			temp = temp.substring(0, location);
		}
		return temp;
	}

}

package com.nb.org.remote.app;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.Property;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
import org.wso2.carbon.identity.sso.saml.stub.types.SAMLSSOServiceProviderDTO;
import org.wso2.carbon.identity.sts.mgt.stub.generic.STSAdminServiceStub;
import org.wso2.carbon.identity.sts.mgt.stub.service.util.xsd.TrustedServiceData;

import com.nb.org.exception.AppUpdateException;
import com.nb.org.util.GlobalConfig;
import com.thoughtworks.xstream.XStream;

/**
 * @author huangxin xin 2016年1月22日
 */
public class AppDefaultData {
	private InputStream inputStream;
	private DocumentBuilder builder;

	public ServiceProvider getDefaultServiceProvider() throws AppUpdateException {
		try {
			inputStream = AppDefaultData.class.getClassLoader().getResourceAsStream("application-default.xml");
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			ServiceProvider sp = null;
			Document document = null;
			Document spdom = builder.newDocument();
			document = builder.parse(inputStream);
			NodeList l = document.getElementsByTagName("ServiceProvider");
			Node item = l.item(0);
			Node spNode = spdom.importNode(item, true);
			spdom.appendChild(spNode);
			org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
			org.dom4j.Document spdom4j = xmlReader.read(spdom);
			XStream xstream = new XStream();
			xstream.alias("ServiceProvider", ServiceProvider.class);
			xstream.alias("ClaimMapping", org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping.class);
			xstream.alias("InboundAuthenticationRequestConfig", InboundAuthenticationRequestConfig.class);
			xstream.alias("Property", Property.class);
			sp = (ServiceProvider) xstream.fromXML(spdom4j.asXML());
			inputStream.close();
			return sp;
		} catch (Exception e) {
			throw new AppUpdateException("默认配置加载失败。");
		}
	}

	public OAuthConsumerAppDTO getDefaultOAuth() throws AppUpdateException {
		try {
			inputStream = AppDefaultData.class.getClassLoader().getResourceAsStream("application-default.xml");
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			OAuthConsumerAppDTO oauth = null;
			Document document = null;
			Document oauthDom = builder.newDocument();
			document = builder.parse(inputStream);
			NodeList l = document.getElementsByTagName("OAuth");
			Node item = l.item(0);
			Node oauthNode = oauthDom.importNode(item, true);
			oauthDom.appendChild(oauthNode);
			org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
			org.dom4j.Document spdom4j = xmlReader.read(oauthDom);
			XStream xstream = new XStream();
			xstream.alias("OAuth", OAuthConsumerAppDTO.class);
			oauth = (OAuthConsumerAppDTO) xstream.fromXML(spdom4j.asXML());
			inputStream.close();
			return oauth;
		} catch (Exception e) {
			throw new AppUpdateException("默认配置加载失败。");
		}
	}

	public String getDefaultSTSCertAlias() throws AppUpdateException {
		inputStream = AppDefaultData.class.getClassLoader().getResourceAsStream("application-default.xml");
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document document = builder.parse(inputStream);
			Node item = document.getElementsByTagName("STS").item(0);
			NodeList certs = item.getChildNodes();
			int len = certs.getLength();
			for (int i = 0; i < len; i++) {
				Node node = certs.item(i);
				if (node.getNodeName().equals("DefaultCertAlias")) {
					return node.getFirstChild().getNodeValue();
				}
			}
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new AppUpdateException("默认配置加载失败。");
		}
	}

	public TrustedServiceData getSTSData(String address, String alias) {
		TrustedServiceData data = new TrustedServiceData();
		data.setCertAlias(alias);
		data.setServiceAddress(address);
		return data;
	}

	public SAMLSSOServiceProviderDTO getDefaultSAML() throws AppUpdateException {
		try {
			inputStream = AppDefaultData.class.getClassLoader().getResourceAsStream("application-default.xml");
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			SAMLSSOServiceProviderDTO saml = null;
			Document document = null;
			Document samlDom = builder.newDocument();
			document = builder.parse(inputStream);
			NodeList l = document.getElementsByTagName("SAML");
			Node item = l.item(0);
			Node samlNode = samlDom.importNode(item, true);
			samlDom.appendChild(samlNode);
			org.dom4j.io.DOMReader xmlReader = new org.dom4j.io.DOMReader();
			org.dom4j.Document spdom4j = xmlReader.read(samlDom);
			XStream xstream = new XStream();
			xstream.alias("SAML", SAMLSSOServiceProviderDTO.class);
			saml = (SAMLSSOServiceProviderDTO) xstream.fromXML(spdom4j.asXML());
			String[] tokenUrl = saml.getRequestedAudiences();
			if (tokenUrl == null || tokenUrl.length == 0)
				tokenUrl = new String[] { new String(GlobalConfig.server + "/oauth2/token") };
			saml.setRequestedAudiences(tokenUrl);
			tokenUrl = saml.getRequestedRecipients();
			if (tokenUrl == null || tokenUrl.length == 0)
				tokenUrl = new String[] { new String(GlobalConfig.server + "/oauth2/token") };
			saml.setRequestedRecipients(tokenUrl);
			inputStream.close();
			return saml;
		} catch (Exception e) {
			throw new AppUpdateException("默认配置加载失败。");
		}
	}
}

package com.nb.org.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nb.org.domain.AppInfo;
import com.nb.org.domain.AppRole;
import com.nb.org.domain.AppRoleDepartment;
import com.nb.org.domain.AppRolePerson;
import com.nb.org.domain.Department;
import com.nb.org.domain.Person;
import com.nb.org.service.IAppInfoService;
import com.nb.org.service.IAppRoleDepService;
import com.nb.org.service.IAppRolePerService;
import com.nb.org.service.IAppRoleService;
import com.nb.org.service.IDepartmentService;
import com.nb.org.service.IPersonService;
import com.nb.org.service.IPositionService;
import com.nb.org.vo.AppRoleVO;

@Controller
@RequestMapping("/rest/appRole")
public class AppRoleRest {

	@Autowired
	private IAppRoleService appRoleService;

	@Autowired
	private IAppInfoService appInfoService;

	@Autowired
	private IPositionService positionService;

	@Autowired
	private IPersonService personService;

	@Autowired
	private IDepartmentService departmentService;

	@Autowired
	private IAppRolePerService appRolePerService;

	@Autowired
	private IAppRoleDepService appRoleDepService;

	/**
	 * @author upshi
	 * @date 20160219
	 * @url /rest/appRole/appId/{appId}
	 */
	@ResponseBody
	@RequestMapping(value = "/appId/{appId}", method = RequestMethod.GET)
	public Map<String, Object> search(@PathVariable Integer appId) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<AppRole> appRoles = null;
		appRoles = appRoleService.getRoleListForApp(appId);
		if (appRoles != null && appRoles.size() != 0) {
			map.put("code", "8000");
			map.put("result", "success");
			map.put("appRoles", appRoles);
		} else {
			map.put("code", "5002");
			map.put("result", "failure");
			map.put("reason", "您查询的应用下没有角色");
		}
		return map;
	}

	/**
	 * @author upshi
	 * @date 20160219
	 * @url /rest/appRole/appName/{appName}
	 */
	@ResponseBody
	@RequestMapping(value = "/appName/{appName}", method = RequestMethod.GET)
	public Map<String, Object> search(@PathVariable String appName) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<AppRole> appRoles = null;
		appRoles = appRoleService.getRolesByAppName(appName);

		if (appRoles != null && appRoles.size() != 0) {
			map.put("code", "8000");
			map.put("result", "success");
			map.put("appRoles", appRoles);
		} else {
			map.put("code", "5002");
			map.put("result", "failure");
			map.put("reason", "您查询的应用下没有角色");
		}
		return map;
	}

	/**
	 * @author upshi
	 * @date 20160219
	 * @url /rest/appRole?appName=&userName=
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.GET)
	public Map<String, Object> search(@RequestParam String appName, @RequestParam String userName) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> roles = null;
		roles = appRoleService.getRolesForPerson(appName, userName);

		if (roles != null && roles.size() != 0) {
			map.put("code", "8000");
			map.put("result", "success");
			map.put("roles", roles);
		} else {
			map.put("code", "5003");
			map.put("result", "failure");
			map.put("reason", "您查询的人员在应用中没有角色");
		}
		return map;
	}

	/**
	 * @author upshi
	 * @date 20160301
	 * @url /rest/appRole
	 *      请求参数json格式:{"name":"","appId":"","personUserNames":[],"departmentNames"
	 *      :[]}
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST)
	public Map<String, Object> addRole(@RequestBody AppRoleVO appRoleVO, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		//AppInfo appInfo = appInfoService.getAppById(appRoleVO.getAppId());
		// 判断有没有权限进行操作
		Map<String, Object> preHandleMap = preHandle(request, appRoleVO.getAppId());
		if (preHandleMap != null) {
			return preHandleMap;
		}

		// 判断角色名是否存在
		List<AppRole> roleListForApp = appRoleService.getRoleListForApp(appRoleVO.getAppId());
		for (AppRole appRole : roleListForApp) {
			if (appRole.getName().equals(appRoleVO.getName())) {
				map.put("code", "5013");
				map.put("result", "failure");
				map.put("reason", "角色名已经存在");
				return map;
			}
		}

		// 判断添加的人员有没有不存在的
		List<String> personUserNames = appRoleVO.getPersonUserNames();
		List<Person> personsResult = null;
		if(personUserNames != null) {
			personsResult = personService.getPersonsByUserNames(personUserNames);
			// 根据参数中的用户名查询出的结果集数量与参数的集合数量是否一致判断是否有不存在的用户名
			if (personsResult != null && personsResult.size() != personUserNames.size()) {
				String inexistenceUserNames = "";
				String resultUserNames = "";
				// 组成查到的用户名字符串
				for (Person p : personsResult) {
					resultUserNames = resultUserNames + p.getUsername() + ",";
				}
				// 判断参数中的用户名,找出不在数据库中的用户名
				for (String s : personUserNames) {
					if (resultUserNames.indexOf("," + s + ",") < 0) {
						inexistenceUserNames = inexistenceUserNames + s + " ";
					}
				}
				map.put("code", "5014");
				map.put("result", "failure");
				map.put("reason", inexistenceUserNames + "用户不存在,创建角色失败");
				return map;
			}
		}

		// 判断部门有没有不存在的
		// 判断添加的人员有没有不存在的
		List<String> departmentsNames = appRoleVO.getDepartmentNames();
		List<Department> departmentsResult = null;
		if(departmentsNames != null) {
			departmentsResult = departmentService.getDepartmentsByNames(departmentsNames);
			// 根据参数中的用户名查询出的结果集数量与参数的集合数量是否一致判断是否有不存在的用户名
			if (departmentsResult != null && departmentsResult.size() != departmentsNames.size()) {
				String inexistenceDepartmentNames = "";
				String resultDepartmentNames = "";
				// 组成查到的用户名字符串
				for (Department d : departmentsResult) {
					resultDepartmentNames = resultDepartmentNames + d.getName() + ",";
				}
				// 判断参数中的用户名,找出不在数据库中的用户名
				for (String s : departmentsNames) {
					if (resultDepartmentNames.indexOf("," + s + ",") < 0) {
						inexistenceDepartmentNames = inexistenceDepartmentNames + s + " ";
					}
				}
				map.put("code", "5015");
				map.put("result", "failure");
				map.put("reason", inexistenceDepartmentNames + "部门不存在,创建角色失败");
				return map;
			}
		}
		
		// 都存在后即可进行添加该角色
		// 构造AppRole对象
		AppRole appRole = new AppRole();
		appRole.setAppId(appRoleVO.getAppId());
		appRole.setName(appRoleVO.getName());
		appRole.setPersons(personsResult);
		appRole.setDepartments(departmentsResult);
		// 调用service方法插入角色信息
		appRoleService.addRoleForApp(appRole);

		map.put("code", "8000");
		map.put("result", "success");
		return map;
	}

	/**
	 * @author upshi
	 * @date 20160302
	 * @url /rest/appRole
	 *      请求参数json格式:{"id":"","name":"","appId":"","addUserNames":[],"removeUserNames":[],"addDepartmentNames":[],"removeDepartmentNames":[]}
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.PUT)
	public Map<String, Object> updateRole(@RequestBody AppRoleVO appRoleVO, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		//AppInfo appInfo = appInfoService.getAppById(appRoleVO.getAppId());
		// 1.判断有没有权限进行操作
		Map<String, Object> preHandleMap = preHandle(request, appRoleVO.getAppId());
		if (preHandleMap != null) {
			return preHandleMap;
		}

		// 根据id获取该条AppRole记录,判断角色名字是否需要修改
		Integer appRoleId = appRoleVO.getId();
		if (appRoleId == null) {
			map.put("code", "5021");
			map.put("result", "failure");
			map.put("reason", "请输入应用角色ID");
			return map;
		}
		// 2.判断应用角色是否存在
		AppRole appRole = appRoleService.getRoleDetailForApp(appRoleId);
		if (appRole == null) {
			map.put("code", "5016");
			map.put("result", "failure");
			map.put("reason", "您输入的应用角色ID不存在");
			return map;
		}

		// 判断角色名是否和数据库中一致
		String roleName = appRoleVO.getName();
		if (roleName != null && !roleName.equals("")) {
			// 如果不一致进行修改
			if (!roleName.equals(appRole.getName())) {
				appRole.setName(roleName);
				appRoleService.updateAppRole(appRole);
			}
		}

		// 3.根据角色名和应用id获取该AppRole对象
		AppRole tempAppRole = new AppRole();
		tempAppRole.setName(appRoleVO.getName());
		tempAppRole.setAppId(appRoleVO.getAppId());
		// 4.查询出的要修改的AppRole对象
		AppRole appRoleResult = appRoleService.getRoleByNameAndApp(tempAppRole);

		// 5.从AppRole对象中获取当前的用户
		List<Person> persons = appRoleResult.getPersons();
		// 把当前用户的名称按逗号隔开拼成字符串,以便后面判断
		StringBuffer personUserNames = new StringBuffer(",");
		for (Person p : persons) {
			personUserNames.append(p.getUsername());
			personUserNames.append(",");
		}

		// 6.从AppRole对象中获取当前的部门
		List<Department> departments = appRoleResult.getDepartments();
		// 把当前部门的名称按逗号隔开拼成字符串,以便后面判断
		StringBuffer departmentNames = new StringBuffer(",");
		for (Department d : departments) {
			departmentNames.append(d.getName());
			departmentNames.append(",");
		}

		// 7.判断用户要增加的用户是否已经是该角色下的用户,如果存在提示不能增加这些用户
		List<String> addUserNames = appRoleVO.getAddUserNames();
		// 定义变量保存要返回的内容
		String returnString = ",";
		if (addUserNames != null && addUserNames.size() > 0) {
			for (String s : addUserNames) {
				if (personUserNames.indexOf("," + s + ",") >= 0) {
					returnString = returnString + s + " ";
				}
			}
			if (returnString.length() != 1) {
				map.put("code", "5017");
				map.put("result", "failure");
				map.put("reason", returnString.substring(1, returnString.length()) + "用户已经属于该角色,无法添加");
				return map;
			}
		}

		// 8.判断用户要移除的用户是否在该角色中,如果不存在提示无法移除这些用户
		List<String> removeUserNames = appRoleVO.getRemoveUserNames();
		returnString = ",";
		if (removeUserNames != null && removeUserNames.size() > 0) {
			for (String s : removeUserNames) {
				if (personUserNames.indexOf("," + s + ",") < 0) {
					returnString = returnString + s + " ";
				}
			}
			if (returnString.length() != 1) {
				map.put("code", "5018");
				map.put("result", "failure");
				map.put("reason", returnString.substring(1, returnString.length()) + "用户不属于该角色,无法移除");
				return map;
			}
		}

		// 9.判断用户要增加的部门是否已经在该角色下,如果存在提示不能增加这些部门
		List<String> addDepartmentNames = appRoleVO.getAddDepartmentNames();
		returnString = ",";
		if (addDepartmentNames != null && addDepartmentNames.size() > 0) {
			for (String s : addDepartmentNames) {
				if (departmentNames.indexOf("," + s + ",") >= 0) {
					returnString = returnString + s + " ";
				}
			}
			if (returnString.length() != 1) {
				map.put("code", "5019");
				map.put("result", "failure");
				map.put("reason", returnString.substring(1, returnString.length()) + "部门已经属于该角色,无法添加");
				return map;
			}
		}

		// 10.判断用户要移除的部门是否存在于该角色中,如果不存在提示不能移除这些部门
		List<String> removeDepartmentNames = appRoleVO.getRemoveDepartmentNames();
		returnString = ",";
		if (removeDepartmentNames != null && removeDepartmentNames.size() > 0) {
			for (String s : removeDepartmentNames) {
				if (departmentNames.indexOf("," + s + ",") < 0) {
					returnString = returnString + s + " ";
				}
			}
			if (returnString.length() != 1) {
				map.put("code", "5020");
				map.put("result", "failure");
				map.put("reason", returnString.substring(1, returnString.length()) + "部门不属于该角色,无法移除");
				return map;
			}
		}

		// 11.都没问题后,把该移除的移除,该添加的添加
		// 11.1添加用户
		if (addUserNames != null && addUserNames.size() > 0) {
			// 根据用户名获取所有要添加用户对象
			List<Person> addUserList = personService.getPersonsByUserNames(addUserNames);
			// 构造要添加的对象的List
			List<AppRolePerson> addAppRolePersons = new ArrayList<AppRolePerson>();
			// 临时变量
			AppRolePerson tempAppRolePerson = null;
			for (Person p : addUserList) {
				tempAppRolePerson = new AppRolePerson();
				tempAppRolePerson.setPerson(p);
				tempAppRolePerson.setAppRole(appRoleResult);

				addAppRolePersons.add(tempAppRolePerson);
			}
			// 执行添加操作
			appRolePerService.addPersonsToRole(addAppRolePersons);
		}

		// 11.2移除用户
		if (removeUserNames != null && removeUserNames.size() > 0) {
			// 根据用户名获取所有要移除用户对象
			List<Person> removeUserList = personService.getPersonsByUserNames(removeUserNames);
			// 构造要移除的对象的List
			List<AppRolePerson> removeAppRolePersons = new ArrayList<AppRolePerson>();
			// 临时变量
			AppRolePerson tempAppRolePerson = null;
			for (Person p : removeUserList) {
				tempAppRolePerson = new AppRolePerson();
				tempAppRolePerson.setPerson(p);
				tempAppRolePerson.setAppRole(appRoleResult);

				removeAppRolePersons.add(tempAppRolePerson);
			}
			// 执行移除操作
			appRolePerService.removePersonsFromRole(removeAppRolePersons);
		}

		// 11.3添加部门
		if (addDepartmentNames != null && addDepartmentNames.size() > 0) {
			// 根据部门名称获取所有要添加部门对象
			List<Department> addDepartmentList = departmentService.getDepartmentsByNames(addDepartmentNames);
			// 构造要添加的对象的List
			List<AppRoleDepartment> addAppRoleDepartments = new ArrayList<AppRoleDepartment>();
			// 临时变量
			AppRoleDepartment tempAppRoleDepartment = null;
			for (Department d : addDepartmentList) {
				tempAppRoleDepartment = new AppRoleDepartment();
				tempAppRoleDepartment.setDepartment(d);
				tempAppRoleDepartment.setAppRole(appRoleResult);

				addAppRoleDepartments.add(tempAppRoleDepartment);
			}
			// 执行添加操作
			appRoleDepService.addDepsToRole(addAppRoleDepartments);
		}
		// 11.4移除部门
		if (removeDepartmentNames != null && removeDepartmentNames.size() > 0) {
			// 根据部门名称获取所有要移除部门对象
			List<Department> removeDepartmentList = departmentService.getDepartmentsByNames(removeDepartmentNames);
			// 构造要移除的对象的List
			List<AppRoleDepartment> removeAppRoleDepartments = new ArrayList<AppRoleDepartment>();
			// 临时变量
			AppRoleDepartment tempAppRoleDepartment = null;
			for (Department d : removeDepartmentList) {
				tempAppRoleDepartment = new AppRoleDepartment();
				tempAppRoleDepartment.setDepartment(d);
				tempAppRoleDepartment.setAppRole(appRoleResult);

				removeAppRoleDepartments.add(tempAppRoleDepartment);
			}
			// 执行添加操作
			appRoleDepService.removeDepsFromRole(removeAppRoleDepartments);
		}

		map.put("code", "8000");
		map.put("result", "success");
		return map;
	}

	/**
	 * @author upshi
	 * @date 20160302
	 * @url /rest/appRole/{id}
	 */
	@ResponseBody
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public Map<String, Object> delete(@PathVariable Integer id, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		AppRole appRole = appRoleService.getRoleDetailForApp(id);
		if (appRole == null) {
			map.put("code", "5022");
			map.put("result", "failure");
			map.put("reason", "您删除的角色不存在");
			return map;
		}
		// 判断有没有权限进行操作
		Map<String, Object> preHandleMap = preHandle(request, appRole.getAppId());
		if (preHandleMap != null) {
			return preHandleMap;
		}

		appRoleService.removeRoleForApp(id);
		map.put("code", "8000");
		map.put("result", "success");
		return map;
	}

	/*
	 * 判断是否有权限执行修改删除等操作
	 */
	private Map<String, Object> preHandle(HttpServletRequest request, Integer appId) {
		Map<String, Object> map = null;
		// 从request中获取执行当操作的用户
		Person person = (Person) request.getAttribute("restUser");
		AppInfo appInfo = appInfoService.getAppById(appId);

		if (appInfo == null) {
			map = new HashMap<String, Object>();
			map.put("code", "5010");
			map.put("result", "failure");
			map.put("reason", "您输入的应用ID不存在");
			return map;
		}

		// 判断人员是否有权删除该应用,应用的拥有者以及应用的管理部门的管理员有权删除
		if (person.getId() != appInfo.getCreator().getId() && !positionService.isAdmin(person.getUsername(), appInfo.getManageDep().getFullname())) {
			map = new HashMap<String, Object>();
			map.put("code", "1000");
			map.put("result", "failure");
			map.put("reason", "您没有此权限进行该操作");
			return map;
		}

		return map;
	}

}

package com.nb.org.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nb.org.dao.IAppInfoDao;
import com.nb.org.dao.IAppRoleDao;
import com.nb.org.dao.IAppRoleDeparmentDao;
import com.nb.org.dao.IAppRolePersonDao;
import com.nb.org.dao.IPersonDao;
import com.nb.org.domain.AppRole;
import com.nb.org.domain.AppRoleDepartment;
import com.nb.org.domain.AppRolePerson;
import com.nb.org.domain.Department;
import com.nb.org.domain.Person;
import com.nb.org.dto.RoleDepsDTO;
import com.nb.org.dto.RolePersDTO;
import com.nb.org.service.IAppRoleService;

@Service("appRoleService")
public class AppRoleServiceImpl implements IAppRoleService {

	@Autowired
	private IAppRoleDeparmentDao roleDepDao;
	
	@Autowired
	private IAppRolePersonDao rolePersonDao;
	
	@Autowired 
	private IPersonDao personDao;
	
	@Autowired
	private IAppRoleDao roleDao;
	@Override
	@Transactional
	public void addRoleForApp(AppRole role) {
		roleDao.insertAppRole(role);
		AppRole tmp = roleDao.getRoleByNameAndApp(role);
		role.setId(tmp.getId());
		List<Person> persons = role.getPersons();
		if(persons != null) {
			for(Person p : persons){
				AppRolePerson person = new AppRolePerson();
				person.setPerson(p);
				person.setAppRole(role);
				rolePersonDao.insertRoleOfPerson(person);
			}
		}
		List<Department> departments = role.getDepartments();
		if(departments != null) {
			for (Department d:departments){
				AppRoleDepartment department = new AppRoleDepartment();
				department.setDepartment(d);
				department.setAppRole(role);
				roleDepDao.insertRoleOfDepartment(department);
			}
		}
	}

	@Override
	@Transactional
	public void removeRoleForApp(int roleId) {
		rolePersonDao.deletePersonsByRoleId(roleId);
		roleDepDao.deleteDepartmentsByRoleId(roleId);
		roleDao.deleteAppRoleById(roleId);
	}

	@Override
	@Transactional
	public void removeRolesForApp(int appId) {
		List<AppRole> roles = roleDao.getRolesByAppId(appId);
		for(AppRole r : roles){
			rolePersonDao.deletePersonsByRoleId(r.getId());
			roleDepDao.deleteDepartmentsByRoleId(r.getId());
		}
		roleDao.deleteRolesByAppId(appId);
	}

	@Override
	@Transactional
	public void editRoleForApp(AppRole role) {
		roleDao.updateAppRole(role);
		List<Person> persons = role.getPersons();
		List<Department> departments = role.getDepartments();
		rolePersonDao.deletePersonsByRoleId(role.getId());
		roleDepDao.deleteDepartmentsByRoleId(role.getId());
		for(Person p : persons){
			AppRolePerson person = new AppRolePerson();
			person.setAppRole(role);
			person.setPerson(p);
			rolePersonDao.insertRoleOfPerson(person);
		}
		for(Department d :departments){
			AppRoleDepartment department = new AppRoleDepartment();
			department.setAppRole(role);
			department.setDepartment(d);
			roleDepDao.insertRoleOfDepartment(department);
		}
	}

	@Override
	public List<AppRole> getRoleListForApp(int appId) {
		return roleDao.getRolesByAppId(appId);
	}
	@Override
	public AppRole getRoleDetailForApp(int roleId) {
		return roleDao.getRoleById(roleId);
	}

	@Override
	public List<RolePersDTO> searchPerson(String name) {
		// TODO Auto-generated method stub
		List<RolePersDTO> persons=roleDao.searchPerson(name);
//		ArrayList<RolePersDTO> dto = new  ArrayList<RolePersDTO>();
//		for(Person p:persons){
//			RolePersDTO per = new RolePersDTO(p.getId(),p.getName(),p.getCreateDep().getFullname());
//			dto.add(per);
//		}
		return persons;
	}

	@Override
	public List<RoleDepsDTO> searchDepartment(String name) {
		// TODO Auto-generated method stub
		return roleDao.searchDepartment(name);
	}

	@Override
	public AppRole getRoleByNameAndApp(AppRole role) {		
		return roleDao.getRoleByNameAndApp(role);
	}

	@Override
	@Transactional
	public List<AppRole> getRolesByAppName(String appName) {
		// TODO Auto-generated method stub
		try{
		int appId = roleDao.getAppIdByAppName(appName);	
		return roleDao.getRolesByAppId(appId);
		}catch(Exception e){
			return new ArrayList<AppRole>();
		}
	}

	@Override
	public List<String> getRolesForPerson(String appName,String username) {
		// TODO Auto-generated method stub
		
		ArrayList<String> roleNames = new ArrayList<String>();
		AppRolePerson rolePerson=new AppRolePerson();
		AppRoleDepartment roleDepartment=new AppRoleDepartment();
		try{
		Person person = personDao.selectPersonByUserName(username);
		rolePerson.setPerson(person);
		int appId = roleDao.getAppIdByAppName(appName);	
		List<AppRole> roles = roleDao.getRolesByAppId(appId);
		for(AppRole r : roles){
			rolePerson.setAppRole(r);
			String name = rolePersonDao.getRoleNameForPerson(rolePerson);
			if(name != null){
				roleNames.add(name);
			}
			for(Department d : person.getDeps()){
				roleDepartment.setDepartment(d);
				roleDepartment.setAppRole(r);
				AppRoleDepartment roleDep = roleDepDao.getRoleOfDepartment(roleDepartment);
				if(roleDep != null && roleDep.getAppRole() != null){
					roleNames.add(roleDep.getAppRole().getName());
				}
			}
		}
		HashSet<String> temp = new HashSet<String>(roleNames);
		roleNames.clear();
		roleNames.addAll(temp);
		}catch(Exception e){
			return roleNames;
		}
		return roleNames;
	}

	public int updateAppRole(AppRole appRole) {
		return roleDao.updateAppRole(appRole);
	}

}

package com.nb.org.util;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nb.org.domain.Department;
import com.nb.org.domain.DepartmentSN;
import com.nb.org.domain.Person;
import com.nb.org.exception.DepartmentException;
import com.nb.org.service.IDepartmentSNService;
import com.nb.org.service.IDepartmentService;


/*
 * 所有对象的SN生成器
 * @author upshi
 * @date 20160119
 */
@Component("snGenerate")
public class SNGenerator {
	
	@Autowired
	private IDepartmentSNService departmentSNService;
	
	@Autowired
	private IDepartmentService departmentService;
	
	
	/*
	 * @author upshi
	 * @date 20160120
	 * 根据父部门生成Department的SN
	 */
	public DepartmentSN generateDepartmentSN(Department parentDept) {
		//先查询数据库中该部门是否有之前被删除的子部门的可用编号
		DepartmentSN departmentSN = departmentSNService.selectByParentDeptIdAndFlag(parentDept.getId(), 1);
		//判读是否为空
		if(departmentSN == null) {
			//如果为空,则继续查询该父部门下子部门编号的最大值,即flag为0的记录
			departmentSN = departmentSNService.selectByParentDeptIdAndFlag(parentDept.getId(), 0);
			//继续判断是否为空
			if(departmentSN == null) {
				//如果为空,说明该父部门原来是叶子节点,第一次在该部门下创建子部门,则新建一个parentDept对象,返回
				//########如果部门新建成功,需要在DepartmentServiceImpl中将该对象insert到数据库中(通过判断id==null和flag=0来确定是insert操作)
				departmentSN = new DepartmentSN(parentDept.getId(),"00",parentDept.getSn(),0);
				return departmentSN;
			} else {
				//如果不为空,该对象的number值为该父部门下所有子部门编号的最大值(包括曾经删除掉的子部门),将该number值取出来加1,返回该对象
				//########如果部门新建成功,需要在DepartmentServiceImpl中update数据库中该对象的属性(通过判断id!=null和flag=0来确定是update操作)
				String number = Integer.toHexString(Integer.parseInt(departmentSN.getNumber(), 16) + 1).toUpperCase();
				//如果编号是0开头的,经过上一行的处理会变成一位,所以要处理一下,补上0
				if(number.length() == 1) {
					number = "0" + number;
				}
				departmentSN.setNumber(number);
				return departmentSN;
			}
		} else {
			//如果不为空,则直接返回该记录
			//#######如果部门新建成功,需要在DepartmentServiceImpl中将该对象从数据库中delete(通过判断flag=1来确定是delete操作)
			return departmentSN;
		}
	}
	
	/**
	 * @Title: getChildPersons
	 * @Description: 查找该部门下的所有人员(包括子部门的人员)
	 * @param @param resultlist
	 * @param @param dep
	 * @param @return
	 * @return List<Person>
	 * @throws
	 */
	private List<Person> getChildPersons(List<Person> resultlist,Department dep ){
		List<Department> list=new ArrayList<Department>();
		try {
			list = departmentService.getDepByParentDep(dep);
		} catch (DepartmentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(dep.getPersons()!=null)
		resultlist.addAll(dep.getPersons());
		if(!list.isEmpty()){
		for(Department d:list){
		getChildPersons(resultlist,d);	
		}
		}
		HashSet<Person> temp=new HashSet<Person>(resultlist);
		resultlist.clear();
		resultlist.addAll(temp);
		return resultlist;
	}
	
	/**
	 * @Title: generatePersonSN
	 * @Description: 生成人员SN编号
	 * @param @param d
	 * @param @return
	 * @return String
	 * @throws
	 */
	public String generatePersonSN(Department d) {
		List<Person> list=new ArrayList<Person>();
		int size=getChildPersons(list,d).size();
		String sn=d.getSn()+Integer.toHexString(size);
		return sn;
	}
	
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场