星期三, 七月 01, 2009

如何在唯一的wxWidgets执行文件中包含资源数据的步骤

编写xrc文件,手工编写是要让人崩溃的,可以下载http://wxformbuilder.org/ 下载用来
工具制作xrc文件

wxWidgets for C++从资源文件中静态装载图像


在wxWidgets中装载图像是非常容易的,但是如果将图像文件和可执行文件放到一起,在发布时只需要发布可执行文件,要实现这种功能,一般可以使用资 源文件来解决。在windows下的资源文件的源文件是*.rc,编译后叫*.res。在linux下类似,源文件为*.xrc,编译后叫*.xres。 但它们是xml格式的,要装载这种资源文件也得动态进行装载。相当于配置文件。

如果想将其直接编译进可执行文件。需要一个工具wxrc。这个工作在wxWidgets中的utils/wxrc目录中,可自己编译,mingw32-make -f makefile.gcc UNICODE=1 BUILD=release。可使用这个工具将*.xrc 生成c++代码,如果是图像,就将其转换成字符数组。然后和其它程序一起进行编译。可使用wxrc -c main.xrc -v -o main.h

main.xrc的格式如下:
<?xml version="1.0"?>
<resource version="2.3.0.1">
<object class="wxBitmap" name="background">background.jpg</object>
</resource>

生成的main.h的格式如下:

//
// This file was automatically generated by wxrc, do not edit by hand.
//

#include
<wx/wxprec.h>

#ifdef __BORLANDC__
#pragma hdrstop

在Visual C++的项目中添加XRC文件
虽然wxWidgets提供了XRC文件的编译器,但是把XRC的文件直接添加到Visual C++的项目中的话确没有任何效果,因为Visual C++默认能够处理的文件类型并不包含XRC文件。其实通过Visual C++的"自定义生成步骤"可以让XRC文件被自动编译:



引用:
打开项目中XRC文件的属性页。
选择"自定义生成步骤"。
在"命令行"处输入" /c /o $(InputDir)$(InputName).cpp $(InputPath)"。
在"输出"处输入"$(InputDir)$(InputName).cpp"。
在"附加依赖项"处输入XRC文件里引用的资源文件名(比如图片文件之类的),让这些资源文件被更新时XRC文件也会被重新编译。
按"确定"按钮关闭属性页。
编译XRC文件产生一个同名的C++源文件。
把XRC文件的目录下同名的C++源文件添加到项目中。
完成上步骤后,就可以让Visual C++自动把XRC文件的内容集成到二进制程序中了,以后XRC文件如果有什么改动,生成项目时会自动更新二进制程序里的XRC内容。


6 获得Windows应用程序实例句柄
声明如下函数:
代码:
    extern "C"
{
WXDLLIMPEXP_BASE HINSTANCE wxGetInstance();


}
这是wxWidgets内部使用的函数,用于获得HINSTANCE类型的。Windows应用程序实例句柄。

wxGridCellAttr SetTextColour windowXP得到异常

wxGridCellAttr SetTextColour exception
wxGridCellAttr *attrRed = new wxGridCellAttr();
attrRed->SetTextColour(wxColour(wxT("#0000ff")));
得到异常。
修改为以下语句则正常工作:

attrRed->SetTextColour(wxColour(0,0,255));

class静态成员变量link时候出现 undefined reference 错误

例子:
头文件
a.h
class a
{
public:
 static string a;
}

a.cpp
// declare class static objects
string a::format;
这样就可以解决这种link出现的  undefined reference 的错误

星期六, 六月 27, 2009

如何处理CodeBlock编译链接出现undefined rererence 的错误.

编译时候出现 :filename.cpp|| undefined reference to `CoCreateInstance@20
这种错误,是codeblock的一个bug.
需要把 链接的库加载项目的的鼠标右键的properties..里,而不是build options..里
选择properties打开project/target options窗口,右下角的按钮 Project's build options...打开
Project build options窗口,这个窗口同项目鼠标右键菜单中的build options竟然不同一,所以在设置中往往
在“正确”设置后,出现了错误,这两个窗口往往都需要同时设置,从最后产生的编译命令行分析,不过是重复加入,实在是奇怪。

需要把mingw\lib下面的库和wxWidges lib\gcc_lib或gcc_dll下面的库都加入到 ,Link  setting 下的link Libraries 里,全部加入


星期五, 六月 26, 2009

JBOSS通过JAAS框架验证用户后,如何得到用户所有的角色?

代码:

private void findRole() throws PolicyContextException {

// Get the Authenticated Subject
Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");

// Now look for a Group called Roles
Set principals = subject.getPrincipals(Principal.class);
Iterator iter = principals.iterator();
while(iter.hasNext()) {
Principal p = (Principal)iter.next();
if(p instanceof SimpleGroup) {
SimpleGroup sg = (SimpleGroup)p;
if("Roles".equals(sg.getName())) {
Enumeration en = sg.members();
while(en.hasMoreElements()) {
String role = en.nextElement().toString();
if(role != null) {
setRole(role);
}
}
}
}
}
}

星期一, 六月 22, 2009

如何在wxWidgets 编译生成wxdbgrid组件

命令行,

wxWidgets-2.8.10\build\msw>mingw32-make -f makefile.gcc UNICODE=1 BUILD=release MONOLITHIC=0  USE_ODBC=1 USE_GUI=1


则lib\gcc_lib下得到libwxmsw28u_dbgrid.a

星期四, 六月 11, 2009

如何用cygwin在控制台 显示彩色的字符

由于cygwin支持mingw,而mingw是不依赖cygwin.dll的。而cygwin.dll是在window下模拟
Linux的API的库,这样造成了一些现实彩色字符的不同技术。

cygwin.dll直接至此ANSI 颜色控制,支持ESC 累得颜色编码,所以直接用printf("\033[1;34m hello \033[0m“)就可以打印出一个蓝色的字符串了。

 但是如果不是用cygwin.dll,而是通过-mno-cygwin编译选项,是用window crt.dll库,则ANSI颜色控制码失去了作用。此时必须使用window下的方法。

 所以,这就要求代码能区别本程序的依赖,是否使用了-mno-cygwin编译出来的代码。

 通过深入研究,发现了 -mno-cygwin编译的依赖宏,并在自己的程序根据是否有特定的宏的出现,作为信号灯来识别。
步骤如下:
发现编译器预编译的宏
g++-3 -E -dM  -mno-cygwin -c testdb.cpp  >2.txt
 生成编译器预编译文件,发现了定义的宏,通过搜索发现了:__MINGW_H 宏。
因此在自己的文件中加入:

#ifdef __MINGW_H
static int MINGW_FLAG=1;
#else
static int MINGW_FLAG=0;

Linux ANSI 颜色控制

控制码 ^ESC,在VI状态下用Ctrl+v,ESC的组合输入,


在C语言中,可以通过printf直接打印出控制符号


ANSI控制码的说明

具体的摘抄一些如下:
[0m 关闭所有属性
[1m 设置高亮度
[4m 下划线
[5m 闪烁
[7m 反显
[8m 消隐
[30m -- [37m 设置前景色
[40m -- [47m 设置背景色
[nA 光标上移n行
[nB 光标下移n行
[nC 光标右移n行
[nD 光标左移n行
[y;xH设置光标位置
[2J 清屏
[K 清除从光标到行尾的内容
[s 保存光标位置
[u 恢复光标位置
[?25l 隐藏光标
[?25h 显示光标

星期日, 六月 07, 2009

SQLITE 使用g++来编译

http://www.mail-archive.com/sqlite-users@sqlite.org/msg30132.html

SQLite is ANSI C, so youshould compile it with gcc. It will still be usable within your C++library/project, as sqlite3.h qualifies all functions extern "C".

gcc -c sqlite3.c

g++ -c main.cpp

g++ -o program main.o sqlite3.o -lpthread -ldl

星期五, 五月 01, 2009

Netbean 6.5 同cygwin c/c++ 工作生成独立.exe文件



cygwin编译生成的.exe在命令行运行的时候,会出现 需要 cygwin1.dll的提示。
非常的不方便.exe的发布。

根据提示可以在c/c++的项目 c++ 编译器里 额外的选项里加入 -mno-cygwin来利用mingw生成独立的.exe
并避免协议法律上的问题。
如图:


不过需要安装的额外的包包含如下:
通过http://cygwin.com/setup.exe 安装如下包
http://wiki.openttd.org/Cygwin
    • binutils: The GNU assembler, linker and binary utilities
    • gcc: C compiler
    • gcc-g++: GCC C++ compiler
    • gcc-mingw-core: Mingw32 support headers and libraries for GCC
    • gcc-mingw-g++: Mingw32 support headers and libraries for GCC C++
    • make: The GNU version of the 'make' utility
    • mingw-runtime: MinGW Runtime
    • subversion: A version control system
  • In the Libs section, you will need:
    • crypt: Encryption/Decryption utility and library
    • zlib: The zlib compression and decompression library
    • mingw-runtime: MinGW Runtime
    • w32api: Win32 API header and library import files
  • In the Mingw section, you will need:
    • mingw-zlib: mingw version of the zlib compression and decompression library.
  • Optionally you might want to install:
    • libpng12-devel from the Grahpics section for making PNG screenshots and loading PNG heightmaps.
    • libfreetype2-devel from the Devel section for using Windows' font in OpenTTD.

星期二, 四月 28, 2009

Visual C++ Express 2008 快捷键

调试快捷键

F7,生成解决方案(生成.exe 或项目目标)
F5,运行当前解决方案


编辑快捷键

Shift+Alt+Enter: 切换全屏编辑 Ctrl+B,T / Ctrl+K,K: 切换书签开关
Ctrl+B,N / Ctrl+K,N: 移动到下一书签 Ctrl+B,P: 移动到上一书签
Ctrl+B,C: 清除全部标签 Ctrl+I: 渐进式搜索
Ctrl+Shift+I: 反向渐进式搜索 Ctrl+F: 查找
Ctrl+Shift+F: 在文件中查找 F3: 查找下一个
Shift+F3: 查找上一个 Ctrl+H: 替换
Ctrl+Shift+H: 在文件中替换 Alt+F12: 查找符号(列出所有查找结果)
Ctrl+Shift+V: 剪贴板循环 Ctrl+左右箭头键: 一次可以移动一个单词
Ctrl+上下箭头键: 滚动代码屏幕,但不移动光标位置。 Ctrl+Shift+L: 删除当前行
Ctrl+M,M: 隐藏或展开当前嵌套的折叠状态 Ctrl+M,P: 停止大纲显示
Ctrl+M,L: 将所有过程设置为相同的隐藏或展开状态 Ctrl+E,S: 查看空白
Ctrl+E,W: 自动换行 Ctrl+G: 转到指定行
Shift+Alt+箭头键: 选择矩形文本 Alt+鼠标左按钮: 选择矩形文本
Ctrl+Shift+U: 全部变为大写 Ctrl+U: 全部变为小写

代码快捷键

Ctrl+J / Ctrl+K,L: 列出成员
Ctrl+Shift+空格键 / Ctrl+K,P: 参数信息

Ctrl+K,I: 快速信息
Ctrl+E,
Ctrl+C / Ctrl+K,Ctrl+C: 注释选定内容
Ctrl+E,
Ctrl+U / Ctrl+K,Ctrl+U: 取消选定注释内容
Ctrl+K,M: 生成方法存根

Ctrl+K,X: 插入代码段 Ctrl+K,S: 插入外侧代码
F12: 转到所调用过程或变量的定义 tab两次: 代码补齐
Alt+鼠标左按钮: 选择矩形文本
Ctrl+Shift+U: 全部变为大写
Ctrl+U: 全部变为小写

窗口快捷键

Ctrl+W,W: 浏览器窗口 Ctrl+W,S: 解决方案管理器 Ctrl+W,C: 类视图
Ctrl+W,E: 错误列表 Ctrl+W,O: 输出视图 Ctrl+W,P: 属性窗口
Ctrl+W,T: 任务列表 Ctrl+W,X: 工具箱 Ctrl+W,B: 书签窗口
Ctrl+W,U: 文档大纲 Ctrl+D,B: 断点窗口 Ctrl+D,I: 即时窗口
Ctrl+Tab: 活动窗体切换 Ctrl+Shift+N: 新建项目 Ctrl+Shift+O: 打开项目
Ctrl+Shift+S: 全部保存 Shift+Alt+C: 新建类 Ctrl+Shift+A: 新建项

VC++ Express 2008 和SQLite 一起工作

首先要下载最新的sqlite.dll,这个是纯粹C的,如果需要C++需要一个CPP的wrapper版本。
目前网络上的版本都不够及时更新,所以是个大问题。这里是比较出名的cppsqlite
http://www.codeproject.com/KB/database/CppSQLite.aspx?fid=34722&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26

SQLITE网站上有如何编译的步骤:

http://www.sqlite.org/cvstrac/wiki?p=HowToCompile

http://www.sqlite.org/download.html 这里搜索dll可以发现最新的dll .zip下载。里面包含一个.def的文件

这个需要在安装VC++ Express 2008后,在命令行用lib来注册

星期一, 三月 30, 2009

MYSQL JDBC CachedRowSetImpl 临时表错误

问题:
In a stored procedure, if a result set is selected from a temporary table and then
deleted, a MySQLSyntaxErrorException occurs from the driver trying to perform SHOW FULL
COLUMNS on the non-existent temporary table.

解决方法:在mysql URL 里加入:
"useDynamicCharsetInfo=false"

Jboss deploy/mysql-ds.xml里加入如下语句:

<connection-url>jdbc:mysql://localhost:3306/mrp?useUnicode=TRUE</connection-url>
<connection-property name="characterEncoding">utf8</connection-property>
<connection-property name="useDynamicCharsetInfo">false</connection-property>

星期二, 三月 24, 2009

Windows环境下配置Apache 2.2.x + SSL

1.下载apache带ssl的模块

Win32 Binary including OpenSSL 0.9.8i (MSI Installer): apache_2.2.11-win32-x86-openssl-0.9.8i.msi [PGP] [MD5]

2.在安装目录bin下生成证书

openssl req -new -x509 -nodes -keyout server.key -out server.crt -subj /C=US/ST=Desert/L=SnakeTown/O=SnakeOilCo/OU=IT/CN=snakeoil.com -config ../conf/openssl.cnf

3.配置apache支持SSL
----------
设置Apache支持SSL
----------
注意: 本设置步骤针对针对Apache 2.2.x版本, 如果正在使用的是Apache 2.0.x版本, 请摸索相似的设置.

在Apache的conf目录中用文本编辑器打开httpd.conf
1. 去掉下面设置行前面的#
LoadModule ssl_module modules/mod_ssl.so
2. 去掉下面设置行前面的# (在2.0.x版本中没有这一项)
Include conf/extra/httpd-ssl.conf

3. 在Apache的conf/extra目录中打开httpd-ssl.conf, 更改如下设置. [apache安装目录]是指Apache的安装目录, 比如c:/Apache; my-server的两个文件就是前一个步骤制作的文件, 文件的位置就是这些文件在磁盘中的位置 (在2.0.x版本中这些设置仍然在 httpd.conf文件中进行)
SSLMutex default
SSLCertificateFile "[Apache安装目录]/conf/ssl/my-server.der.crt"
SSLCertificateKeyFile "[Apache安装目录]/conf/ssl/my-server.key"

4.测试

----------
测试
----------
1. 保存设置文件
2. 在开始菜单中运行Apache的Test Configuration工具, 检查设置文件是否正确
3. 重新启动Apache 2.2.x
4. 顺利启动之后, 在浏览器中输入
https://localhost 看看是否可以访问, 如果可以访问, 则设置成功!

星期五, 一月 09, 2009

SQLITE超强select case语法

1.动态决定输出,

select case
when red1%7=0 or red2%7=0 or red3%7=0 or red4%7=0 or red5%7=0 or red6%7=0 then 7
when red1%9=0 or red2%9=0 or red3%9=0 or red4%9=0 or red5%9=0 or red6%9=0 then 9
when red1%11=0 or red2%11=0 or red3%11=0 or red4%11=0 or red5%11=0 or red6%11=0 then 11
else term
end as result,rowid,count(*)
from _DBHISTORY group by result
2.标准switch case
select column_value case
when 1 then 1
when 2 then 2
else
3
end as result,rowid

from tableName

星期四, 十二月 25, 2008

文本聚类算法TCUSS(Text clustering using semantic similarity)

http://club.ufida.com.cn/blogs/rbg/archive/2008/05/28/_8259554F6E789A5B2D4E8765575B267B324E8476F8763C4FA65E2800_ZT_2900_.aspx

动态规划(dynamic programming)是运筹学的一个分支,是求解决策过程(decision process)最优化的数学方法

动态规划求解最长公共子串问题


算法思想

求字符串str1,str2的最长公共子串的长度。

定义二元函数函数f(m,n):分别以str1[m],str2[n]结尾的连续公共子串的长度

而对于f(m+1,n+1) 有以下两种情况

1.str1[m+1] != str2[n+1],则有f(m+1,n+1) =0

2.str1[m+1] == str2[n+1],则有f(m+1,n+1) = f(m,n) + 1

另外f(0,j) = 0(j>=0)

f(j,0) = 0 (j>=0)

按照上面这个公式,我们用容易写出这个算法的实现

算法实现

1 int commstr(char *str1, char *str2)

2 /* 返回str1,str2的最长公共之串长度*/

3 {

4 int len1=strlen(str1),len2=strlen(str2),row,col,max=0;

5 int **pf = new int*[len1+1];//动态分配一个二维数组作为辅助空间

6 for (row=0; row

7 pf[row] = new int[len2+1];

8

9 //数组赋初值

10 for (row=0; row

11 pf[row][0] = 0;

12 for (col=0; col

13 pf[0][col] = 0;

14

15 for (row=1; row<=len1; row++)

16 for (col=1;col<=len2; col++)

17 {

18 if (str1[row-1] == str2[col-1])

19 {

20 pf[row][col] = pf[row-1][col-1] + 1;

21 max = pf[row][col] > max ? pf[row][col] : max;

22 }

23 else

24 pf[row][col] = 0;

25 }

26 //空间回收

27 for (row=0; row

28 delete[] pf[row];

29 delete[] pf;

30

31 return max;

32 }



程序的输出

字符串"blog.csdn.net"和"csdn.blog"求公共子串时的输出结果

String:

1. blog.csdn.net

2. csdn.blog

c s d n . b l o g

0 0 0 0 0 0 0 0 0 0

b 0 0 0 0 0 0 1 0 0 0

l 0 0 0 0 0 0 0 2 0 0

o 0 0 0 0 0 0 0 0 3 0

g 0 0 0 0 0 0 0 0 0 4

. 0 0 0 0 0 1 0 0 0 0

c 0 1 0 0 0 0 0 0 0 0

s 0 0 2 0 0 0 0 0 0 0

d 0 0 0 3 0 0 0 0 0 0

n 0 0 0 0 4 0 0 0 0 0

. 0 0 0 0 0 5 0 0 0 0

n 0 0 0 0 1 0 0 0 0 0

e 0 0 0 0 0 0 0 0 0 0

t 0 0 0 0 0 0 0 0 0 0


max substr length:5

这是程序的输出结果,请注意红色字体


时间空间复杂度分析

如果用n,m表示两个字符串的长度的话,那么算法的

时间复杂度为O(n*m),空间复杂度也为O(n*m)

附:完整的源程序g++编译通过

#include

#include

void print_table(char *str1,char *str2,int **pf)

{

int i,j,row,col;

row = strlen(str1);

col = strlen(str2);

printf("\t\t");

for (i=0; i

printf("%c\t",str2[i]);

for (i=0; i<=row; i++)

{

for (j=0; j<=col; j++)

{

if (j == 0)

{

printf("\n");

if (i)

printf("%c\t",str1[i-1]);

else

printf("\t");

}

printf("%d\t",pf[i][j]);

}

}

}

int commstr(char *str1, char *str2)

/* 返回str1,str2的最长公共之串长度*/

{

int len1=strlen(str1),len2=strlen(str2),row,col,max=0;

int **pf = new int*[len1+1];//动态分配一个二维数组作为辅助空间

for (row=0; row

pf[row] = new int[len2+1];

//数组赋初值

for (row=0; row

pf[row][0] = 0;

for (col=0; col

pf[0][col] = 0;

for (row=1; row<=len1; row++)

for (col=1;col<=len2; col++)

{

if (str1[row-1] == str2[col-1])

{

pf[row][col] = pf[row-1][col-1] + 1;

max = pf[row][col] > max ? pf[row][col] : max;

}

else

pf[row][col] = 0;

}

print_table(str1,str2,pf);

//空间回收

for (row=0; row

delete[] pf[row];

delete[] pf;

return max;

}

int main(int argc,char **argv)

{

if (argc >= 3)

{

printf("String:\n\t1. %s\n\t2. %s\n",argv[1],argv[2]);

printf("\nmax substr length:%d\n",commstr(argv[1],argv[2]));

}

return 0;

}

星期三, 十二月 24, 2008

数据库自我关联

这个是SQLITE 得到一个记录和其随后记录的SQL:通过rowid来关联

select a.*,b.* from _dbhistory a left join _dbhistory b on a.rowid=(b.rowid-1)

星期五, 十一月 21, 2008

DhtmlxGrid 错误跟踪

function myErrorHandler(type, desc, erData)
{
//custom code can be placed here
return false;
}
dhtmlxError.catchError("LoadXML", myErrorHandler);

星期三, 十一月 19, 2008

SQLITE 3.6.5 SQL小窍门

1.得到最近的几期数据

where rowid>((select max(rowid) from 表名)-想要的记录条数)

星期一, 十一月 17, 2008

MathType快捷键

插入一个分数:Ctrl+F
插入一个上标:Ctrl+H
插入一个下标:Ctrl+L

Right arrow with upper text slot (Ctrl+T,Shift+Right) , 输入条件推理
Right arrow with lower text slot (Ctrl+T,CtrlAlt+Right) 输入条件推理
Right arrow with upper and lower text slots (Ctrl+T,Right) 输入条件推理
Curly brackets 大括号{
Left-pointing angle brackets 向左的尖括号<
Right-pointing angle bracket from Symbol style (Ctrl+Shift+K,>)
Left white square bracket from Extra Math style (Ctrl+Shift+K,[)
左白方括号
Right white square bracket from Extra Math style (Ctrl+Shift+K,])

星期四, 十一月 06, 2008

Java JPopupMenu selection 丢失。

Java JpopupMenu selection 有时候invisible,这种问题原因是事件丢失。
简单使用如下方法就可以了:

jpopup.setInvoker(jpopup);

如果想修改selection的颜色,可以使用如下方法,

UIManager.put("MenuItem.selectionBackground", Color.YELLOW);


星期三, 十一月 05, 2008

小窍门:Java如何让一个窗体显示在最上面?

SwingUtilities.windowForComponent( JPupupMenu ).window.setAlwaysOnTop( true )

使用这个方法可以做到。

如何在任何地方得到鼠标的的屏幕坐标?

jdk 6.0提供MouseInfo.getPointerInfo() .getLocation() 得到Point.getX(),.getY()

星期六, 十一月 01, 2008

如何选择JTable中任一行和任一列?

主要代码如下:

table.setModel(dayModel);
table.setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionInterval(2, 2);
table.getColumnModel().getSelectionModel().setSelectionInterval(3, 3);
你可以修改上面的2行,3列为你自己的任一行或列。非常的easy

星期一, 十月 27, 2008

如何提高SQLITE JDBC大批量插入数据的速度?

应为每一个Insert into操作默认都需要一个事物,所以通过显示的声明一个事物,可以大大提高数据插入的时间。
类似语句如下:

stmt.execute("BEGIN");
for(int i=0;i<commands.length;i++)
{
stmt.addBatch(commands[i]);
}
stmt.executeBatch();
stmt.execute("end");

曾经大约800数据,使用默认方法插入,大概需要141秒,而采用新方法后,使用纯Java的JDBC
速度提高到4秒,而使用JNI的JDBC,速度提高到几乎可以忽略不计的地步。

Very nice.!!!

星期五, 十月 24, 2008

Java JScrollPane getVerticalScrollBar.setValue没有效果解决方法。

JScrollPane scroll=new JscrollPane(new JEditorPane());

toolTip.getContentPane().add(scroll);
toolTip.pack();

//以下代码可以让scroll滚动到top顶端。

SwingUtilities.invokeLater(new Runnable(){public void run()
{
scroll.getVerticalScrollBar().setValue(0);
}
});

星期四, 十月 23, 2008

Servlet download 如何为已知的 MIME 类型激活“文件下载”对话框?

根据微软的一个文章:http://support.microsoft.com/kb/q260519/
参考如下:
您可以使用 Content-disposition 头来覆盖此默认行为。其格式是:
Content-disposition: attachment; filename=fname.ext
ASP:代码

Response.AddHeader "content-disposition","attachment; filename=fname.ext"

Servlet代码:
realName="yourfiel.n";
response.addHeader("Content-disposition","attachment; filename="+realName);
//realName如果是汉字编码会造成出现不了制定的文件名的情况,需要编码
//把以上代码修改为
//response.addHeader("Content-disposition","attachment; filename="+java.net.URLEncoder.encode(realName,"UTF-8"));

response.setIntHeader("Content-length", (int)rs.getBlob("ATTACH_FILE").length());

InputStream is = rs.getBinaryStream("ATTACH_FILE");

byte[] buf = new byte[3000];
int read = 0;
while ((read = is.read(buf)) > 0)
{
// fos.write(buf, 0, read);
outs.write(buf, 0, read);
}
// fos.close();
is.close();
outs.flush();
// outs.close();
}


星期四, 十月 16, 2008

SQLite自定义函数简介

SQLite自定义函数简介

SQLite最大的特色之一就是可以用户定义函数。用户自定义函数可以像系统内置函数一样可以在注册之后像系统内置函数一样在SQL语句中使用。用户使用自定义函数类似存储过程,方便用户对常见功能的调用,也加快了执行速度。用户自定义函数整体上可以分为两种:简单函数和聚集函数。

简单函数(simple function)

简单函数用在任何表达式中,常见的有max(x,y..), min(x,y..), random(*), last_insert_rowid(), length(x),lower(x), upper(x), round(x,y), round(*), substr(x,y,z), typeof(x)

聚集函数(aggregate function)

聚集函数经常用在select语句中,常见的有avg(x),count(x), count(*), max(x), min(x), sum(x), total(x)

  有些函数既是简单函数,又是聚集函数。比如只有一个参数的min()是一个聚集函数,而有多个参数的min()是一个简单函数。

SQLITE比较好的书有两本:
一个是:O'Reilly出版的 Inside SQLite
一个是:Apress.The.Definitive.Guide.to.SQLite.May.2006

星期一, 十月 13, 2008

如何立即刷新Java Swing Jcomponent组件?

例子:按下一个button,调用JTextArea.setText()之后,JTextArea的内容不会立即更新,必须要等待button捆绑的ActionListener过程完全完成之后,才会刷新。
如果想立即刷新JTextArea的内容去,需要调用一下语句。

JTextArea sql2= new JTextArea(5,10);
Point pt=sql2.getLocation();
Dimension ds=sql2.getSize();
sql2.paintImmediately((int)pt.getX(),(int)pt.getY(), (int)ds.getWidth(),(int)ds.getHeight());

这个工作的非常好。

星期四, 十月 09, 2008

得到当前运行class的物理位置

可以使用如下简单语句:

URL classFileDir =new yourClassName().getClass().getResource(".");

print结果为:file:....的URL

星期三, 十月 08, 2008

Windows XP SP2手工修改屏幕分辨率

有时候设置了不对的屏幕分辨率,会造成屏幕发黑无法启动。这是有需要在启动的时候按下F6键,然后进入注册表删除设置的屏幕分辨率,
Intel(R) Extreme Graphics 除了在注册表:
HKEY_CURRENT_CONFIG\System\CurrentControlSet\Control\VIDEO有引用,
本身在:
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\IALM]也有设置,必须删除这个设置
再启动机器后,才能正常进入。

[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\IALM\DEVICE0]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\IALM\DEVICE0\Mon80861100]

这两个注册表项目要删除掉

星期六, 九月 27, 2008

beanshell Bsh.Console如何在jdk 1.6中使用

直接使用String.format(format,param)会出现错误。
必须使用如下语法,
String.format("%3.2f",new Object[]{(float)6/11});

就可以使用了

星期五, 九月 19, 2008

dhtmlXGrid 覆盖函数。

这是覆盖每个cell 动态的tooltip的提示的方法。

dhtmlXGridCellObject.prototype.getTitle=function()
{
ccolName=this.grid.getColumnId(this.cell._cellIndex);
rowID=this.cell.parentNode.idd;
result=this.cell.innerHTML;
if(ccolName=='RULE_NAME')
result=this.grid.cells(rowID,4).getValue();
return result;
}

修改每个行的颜色
mygrid.setRowColor(rowid,"yellow");
或者更加底层的,可以修改更多属性CSS

mygrid.rowsAr[idrow].style.backgroundColor="yellow"

星期四, 九月 18, 2008

dhtmlXGrid 1.3版本如何修改每个cell的帮助提示呢?Tooltip

经过dhtmlXGrid论坛发现了一个渐变的方法。

dhtmlXGridCellObject.prototype.getTitle=function()
{
return this.cell.innerHTML+"<h1>F1 HELP</H1><BR/><P>..."+this.cell._cellIndex+"|||"+this.grid.getColumnId(this.cell._cellIndex);
}

不过这个innerHTML只承认纯文本,所以HTML语法无法使用了,\nJavascript符号还是认识的。


星期六, 九月 13, 2008

JBOSS JAAS如何编写自己的身份(principal)?

详细的步骤在:http://wiki.jboss.org/wiki/UsingCustomPrincpalsWith
不过经过事件发现只需要重载两个方法就可以了。如果直接从org.jboss.security.auth.spi.DatabaseServerLoginModule扩展,这样可以利用JBOSS已经有的密码加密,编码等其他一些特性,不需要再重写。

类似如下:
public class StandardLoginModule extends DatabaseServerLoginModule
编写自己的定制身份类Principal,可以加入除了名字之外的其他属性.

public class userPropertiesPrincipal extends SimplePrincipal
{
//User's property
private String email;
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email=email;
}
//gender
private String gender;
public String getGender()
{
return gender;
}
public void setGender(String gender)
{
this.gender=gender;
}
public userPropertiesPrincipal(String name)
{
super(name);
}

}

必须重载的三个方法(红色)
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map sharedState, Map options)
   public boolean login() throws LoginException
{
}
   protected Principal getIdentity()
{
 可能需要重载的类.
protected Group[] getRoleSets() throws LoginException
{}

具体设置步骤:在login-config.xml里加入,通过
principalClass来制定自己定制的身份类.也注意加入了
userPropertiesQuery,这个需要在initialize方法中从Map options中取出来,如下:
super.initialize(subject, callbackHandler, sharedState, options);

userPropertiesQuery=(String ) options.get("userPropertiesQuery");
if(userPropertiesQuery==null)
userPropertiesQuery="select * from sysUser where userid=?";


<application-policy name = "seamAC">
<authentication>

<login-module code = "org.security.login.jass.StandardLoginModule"
flag = "required">

<module-option name = "dsJndiName">java:/SecMasterDS</module-option>
<module-option name = "principalsQuery">select password from sysUser where userid=? </module-option>
<module-option name = "userPropertiesQuery">select * from sysUser where userid=? </module-option>
<module-option name = "rolesQuery">SELECT A.roleID as Role,'Roles' FROM sysRoles A,UserRoles B WHERE A.roleID=B.roleID AND B.userId=?</module-option>
<module-option name = "debug">true</module-option>
<module-option name="principalClass">org.security.login.jass.userPropertiesPrincipal</module-option>
<!--Password is md5 encrypt-->
<module-option name="hashAlgorithm">MD5</module-option>
<module-option name ="hashEncoding">HEX</module-option>
</login-module>
</authentication>
</application-policy>

Web.xml中必须指明使用使用JAAS Security Manage RealM

<Realm className="org.jboss.web.tomcat.security.JBossSecurityMgrRealm"
certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"
allRolesMode="authOnly"
debug="99"
/>

星期四, 九月 11, 2008

Jboss如何获取用户验证后的角色?

通过JAAS验证的用户,要想得到验证的用户的所有的角色,JBOSS目前推荐的是如下代码段
主要是基于新的JACC规范:
Java Authorization Contract for Containers (Java ACC) specification (JSR-115)

import javax.security.auth.Subject ;
import javax.security.jacc.PolicyContext;

private String findRole() throws Exception
{
String result="";

// Get the Authenticated Subject
Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");

// Now look for a Group called Roles
Set principals = subject.getPrincipals(Principal.class);
Iterator iter = principals.iterator();
while(iter.hasNext())
{
Principal p = (Principal)iter.next();
if(p instanceof SimpleGroup)
{
SimpleGroup sg = (SimpleGroup)p;
if("Roles".equals(sg.getName()))
{
Enumeration en = sg.members();
while(en.hasMoreElements())
{
String role = en.nextElement().toString();
result=result+","+role;
System.out.println("Role:"+role);
}
}
}
}
return result;
}

JAASRealm和Jboss(CMA) Container Manager Authentication

这是为了结合JAAS和CMA两者的有点提出的接口。
在http://www.jboss.org/file-access/default/members/jbossweb/freezone/docs/2.1.0/realm-howto.html#JAASRealm,描述了相关配置
web.xml

<Realm className="org.jboss.web.tomcat.security.JBossSecurityMgrRealm"
certificatePrincipal="org.jboss.security.auth.certs.SubjectDNMapping"
allRolesMode="authOnly"
debug="99"
/>


其他配置同JAAS标准配置一样,需要在web.xml,login-config.xml和LoginModule中调用同一个appName

但是注意,在这个LoginModule你必须自己保存用户的验证信息。
It is the responsibility of your login module to create and save User and Role objects representing Principals for the user

下列代码就是Jboss实现的:org.jboss.web.tomcat.security.login.WebAuthentication


/*
* JBoss, Home of Professional Open Source
* Copyright 2007, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.web.tomcat.security.login;

import java.security.Principal;
import java.security.cert.X509Certificate;

import javax.naming.NamingException;

import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
import org.apache.catalina.connector.Request;
import org.jboss.web.tomcat.security.SecurityAssociationValve;

//$Id$

/**
* JBAS-4077: Programmatic Web Login
* @author Anil.Saldhana@redhat.com
* @since Mar 12, 2007
* @version $Revision$
*/
public class WebAuthentication
{
private static final String AUTH_TYPE = "PROGRAMMATIC_WEB_LOGIN";
public WebAuthentication()
{
}

/**
* Login an user via the CLIENT-CERT method
* @param certs X509 certificates
* @return Authenticated User Principal
*/
public boolean login(X509Certificate[] certs)
{
//Get the active request
Request request = (Request) SecurityAssociationValve.activeRequest.get();
if(request == null)
throw new IllegalStateException("request is null");
Principal p = request.getContext().getRealm().authenticate(certs);
if(p != null)
{
register(request,p, null, null);
}
return p!= null;
}

/**
* Login an user via the BASIC, FORM, DIGEST methods
* @param username
* @param credential
* @return
* @throws NamingException
*/
public boolean login(String username, Object credential)
{
//Get the active request
Request request = (Request) SecurityAssociationValve.activeRequest.get();
if(request == null)
throw new IllegalStateException("request is null");

Principal p = null;
if(credential instanceof String)
{
p = request.getContext().getRealm().authenticate(username, (String)credential);
}
else if (credential instanceof byte[])
{
p = request.getContext().getRealm().authenticate(username, (byte[])credential);
}
if(p != null)
{
register(request,p, username, credential);
}
return p != null;
}

/**
* Log the user out
*
*/
public void logout()
{
//Get the active request
Request request = (Request) SecurityAssociationValve.activeRequest.get();
if(request == null)
throw new IllegalStateException("request is null");
unregister(request);
}

/**
* Register the principal with the request, session etc just the way AuthenticatorBase does
* @param request Catalina Request
* @param principal User Principal generated via authentication
* @param username username passed by the user (null for client-cert)
* @param credential Password (null for client-cert and digest)
*/
protected void register(Request request, Principal principal, String username, Object password)
{
request.setAuthType(AUTH_TYPE);
request.setUserPrincipal(principal);

//Cache the authentication principal in the session
Session session = request.getSessionInternal(false);
if(session != null)
{
session.setAuthType(AUTH_TYPE);
session.setPrincipal(principal);
if (username != null)
session.setNote(Constants.SESS_USERNAME_NOTE, username);
else
session.removeNote(Constants.SESS_USERNAME_NOTE);
if (password != null)
session.setNote(Constants.SESS_PASSWORD_NOTE, getPasswordAsString(password));
else
session.removeNote(Constants.SESS_PASSWORD_NOTE);
}
}

/**
* Log the user out
* @param request
*/
protected void unregister(Request request)
{
request.setAuthType(null);
request.setUserPrincipal(null);

//Cache the authentication principal in the session
Session session = request.getSessionInternal(false);
if(session != null)
{
session.setAuthType(null);
session.setPrincipal(null);
session.removeNote(Constants.SESS_USERNAME_NOTE);
session.removeNote(Constants.SESS_PASSWORD_NOTE);
}
}

private String getPasswordAsString(Object cred)
{
String p = null;

if(cred instanceof String)
{
p = (String)cred;
}
else if(cred instanceof byte[])
{
p = new String((byte[])cred);
}
return p;
}
}

星期三, 九月 10, 2008

JBOSS JAAS和tomcat j_security_check CMS关系(之二)

Jboss 的 WebAuthentication的login方法到底做了什么工作?将JAAS和tomcat container链接了起来?
这个要查看代码:

http://www.javakey.net/source/jboss/4.x/org/jboss/web/tomcat/security/login/WebAuthentication.java.html

从这里可以看到,如何从tomcat中获取当前激活的
 org.apache.catalina.connector.Request(http://www.docjar.com/html/api/org/apache/catalina/connector/Request.java.html)
的后门方法

Request request = (Request) SecurityAssociationValve.activeRequest.get();

这个方式是非常cool的
.这里实际调用了Request上下文的RealM的
authenticate多元方法.
这个方法是在tomcat web.xml里通过来定义的。
比如:jboss 4.2.3GA. server\default\deploy\jboss-web.deployer\server.xml
里定义:
<realm classname="org.jboss.web.tomcat.security.JBossSecurityMgrRealm" certificateprincipal="org.jboss.security.auth.certs.SubjectDNMapping" allrolesmode="authOnly">

Jboss相关类源代码:http://www.javakey.net/source/jboss/4.x/allClasses.html
整个工作流程:
JAASRealm authenticates the user and creates a GenericPrincipal with
userPrincipal set to some principal returned by LoginModule.

Later RealmBase.hasResourcePermission() calls request.getUserPrincipal()
to recover authenticated user principal

Request.getUserPrincipal() checks if the principal is instanceof
GenericPrincipal, and if it is, it returns its userPrincipal.

RealmBase.hasRole() checks if the principal is instanceof GenericPrincipal
and if not it fails immediately.

Note: previous versions of JAASRealm had their own hasRole() implementation.

Note: request.isUserInRole() is not getting userPrincipal from
GenericPrincipal when calling realm.hasRole() and this one seems to

work.


星期六, 九月 06, 2008

JBOSS JAAS和tomcat j_security_check CMS关系

JAAS是JAVA强大的安全框架模型,JBOSS 对其的支持也是完全和强劲的。

但JAAS总体来说是基于组件的AAA体系(Authentication(验证) Authorization(授权) Accounting(审计)).

Web应用中,往往是基于角色的安全控制(RBAC Role-Based Access Control)比较多,往往授权关系是树形的和矩阵性的复杂关系。

tomcat实现了一个容器类的范围内的验证系统,也就是所谓的CMS(Container Managed Security),这种方式的好处是比较符合要么全有,

要么全无的安全认证,粒度不如JAAS控制的细致。web.xml通过

<security-constraint>
  <web-resource-collection>

<auth-constraint>

三个标志来控制不同角色访问的内容范围.

JBOSS中支持这两种验证方式,但是就出现了一个比较严重的问题。

两种方式是独立的,有各自的LoginContext上下文,必须通过程序的方式在JAAS模块中对Container来进行验证。JBOSS 4.2.3通过class:

org.jboss.web.tomcat.security.login.WebAuthentication;

来实现了这两者对接。综合了两种方式的有点。

另外一种常见的技术是用login proxy的方式来手工调用jsp让内置的j_security_check起作用来综合JAAS和CMS的有点,这里也加入简单说明

在servlet或JSF的backing bean的action对应的方法中,加入如下语句:
String url="/login.jsp"

        RequestDispatcher  dispatcher = request.getRequestDispatcher(url);
        dispatcher.forward(request, response);
login.jsp包含如下内容:

<html>
    <head>
      <meta
http-equiv="Content-Type"
content="text/html; charset=windows-1252"/>
<title>Logging in</title>
    </head>
      <body
onload="document.forms[0].submit()">
      <form
method="post" action="j_security_check">
<input type="hidden" name="j_username"
value="${param.j_username}"/>
<input type="hidden" name="j_password"
value="${param.j_password}"/>
      </form>
    </body>
  </html>

上面的j_username和j_password都是从上页用户输入后传递过来的

上述的方式比较简陋,所以下面就是程序完全控制的方式。

以一个JSF的完全应用为例子

首先编写:login.jsp

<?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="2.0"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
>
<jsp:directive.page  contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" />
<html>
    <head>
    <meta http-equiv="Content-Type"
            content="text/html; charset=UTF-8"></meta>
        <title>Login Wizard</title>
    </head>
    <body>

<f:view >
        <h:form >
            <h:outputLabel  value="#{SysRes.username}"/><h:inputText value="#{loginManager.userID}" id="j_username" /><br/>
            <h:outputLabel value="#{SysRes.password}"/><h:inputSecret value="#{loginManager.password}" id="j_password" /><br/>
            <h:commandButton id="checkout" value="${SysRes.OK}" action="#{loginManager.loginAction}" />   
        </h:form>
</f:view>
    </body>   
</html> 
</jsp:root>

 

其次配置faces-config.xml这个是默认的配置文件,可以通过在web.xml中定义改变之,后面举例

<managed-bean>
<managed-bean-name>loginManager</managed-bean-name>
<managed-bean-class>org.security.login.LoginManager</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

 

三:再看managed-bean,代码如下

package org.security.login;

import java.security.Principal;
import java.util.Set;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.security.auth.login.LoginContext;
import javax.security.auth.callback.CallbackHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import javax.faces.event.ActionEvent;

import javax.security.auth.Subject ;
import javax.servlet.RequestDispatcher;

import org.jboss.security.SimplePrincipal;
import org.jboss.web.tomcat.security.login.WebAuthentication;
import org.security.login.jass.*;

public class LoginManager
{
       private String _uid = "";
        private String _pwd = "";
         private String requestURI="";
        public String getUserID() { return _uid; }
        public void setUserID(String uid) { _uid = uid; }
        public String getPassword() { return _pwd; }
        public void setPassword(String pwd) { _pwd = pwd; }
        public String loginAction() throws Exception
        {
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response =
            (HttpServletResponse) context.getExternalContext().getResponse();
            HttpServletRequest request =
                (HttpServletRequest) context.getExternalContext().getRequest();           
        String securityDomain = "seamAC";//安全区域,在logic-config.xml中定义
        CallbackHandler callbackHandler = new StandardCallbackHandler(getUserID(),getPassword());
        try
        {
            LoginContext lc =
            new LoginContext( securityDomain,
                      callbackHandler );
            lc.login();
            WebAuthentication pwl = new WebAuthentication();
            boolean flag=pwl.login(getUserID(),getPassword());
            System.out.println("WebAuthentication is?"+flag);
            System.out.println("User Principal="+request.getUserPrincipal());
        }
        catch ( Exception e )
        {
            e.printStackTrace();
//            FacesContext context = FacesContext.getCurrentInstance();
//            HttpServletResponse response =
//            (HttpServletResponse) context.getExternalContext().getResponse();
//            response.sendError(100);
//            context.responseComplete();
           // FacesContext.getCurrentInstance().addMessage("checkout",new FacesMessage(e.getMessage()));
//            throw e;
            return "loginFail";
        }
        String url=request.getHeader("referer");
        String cUrl=request.getRequestURI();
        //再次获取
        request =(HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();       
        System.out.println("referer:"+url+" curl:"+cUrl);
        System.out.println("用户角色sysAdmin:"+request.isUserInRole("sysAdmin"));
        System.out.println("用户角色guest:"+request.isUserInRole("guest"));

//        Principal principal = new SimplePrincipal(getUserID());
//        ObjectName jaasMgr = new ObjectName("jboss.security:service=JaasSecurityManager");
//        Object[] params = { securityDomain, principal };
//        String[] signature = { "java.lang.String", Principal.class.getName() };
//        MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
//        server.invoke(jaasMgr, "flushAuthenticationCache", params, signature);
        if(!(url==null ||url.trim().equals("")))
        {   
            String host=request.getHeader("host");
            String cpath=request.getContextPath();
            url=url.replace("http://"+host+cpath,"");
            System.out.println("url now:"+url+" cpath:"+cpath);           
                response.sendRedirect(cpath+"/"+url);   
        //use j_security_check proxy tech,j_username,j_password
//        RequestDispatcher  dispatcher = request.getRequestDispatcher(url);
//        dispatcher.forward(request, response);
        }       
        return "loginPass";   
        }
        public void logout(){
            FacesContext fc = javax.faces.context.FacesContext.getCurrentInstance();
            ((HttpSession)fc.getExternalContext().getSession(false)).invalidate();
            Application ap = fc.getApplication();
            NavigationHandler nh = ap.getNavigationHandler();
            nh.handleNavigation(fc,null,"logout");
        }

}

 

四:配置web.xml 加入受保护的资源

<!-- 安全部分的配置 -->
<security-constraint>
  <web-resource-collection>
   <web-resource-name>Secure Pages</web-resource-name>
   <url-pattern>/Genesis/*</url-pattern>
   <url-pattern>/Guest/*</url-pattern>  
   <http-method>GET</http-method>
   <http-method>POST</http-method>
   <!-- http-method>HEAD</http-method>
   <http-method>PUT</http-method>
   <http-method>OPTIONS</http-method>
   <http-method>TRACE</http-method>
   <http-method>DELETE</http-method -->
  </web-resource-collection>
<!-- only Admin role can access -->
  <auth-constraint>
<role-name>sysAdmin</role-name>
  </auth-constraint>

</security-constraint>

<!-- 登录验证方式 -->
<login-config>
  <auth-method>FORM</auth-method>
  <realm-name>seamAC</realm-name>
  <form-login-config>
   <form-login-page>/Login.jsp</form-login-page>
   <form-error-page>/Login.jsp</form-error-page>
  </form-login-config>
</login-config>
<!-- Declare all Role List -->
<security-role>
  <role-name>sysAdmin</role-name>
</security-role>
  <security-role>
  <role-name>sysGuest</role-name> 
</security-role>

五:配置jboss相关部分.使用Jboss 4.2.3 GA JDK1.6 update 10
   JAAS部分:conf/login-config.xml,注意seamAC就是LoginManager class中的login方法中引用的,Realm名字.

<!--JAAS  -->
    <application-policy name = "seamAC">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule"
             flag = "required">
             <module-option name = "unauthenticatedIdentity">guest</module-option>
             <module-option name = "dsJndiName">java:/SecMasterDS</module-option>
             <module-option name = "principalsQuery">select password from sysUser where userid=? </module-option>
             <module-option name = "rolesQuery">SELECT A.roleID as Role,'Roles' FROM sysRoles A,UserRoles B WHERE A.roleID=B.roleID AND B.userId=?</module-option>
             <module-option name = "debug">true</module-option>
<!--Password is md5 encrypt-->
                        <module-option name="hashAlgorithm">MD5</module-option>
            <module-option name ="hashEncoding">HEX</module-option>
          </login-module>
       </authentication>
    </application-policy>

注意:rolesQuery部分,根据Jboss的class org/jboss/security/auth/spi/DatabaseServerLoginModule.java中有关角色部分的说明,必须有一个roleGroup的字段值为Roles,否则出现用户没有角色的错误,小心注意,这是很愚蠢的假定,往往配置了很久,不能工作,就是这些小地方。

  141   /** Overriden by subclasses to return the Groups that correspond to the
142   to the role sets assigned to the user. Subclasses should create at
143   least a Group named "Roles" that contains the roles assigned to the user.
144   A second common group is "CallerPrincipal" that provides the application
145   identity of the user rather than the security domain identity.
146   @return Group[] containing the sets of roles
147   */

数据库部分:deploy/mysql-ds.xml(使用MYSQL 5.1),注意SecMasterDS



<local-tx-datasource>
   <jndi-name>SecMasterDS</jndi-name>
   <connection-url>jdbc:mysql://localhost:3306/gate?useUnicode=TRUE</connection-url>
   <driver-class>com.mysql.jdbc.Driver</driver-class>
   <user-name>root</user-name>
   <password></password>
   <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
   <metadata>
      <type-mapping>mySQL</type-mapping>
   </metadata>
</local-tx-datasource>

 


支持,繁琐的配置终于可以工作了,访问一个目录,然后经过验证,显示出来内容,实在是非常惬意的事情。更加人性化的界面,比如不具有权限的人向访问一个特定角色的资源,可以在web.xml中截获403错误来做到:



< error-page>
  <error-code>403</error-code>
  <location>/roleerror.jsp</location>
</error-page>

JBOSS JAAS 同JSF 相关问题

如果出现验证后出现,isUserInRole返回false的情况
首先打开
conf/jboss-log4j.xml 的debug.


http://wiki.jboss.org/wiki/SecurityFAQ

<!--Debug log login sql -->
<category name="org.jboss.security">
<priority value="TRACE" class="org.jboss.logging.XLevel"/>
</category>
<category name="org.jboss.web.tomcat.security">
<priority value="TRACE" class="org.jboss.logging.XLevel"/>
</category>
<category name="org.apache.catalina">
<priority value="DEBUG"/>
</category>

星期五, 九月 05, 2008

JSF 或JSP EL(Express Language)中的变量

在JSF和JSP中,EL引用一个变量,语法如下#{class.fieldName}或${class.fieldName}
这里fieldName必须是首字母小写的,但对应的class的方法名为getFieldName()
这种奇怪的语法是来自类 java.beans.PropertyDescriptor 的构造函数规定的
PropertyDescriptor

public PropertyDescriptor(String propertyName,
Class beanClass) throws IntrospectionException

为某特性构造 PropertyDescriptor ,它通过拥有 getFoo 和 setFoo 访问者来遵循标准 Java 约定。因此若参数名是“fred”,则假定读程序方法是“getFred”并且写程序方法是“setFred”。注意特性名应以小写字符开始, 它将在方法名中被大写化。

Note that the property name should start with a lower case character, which will be capitalized in the method names.