2009年7月19日 星期日

JTable Sorter

jdk 6.x required.

http://www.diybl.com/course/3_program/java/javashl/2008510/115089.html

2009年7月16日 星期四

JTable, RowSorter, SelectionModel

JTable 行排序以及排序后如何把视图(view)上的选中行对应到模型(Model)上的行

前提条件: Sun JDK 1.6 及以上版本

排序的简单实现
--------------
最简单的实现办法如下代码示意:
jtable.setRowSorter( new TableRowSorter(model) )

参数 model 代表 TableModel 的实现类.

以上代码仅示意,你可以扩展抽象类 javax.swing.RowSorter 来实现定制.



选中的行 index 和模型上的 index
--------------------------------
自 jdk 1.6 , JTable 新增了方法 public int convertRowIndexToModel(int viewRowIndex)
至此,就获得了行索引在视图与模型间的对应关系.以下列出关键代码

jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
int i= jtable.getSelectedRow();

if (i >= 0) {
int R = jtable.convertRowIndexToModel(i);
StudentTableModel model = (StudentTableModel)jtable.getModel();
Student s= model.getRowAt(R);
textArea.setText(String.format("index to model = %d\tindex to view = %d\tobject = %s", R, i, s==null?"?" : s.toString()));
}
}
});

后文贴出完整源代码.源代码总共3个文件: Student.java; StudentTableModel.java; SortableTable.java
SortableTable.java 是启动类

Student.java
----------------
import java.util.*;
/**
* @author Hardneedl
*/
class Student {
private String name;
private String id;
private java.util.Date birthday;

Student(String id, String name, Date d) {
this.setId(id);
this.setName(name);
this.setBirthday(d);
}
Student() {}
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 java.util.Date getBirthday() {return birthday;}
public void setBirthday(java.util.Date birthday) {this.birthday = birthday;}

public boolean equals(Object obj) {
if (obj instanceof Student) {
Student st = (Student)obj;
String i = st.getId();
return i!=null && i.equals(getId());
}
return false;
}

public String toString() {return getName();}
}


StudentTableModel.java


import javax.swing.table.*;
import java.util.*;
/**
* @author Hardneedl
*/
class StudentTableModel extends AbstractTableModel {
private java.util.List studentList = new java.util.ArrayList(0);

StudentTableModel() {}
StudentTableModel(List studentList) {
this();
this.studentList.clear();
if (studentList != null) this.studentList.addAll(studentList);
}

void setDatas(java.util.Liststudents){
studentList.clear();
if (students!=null) studentList.addAll(students);
}

void addStudent(Student s){
if(s!=null) {
studentList.add(s);
fireTableDataChanged();
}
}
void removeStudent(Student s){
if (s!=null) {
studentList.remove(s);
fireTableDataChanged();
}
}

public int getRowCount() {return studentList.size();}
public int getColumnCount() {return 3;}
public Object getValueAt(int r, int c) {
Student st = studentList.get(r);
switch(c){
case 0:return st.getId();
case 1:return st.getName();
case 2:return st.getBirthday();
default:return null;
}
}

public String getColumnName(int column) {
switch(column){
case 0:return "ID";
case 1:return "Name";
case 2:return "Birthday";
default:return "???";
}
}

public void setValueAt(Object value, int rowIndex, int columnIndex) {
Student st = studentList.get(rowIndex);
if (st == null) return;
switch(columnIndex) {
case 0:
st.setId(value.toString());
break;

case 1:
st.setName(value.toString());
break;

case 2:
if (value instanceof Date)
st.setBirthday((Date)value);
break;

}
}
public boolean isCellEditable(int rowIndex, int columnIndex) {return true;}
Student getRowAt(int r){return studentList.get(r);}
}


SortableTable.java

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
import java.text.*;
/**
* @author Hardneedl
*/
class SortableTable extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);

private JTable jtable;
private JTextArea textArea;
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "JTable Sort Demo";}

SortableTable() throws HeadlessException {init();doLay();attachListeners();}

private void init() {
StudentTableModel model=new StudentTableModel();
model.addStudent(new Student("1", "Martin", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("2", "Rose", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("3", "Daisy", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("4", "Tom", new Date(Calendar.getInstance().getTimeInMillis())));
model.addStudent(new Student("5", "Needl", new Date(Calendar.getInstance().getTimeInMillis())));

jtable = new JTable(model);
jtable.setRowSorter( new TableRowSorter(model) );
jtable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer(){
private SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cmp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(dateFormat.format(value));
setHorizontalAlignment(SwingConstants.RIGHT);
return cmp;
}
});


jtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

textArea = new JTextArea(){
public Color getBackground() {return Color.ORANGE;}
public Color getForeground() {return Color.BLUE;}
public boolean isEditable() {return false;}
};
}

private void doLay() {
Container container = getContentPane();
container.add(new JScrollPane(jtable), BorderLayout.CENTER);
container.add(textArea, BorderLayout.SOUTH);
pack();
}

private void attachListeners() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
int i= jtable.getSelectedRow();

if (i >= 0) {
int R = jtable.convertRowIndexToModel(i);
StudentTableModel model = (StudentTableModel)jtable.getModel();
Student s= model.getRowAt(R);
textArea.setText(String.format("index to model = %d\tindex to view = %d\tobject = %s", R, i, s==null?"?" : s.toString()));
}
}
});
}

public static void main(String[] args) {new SortableTable().setVisible(true);}
}



source: http://hi.baidu.com/hardneedl/blog/

2009年7月15日 星期三

Apache + Tomcat整合

實踐apache和tomcat的整合,原來這麼簡單.

1:安裝tomcat,jdk,這些就不說了,這個大家應該都會

2:下載apache_2.2.11-win32-x86-no_ssl.msi,這在apache網站上就有,

3:下載mod_jk-1.2.28-httpd-2.2.3.so,這個是apache和tomcat整合必須的,在apache網站上也有,

4:安裝好apache http server後,進入到apache的安裝目錄下, Apache2.2\conf ,在此新建一個workers.properties文件,將以下內容copy到workers.properties文件中
# Defining a worker named worker1 and of type ajp13
worker.list=ajp13w
worker.ajp13w.type=ajp13
worker.ajp13w.host=127.0.0.1
worker.ajp13w.port=8009
worker.ajp13w.lbfactor=1

5: copy mod_jk-1.2.28-httpd-2.2.3.so文件到Apache2.2\modules目錄下,並且改名為mod_jk.so(為了方便)

6:配置Apache2.2\conf目錄下httpd.conf文件,增加以下內容:
LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkMount /*.jsp ajp13w
JkMount /*.jspx ajp13w
JkMount /servlet/* ajp13w
JkMount /*.servlet ajp13w
JkMount /* ajp13w
上面都配置好之後,啟動tomcat ,啟動apache,輸入http://localhost ,看到tomcat的首頁就ok了

source: 夢源著http://www.blogjava.net/mengyuan760

2009年7月7日 星期二

iReport 3.5.2 org.xml.sax.SAXParseException

the report jrxml file edit using iReport 3.5.2

try to run my report unit from there I get an error:

com.jaspersoft.jasperserver.api.JSExceptionWrapper: org.xml.sax.SAXParseException: cvc-complex-type.3.2.2: Attribute 'splitType' is not allowed to appear in element 'band'.



Just configure compatibility with JasperReports 3.5.0 like this:

Tools/Options/General/Compatibility Select the JR version you use on your JS...

2009年6月30日 星期二

2009 新書介紹: Network Infrastructure Security


Springer, 1 edition (May 20, 2009)

Research on Internet security over the past few decades has focused mainly on information assurance, issues of data confidentiality and integrity as explored through cryptograph algorithms, digital signature, authentication code, etc. Unlike other books on network information security, Network Infrastructure Security by Angus Wong and Alan Yeung addresses the emerging concern with better detecting and preventing routers and other network devices from being attacked or compromised.

Attacks to network infrastructure affect large portions of the Internet at a time and create large amounts of service disruption, due to breaches such as IP spoofing, routing table poisoning and routing loops. Daily operations around the world highly depend on the availability and reliability of the Internet, which makes the security of this infrastructure a top priority issue in the field.

Network Infrastructure Security is a book that bridges the gap between the study of the traffic flow of networks and the study of the actual network configuration. This book makes effective use of examples and figures to illustrate network infrastructure attacks from a theoretical point of view. The book includes conceptual examples that show how network attacks can be run, along with appropriate countermeasures and solutions.

2009年6月29日 星期一

JS instanceof判斷類型問題

判斷變量類型:一般情況下,可以先用typeof運算符,如果結果是"object",再用instanceof來判斷;
特別的地方是:
instanceof不認為原始類型值的變量是對象,

1. var temp="a string for test";
2. //下面這句返回"string"
3. alert( typeof temp);
4. //下面這句返回"false"
5. alert(temp instanceof String);
6.
7. //看看Ext內部實現,判斷String類型
8. if( typeof temp== "string"){
9. }

其他附加問題:

* null:表示尚未存在的對象,注意,儘管尚未存在,也是個對像啊,所以用typeof檢測一個null值變量的結果是Object;不過,為了便於寫 if語句,在js中,"undefined==false ", "null=false",因此,"undefined==null"。
*整數:最容易犯的錯誤就是,忘了070其實是個八進制數,相當於十進制的56;
*浮點數:“在進行運算之前,真正存儲的是字符串”——這應該是解釋執行的本質決定的吧——直接後果是,alert(0.8)這樣的語句可以正確輸出,而alert(2 *0.8)的輸出就成了"2.40000000000000003"
*數字邊界:數字有幾個邊界值,分別是Number.MAX_VALUE(最大值), Number.MIN_VALUE(最小值), Number.POSITIVE_INFINITY(正無窮), Number.NEGATIVE_INFINITY(負無窮), Infinity(無窮大,- Infinity,這個有點莫名其妙,不知道為啥又搞出一套);特別地,還有一個isFinit(iNumber)函數來判斷數字是否為無窮大。
* NaN:一些需要數字作為參數的函數,當傳入的實參無法轉換為數字時,往往會返回這個值;關於NaN,最重要的就是要記住NaN!=NaN,因此判斷一個變量是否為NaN,一定要使用isNaN(var)函數。
*將字符串轉換為數字:sVar.parseInt()是最常用的函數,也最容易出錯,為了保險起見,最好每次調用的時候,都加上“進制”的參數,比 如:a .parseInt(10),就制定了按十進制轉換字符串a;Number(sVar)也是一種轉換方式,不同的是,它要求整個字符串都得是有效數字,因 此Number("4.5.5")將返回NaN;

source: http://www.blogjava.net/oathleo

2009年6月28日 星期日

Oracle - 如何在 SELECT statement 中,實作 IF-THEN-ELSE 邏輯 ?

How does one implement IF-THEN-ELSE logic in a SELECT statement?

Submitted by admin on Sat, 2005-11-12 06:38

Oracle SQL supports several methods of coding conditional IF-THEN-ELSE logic in SQL statements. Here are some:
CASE Expressions

From Oracle 8i one can use CASE statements in SQL. Look at this example:

SELECT ename, CASE WHEN sal = 1000 THEN 'Minimum wage'
WHEN sal > 1000 THEN 'Over paid'
ELSE 'Under paid'
END AS "Salary Status"
FROM emp;
DECODE() Function

The Oracle decode function acts like a procedural statement inside an
SQL statement to return different values or columns based on the values of
other columns in the select statement. Examples:

select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown')
from employees;

select a, b, decode( abs(a-b), a-b, 'a > b',
0, 'a = b',
'a < b') from tableX;

Note: The decode function is not ANSI SQL and is rarely implemented
in other RDBMS offerings. It is one of the good things about Oracle,
but use it sparingly if portability is required.


GREATEST() and LEAST() Functions

select decode( GREATEST(A,B), A, 'A is greater OR EQUAL than B',
'B is greater than A')...



select decode( GREATEST(A,B),
A, decode(A, B, 'A NOT GREATER THAN B', 'A GREATER THAN B'),
'A NOT GREATER THAN B')...

NVL() and NVL2() Functions

NVL and NVL2 can be used to test for NULL values.

NVL(a,b) == if 'a' is null then return 'b'.

SELECT nvl(ename, 'No Name')
FROM emp;

NVL2(a,b,c) == if 'a' is not null then return 'b' else return 'c'.

SELECT nvl2(ename, 'Do have a name', 'No Name')
FROM emp;

COALESCE() Function

COALESCE() returns the first expression that is not null. Example:

SELECT 'Dear '||COALESCE(preferred_name, first_name, 'Sir or Madam')
FROM emp2;

NULLIF() Function

NULLIF() returns a NULL value if both parameters are equal in value. The following query would return NULL:

SELECT NULLIF(ename, ename)
FROM emp;

source: http://robertvmp.pixnet.net/blog/post/24147936