Servlet code :
/*
 * Created on 2005/3/1--下午 02:10:35  by  jack
 */
 
package crm.action;
 
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
 
import crm.form.CandidateForm;
import crm.form.DocnoForm;
import crm.form.ElectionForm;
import crm.form.ResolveForm;
import crm.form.ShmmosForm;
import crm.lang.Access;
 
/**
 * @author jack
 * @version 1.0, 2005/3/1
 */
public class SocketServlet extends HttpServlet {
    private static final long serialVersionUID = 3257288011091031095L;
 
    private final static Logger log = Logger.getLogger(SocketServlet.class);
 
    private Connection con = null;
 
    private final DocnoForm docno = new DocnoForm();
 
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        String method = request.getParameter("method");
        log.debug("method=" + method);
        if (method == null) {
            message(response, "method is null");
            return;
        }
 
        if (method.equalsIgnoreCase("SHMMOS")) {
            resultShmmos(request, response);
        } else if (method.equalsIgnoreCase("DOCNO")) {
            resultDocno(request, response);
        } else if (method.equalsIgnoreCase("RESOLVE")) {
            resultResolve(request, response);
        } else if (method.equalsIgnoreCase("ELECTION")) {
            modifyElection(request, response);
        } else if (method.equalsIgnoreCase("CANDIDATE")) {
            resultCandidate(request, response);
        } else if (method.equalsIgnoreCase("SELECT_ELECTION")) {
            resultElection(request, response);
        } else if (method.equalsIgnoreCase("UPDATE_ELECTION")) {
            updateElection(request, response);
        } else {
            message(response, "Not match method");
            return;
        }
    }
 
    private synchronized void updateElection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        // FIXME delete election        
        String candidate = request.getParameter("candidate");
        if ((candidate == null) || (candidate.equals(""))) {
            message(response, "key 值為空白");
            return;
        }
 
        try {
            int sn = Integer.parseInt(candidate);
            String sql = "delete from election where candidate=? ";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, sn);
            pstmt.execute();
            pstmt.close();
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
        modifyElection(request, response);
    }
 
    private synchronized void modifyElection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        String[] lst = request.getParameterValues("election");
        String category = request.getParameter("category");
        log.debug("category=" + category);
        ElectionForm elect = null;
        
        try {
            con.setAutoCommit(true);
            String sql = "select pg_insert_election(?, ?, ?, ?)";
            PreparedStatement pstmt = con.prepareStatement(sql);
            for (int i = 0; i < lst.length; i++) {
                elect = ElectionForm.load(lst[i]);
                pstmt.setInt(1, elect.getCandidate());
                pstmt.setInt(2, elect.getPsntid());
                pstmt.setDouble(3, elect.getVoteqty());
                pstmt.setDouble(4, elect.getBalance());
                log.debug("elect.getBalance()="+elect.getBalance());
                pstmt.executeQuery();
            }
            con.setAutoCommit(false);
            pstmt.close();
            pstmt = null;
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
        message(response, "success");
    }
 
    private void resultCandidate(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        CandidateForm candidate = new CandidateForm();
        ArrayList lst = new ArrayList();
        try {
            String sql = "select * from candidate where 1=? order by sn ";
            Object[] obj = { new Integer(1) };
            lst = (ArrayList) Access.executeQuery(con, sql, obj, candidate);
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
 
        ObjectOutputStream out = new ObjectOutputStream(response
                .getOutputStream());
        out.writeObject(lst);
        out.flush();
        out.close();
    }
 
    private void resultResolve(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        String[] lst = request.getParameterValues("resolve");
 
        try {
            String sql = "insert into resolve values(?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(sql);
            ResolveForm resolve = null;
 
            for (int i = 0; i < lst.length; i++) {
                resolve = ResolveForm.load(lst[i]);
                log.debug(resolve.toString());
                pstmt.setInt(1, resolve.getBill());
                pstmt.setInt(2, resolve.getPsntid());
                pstmt.setString(3, resolve.getChoose());
                pstmt.addBatch();
            }
            con.setAutoCommit(true);
            int[] cnt = pstmt.executeBatch();
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
        message(response, "success");
    }
 
    private void message(HttpServletResponse response, String e)
            throws ServletException, IOException {
 
        log.info("send message");
        DataOutputStream out = new DataOutputStream(response.getOutputStream());
        out.writeBytes(e);
        out.flush();
        out.close();
    }
 
    private void resultDocno(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        DocnoForm docno = new DocnoForm();
        try {
            String sql = "select * from docno where 1=? ";
            Object[] obj = { new Integer(1) };
            ArrayList lst = (ArrayList) Access.executeQuery(con, sql, obj,
                    docno);
            if ((lst != null) && (!lst.isEmpty())) {
                docno = (DocnoForm) lst.get(0);
            }
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
 
        ObjectOutputStream out = new ObjectOutputStream(response
                .getOutputStream());
        out.writeObject(docno);
        out.flush();
        out.close();
    }
 
    private void resultShmmos(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        String psntid = request.getParameter("psntid");
        if (psntid == null) {
            return;
        }
 
        ShmmosForm shmmos = new ShmmosForm();
        try {
            String sql = "select * from  shmmos where psntid=? ";
 
            Object[] obj = { new Integer(psntid) };
            ArrayList lst = (ArrayList) Access.executeQuery(con, sql, obj,
                    shmmos);
            if ((lst != null) && (!lst.isEmpty())) {
                shmmos = (ShmmosForm) lst.get(0);
            }
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
 
        ObjectOutputStream out = new ObjectOutputStream(response
                .getOutputStream());
        out.writeObject(shmmos);
        out.flush();
        out.close();
    }
 
    private void resultElection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
 
        String candidate = request.getParameter("candidate");
        if (candidate == null) {
            return;
        }
 
        ElectionForm elect = new ElectionForm();
        ArrayList lst = null;
        try {
            String sql = "select oid, * from  election where candidate=? ";
 
            Object[] obj = { new Integer(candidate) };
            lst = (ArrayList) Access.executeQuery(con, sql, obj, elect);
        } catch (SQLException e) {
            log.error(e);
            message(response, e.toString());
            return;
        }
 
        if ((lst != null) && (!lst.isEmpty())) {
            ObjectOutputStream out = new ObjectOutputStream(response
                    .getOutputStream());
            out.writeObject(lst);
            out.flush();
            out.close();
        }
    }
 
    public void destroy() {
        if (con != null) {
            try {
                con.close();
                con = null;
            } catch (SQLException e) {
            }
        }
    }
 
    public void init(ServletConfig config) throws ServletException {
        String url = config.getInitParameter("url");
        String driver = config.getInitParameter("driver");
        String user = config.getInitParameter("user");
        String password = config.getInitParameter("password");
 
        try {
            Class.forName(driver);
            try {
                con = DriverManager.getConnection(url, user, password);
                log.info(SocketServlet.class.getName() + " is inited");
 
                String sql = "select * from docno ";
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    docno.setDirector(rs.getInt("director"));
                    docno.setSupervisor(rs.getInt("supervisor"));
                }
                log.debug("docno.getDirector()=" + docno.getDirector());
                rs.close();
                ps.close();
            } catch (SQLException e) {
                log.error(e);
            }
        } catch (ClassNotFoundException e) {
            log.error(e);
        }
    }
}

identical 發表在 痞客邦 留言(0) 人氣()

code:
package org.eclipseguide.swt;

import  // 略

public class Resolve extends BasicFramework {
    private final static String PREFIX = "議案 ";
    private static int tableCols;
    private static String url = null;
    private static String driver = null;
    private static String user = null;
    private static String passwd = null;
    private static String sql = null;
    private static String imgPath = null;
    private static String servlet = null;
    private static ResourceBundle bundle;
    private Table table = null;
    private TableEditor editor = null;
    private Menu menu = null;
    private Text txtSum = null;
    private Text txtCount = null;
    private Text txtServlet = null;
    private Label lblBill = null;
    private Button btnSave;
    private Connection con = null;
    private StringBuffer sb = new StringBuffer();
    private int msgCnt = 0;
    private int bill = 0;
    private String choose = " ";
    private final static String TABLE_HEAD[] = { "出席證號", "姓名", "股數", "證件字號" };
 
    static {
        bundle = ResourceBundle.getBundle("init");
        url = bundle.getString("url");
        driver = bundle.getString("driver");
        user = bundle.getString("user");
        passwd = bundle.getString("passwd");
        sql = bundle.getString("sql");
        imgPath = bundle.getString("imgPath");
        servlet = bundle.getString("servlet");
        try {
            tableCols = Integer.parseInt(bundle.getString("tableCols"));
        } catch (NumberFormatException e) {
            tableCols = 25;
        }
    }
 
    public Resolve() {
        super(" 表決票 - 記票程式");
        fileSubMenuHeader.setText("檔案");
        fileExit.setText("離開");
        helpSubMenuHeader.setText("說明");
        helpAbout.setText("關於");
        shell.setLayout(new FormLayout());
        createMenu();
        createTable();
        createEditor();
        createPopupMenu();
        createOthers();
        Thread t = new Thread(new DocnoSocket());
        t.start();
        this.mainLoop(500, 420);
    }
 
    private void createMenu() {
        MenuItem msgSubMenu = new MenuItem(fileSubMenu, SWT.SEPARATOR);
        msgSubMenu = new MenuItem(fileSubMenu, SWT.PUSH);
        msgSubMenu.setText("訊息");
        msgSubMenu.addSelectionListener(new SelectionListener() {
            public void widgetSelected(SelectionEvent e) {
                MessageBox msg = new MessageBox(shell);
                msg.setText("訊息說明");
                if (sb.length() == 0) {
                    msg.setMessage("沒有錯誤訊息");
                } else {
                    msg.setMessage(sb.toString());
                }
                msg.open();
            }
 
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }
        });
    }
 
    private void createOthers() {
        FormData fd = null;
        lblBill = new Label(shell, SWT.BORDER);
        lblBill.setText("沒有表決議案");
        fd = new FormData();
        fd.top = new FormAttachment(1, 0);
        fd.left = new FormAttachment(1, 0);
        fd.right = new FormAttachment(99, 0);
        fd.height = 40;
        lblBill.setLayoutData(fd);
        lblBill.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                Rectangle rect = lblBill.getBounds();
                lblBill.setVisible(false);
                final Group g = new Group(shell, SWT.NONE);
                g.setText(" 議案");
                g.setBounds(rect.x, 1, rect.width, rect.height + 5);
                g.setLayout(new RowLayout());
                appendMsg("共 " + bill + " 個議案" + "@" + rect.x + "," + rect.y);
                rect.y += 12;
                rect.x += 5;
                int base = rect.x;
                for (int i = 1; i <= bill; i++) {
                    if (i > 14)
                        break;
                    final Button b1 = new Button(g, SWT.RADIO);
                    String str = PREFIX + i;
                    b1.setText(str);
                    b1.addFocusListener(new FocusListener() {
                        public void focusGained(FocusEvent e) {
                            RGB rgb = new RGB(255, 0, 0);
                            b1.setForeground(new Color(display, rgb));
                            int i = bill;
                            bill = getBill(b1.getText());
                            if (i != bill) {
                                appendMsg("目前為" + PREFIX + bill);
                            }
                        }
                        public void focusLost(FocusEvent e) {
                            RGB rgb = new RGB(0, 0, 0);
                            b1.setForeground(new Color(display, rgb));
                        }
                    });
                    rect.width = 62;
                    rect.height = 15;
                    if (((i % 7) == 1) && (i > 7)) {
                        rect.x = base;
                        rect.y += 15;
                    }
                    b1.setBounds(rect);
                    rect.x += 66;
                }
                bill = 0;
            }
        });
        fd = new FormData();
        fd.top = new FormAttachment(lblBill, 10, SWT.BOTTOM);
        fd.left = new FormAttachment(1, 0);
        fd.right = new FormAttachment(99, 0);
        fd.bottom = new FormAttachment(85, 0);
        table.setLayoutData(fd);
        txtCount = new Text(shell, SWT.NONE | SWT.LEFT);
        txtCount.setEditable(false);
        fd = new FormData();
        fd.top = new FormAttachment(table, 5, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 10);
        fd.right = new FormAttachment(30, 0);
        txtCount.setLayoutData(fd);
        txtSum = new Text(shell, SWT.NONE | SWT.LEFT);
        txtSum.setEditable(false);
        fd = new FormData();
        fd.top = new FormAttachment(table, 25, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 10);
        fd.right = new FormAttachment(30, 0);
        txtSum.setLayoutData(fd);
        final Group g = new Group(shell, SWT.NORMAL);
        g.setText("種類");
        fd = new FormData();
        fd.top = new FormAttachment(table, 10, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 220);
        fd.width = 110;
        fd.height = 20;
        g.setLayoutData(fd);
        g.setLayout(new RowLayout());
        Button rb = new Button(g, SWT.RADIO);
        rb.setText("同意");
        rb.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                choose = "Y";
            }
        });
        rb = new Button(g, SWT.RADIO);
        rb.setText("不同意");
        rb.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                choose = "N";
            }
        });
        btnSave = new Button(shell, SWT.PUSH);
        btnSave.setText("送出");
        fd = new FormData();
        fd.top = new FormAttachment(table, 17, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 360);
        fd.width = 50;
        fd.height = 25;
        btnSave.setLayoutData(fd);
        btnSave.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                MessageBox msg = new MessageBox(shell);
                msg.setText("訊息");
                if ((bill > 0)
                        && ((choose.equalsIgnoreCase("Y")) || (choose
                                .equalsIgnoreCase("N")))) {
                    Thread t = new Thread(new SaveResolveSocket());
                    t.start();
                    msg.setMessage("\r\n資料已送出 !!");
                } else {
                    msg.setMessage("\r\n未選擇議案 或 種類 !!");
                }
                msg.open();
            }
        });
        final Button btnClear = new Button(shell, SWT.PUSH);
        btnClear.setText("清除");
        btnClear.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                clearTable();
            }
        });
        fd = new FormData();
        fd.top = new FormAttachment(table, 17, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 410);
        fd.width = 50;
        fd.height = 25;
        btnClear.setLayoutData(fd);
        txtServlet = new Text(shell, SWT.NONE | SWT.LEFT);
        txtServlet.setText(servlet);
        txtServlet.addListener(SWT.Traverse, new Listener() {
            public void handleEvent(Event e) {
                if (e.detail == SWT.TRAVERSE_RETURN) {
                    System.out.println(txtServlet.getText());
                    Thread t = new Thread(new DocnoSocket());
                    t.start();
                }
            }
        });
        fd = new FormData();
        fd.top = new FormAttachment(txtSum, 5, SWT.BOTTOM);
        fd.left = new FormAttachment(0, 10);
        fd.width = 200;
        fd.height = 15;
        txtServlet.setLayoutData(fd);
        disableTable();
        txtServlet.setVisible(false);
    }
 
    private void createTable() {
        table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION);
        TableColumn tc1 = new TableColumn(table, SWT.RIGHT);
        TableColumn tc2 = new TableColumn(table, SWT.NONE);
        TableColumn tc3 = new TableColumn(table, SWT.RIGHT);
        TableColumn tc4 = new TableColumn(table, SWT.CENTER);
        tc1.setText(TABLE_HEAD[0]);
        tc2.setText(TABLE_HEAD[1]);
        tc3.setText(TABLE_HEAD[2]);
        tc4.setText(TABLE_HEAD[3]);
        tc1.setWidth(80);
        tc2.setWidth(160);
        tc3.setWidth(120);
        tc4.setWidth(100);
        tc2.setResizable(true);
        tc3.setResizable(true);
        tc4.setResizable(true);
        table.setHeaderVisible(true);
        table.setLinesVisible(true);
        table.addListener(SWT.Selection, new SummaryListener());
        table.addListener(SWT.MouseDown, new TextEditListener());
        for (int i = 0; i < tableCols; i++) {
            TableItem item = new TableItem(table, SWT.NONE);
            String[] data = new String[4];
            item.setText(data);
        }
    }
 
    private void clearTable() {
        table.clearAll();
        table.notifyListeners(SWT.Selection, new Event());
    }
 
    private void disableTable() {
        table.setEnabled(false);
        btnSave.setEnabled(false);
        txtServlet.setVisible(true);
    }
 
    private void enableTable() {
        table.setEnabled(true);
        btnSave.setEnabled(true);
        txtServlet.setVisible(false);
    }
 
    private void createEditor() {
        editor = new TableEditor(table);
        editor.horizontalAlignment = SWT.LEFT;
        editor.grabHorizontal = true;
    }
 
    private void createPopupMenu() {
        menu = new Menu(shell, SWT.POP_UP);
        table.setMenu(menu);
        MenuItem item = new MenuItem(menu, SWT.PUSH);
        item.setText("刪除");
        item.addListener(SWT.Selection, new DelItemListener());
    }
 
    private void appendMsg(String msg) {
        msgCnt++;
        sb.append(msgCnt);
        sb.append(". ");
        sb.append(msg);
        sb.append("\r\n");
    }
 
    public void dispose() {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
            }
            con = null;
        }
    }
 
    public void displayHelpAboutDialog() {
        MessageBox msg = new MessageBox(shell);
        msg.setText("關於計票程式");
        msg.setMessage("\r\n版權所有  :  jihsun securities co., ltd."
                + "\r\n\r\n作者\t  :   jack" + "\r\n\r\n時間\t  :   2005-03-04"
                + "\r\n\r\n版本\t  :   v 1.0");
        msg.open();
    }
 
    private int getBill(String str) {
        String s = str.replaceAll(PREFIX, "");
        try {
            bill = Integer.parseInt(s);
        } catch (NumberFormatException e) {
            bill = 0;
        }
        return bill;
    }
 
    public static void main(String[] args) {
        new Resolve();
    }
 
    class TextEditListener implements Listener {
        public void handleEvent(Event event) {
            Point pt = new Point(event.x, event.y);
            final TableItem item = table.getItem(table.getSelectionIndex());
            int i = 0;
            Rectangle rect = item.getBounds(i);
            if (event.y <= 0) {
                pt = new Point(rect.x, rect.y);
            }
            if (rect.contains(pt)) {
                final int column = i;
                final Text text = new Text(table, SWT.NONE);
                text.setTextLimit(10);
                Listener textListener = new Listener() {
                    public void handleEvent(final Event e) {
                        switch (e.type) {
                        case SWT.FocusOut:
                            item.setText(column, text.getText());
                            text.dispose();
                            break;
                        case SWT.Traverse:
                            switch (e.detail) {
                            case SWT.TRAVERSE_RETURN:
                                item.setText(column, text.getText());
                                text.dispose();
                                if (!item.getText().equals("")) {
                                    //                                    Thread t = new Thread(new Register());
                                    Thread t = new Thread(new ShmmosSocket());
                                    t.start();
                                }
                            case SWT.TRAVERSE_ESCAPE:
                                e.doit = false;
                            }
                            break;
                        }
                    }
                };
                text.addListener(SWT.FocusOut, textListener);
                text.addListener(SWT.Traverse, textListener);
                editor.setEditor(text, item, i);
                text.setText(item.getText(i));
                text.selectAll();
                text.setFocus();
                return;
            }
        }
    }
 
    class DelItemListener implements Listener {
        public void handleEvent(Event event) {
            final TableItem item = table.getItem(table.getSelectionIndex());
            for (int i = 0; i < table.getColumnCount(); i++) {
                item.setText(i, "");
            }
            if (table.getSelectionIndex() < (tableCols - 1)) {
                table.setSelection(table.getSelectionIndex() + 1);
                table.notifyListeners(SWT.Selection, new Event());
                table.notifyListeners(SWT.MouseDown, new Event());
            }
        }
    }
 
    class SummaryListener implements Listener {
        public void handleEvent(Event event) {
            long sum = 0;
            int count = 0;
            for (int i = 0; i < table.getItemCount(); i++) {
                TableItem item = table.getItem(i);
                if (!item.getText().equals("")) {
                    String ss = item.getText(2).replaceAll(",", "");
                    long stkqty = 0;
                    try {
                        stkqty = Long.parseLong(ss);
                        count++;
                    } catch (NumberFormatException e) {
                        stkqty = 0;
                    }
                    sum += stkqty;
                }
            }
            txtSum.setText("合計權數 :  " + Format.longFormat(sum) + " 權");
            txtCount.setText("合計人數 :  " + Format.longFormat(count) + " 人");
        }
    }
 
    class Register implements Runnable {
        public void run() {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    final TableItem item = table.getItem(table
                            .getSelectionIndex());
                    try {
                        PreparedStatement pstmt = con.prepareStatement(sql);
                        pstmt.setString(1, item.getText());
                        ResultSet rs = pstmt.executeQuery();
                        if (rs.next()) {
                            String[] data = { rs.getString(1), rs.getString(2),
                                    Format.longFormat(rs.getLong(3)),
                                    rs.getString(4) };
                            item.setText(data);
                        } else {
                            String[] data = { item.getText(), "", "", "" };
                            item.setText(data);
                        }
                    } catch (SQLException e) {
                    }
                    if (table.getSelectionIndex() < (tableCols - 1)) {
                        table.setSelection(table.getSelectionIndex() + 1);
                        table.notifyListeners(SWT.Selection, new Event());
                        table.notifyListeners(SWT.MouseDown, new Event());
                    }
                }
            });
        }
    }
 
    class ConnectDB implements Runnable {
        public void run() {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    try {
                        Class.forName(driver);
                        try {
                            con = DriverManager
                                    .getConnection(url, user, passwd);
                            table.addListener(SWT.MouseDown,
                                    new TextEditListener());
                            appendMsg("連接資料庫==> Ok");
                            txtCount.setText("");
                        } catch (SQLException e) {
                            appendMsg(e.toString());
                            txtCount.setText("資料庫連接失敗 !!");
                        }
                    } catch (ClassNotFoundException e) {
                        appendMsg(e.toString());
                        txtCount.setText("資料庫軀動程式載入失敗 !!");
                    }
                }
            });
        }
    }
 
    class ShmmosSocket implements Runnable {
         public void run() {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    final TableItem item = table.getItem(table
                            .getSelectionIndex());
                    try {
                        URL url = new URL(txtServlet.getText());
                        HttpURLConnection uc = (HttpURLConnection) url
                                .openConnection();
                        uc.setDoOutput(true);
                        uc.setUseCaches(false);
                        DataOutputStream out = new DataOutputStream(
                                new BufferedOutputStream(uc.getOutputStream()));
                        String psntid = "method=SHMMOS&psntid="
                                + item.getText(0);
                        out.writeBytes(psntid);
                        out.flush();
                        out.close();
                        InputStream raw = uc.getInputStream();
                        ObjectInputStream dis = new ObjectInputStream(
                                new BufferedInputStream(raw));
 
                        String[] data = { item.getText(0), "", "", "" };
                        ShmmosForm shmmos = null;
                        try {
                            shmmos = (ShmmosForm) dis.readObject();
                            data[0] = String.valueOf(shmmos.getPsntid());
                            data[1] = shmmos.getPatname();
                            data[2] = shmmos.getVoteqty_fmt();
                            data[3] = shmmos.getRegid();
                        } catch (ClassNotFoundException e) {
                            appendMsg(e.toString());
                        }
                        dis.close();
                        item.setText(data);
                    } catch (MalformedURLException e) {
                        appendMsg(e.toString());
                    } catch (IOException e) {
                        appendMsg(e.toString());
                    }
                    if (table.getSelectionIndex() < (tableCols - 1)) {
                        table.setSelection(table.getSelectionIndex() + 1);
                        table.notifyListeners(SWT.Selection, new Event());
                        table.notifyListeners(SWT.MouseDown, new Event());
                    }
                }
            });
        }
    }
 
    class DocnoSocket implements Runnable {
         public void run() {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    try {
                        URL url = new URL(txtServlet.getText());
                        HttpURLConnection uc = (HttpURLConnection) url
                                .openConnection();
                        uc.setDoOutput(true);
                        uc.setUseCaches(false);
                         DataOutputStream out = new DataOutputStream(
                                new BufferedOutputStream(uc.getOutputStream()));
                         String method = "method=DOCNO";
                        out.writeBytes(method);
                        out.flush();
                        out.close();
                         InputStream raw = uc.getInputStream();
                        ObjectInputStream dis = new ObjectInputStream(
                                new BufferedInputStream(raw));
                         DocnoForm docno = null;
                        try {
                            docno = (DocnoForm) dis.readObject();
                        } catch (ClassNotFoundException e) {
                            appendMsg(e.toString());
                        }
                        dis.close();
                         if ((docno == null) || (docno.getResolve() == 0)) {
                            disableTable();
                        } else {
                            clearTable();
                            bill = docno.getResolve();
                            lblBill.notifyListeners(SWT.Selection, new Event());
                        }
                        enableTable();
                    } catch (MalformedURLException e) {
                        appendMsg(e.toString());
                        disableTable();
                    } catch (IOException e) {
                        appendMsg(e.toString());
                        disableTable();
                    }
                }
            });
        }
     }
 
   class SaveResolveSocket implements Runnable {
         public void run() {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    try {
                        btnSave.setEnabled(false);
                         ArrayList lst = new ArrayList();
                        ResolveForm resolve = null;
                        for (int i = 0; i < tableCols; i++) {
                            TableItem item = table.getItem(i);
                            if (!item.getText(2).equals("")) {
                                resolve = new ResolveForm();
                                resolve.setBill(bill);
                                resolve.setPsntid(Integer.parseInt(item
                                        .getText(0)));
                                try {
                                    resolve.setVoteqty(Double.parseDouble(item
                                            .getText(2).replaceAll(",", "")));
                                } catch (NumberFormatException e) {
                                    resolve.setVoteqty(0);
                                }
                                resolve.setChoose(choose);
                                lst.add(resolve);
                            }
                        }
                         System.out.println("lst.isEmpty==" + lst.isEmpty());
                        if (lst.isEmpty()) {
                            return;
                        }
                        StringBuffer sb = new StringBuffer("method=RESOLVE");
                        Iterator it = lst.iterator();
                        while (it.hasNext()) {
                            resolve = (ResolveForm) it.next();
                            sb.append(resolve.toString());
                        }
                        URL url = new URL(txtServlet.getText());
                        HttpURLConnection uc = (HttpURLConnection) url
                                .openConnection();
                        uc.setDoOutput(true);
                        uc.setUseCaches(false);
                        DataOutputStream out = new DataOutputStream(
                                new BufferedOutputStream(uc.getOutputStream()));
                        System.out.println(sb.toString());
                        out.writeBytes(sb.toString());
                        out.flush();
                        out.close();
                        InputStream raw = uc.getInputStream();
                        DataInputStream dis = new DataInputStream(
                                new BufferedInputStream(raw));
                        ... // 太長了,超過 PIXNET 的限制

identical 發表在 痞客邦 留言(0) 人氣()

BasicFramework code : (來源 SWT)
package org.eclipseguide.swt;
 
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.widgets.*;
 
public abstract class BasicFramework
{
 
   protected Display display;
   protected Shell shell;
   protected Menu menuBar, fileSubMenu, helpSubMenu;
   protected MenuItem fileSubMenuHeader;
   protected MenuItem fileExit, helpSubMenuHeader;
   protected MenuItem helpAbout;
 
   public abstract void dispose();
   public abstract void displayHelpAboutDialog();
 
   class FileExitListener implements SelectionListener
   {
      public void widgetSelected(SelectionEvent event)
      {
         shell.close();
         dispose();
      }
 
      public void widgetDefaultSelected(SelectionEvent event)
      {
         shell.close();
         dispose();
      }
   }
 
   class HelpAboutListener implements SelectionListener
   {
      public void widgetSelected(SelectionEvent event)
      {
         displayHelpAboutDialog();
      }
 
      public void widgetDefaultSelected(SelectionEvent event)
      {
         displayHelpAboutDialog();
      }
   }
 
   public BasicFramework(String windowTitle)
   {
      display = new Display();
      shell = new Shell(display);
      shell.setText(windowTitle);
 
      menuBar = new Menu(shell, SWT.BAR);
      fileSubMenuHeader = new MenuItem(menuBar, SWT.CASCADE);
      fileSubMenuHeader.setText("&File");
 
      fileSubMenu = new Menu(shell, SWT.DROP_DOWN);
      fileSubMenuHeader.setMenu(fileSubMenu);
 
      fileExit = new MenuItem(fileSubMenu, SWT.PUSH);
      fileExit.setText("E&xit");
 
      helpSubMenuHeader = new MenuItem(menuBar, SWT.CASCADE);
      helpSubMenuHeader.setText("&Help");
 
      helpSubMenu = new Menu(shell, SWT.DROP_DOWN);
      helpSubMenuHeader.setMenu(helpSubMenu);
 
      helpAbout = new MenuItem(helpSubMenu, SWT.PUSH);
      helpAbout.setText("&About");
 
      fileExit.addSelectionListener(new FileExitListener());
      helpAbout.addSelectionListener(new HelpAboutListener());
 
      shell.setMenuBar(menuBar);
   }
 
   public void mainLoop(int hSize, int vSize)
   {
      shell.setSize(hSize, vSize);
      shell.setVisible(true);
      shell.open();
 
      while (!shell.isDisposed())
      {
         if (!display.readAndDispatch())
            display.sleep();
      }
   }
}

identical 發表在 痞客邦 留言(0) 人氣()

寫一支 web start 的程式其實還蠻有意思的,感覺得安全性相當的高,但難免有點囉嗦及不方便。
事隔二年了,都快要忘了,來吧它整理一下吧--


1。server side
2。client side
3。client server 的溝通
4。描述檔 (jnlp)
5。sign-jar




1。server side --> see code
  • extends HttpServlet
  • overwrite doPost() & doGet()
  • 依 client 傳來的參數 ex: http://127.0.0.1/path/servlet.do?method=xxx 處理
  • 由 response.getOutputStream() 取得 stream, 寫回結果

2。client side (GUI 為 SWT)

  • abstract class BasicFramework (from :org.eclipseguide.swt) --> see code
  • myClass extends BasicFramework --> see code

3。client server 的溝通 --> see code
  • 透過幾個 inner class 與 web 溝通
  • 主要為 implements Listener & implements Runnable
  • client 傳參數給 web ,但 web 傳回的 stream 要再自行處理使成為 SomeSortofClass

4。描述檔 (jnlp)
<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://10.2.2.219/vote" href="resolve.jnlp">
 <information>
  <title>Resolve Vote</title>
  <vendor>jihsun securities co.</vendor>
  <homepage href="index.html"/>
  <description>表決議案計票</description>
 </information>
  <security>
     <all-permissions/>
  </security>
 <resources>
  <j2se version="1.4"/>
  <jar href="vote.jar"/>
  <nativelib href="swt-lib.jar"/>
 </resources>
 <resources os="Windows">  
     <jar href="swt.jar"/>
     <jar href="pg74.215.jdbc3.jar"/>
     <jar href="servlet-api.jar"/>
     <jar href="struts.jar"/>
 </resources>
 <resources os="Linux">  
     <jar href="swt-linux.jar"/>
     <jar href="swt-pi.jar"/>     
     <jar href="pg74.215.jdbc3.jar"/>
     <jar href="servlet-api.jar"/>
     <jar href="struts.jar"/>
 </resources>
 <application-desc main-class="org.eclipseguide.swt.Resolve"/>
</jnlp>

ps. 來源 ip 很重要,當產生 sign-jar 時會加入 keystore 中,當 web 的 ip 更新時 web-start 便會不能做用,這應該是安全上的考量。

5。sign-jar
<target name="sign-jars" depends="package-swtlib">
    <echo level="info">Signing JARS...</echo>
    <signjar jar="${dist.dir}/swt-lib.jar" keystore="${keystore}" alias="myself" storepass="key"/>
    <signjar jar="${dist.dir}/${myname}.jar" keystore="${keystore}" alias="myself" storepass="key"/>
     
    <copy file="${eclipse.dir}/windows/swt.jar" todir="${dist.dir}"/>
    <signjar jar="${dist.dir}/swt.jar" keystore="${keystore}" alias="myself" storepass="key"/>
    
    <copy file="${eclipse.dir}/unix/swt-linux.jar" todir="${dist.dir}"/>
    <signjar jar="${dist.dir}/swt-linux.jar" keystore="${keystore}" alias="myself" storepass="key"/>
    
    <copy file="${eclipse.dir}/unix/swt-pi.jar" todir="${dist.dir}"/>
    <signjar jar="${dist.dir}/swt-pi.jar" keystore="${keystore}" alias="myself" storepass="key"/>
 
    <signjar jar="${dist.dir}/pg74.215.jdbc3.jar" keystore="${keystore}" alias="myself" storepass="key"/>
    <signjar jar="${dist.dir}/servlet-api.jar" keystore="${keystore}" alias="myself" storepass="key"/>
    <signjar jar="${dist.dir}/struts.jar" keystore="${keystore}" alias="myself" storepass="key"/>
</target>
 

identical 發表在 痞客邦 留言(0) 人氣()

有一陣子沒用 java mail了,都有點忘了呵呵;java mail 經過幾年也有了一些容易感覺出來的變化

相同的:
一樣要用到 jaf 這個 framework (activation.jar) 跟 mail.jar (也可用單獨的 imap.jar, pop3.jar, smtp.jar.. 等);只是版本變新了

不同的:
選擇變多了,多了 jakarta 的 common-email-xxx.jar (分類在 common 專案中),感覺上好像有讓 java mail 變好用了 :-)

以下是直接用 java mail 的 code, 最原始的來源好像是用 java 附的 sample 中的一支 mail class 去改的

public String Send() {
String errMsg = null;

// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.smtpServer", smtpServer);

Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);

try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);

if (cc != null) {
InternetAddress[] addressCC = {new InternetAddress(cc)};
msg.setRecipients(Message.RecipientType.CC, addressCC);
}
msg.setSubject(subject);

// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();

// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setContent(msgContext,"text/html");

mp.addBodyPart(mbp1);

if (attach.isEmpty()==false) {
for (Enumeration e=attach.elements(); e.hasMoreElements();) {
String file = (String)e.nextElement();

file = attFilePath + file;
FileDataSource fds = new FileDataSource(file);

// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}
}

// add the Multipart to the message
msg.setContent(mp);

// set the Date: header
msg.setSentDate(new Date());

// send the message
Transport.send(msg);

errMsg = "true";

}
catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
errMsg = "message : " + ex.toString();
}
}

return errMsg;
}


以下是用 common-email 的 code

public static void send(Hashtable ht, Staff me, ArticleForm form,

String host, String serv, String contextPath) {

HtmlEmail email = new HtmlEmail();
email.setHostName(host);

try {
String subject = ((ArticleForm) form).getCreator() + " 發佈訊息";
email.setSubject(subject);

StringBuffer msg = new StringBuffer("");
msg.append("");
msg.append(((ArticleForm) form).getTitle());
msg.append("... (按我)");
msg.append("
");
msg.append("
");
log.debug(msg.toString());

email.setHtmlMsg(zhtw2en(msg.toString()));
String sender = me.getEmail() + Tokens.EMAIL_SEP + serv;
log.debug(sender);

email.setFrom(sender, "Me");
email.addCc(sender);

List list = new Vector();
Set set = ht.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {
String s = (String) it.next();
Staff u = (Staff) ht.get(s);
if (u.getName().equals(me.getName()))
continue;

// log.debug(u.getEmail() + "," + u.getIp());
if ((u.getEmail() != null) && (u.getEmail().length() > 0)) {
String em = u.getEmail() + Tokens.EMAIL_SEP + serv;
log.debug(em);

try {
list.add(new InternetAddress(em));
} catch (AddressException e) {
log.error(e);
}
}
}
email.setTo(list);
email.send();
} catch (EmailException e) {
log.error("mail:" + e);
}
}
二段 code 都是用 mail 寄送 html 格式的訊息,另
1。要下載 jaf & mai.jar 參考資料:JavaWorld (sun 網站也有)
2。要執行 mail 的 class 要加入 jaf & mail 的 jar file 在 CLASSPATH
3。在 code 中直接用中文實在不是好習慣,因為在 cross platform 時會有問題

identical 發表在 痞客邦 留言(0) 人氣()

其實很少寫需要單獨執行的 java 程式,有幾個原因吧
1。因為我都是開發 web application
2。java 要在 console 下執行實在很麻煩
3。tool 用多了(我都是用 eclipse, 也用過幾天 Gel),要改用 vi or notepad 都有點太...
anyway, 還是有需要的時候

有關於 Running JAR-Packaged Software
要於 jar file 中加入特定的資訊
1.先建立一個 text file (ex.mainClass) , 並將
"Main-Class: myClassName " 或其他資訊加入
ps. 如果執行時要使用其他的 jar file 裡,要另外加入:
"Class-Path: extendJar...."
2.再用 jar 這支 tool 來產生 jar file,語法如下:
jar cmf mainClass jarName.jar classList
3.完成以上的步驟我們就有可執行的 jar file 了
java -jar jarName.jar

參考資料:sun 網站,忘了 url, sun forum

後記:eclipse 好像有一個選項可以在產生 jar file 的時候一併加入 Main-Class 印像中好像用過,呵呵

identical 發表在 痞客邦 留言(0) 人氣()

終於正式使用 jfreechar 了,真的好用

這是成果,不過遇到了一些困擾

  • tomcat+struts+tile+jfreechart 使用 response.getOutputStream() 會有問題
  • 使用 FileOutputStream 要注意路徑與會產生檔案的問題

    第一個問題是因為 struts+tile 的關係,應該是 tile 產生 html 的方式在的不同,所以我只好先產生圖檔再去 refer 它,但也因此產生第二個問題

    第二個問題比較麻煩,路徑的話只要
    servlet.getServletContext().getRealPath("");
    就可取得實際位置,再找個目錄放檔案;但產生的 temp 就不知道要如何處理了,困擾

        public synchronized final static String draw(ArrayList lst, String path) {

            if ((lst == null) || (lst.isEmpty())) {
                return &quot;&quot;;
            }

            int i = 0;
            String title = &quot;&quot;;
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            Iterator it = lst.iterator();
            while (it.hasNext()) {
                ChartForm chr = (ChartForm) it.next();
                if (chr.getCnt() &gt; 0) {
                    String s = chr.getDay().substring(
                        chr.getDay().indexOf("月") + 1,
                        chr.getDay().indexOf("日"));
                    dataset.setValue(chr.getCnt(), chr.getM(), s);
                } else {
                    dataset.setValue(chr.getCnt(), chr.getM(), &quot;&quot;);
                }

                i++;
                if (i == 1) {
                    title = chr.getDay()
                    .substring(0, chr.getDay().indexOf(&quot;月&quot;) + 1);
                }
            }
            // dataSet.setCategories(xAxisData);
            title += "家數圖";

            PlotOrientation plot = PlotOrientation.VERTICAL;
            JFreeChart chart = null;
            chart = ChartFactory.createBarChart(title, "日期", "家數",
                    dataset, plot, false, false, false);

            Date d = new Date();
            String s = d.toString();
            s = path + File.separator + &quot;jpg&quot; + File.separator
                    + s.replaceAll(" ", "_").replaceAll(":", "_")
                     + ".jpg";
            System.out.println(s);
            File f = new File(s);
            try {
                FileOutputStream ostream = new FileOutputStream(f);

                ChartUtilities.writeChartAsJPEG(
                    ostream, chart, 400, 300);

                ostream.close();
            } catch (IOException e) {

            }

            return f.getName();
        }
  • identical 發表在 痞客邦 留言(0) 人氣()

    1 2