程式碼直接上:
入口類
import java.io.File; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; public class MainPane { public static void main(String[] args) throws Throwable { File file = new File("acl.properties"); ProperityUtils.loadProperty2System(file.getAbsolutePath()); //System.out.println(System.getProperty("username")); String userId = System.getProperty("username","user"); String password = System.getProperty("password","pwd"); String url = System.getProperty("url","http://127.0.0.1/web"); String json = "" String session = Http.sendPost(url, json); JSONObject jsonobject = new JSONObject(session); String sid = jsonobject.getString("sessionId"); String user = jsonobject.getString("id"); String stationId = jsonobject.getString("stationId"); String getGroupUrl = url; System.out.println(getGroupUrl); String groups = Http.sendGet(getGroupUrl); JSONArray array = new JSONArray(groups); System.out.println(array.length()); List<FolderMo> mo = new ArrayList<FolderMo>(); for (int i = 0; i < array.length(); i++) { FolderMo fm = new FolderMo(array.getJSONObject(i).getString("name"), array.getJSONObject(i).getString("id"), ""); mo.add(fm); } //啟動皮膚 new ShowPane(sid, stationId, url).start(mo); } }
展示類:
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import org.json.JSONArray; import org.json.JSONObject; public class ShowPane implements MouseListener, ActionListener{ JPopupMenu popMenu;// 右鍵選單 JMenuItem addItem;// 新增 JMenuItem delItem;// 刪除 JMenuItem editItem;// 修改 JPopupMenu treePopMenu; //樹選單 JMenuItem moveItem;// 移動到上一級 JTable table; JTree tree; public String sid; public String stationId; public String url; Map<String,String> map = new HashMap<String, String>(); Map<String,Integer> rowMap = new HashMap<String, Integer>(); public ShowPane(String sid, String stationId, String url) { this.sid = sid; this.stationId = stationId; this.url = url; System.out.println(this.url+"="+this.sid+"="+this.stationId); popMenu = new JPopupMenu(); addItem = new JMenuItem("新增"); addItem.addActionListener(this); delItem = new JMenuItem("刪除"); delItem.addActionListener(this); editItem = new JMenuItem("提交"); editItem.addActionListener(this); popMenu.add(addItem); popMenu.add(delItem); popMenu.add(editItem); treePopMenu = new JPopupMenu(); moveItem = new JMenuItem("移動到上一級"); moveItem.addActionListener(this); treePopMenu.add(moveItem); } public void start(List<FolderMo> folder) { DefaultMutableTreeNode top = new DefaultMutableTreeNode(this.stationId); DefaultMutableTreeNode node = new DefaultMutableTreeNode(""); for (FolderMo folderMo : folder) { node = new DefaultMutableTreeNode(folderMo); top.add(node); } tree = new JTree(top); Vector<String> columnNames = new Vector<String>(); //設定列名 columnNames.add("id"); columnNames.add("type"); columnNames.add("privileges"); Vector<Vector<Object>> rowData = new Vector<Vector<Object>>(); //Vector<Object> hang = new Vector<Object>();//設定每一行的值 //rowData.add(hang);//加入rowData中 DefaultTableModel tablemodel = new DefaultTableModel(rowData,columnNames); table = new JTable(tablemodel); /* TableColumn column = table.getColumnModel().getColumn(1); column.setMinWidth(100); column.setMaxWidth(300); column.setPreferredWidth(150); column = table.getColumnModel().getColumn(2); column.setMinWidth(300); column.setMaxWidth(500); column.setPreferredWidth(400);*/ JFrame f = new JFrame("資料夾許可權(運維人員使用)"); Box box = Box.createHorizontalBox(); //建立Box 類物件 //f.add(tree); JScrollPane treePane = new JScrollPane(tree) { /** * */ private static final long serialVersionUID = 1L; @Override public Dimension getPreferredSize() { return new Dimension(200, 600); } }; box.add(treePane, BorderLayout.WEST); box.add(new JScrollPane(table), BorderLayout.EAST); f.getContentPane().add(box, BorderLayout.CENTER); f.setLocation(100, 100); f.setSize(700, 700); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 新增選擇事件 tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree .getLastSelectedPathComponent(); if (node == null) return; Object object = node.getUserObject(); FolderMo folder = (FolderMo) object; System.out.println("你選擇了:" + folder.showString()); map.put("folderId", folder.getId()); //更新表格 updateTable(folder); //更新樹 updateTree(folder,node); } protected void updateTree(FolderMo folder,DefaultMutableTreeNode node) { String fs = getFolderList(url, sid, folder.getId()); if("".equals(fs)) { System.out.println(folder.getName()+"下未查詢到子資料夾"); }else { if(node.isLeaf()) { node.removeAllChildren(); } JSONArray array = new JSONArray(fs); for (int i = 0; i < array.length(); i++) { FolderMo fm = new FolderMo(array.getJSONObject(i).getString("name"), array.getJSONObject(i).getString("id"), array.getJSONObject(i).get("acl").toString()); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(fm); node.add(node2); } tree.expandPath(new TreePath(node)); } } protected void updateTable(FolderMo folder) { String acl = folder.getAcl(); if("".equals(acl)) { return; } tablemodel.getDataVector().clear(); JSONArray acls = new JSONArray(acl); for (int i = 0; i < acls.length(); i++) { Vector<Object> hang = new Vector<Object>();//設定每一行的值 hang.add(acls.getJSONObject(i).getString("id")); hang.add(acls.getJSONObject(i).getString("type")); hang.add(acls.getJSONObject(i).get("privileges").toString()); rowData.add(hang);//加入rowData中 } tablemodel.setDataVector(rowData, columnNames); table.updateUI(); } }); tree.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { TreePath path = tree.getPathForLocation(e.getX(), e.getY()); if (path == null) { return; } //System.out.println("當前目錄"+path.toString()); if(path.getPath().length < 3) { System.out.println("當前目錄"+path+"不允許上移"); return; } tree.setSelectionPath(path); if (e.getButton() == 3) { treePopMenu.show(tree, e.getX(), e.getY()); } } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } }); table.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { //獲取滑鼠右鍵選中的行 int row = table.rowAtPoint(e.getPoint()); if (row == -1) { rowMap.remove("row"); return ; }else { rowMap.put("row", row); } //獲取已選中的行 int[] rows = table.getSelectedRows(); boolean inSelected = false ; //判斷當前右鍵所在行是否已選中 for(int r : rows){ if(row == r){ inSelected = true ; break ; } } //當前滑鼠右鍵點選所在行不被選中則高亮顯示選中行 if(!inSelected){ table.setRowSelectionInterval(row, row); } // TODO Auto-generated method stub if (e.getButton() == 3) { popMenu.show(table, e.getX(), e.getY()); } } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } }); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == moveItem) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object object = node.getUserObject(); FolderMo folder = (FolderMo) object; String moIds = folder.getId(); System.out.println("當前節點:" + folder.showString()); node = (DefaultMutableTreeNode)node.getParent(); object = node.getUserObject(); folder = (FolderMo) object; String targetFolderId = folder.getId(); System.out.println("當前節點的父節點:" + folder.showString()); String result = moveFolderToUp(moIds,targetFolderId); if("".equals(result)) { tree.collapsePath(new TreePath(node)); //關閉 }else { System.out.println("移動資料夾失敗"+result); } return; } DefaultTableModel tableModel = (DefaultTableModel) table.getModel(); if (e.getActionCommand().equals("新增")) { tableModel.addRow(new Object[] { "", "Group", "[\"refRead\",\"write\",\"delete\",\"read\",\"editAcl\",\"create\",\"list\"]" }); } if (e.getActionCommand().equals("刪除")) { //tableModel.removeRow(rowMap.get("row"));// rowIndex是要刪除的行序號 int[] rows = table.getSelectedRows(); for (int i = 0; i < rows.length; i++) { int row = rows[i]-i; tableModel.removeRow(row);// rowIndex是要刪除的行序號 } } if (e.getActionCommand().equals("提交")) { // 更新acl System.out.println("資料夾Id:" + map.get("folderId")); int rowCount = tableModel.getRowCount(); AclMo[] acls = new AclMo[rowCount]; for (int i = 0; i < rowCount; i++) { AclMo mo = new AclMo(); mo.setId((String)tableModel.getValueAt(i, 0));// 取得第i行第一列的資料 mo.setType((String)tableModel.getValueAt(i, 1));// 取得第i行第二列的資料 String privileges = (String)tableModel.getValueAt(i, 2); mo.setPrivileges(privileges.replace("[", "").replace("]", "").replaceAll("\"", ""));// 取得第i行第三列的資料 acls[i] = mo; } System.out.println("更新許可權請求引數如下:"); System.out.println(JSONObject.valueToString(acls)); String result = updateAcl(map.get("folderId"),JSONObject.valueToString(acls)); if("".equals(result)) { System.out.println(map.get("folderId") + "更新許可權成功"); }else { System.out.println(map.get("folderId") +"更新許可權失敗:"+result); } } } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { //選單被按下 } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } public String updateAcl(String moId, String acls) { String result = Http.sendPost2(updateAclUrl,acls); return result; } public String moveFolderToUp(String moIds, String targetFolderId) { String result = Http.sendPost2(moveFolderurl,""); return result; } public static String getFolderList(String url, String sid, String parentId) { String folders = Http.sendGet(getFolderurl); return folders; } }
工具類:
1、 https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar 2、 import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Iterator; import java.util.Properties; public class ProperityUtils { public static String loadProperty2System(String location) throws IOException { File file = new File(location); if (file.isFile() && file.getName().endsWith(".properties")) { Properties ppt = new Properties(); FileInputStream fi = new FileInputStream(file); Throwable e = null; try { ppt.load(fi); Iterator<String> iterator = (Iterator<String>) ppt.stringPropertyNames().iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.setProperty(key, ppt.getProperty(key)); // if (!System.getProperties().containsKey(key)) { // } } } catch (Throwable e2) { e = e2; throw e2; } finally { if (fi != null) { if (e != null) { try { fi.close(); } catch (Throwable e3) { e.addSuppressed(e3); } } else { fi.close(); } } } } else { System.out.println("“" + location + "”,Can not load any property file."); } return file.getAbsolutePath(); } } 3、 import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Http { public static String sendPost2(String u, String param) { StringBuffer sbf = new StringBuffer(); try { URL url = new URL(u); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (!"".equals(param)) { // 正文,正文內容其實跟get的URL中 '? '後的引數字串一致 // String content = "欄位名=" + URLEncoder.encode("字串值", "編碼"); out.writeBytes(param); } out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } System.out.println(sbf); reader.close(); // 斷開連線 connection.disconnect(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sbf.toString(); } /** * 傳送http POST請求 * * @param * @return 遠端響應結果 */ public static String sendPost(String u, String json) { StringBuffer sbf = new StringBuffer(); try { URL url = new URL(u); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.addRequestProperty("role", "Admin"); connection.addRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (!"".equals(json)) { out.writeBytes(json); } out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } System.out.println(sbf); reader.close(); // 斷開連線 connection.disconnect(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sbf.toString(); } public static String sendGet(String u) { StringBuffer sbf = new StringBuffer(); try { URL url = new URL(u); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); // 設定可輸入 connection.setDoOutput(true); // 設定該連線是可以輸出的 connection.setRequestMethod("GET"); // 設定請求方式 connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String lines; while ((lines = reader.readLine()) != null) { lines = new String(lines.getBytes(), "utf-8"); sbf.append(lines); } System.out.println(sbf); reader.close(); // 斷開連線 connection.disconnect(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sbf.toString(); } /** * 解決編碼問題 * @param uri * @param data */ public void sendGet2(String uri,String data) { try { URL url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); // 設定可輸入 connection.setDoOutput(true); // 設定該連線是可以輸出的 connection.setRequestMethod("GET"); // 設定請求方式 connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream())); pw.write(data); pw.flush(); pw.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")); String line = null; StringBuilder result = new StringBuilder(); while ((line = br.readLine()) != null) { // 讀取資料 result.append(line + "\n"); } connection.disconnect(); System.out.println(result.toString()); } catch (Exception e) { e.printStackTrace(); } } }
4、model:
public class FolderMo { private String name; private String id; private String acl; public FolderMo(String n) { name = n; } public FolderMo(String n, String id,String acl) { name = n; this.id = id; this.acl = acl; } public FolderMo() { } // 重點在toString,節點的顯示文字就是toString public String toString() { return name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAcl() { return acl; } public void setAcl(String acl) { this.acl = acl; } public String showString() { return id+"-"+name; } }
public class AclMo { private String id; private String type; private String privileges; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getPrivileges() { return privileges; } public void setPrivileges(String privileges) { this.privileges = privileges; } }
解決啟動亂碼:
新建start.bat.輸入下面兩行
java -Dfile.encoding=utf-8 -jar your.jar
pause
和jar包放置的同一個目錄下面