星期一, 五月 31, 2004

如何在Linux或Unix下,没有启动X Server 使用Java图形库

J2sdk 1.4支持一种所谓的"headless无头"的图形模式.
我们运行在Unix类操作系统下,在X Server没有启动的时候,很多图形库类无法使用,因为这些类需要获得图形设备的一些具体参数,比如dpi,color depth,raster等,在Linux下运行Java application Server经常是不启动X server的,在这种情况下如果需要使用图形类Class.需要在启动的命令行加入以下参数


-Djava.awt.headless=true


JAVA_OPTS=$JAVA_OPTS: -Djava.awt.headless=true

重新启动Application Server如Tomcat,就可以在Servlet中使用这些图形类了.

public BufferedImage DisplayTextPicture(String willtext)
{
int width = 48;
int height = 48;
float size = 8.0f;
int StringH = 8;
BufferedImage buffer = new BufferedImage(width,
height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 =(Graphics2D)buffer.getGraphics();
Font font = new Font("serif", Font.BOLD, StringH);
font = font.deriveFont(size);
FontRenderContext fc = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(willtext,
fc);
width = (int) bounds.getWidth();
height = (int) bounds.getHeight() * 2;
buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
g2 = (Graphics2D)buffer.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(Color.white);
g2.fillRect(0, 0, width, height);
g2.setColor(Color.red);
String[] tem = willtext.split("\n");
for (int i = 0; i < tem.length; i++)
g2.drawString(tem[i], 0,
(int) - bounds.getY() + i * StringH);
return buffer;
}
public void Display2Servlet(String text,OutputStream os)
{
OutputStream sos=os;

try
{

boolean flag= ImageIO.write(DisplayTextPicture(text), "png", sos);
if(!flag){logger.log(Level.WARNING,"not success");}
sos.flush();
sos.close();
}catch(Exception e)
{
logger.log(Level.WARNING,e.getMessage());
return;
}
}
}

注意:通过 System.setProperty("java.awt.headless", "true");来改变GraphicsEnvirmont()为"无头"模式,可能是不起作用的,所以最好在命令行启动时候加入.

如何让MYSQL for window 建立的表格名称保持大小写敏感.

在启动mysqld.exe的时候加入以下参数,就可以建立起大小写敏感的表格.
mysqld.exe -O lower_case_table_names=0

星期日, 五月 30, 2004

Java 如何在一个类中得知被哪个class的哪个方法调用。

import java.util.*;
import java.io.*;

public class mytest
{
public void inferCaller() {
// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();
// First, search back to a method in the Logger class.
int ix = 0;


while (ix < stack.length) {
StackTraceElement frame = stack[ix];
String cname = frame.getClassName();

if (cname.equals(getClass().getName())) //当前的类正在被call的method
{
System.out.println("ix="+ix);
break;
}
System.out.println(cname+"类:"+frame.getMethodName());
ix++;
}
//ix=0;
// Now search for the first frame before the "Logger" class.
while (ix < stack.length) {
StackTraceElement frame = stack[ix];
String cname = frame.getClassName();
if (!cname.equals(getClass().getName()))
{
// We've found the relevant frame.
//在当前类之前的类是调用自己的类.
System.out.println(cname+":"+frame.getMethodName());
}

ix++;
}
}
}

星期五, 五月 28, 2004

jboss Transaction marked for rollback, possibly a timeout错误分析

在一个Stateless Session Bean中完成以下任务.
1.在A表中建立一个记录.
2.在B表中建立一个记录.
思路:
在SessbionBean中分别调用两个table对应的entityBean的remote方法.
出现错误.

修正:在一个Entitybean的Create方法中完成插入两条记录.

MBSC 多字节字符传递规则.(JSP->Servlet/JSP->JSP)

多字节字符(比如汉字)在JSP之间传递,和JSP->Servlet之间传递的规则不同.

1.JSP->JSP
汉字通过URL?a= &b= 方式在JSP之间传递的时候,必须将汉字java.net.URLEncoder.encode((String)request.getAttribute("academicPeriod"),"gb2312"),来编码,汉字的字符是要根据实际数据显示渲染的charset来定.

2.JSP->Servlet
汉字从JSP->Servlet必须编码为本地字符编码,不能为UTF-8字符.如果为UTF-8字符必须通过new String(STR.getBytes("UTF-8","iso-8859-1")来转换.

3.如果页面导航逻辑没有冲突,可以考虑把要传递的内容设置在bean或request.setAttribute().

星期三, 五月 19, 2004

DHTML Table Widgets/XSLT 功能.非常好.收集起来

DHTML Table Widgets

在XML得到一组唯一的属性值

Top XML : User Contributions
preceding-sibling", like select="/publish/book[not(year = preceding-sibling::book/year)]

在XML得到一组唯一的属性值

星期二, 五月 18, 2004

如何利用JSTL XML功能来把JDBC得到的数据转为HTML显示?

Solution:
利用<x:parse var="xmldata">
<%
...Java Code.从jdbc得到数据.通过out.println输出.
%>
</x:parse>
<c:import var="xslt" url="/WEB-INF/xml/adsearchEmployee.xsl"/>
<x:transform xml="${xmldata}" xslt="${xslt}"/>
这样就得到了经过XSLT格式化的数据,Cool啊.

在JSTL 1.0中的XML如何支持Unicode?

<c:import url="/WEB-INF/xml/employeetest.xml" var="xml" charEncoding="UTF-8"/>
<c:import url="/WEB-INF/xml/adsearchEmployee.xsl" var="xslt"/>
<x:transform xml="${xml}" xslt="${xslt}"/>

通过制定charEncoding来输入Unicode的XML数据文件.

星期六, 五月 15, 2004

groovy 和james真是两个好东西。

http://groovy.codehaus.org/ 推出了1.0 beta 5.汉字问题似乎解决了。
http://james.apache.org 最棒的纯java Email 平台。很棒啊。看看稳定性。

星期五, 五月 14, 2004

如何在Javascript压缩(trim)空格

String.prototype.trim = _trim;

/**
* remove White Space from start and/or end of given string
* White Space is defined as:
* - Space
* - Carriage Return
* - newline
* - form feed
* - TABs
* - Vertical TABs
**/

function _trim ( )
{
// / open search
// ^ beginning of string
// \s find White Space, space, TAB and Carriage Returns
// + one or more
// | logical OR
// \s find White Space, space, TAB and Carriage Returns
// $ at end of string
// / close search
// g global search

return this.replace(/^\s+|\s+$/g, "");
}

// Test this
var strDemo = ' something ';
var strStrip = strDemo.trim();

alert ( '|' + strDemo + '|\n' + '|' + strStrip + '|');

完整的email-post 测试

希望Blogger支持的Email-Post好用.
能正常支持汉字啊(最低要求了).

星期二, 五月 11, 2004

常用单词缩写及其他

MTBF ? Mean Time Between Failures
The Architect’s Role
? The architect:
Visualizes the behavior of the system
Creates the blueprint for the system
Defines the way in which the elements of
the system work together
Distinguishes between functional and nonfunctional
system requirements
Is responsible for integrating non-functional
requirements into the system

星期五, 五月 07, 2004

使用Servlet动态生成文本图象.

/**
*使用方法在HTML使用<img src="http://servletname"
*/
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Color;
import java.awt.Font;
import javax.imageio.ImageIO;
import java.awt.font.*;
import java.awt.geom.*;

public class DisplayPicture extends HttpServlet {
private static final String text="不存在图片";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OutputStream sos=response.getOutputStream();
String storedirectory=getServletConfig().getInitParameter("FileDirectory");
if(storedirectory==null || storedirectory=="")
{
DisplayTextPicture("web.xml??");
return;
}

File pf=new File(storedirectory+"\\2.jpg");
FileInputStream fis;
if(!pf.exists())
{
response.setContentType("image/png");
ImageIO.write(DisplayTextPicture(text+"\n"+storedirectory),"png",sos);
sos.close();
return;
}
//set contenttype
response.setContentType("image/"+getFileType(pf));
fis = new FileInputStream(pf);
byte[] input=new byte[512];
int count=0;
while(fis.read(input) !=-1)
{
sos.write(input);
}
fis.close();
sos.flush();
sos.close();
}

public String getFileType(File pf)
{
String type="gif";
if(pf.getName().toLowerCase().endsWith(".png"))
{
type = "png";
}
if(pf.getName().toLowerCase().endsWith(".gif"))
{
type = "gif";
}
if(pf.getName().toLowerCase().endsWith(".jpg"))
{
type = "jpg";
}
if(pf.getName().toLowerCase().endsWith(".bmp"))
{
type = "bmp";
}
return type;
}
/**
*DisplayTextPicture支持多行显示图片,分割符号为\n
**/
public BufferedImage DisplayTextPicture(String willtext)
{
int width=48;
int height=48;
float size=20.0f;
int StringH=20;
BufferedImage buffer =new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g2=buffer.createGraphics();
Font font = new Font("serif", Font.BOLD, StringH);
font = font.deriveFont(size);
FontRenderContext fc = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(willtext,fc);
width = (int) bounds.getWidth();
height = (int) bounds.getHeight()*2;

buffer =new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
g2=buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(Color.white);
g2.fillRect(0,0,width,height);
g2.setColor(Color.blue);
String[] tem=willtext.split("\n");
for(int i=0;i<tem.length;i++)
g2.drawString(tem[i],0,(int)-bounds.getY()+i*StringH);
return buffer;
}
}

星期四, 五月 06, 2004

IE 层如何显示Layer.

document.all.contentLayer.style.visibility = "visible";
<div id="contentLayer" style="position:absolute; width:202px; height:52px; z-index:1; top: 242px; visibility: visible;background-image:url(c://2.jpg)" >

星期五, 四月 30, 2004

UTR#17: Character Encoding Model/要了解Java 最新的Unicode支持问题,必须了解的ABC.

UTR#17: Character Encoding Model: "Character Encoding Model"

Java Platform补充字符(supplementary characters)在j2se 1.5

Java 使用固定宽度的16bit的来表示char字符,所以Java可以处理多达65536个字符.
但是Unicode 现在可以支持1,112,064个字符.
中国现在支持gb18030,台湾支持:CNS-11643字符.
有关J2SE 1.5如何支持这些字符参看http://java.sun.com/developer/technicalArticles/Intl/Supplementary/

Support for supplementary characters is likely to also become a common business requirement in East Asian markets. Government applications are going to require them in order to correctly represent names that include rare Chinese characters. Publishing applications may need them in order to represent the full set of historical and variant characters. The Chinese government requires support for GB18030, a character encoding that encodes the entire Unicode character set, and so includes supplementary characters if Unicode version 3.1 or later is assumed. The Taiwanese standard CNS-11643 includes numerous characters that have been included in Unicode 3.1 as supplementary characters. The Hong Kong government defined a collection of characters that are needed for Cantonese, and some of these characters are supplementary characters in Unicode. Finally, some vendors in Japan are planning to use the large private use area in the supplementary character space for more than 50,000 kanji character variants in order to migrate from their proprietary systems to solutions based on the Java platform.

如何用Javascript判断上传文件的大小及是否图片.小窍门.

代码使用与IE 6.FireFox需要修改关于层的访问代码.

<html>
<head>
<title>
UploadFile
</title>
<script>
isimage=false;
function displayimg()
{
isimage=false;//判断文件是否图片的标志
var tmpstr=document.mainform.name.value;
if(tmpstr!=null || tmpstr!='')
document.all.contentLayer.document.user.src=tmpstr;
if(isimage==false)alert("文件不是图片");
}
function checksize()
{
isimage=true; //如果文件不是图片,onload的时候就不会调用这个函数
var limitsize=3072;
/*
if (dumy.fileSize>limitsize)
{
mainform.reset();
alert("fileSize should be less than "+limitsize + " bytes");
}
alert("width"+dumy.width+" height"+dumy.height);
*/
}

</script>
</head>
<body bgcolor>
上传:<strong><font size=+1></h1></font></strong>的照片
<FORM name="mainform" action='' ENCTYPE='multipart/form-data' method='POST' >
<INPUT TYPE='file' NAME='name' size="40" maxlength="255" onchange="displayimg();">
<INPUT TYPE='submit' VALUE='start...' >
</FORM>
<hr>
<div id="contentLayer">
Preview:<img id ="dumy" name=user src="../IMAGES/image1/person.GIF" onload="checksize();">
</div>

</body>
</html>


星期三, 四月 28, 2004

TheServerSide.com - TSS Featured Entry

TheServerSide.com - TSS Featured Entry

这里有些经验非常好.paste过来.留着
To get JVM Metrics, i.e. Heap/Garbage Collection stats, add the following to your java command:
-verbose:gc -XX:+PrintGCTimeStamps
The default JVM heap size is 64MB, which is likely too small for most webapps. You can change the default min/max by adding the following to your JAVA_OPTS (or CATALINA_OPTS) environment variable:
-Xms128m -Xmx256m
Young generation sizing - let the JVM do it by specifying:
-XX:+AggressiveHeap
Connection Pool Size: 15-20 is more than enough to handle an average application. Never have more connections than threads that can use them. For MySQL, the pool size is resource throttling, not saving connection setup time. Click here for a chart that shows the number of connections used doesn't change between a pool size of 10 and 20.
Connection/J 3.0 is 40-400% faster than 2.0.14 depending on the situation - use the latest driver!
Finally, here is the really good stuff. Below are a number of parameters you can add to your JDBC URL (like autoReconnect=true) to get information from MySQL's JDBC Driver:

Logging Slow Queries: logSlowQueries=true and slowQueryThresholdMillis=n (2000 default)
Reporting Performance Metrics: gatherPerfMetrics=true and reportMetricsIntervalMillis=n (30s default)
Usage Advisor (abandoned objects, un-used columns in selects, incomplete ResultSet traversal): useUsageAdvisor=true

星期二, 四月 27, 2004

JDBC Rowset 1.0终于到了FCS阶段了。

使用了以下,很好,preview 2中发现的两个bug都修正了。尤其是愚蠢的Thread.currentTread().getSystemClassLoader()错误。

干的好。
非常漂亮。