package com.vci.client.framework.systemConfig.stafforgmanage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.JPanel; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Workbook; import com.vci.client.LogonApplication; import com.vci.client.common.ConfigUtils; import com.vci.client.common.objects.DeptObject; import com.vci.client.common.objects.UserObject; import com.vci.client.common.providers.ServiceProvider; import com.vci.client.framework.delegate.RightManagementClientDelegate; import com.vci.client.framework.systemConfig.object.TransmitMethod; import com.vci.client.framework.util.RightControlUtil; import com.vci.client.utils.excel.ExcelCellStyleSettingCallback; import com.vci.client.utils.excel.ExcelDocumentUtils; import com.vci.client.utils.excel.ExcelFileOperation; import com.vci.client.utils.excel.SheetDataSet; import com.vci.client.utils.excel.WorkboolStyleSetting; import com.vci.client.ui.exception.VCIException; import com.vci.client.ui.locale.LocaleDisplay; import com.vci.client.ui.process.QANProcessBar; import com.vci.client.ui.process.QANProcessBarFrame; import com.vci.client.ui.swing.VCIOptionPane; import com.vci.client.ui.swing.VCISwingUtil; import com.vci.client.ui.swing.components.VCIJOptionPane; import com.vci.common.utility.ObjectUtility; import com.vci.corba.common.VCIError; import com.vci.corba.omd.etm.EnumChild; import com.vci.corba.omd.etm.EnumItem; public class UsersExcelImportDialogActionListener extends JPanel implements ActionListener { /** * */ private static final long serialVersionUID = 1L; /** * 父窗体 */ private static final String ENUM_USERSECURITYENUM = "usersecurityenum"; private UsersImportDialog ownerDialog = null; /** * 必填列 */ private ArrayList ColumnNameisRed = new ArrayList(); /** * 所有user信息。 */ private ArrayList fileDatas = new ArrayList(); /** * 用户 */ private ArrayList deptAndUserRelation = new ArrayList(); private UserObject logonUserInfo;// private String userName = LogonApplication.getUserEntityObject().getUserName(); public UsersExcelImportDialogActionListener( UsersImportDialog excelImprotDialog) { this.ownerDialog = excelImprotDialog; } public UsersExcelImportDialogActionListener() { // TODO Auto-generated constructor stub } @Override public void actionPerformed(ActionEvent e) { try{ logonUserInfo = new RightManagementClientDelegate(LogonApplication.getUserEntityObject()).fetchUserInfoByName(userName); }catch(VCIException ex) { VCIOptionPane.showError(LogonApplication.frame,"RMIPFramework", ex); return; } String actionCommand = e.getActionCommand(); if (actionCommand.equals(ownerDialog.getBtnSave().getActionCommand())) { LinkedList selectedFiles = this.ownerDialog.getSelectedFiles(); if (selectedFiles == null || selectedFiles.isEmpty()) { VCIOptionPane.showMessageDialog(LogonApplication.frame, "未选择文件!"); return; } fileDatas.clear(); deptAndUserRelation.clear(); save(); } else if (actionCommand.equals(ownerDialog.getBtnSelect() .getActionCommand())) { getFile(); } else if (actionCommand.equals(ownerDialog.getBtnExport() .getActionCommand())) { downloadImportStuffTemplate(); } } /** * 保存对象 */ private void save() { final QANProcessBarFrame frame = new QANProcessBarFrame(); Thread t = new Thread() { public void run() { boolean b = false; frame.setContent("正在进行处理数据,请稍等......"); try { b = importData(frame); } catch (VCIError e) { frame.setProcessBarCancel(true); VCIOptionPane.showMessageDialog(LogonApplication.frame, e.code); } catch (VCIException e){ } catch (IOException e) { e.printStackTrace(); } finally { frame.setProcessBarCancel(true); if (b) { VCIOptionPane.showMessageDialog(LogonApplication.frame, "导入成功!"); ownerDialog.dispose(); }else{ VCIOptionPane.showMessageDialog(LogonApplication.frame, "导入失败!"); } } } }; QANProcessBar bar = new QANProcessBar(t, frame, frame, "导入人员数据......", false); bar.setVisible(true); } /** * 导入 * * @param sheetDataSet * @return * @throws IOException * @throws VCIError * @throws VCIException * @autor caicong * @data 2014-3-12 */ private boolean importData(QANProcessBarFrame frame) throws VCIError, VCIException, IOException { frame.setContent("正在获取系统部门数据......"); HashMap allDept = ownerDialog.getAllDept(); if (allDept.size() == 0) { fetchAllDeptMessage(); } frame.setContent("正在收集表单数据......"); boolean isSuccess = collectionDatas(); if(!isSuccess) return false; frame.setContent("正在导入表单人员信息......"); boolean b = importExcelData(); return b; } /** * 收集表单信息。 * * @throws VCIError * @throws IOException */ private boolean collectionDatas() throws VCIError, IOException, VCIException{ UserObject[] users = new RightManagementClientDelegate(LogonApplication.getUserEntityObject()).fetchUserInfo(); Map mapUser = new HashMap(); for (UserObject u : users) { mapUser.put(u.getUserName(), u); } String flag = ConfigUtils.getConfigValue("exportSecretGrade"); LinkedList selectedFiles = this.ownerDialog.getSelectedFiles(); for (File f : selectedFiles) { List sheetDataSets = this.getFileList(f); if (sheetDataSets != null && !sheetDataSets.isEmpty()) { for (SheetDataSet sheet : sheetDataSets) { // sheet不能为空并且必须有出表头外的一条数据 if (sheet != null && sheet.getDataSet() != null && sheet.getDataSet().size() > 1) { List dataSet = sheet.getDataSet(); for (int i = 1; i < dataSet.size(); i++) { String[] oneData = dataSet.get(i); String userName = oneData[0]; // 账户 UserObject userObj = null; userObj = mapUser.get(userName); if (userObj == null) { String userId = ObjectUtility.getNewObjectID36(); if (ownerDialog.getAllDept().size() != 0) { boolean b = validateExcelDatas(oneData, i, userId);// if(!b) return false; } userObj = new UserObject(); userObj.setId(userId); userObj.setUserName(userName); } else { String userId = userObj.getId(); if (ownerDialog.getAllDept().size() != 0) { boolean b = validateExcelDatas(oneData, i, userId);// if(!b) return false; } } userObj.setPwd(oneData[1]);// 密码 userObj.setTrueName(oneData[2]);// 姓名 userObj.setEmail(oneData[3]);// 邮箱 userObj.setSpecialties(oneData[4]);// 专业 userObj.setDesc(oneData[5]);// 描述 // oneData[6]为部门信息,不在此处赋值处理 //判断是否导入密级 if (flag != null && flag.equalsIgnoreCase("true")) { userObj.setSecretGrade(oneData[7]);// 密级 } userObj.setPwdUpdateTime(System.currentTimeMillis());//"1970-1-1 00:00:00"); userObj.setGrantor(""); userObj.setUserType(logonUserInfo.getUserType()); userObj.setCreateTime(System.currentTimeMillis()); userObj.setCreateUser(userName); userObj.setUpdateTime(System.currentTimeMillis()); userObj.setUpdateUser(userName); fileDatas.add(userObj); } } } } } return true; } /** * 获取所有部门信息。 * @throws VCIException */ private void fetchAllDeptMessage() throws VCIException { DeptObject[] fetchDepartmentInfo = new RightManagementClientDelegate(LogonApplication.getUserEntityObject()).fetchDepartmentInfo(); if(fetchDepartmentInfo == null){ return; } HashMap depts = new HashMap(); for(DeptObject obj : fetchDepartmentInfo){ depts.put(obj.getId(),new String[]{obj.getParentId(), obj.getName()}); } Set keySet = depts.keySet(); Iterator iterator = keySet.iterator(); while(iterator.hasNext()){ String key = iterator.next(); String[] PidAndName = depts.get(key); LinkedList nameList = new LinkedList(); nameList.add(PidAndName[1]); while(PidAndName[0]!=null && !PidAndName[0].equals("")){ PidAndName = depts.get(PidAndName[0]); if(PidAndName == null) break; nameList.add(PidAndName[1]); } StringBuffer absoluteName = new StringBuffer(); String[] arrayNames = nameList.toArray(new String[]{}); for(int i = arrayNames.length-1 ; i >= 0 ; i-- ){ if(i == arrayNames.length-1){ absoluteName.append(arrayNames[i]); }else{ absoluteName.append("/"+arrayNames[i]); } } ownerDialog.getAllDept().put(absoluteName.toString(), key); } } /** * 校验表单信息。 * * @param oneData * @param i * @param userId */ private boolean validateExcelDatas(String[] oneData, int i, String userId) { boolean check = check(oneData,i); if(!check){ return false; } try { EnumItem item = ServiceProvider.getOMDService().getEnumService().getEmItemByName(ENUM_USERSECURITYENUM); EnumChild[] children = item.children; boolean isExist = true; String flag = ConfigUtils.getConfigValue("exportSecretGrade"); if (flag != null && flag.equalsIgnoreCase("true")) { for(EnumChild child: children){ if(child.value.equals(oneData[7])||child.name.equals(oneData[7])){ oneData[7] = child.value; isExist = false; break; } } } else { isExist = false; } if (isExist) { VCIOptionPane.showMessageDialog(LogonApplication.frame, "传入的密级不符合规则!"); return false; } } catch (VCIError e) { e.printStackTrace(); } HashMap departments = ownerDialog.getAllDept(); if(oneData[6].trim()!=null && !oneData[6].trim().equals("")){ String deptId = departments.get(oneData[6].trim()); if ("".equals(deptId) || deptId == null) { VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"的部门在系统中不存在!", "RMIPFramework", getLocale())); return false; }else{ String[] deptIdAndUserId = new String[2]; deptIdAndUserId[0] = userId; deptIdAndUserId[1] = deptId; deptAndUserRelation.add(deptIdAndUserId); return true; } }else return true; } /** * 导入表单数据 * @throws VCIException */ private boolean importExcelData() throws VCIError { boolean b = new RightManagementClientDelegate(LogonApplication.getUserEntityObject()).batchSaveUsers(fileDatas.toArray(new UserObject[]{}),deptAndUserRelation.toArray(new String[][]{})); return b; } /** * 下载导入人员的excel模板。 */ public void downloadImportStuffTemplate() { String[] columns = new String[] { "账号", "密码", "姓名", "电子邮箱", "专业", "描述", "部门(上下级部门之间以反斜杠隔开(/))"};// 设置表单列名 //获取是否导出密级配置项 String flag = ConfigUtils.getConfigValue("exportSecretGrade"); if (flag != null && flag.equalsIgnoreCase("true")) { columns = new String[] { "账号", "密码", "姓名", "电子邮箱", "专业", "描述", "部门(上下级部门之间以反斜杠隔开(/))" ,"密级"}; } ColumnNameisRed.clear(); ColumnNameisRed.add(0); ColumnNameisRed.add(1); ColumnNameisRed.add(2); final boolean[] ress = new boolean[1]; String[][] datas = new String[1][columns.length]; datas[0] = columns; ress[0] = exportExcel(datas, "人员模板"); final QANProcessBarFrame frame = new QANProcessBarFrame(); // final QANProcessBarFrame frame = null; final QANProcessBar[] bar = new QANProcessBar[1]; bar[0] = new QANProcessBar(new Thread() { public void run() { try { frame.setContent("正在导出Excel文件,请稍等......"); // String[][] datas = new String[1][columns.length]; // datas[0] = columns; // ress[0] = exportExcel(datas, "人员模板"); } finally { frame.setProcessBarCancel(true); } } }, frame, frame, "人员模板导出", false); bar[0].setVisible(true); if (ress[0]) { VCIOptionPane.showMessageDialog(LogonApplication.frame, "导出成功!"); } } /** * 获取选中的文件 * * @return * @autor caicong * @data 2014-3-12 */ @SuppressWarnings({ "deprecation", "unused" }) private LinkedList getSelectedFiles() { LinkedList selectedFiles = ownerDialog.tablePanel .getSelectedRowObjects(); return selectedFiles; } /** * 获取表单数据 * * @param f * @return * @throws IOException * @throws VCIError * @autor caicong * @data 2014-3-11 */ private List getFileList(File f) throws VCIError, IOException { // 获取流 BufferedInputStream fileInputStream = new BufferedInputStream( new FileInputStream(f)); String name = f.getName(); // 获取表list List sheetDataSets = ExcelDocumentUtils .readExcelDocument(name, fileInputStream); return sheetDataSets; } private void getFile() { File f = getRequiredFile(true); if (f == null) return; ArrayList lists = ownerDialog.getLists(); /** 判断导入的文件是否被使用的校验,如果文件已经打开,不允许导入 **/ if (lists.contains(f)) { VCIOptionPane.showMessageDialog(LogonApplication.frame, "文件重复,请重新选择!"); return; } // 将文件保存到table中 lists.add(f); ownerDialog.tablePanel.refreshTableData(); } private File getRequiredFile(boolean isRead) { File files = getExcelFile(); // add by xchao 2014.04.15 begin // 有错误数据要输出时,必须选择有效的excel文件 while (files == null) { return null; } String fileName = files.getAbsolutePath(); // 需要写入时,必须选择一个有效的、可以写入的文件 if (!isRead) { // 如果文件被打开着,则必须选择其它的未打开着的文件 while (files.exists() && !files.renameTo(new File(fileName))) { VCIJOptionPane.showMessageDialog(null, "另一个程序正在使用此文件,进程无法访问,请重新选择!"); // 重新选择文件时,也必须选择有效的excel文件 files = null; while (files == null) { files = getExcelFile(); while (files == null) { return null; } } fileName = files.getAbsolutePath(); } } return files; } public String[] getExcel() { return null; } private boolean exportExcel(String[][] datas, String sheetName) { File file = getRequiredFile(false); if (file == null) { return false; } String fileName = file.getAbsolutePath(); // add by xchao 2014.05.15 end new ExcelFileOperation().writeExcelFileInfo(fileName, sheetName, datas, new ExcelCellStyleSettingCallback() { @Override public WorkboolStyleSetting doSetWorkbookStyle( final Workbook workbook) { WorkboolStyleSetting setting = new WorkboolStyleSetting() { @Override public LinkedHashMap getStyleMap() { LinkedHashMap styleMap = new LinkedHashMap(); org.apache.poi.ss.usermodel.CellStyle style = workbook.createCellStyle(); org.apache.poi.ss.usermodel.Font font = (org.apache.poi.ss.usermodel.Font) workbook.createFont(); font.setColor(HSSFFont.COLOR_RED); style.setFont(font); for (int column : ColumnNameisRed) { styleMap.put("0*" + (column) + "", style); } return styleMap; } }; return setting; } }); return true; } private File getExcelFile() { File file = null; String filePath = VCISwingUtil.getExcelFileURL(ownerDialog, true, ""); if (filePath != null) { file = new File(filePath); } return file; } @SuppressWarnings("static-access") private boolean check(String[] oneData, int i){ String userName = oneData[0]; String pwd = oneData[1]; String trueName = oneData[2]; String email = oneData[3]; String desc = oneData[4]; // String companyId = panel.getCompanyId(); if(new RightControlUtil().isAdminOrDeveloperOrRoot(userName)){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.usernameerror1", "RMIPFramework", getLocale())); return false; } if("".equals(userName)){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.usernameerror2", "RMIPFramework", getLocale())); return false; } if("".equals(pwd)){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.pwderror1", "RMIPFramework", getLocale())); return false; } if (userName.getBytes().length > 128){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.usernameerror3", "RMIPFramework", getLocale())); return false; } if (pwd.getBytes().length > 128){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.pwderror3", "RMIPFramework", getLocale())); return false; } if (trueName.getBytes().length > 64){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.firstnameerror", "RMIPFramework", getLocale())); return false; } if (email.getBytes().length > 128){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第"+i+"行"+"rmip.stafforg.operate.emailerror", "RMIPFramework", getLocale())); return false; } if (desc.getBytes().length > 255 ){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.descerror", "RMIPFramework", getLocale())); return false; } String regEx = "^[A-Za-z0-9_]+$"; if (!TransmitMethod.checkCharacter(userName, regEx)) { VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.usernameerror4", "RMIPFramework", getLocale())); return false; } if(trueName.equals("")){ VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.firstnameerror1", "RMIPFramework", getLocale())); return false; } if (!email.equals("")){ regEx = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; if (!TransmitMethod.checkCharacter(email, regEx)) { VCIOptionPane.showMessageDialog(ownerDialog, LocaleDisplay.getI18nString("第【"+i+"】行"+"rmip.stafforg.operate.emailerror1", "RMIPFramework", getLocale())); return false; } } boolean rs = checkName(userName,i); if (!rs) { return rs; } return true; } /*** * 看用户名是否重复 * @param name 用户名 * @return */ private boolean checkName(String name,int line) { UserObject[] userInfo = null; try { userInfo = new RightManagementClientDelegate(LogonApplication.getUserEntityObject()).fetchUserInfo(); int size = userInfo.length; for(int i = 0; i < size; i++){ if (name.equals(userInfo[i].getUserName())) { VCIOptionPane.showMessageDialog(ownerDialog, "第【"+line+"】行用户名在系统中已经存在,请修改!"); return false; } } } catch (VCIException e) { VCIOptionPane.showError(LogonApplication.frame,"RMIPFramework", e); return false; } return true; } }