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

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 變好用了 :-)

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

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

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) 人氣()

有人說需要為發明之母,我深深的認同總是覺得人類的生活上有些方式或說邏輯總是一再的重覆,只是方式或是媒介有所改變最近忽然感覺到 blog 的重要性了,以前沒寫日記或筆記的習慣經常重覆要找類似的資料或是邏輯,就以最近要用 java 套表時,那種深深的痛苦,唉喲,真是讓我感觸良多 :-)研究了二天的 javax.print, java.awt.print 又不能征服它,又做了重覆的苦工,呵呵, Orz它有一堆的 attribute 但...,網路上可用的資料實在太少了,IPS 從二年前 (2005) Draft 0.1 到現在(2007.3) 我再去找,它仍舊是那一份 Alpha Draft,呵呵不過也因為這樣才發現自己中 google 毒很深,因為一但在 google 上找不到太多相關資料時,你就知道這件事很不樂觀了,呵呵 (不過仍舊有可能是我不夠會用 google 大神)by the way 它實際上的做為是implements java.awt.print.Printable實做 public int print(Graphics g, PageFormat pf, int pageIndex)我是在 construct 中呼叫 print()

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

雙網卡的 route
幾個月前因為需要, 必須連接二個網段
只好努力的找方法, 也終於有機會玩一下 iptable
但是實在是太複雜了, 只好將 opensuse 9 預設的 fireware 關了
因為只是內網我想影響不大 ~~ (天知道 ^^)

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

沒想到 2007-01-01 就要 coding 呵呵
因為朋友要出個媒體給主管機關, 沒想到他們到現在還規定
中文英數字要全型空白也要全型, 想到最簡單的方式是用 access
input : excel file
output : fixed text file

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

用 java 也三年了, 結果 microsoft 用戶端的程式,
還是習慣用 microsoft 的東西, 呵呵 Orz
不過 database 當然還是要用我習慣的 PostgreSQL,
只是沒想到 C# 與 PostgreSQL 不太馬吉, 還好有高人的指點
(ps. 高人 = google + 不知名的好心人)
順手將之記下, 以免日後又給他忘記了

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

1
Blog Stats
⚠️

成人內容提醒

本部落格內容僅限年滿十八歲者瀏覽。
若您未滿十八歲,請立即離開。

已滿十八歲者,亦請勿將內容提供給未成年人士。