2009年3月23日 星期一

Linux 下jdk6 和tomcat6的安装配置

linux 下安装jdk6

1、到 sun 网站下载 jdk rpm 软件包 jdk-6u11-linux-i586-rpm.bin;
2、在/usr下建立一个java目录,拷贝 jdk-6u11-linux-i586-rpm.bin 到 java目录;
3、给 jdk-6u11-linux-i586-rpm.bin 加上执行权限,
命令:chmod a+x jdk-6u11-linux-i586-rpm.bin
4、执行: ./jdk-6u11-linux-i586-rpm.bin,得到 jdk-6u11-linux-i586.rpm
5、执行: rmp -ivh jdk-6u11-linux-i586.rpm
6、至此,安装成功,设置环境变量;
7、设置linux的全局环境变量,需要root权限,可在命令行下输入su 切换到root用户;
8、修改etc/profile 文件,在最后加入如下代码:

#set java environment
export JAVA_HOME=/usr/java/jdk1.6.0_11
export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH
export CLASSPATH=$CLASSPATH:$JAVA_HOME/lib:$JAVA_HOME/jre/lib

linux 下安装tomcat6
1、到apache网站下载tomcat文件 apache-tomcat-6.0.18.tar.gz;
2、在/usr目录下建立tomcat目录;
3、解压apache-tomcat-6.0.18.tar.gz 文件,
命令 tar -xvzf apache-tomcat-6.0.18.tar.gz
4、修改etc/profile 文件,在最后加入如下代码:
export TOMCAT_HOME=/usr/tomcat
5、如果需要使用manager功能,需修改Tomcat_HOME/conf/tomcat-users.xml 文件,加入


6、启动tomcat,命令行方式改变到安装目录,运行
./catalina.sh run 命令 启动tomcat 有控制台
./catalina.sh start 命令 启动tomcat 无控制台
./startup.sh 启动tomcat 无控制台
7、关闭tomcat,执行
./shutdown.sh 或者 ./catalina.sh stop
8、测试tomcat安装是否成功
http://localhost:8080

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

JVM內存的設置的原理

默認的java虛擬機的大小比較小,在對大數據進行處理時java就會報錯:java.lang.OutOfMemoryError。

設置jvm內存的方法,對於單獨的.class,可以用下面的方法對Test運行時的jvm內存進行設置。
java -Xms64m -Xmx256m Test

-Xms是設置內存初始化的大小
-Xmx是設置最大能夠使用內存的大小(最好不要超過物理內存大小)

在weblogic中,可以在startweblogic.cmd中對每個domain虛擬內存的大小進行設置,默認的設置是在commEnv.cmd裡面。

JVM內存的調優

1. Heap設定與垃圾回收
Java Heap分為3個區,Young,Old和Permanent。 Young保存剛實例化的對象。當該區被填滿時,GC會將對象移到Old區。 Permanent區則負責保存反射對象,本文不討論該區。
JVM的Heap分配可以使用-X參數設定,
-Xms初始Heap大小
-Xmx java heap最大值
-Xmn young generation的heap大小

JVM有2個GC線程。
第一個線程負責回收Heap的Young區。
第二個線程在Heap不足時,遍歷Heap,將Young區升級為Older區。 Older區的大小等於-Xmx減去-Xmn,不能將-Xms的值設的過大,因為第二個線程被迫運行會降低JVM的性能。
為什麼一些程序頻繁發生GC?有如下原因:
程序內調用了System.gc()或Runtime.gc()。
一些中間件軟件調用自己的GC方法,此時需要設置參數禁止這些GC。
Java的Heap太小,一般默認的Heap值都很小。
頻繁實例化對象,Release對象。此時盡量保存並重用對象,例如使用StringBuffer()和String()。
如果你發現每次GC後,Heap的剩餘空間會是總空間的50%,這表示你的Heap處於健康狀態。許多Server端的Java程序每次GC後最好能有65%的剩餘空間。

經驗之談:
1. Server端JVM最好將-Xms和-Xmx設為相同值。為了優化GC,最好讓-Xmn值約等於-Xmx的1/3[2]。
2.一個GUI程序最好是每10到20秒間運行一次GC,每次在半秒之內完成[2]。
注意:
1.增加Heap的大小雖然會降低GC的頻率,但也增加了每次GC的時間。並且GC運行時,所有的用戶線程將暫停,也就是GC期間,Java應用程序不做任何工作。
2. Heap大小並不決定進程的內存使用量。進程的內存使用量要大於-Xmx定義的值,因為Java為其他任務分配內存,例如每個線程的Stack等。

2. Stack的設定
每個線程都有他自己的Stack。
-Xss每個線程的Stack大小

Stack的大小限制著線程的數量。如果Stack過大就好導致內存溢漏。 -Xss參數決定Stack大小,例如-Xss1024K。如果Stack太小,也會導致Stack溢漏。

3.硬件環境
硬件環境也影響GC的效率,例如機器的種類,內存,swap空間,和CPU的數量。
如果你的程序需要頻繁創建很多transient對象,會導致JVM頻繁GC。這種情況你可以增加機器的內存,來減少Swap空間的使用[2]。

4.4種GC
第一種為單線程GC,也是默認的GC。 ,該GC適用於單CPU機器。

第二種為Throughput GC,是多線程的GC,適用於多CPU,使用大量線程的程序。第二種GC與第一種GC相似,不同在於GC在收集Young區是多線程的,但在Old區和第一種一樣,仍然採用單線程。 -XX:+UseParallelGC參數啟動該GC。

第三種為Concurrent Low Pause GC,類似於第一種,適用於多CPU,並要求縮短因GC造成程序停滯的時間。這種GC可以在Old區的回收同時,運行應用程序。 -XX:+UseConcMarkSweepGC參數啟動該GC。

第四種為Incremental Low Pause GC,適用於要求縮短因GC造成程序停滯的時間。這種GC可以在Young區回收的同時,回收一部分Old區對象。 -Xincgc參數啟動該GC。
4種GC的具體描述參見[3]。

參考文章:
1. JVM Tuning. http://www.caucho.com/resin-3.0/performance/jvm-tuning.xtp#garbage-collection
2. Performance tuning Java: Tuning steps
http://h21007.www2.hp.com/dspp/tech/tech_TechDocumentDetailPage_IDX/1,1701,1604,00.html
3. Tuning Garbage Collection with the 1.4.2 JavaTM Virtual Machine .
http://java.sun.com/docs/hotspot/gc1.4.2/


C:\>java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:
set search path for bootstrap classes and resources
-Xbootclasspath/a:
append to end of bootstrap class path
-Xbootclasspath/p:
prepend in front of bootstrap class path
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xbatch disable background compilation
-Xms set initial Java heap size
-Xmx set maximum Java heap size
-Xss set java thread stack size
-Xprof output cpu profiling data
-Xrunhprof[:help]|[:

2009年3月20日 星期五

java.lang.OutOfMemoryError: PermGen space及其解決方法

1、PermGen space的全稱是Permanent Generation space,是指記憶體的永久保存區域OutOfMemoryError: PermGen space從表面上看就是記憶體益出,解決方法也一定是加大記憶體。說說為什麼會記憶體益出:這一部分用於存放Class和Meta的資訊,Class在被 Load的時候被放入PermGen space區域,它和和存放Instance的Heap區域不同,GC(Garbage Collection)不會在主程序運行期對PermGen space進行清理,所以如果你的APP會LOAD很多CLASS的話,就很可能出現PermGen space錯誤。這種錯誤常見在web伺服器對JSP進行pre compile的時候。
改正方法:-Xms256m -Xmx256m -XX:MaxNewSize=256m -XX:MaxPermSize=256m

2、在tomcat中redeploy時出現outofmemory的錯誤. 可以有以下幾個方面的原因:

1. 使用了proxool,因為proxool內部包含了一個老版本的cglib.
2. log4j,最好不用,只用common-logging
3. 老版本的cglib,快點更新到最新版。
4. 更新到最新的hibernate3.2

3、這裏以tomcat環境為例,其他WEB伺服器如jboss,weblogic等是同一個道理。

一、java.lang.OutOfMemoryError: PermGen space

PermGen space的全稱是Permanent Generation space,是指記憶體的永久保存區域,這塊記憶體主要是被JVM存放Class和Meta資訊的,Class在被Loader時就會被放到 PermGen space中,它和存放類實例(Instance)的Heap區域不同,GC(Garbage Collection)不會在主程序運行期對PermGen space進行清理,所以如果你的應用中有很多CLASS的話,就很可能出現PermGen space錯誤,這種錯誤常見在web伺服器對JSP進行pre compile的時候。如果你的WEB APP下都用了大量的第三方jar, 其大小超過了jvm默認的大小(4M)那麼就會產生此錯誤資訊了。

解決方法: 手動設置MaxPermSize大小
修改TOMCAT_HOME/bin/catalina.sh
在“echo "Using CATALINA_BASE: $CATALINA_BASE"”上面加入以下行:

JAVA_OPTS="-server -XX:PermSize=64M -XX:MaxPermSize=128m
建議:將相同的第三方jar檔移置到tomcat/shared/lib目錄下,這樣可以達到減少jar 文檔重複佔用記憶體的目的。
二、java.lang.OutOfMemoryError: Java heap space
Heap size 設置
JVM堆的設置是指java程式運行過程中 JVM可以調配使用的記憶體空間的設置.JVM在啟動的時候會自動設置Heap size的值,其初始空間(即-Xms)是實體記憶體的1/64,最大空間(-Xmx)是實體記憶體的1/4。可以利用JVM提供的-Xmn -Xms -Xmx等選項可進行設置。Heap size 的大小是Young Generation 和Tenured Generaion 之和。

提示:在JVM中如果98%的時間是用於GC且可用的Heap size 不足2%的時候將拋出此異常資訊。

提示:Heap Size 最大不要超過可用實體記憶體的80%,一般的要將-Xms和-Xmx選項設置為相同,而-Xmn為1/4的-Xmx值。
解決方法:手動設置Heap size
修改TOMCAT_HOME/bin/catalina.sh
在“echo "Using CATALINA_BASE: $CATALINA_BASE"”上面加入以下行:
JAVA_OPTS="-server -Xms800m -Xmx800m -XX:MaxNewSize=256m"
三、實例,以下給出1G記憶體環境下java jvm 的參數設置參考:
JAVA_OPTS="-server -Xms800m -Xmx800m -XX:PermSize=64M -XX:MaxNewSize=256m -XX:MaxPermSize=128m -Djava.awt.headless=true "

三、相關資料
/show/3/7/20061112220131.htm
/show/3/7/20061112220054.htm
/show/3/7/20061112220201.htm

Source: http://www.soezblog.com/plate/group/web/papermsg.jsp?UI=markcool&GI=47&PI=827

2009年3月19日 星期四

Java 建立由 LDAP AD 認證的機制

環境:
OS : Windows Server 2k3
Domain: mydomain.com
Host : x.x.x.x(此為指定 ip address)

以 Java 程式撰寫 對 LDAP-AD 的認證, 程式碼如下:


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
 /**
     * AD LDAP 登入認證
     *
     * @param ldap_url   like ldap://x.x.x.x:389/DC=mydomain,DC=com
     * @param account
     * @param password
     * @return String[0] array 0 :0 success,1 fail,2 LDAP connect fail,3 unknow
     */
    public String[] LDAP_AUTH_AD(String ldap_url, String account, String password) {
        String[] returnStr = new String[2];
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldap_url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, account+"@mydomain.com");
        env.put(Context.SECURITY_CREDENTIALS, password);

        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
            returnStr[0] = "0";
        } catch (javax.naming.AuthenticationException e) {
            returnStr[0] = "1";

            return returnStr;
        } catch (javax.naming.CommunicationException e) {
            // System.out.println("Can't connect to ldap server!");
            returnStr[0] = "2";

            return returnStr;
        } catch (Exception e) {
            System.out.println("error");
            e.printStackTrace();
            returnStr[0] = "3";

            return returnStr;
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {

                }
            }
        }
    }




From: Polin Wei

Java Filtering 過濾器的使用

Servlet 2.3 規則中最重要的新特性- Filtering , 它相容於 Servlet 2.3 規格的 J2EE 容器(Context)間快速地成為最常被用到的增值特性.

過濾器 (Filtering) 可以在資源被取出前或取出後插手檢查, 以 HTTP 為主的 請求(Request) / 回應(Response) 的中間層伺服器來說, 過濾器 (Filtering) 可以用來:

1. 在請求(Request)的表頭到達資源手中前先看看其中的內容

2. 在請求(Request)的表頭被送達資源時看看其中的內容

3. 提供修改過的請求(Request)被容器(Context)所處理過的資源

4. 在回應(Response)被傳回前, 先行存取並修改

5. 在請求(Request)到逹資源前全部加以終止

過濾器 (Filtering) 為 javax.servlet.Filter 的介面類別, 這類別所該實作的部份有三個方法:

1. doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
這是 過濾器 (Filtering) 的主要方法, 幾乎所有 過濾器 (Filtering) 的工作都在此完成. 在這個方法中需呼叫 chain.doFilter(request, response) 這個方法, 以便將控制傳給下一個過濾器 ( Pass control on to the next filter )

2. init(FilterConfig fConfig)
在 doFilter() 方法被第一次呼叫前設定 FilterConfig 物件. FilterConfig 物件提供 過濾器 (Filtering) 的初始化參數, 並允許它存取相關的 ServletContext.

3. destroy()
當 過濾器 (Filtering) 被帶出服務前, 容器(Context)會呼叫 destroy()

上述所提的 FilterConfig 物件在 init(FilterConfig fConfig) 時會取得, 而 FilterConfig 可以被 過濾器 (Filtering) 用來取得這個 過濾器 (Filtering) 的初始化參數, 文字型名稱, 或正在執行的 ServletContext. 它主要有四個方法:

1. getFilterName()
取得 過濾器 (Filtering) 定義於配置描述檔 web.xml 中的文字型名稱.

2. getInitParameter(String paramName)
取得所指定的初始化參數的字串值. 找不到則回傳 null

3. getInitParameterNames()
取得一個 java.util.Enumeration , 其中含有所有這個實體中所具有的初始化參數的名稱. 這些參數都是在配置描述元 web.xml 中的 定義中所指定的. 若無則回傳 null

4. getServletContext()
取得正在其中執行的 ServletConext . 這個內容通常是在伺服器上的 server.xml 檔中指定.


程式實作:
step 01: 先建立一個 LoggerFilter.java 

package com.demos.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Servlet Filter implementation class LoggerFilter
 */
public class LoggerFilter implements Filter {
    
    protected FilterConfig filterConfig = null;

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
        this.filterConfig = null;
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (filterConfig==null)
            return;

        long bef = System.currentTimeMillis();
        ServletContext context = filterConfig.getServletContext();
        context.log("in LoggerFilter Class");

        // Pass control on to the next filter
        chain.doFilter(request, response);
   
        long aft = System.currentTimeMillis();
        context.log("Request to " + request.getRemoteHost() + "Total time(ms): " + (aft - bef));

    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
        this.filterConfig = fConfig;
    }
}


step 02: 在 web.xml 上加入Filter的參數

    loggerFilter
    com.demos.filter.LoggerFilter


    loggerFilter
    /*


的樣式可以對 URL 或 servlet 來作 Filter:

/*
action



step 03: 在 console 中看的結果如下:
2009/3/18 下午 6:36:30 org.apache.catalina.core.ApplicationContext log
資訊: in LoggerFilter Class
2009/3/18 下午 6:36:31 org.apache.catalina.core.ApplicationContext log
資訊: Request to 127.0.0.1Total time(ms): 234


實際系統上運用 Filtering 可以讓系統在每一個網頁在載入時, 塞入編碼原則為 UTF-8 , 以避免網頁出現亂碼. 程式碼SetCharacterEncodingFilter.java如下:
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
 * @author Craig McClanahan
 * @version $Revision: 1.2 $ $Date: 2004/03/18 16:40:28 $
 */

package com.demos.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacterEncodingFilter implements Filter {


    // ----------------------------------------------------- Instance Variables


    /**
     * The default character encoding to set for requests that pass through
     * this filter.
     */
    protected String encoding = null;


    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    protected FilterConfig filterConfig = null;


    /**
     * Should a character encoding specified by the client be ignored?
     */
    protected boolean ignore = true;


    // --------------------------------------------------------- Public Methods

    /**
     * Take this filter out of service.
     */
    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }


    /**
     * Select and set (if specified) the character encoding to be used to
     * interpret request parameters for this request.
     *
     * @param request The servlet request we are processing
     * @param result The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
    throws IOException, ServletException {

        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }
    // Pass control on to the next filter
        chain.doFilter(request, response);

    }

    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
    public void init(FilterConfig filterConfig) throws ServletException {

    this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;

    }

    // ------------------------------------------------------ Protected Methods
    protected String selectEncoding(ServletRequest request) {
        return (this.encoding);
    }
}


而 web.xml 也要相對的加入

    Set Character Encoding
   
        com.gu.filters.SetCharacterEncodingFilter
   

   
        encoding
        utf-8
   

   
        ignore
        true
   



    Set Character Encoding
    action




From: Polin Wei

2009年3月16日 星期一

How to setup SVN server

  • 先去Subversion的網站抓SVN Server
  • 把SVN加入到環境變數PATH中,如C:\Program Files\Subversion\bin\
  • 選一個目錄,專門用來放許多案子用的,假設為D:\projects
  • 建立你現在要產生的專案repository, 比如要建PostEX專案
    • svnadmin create d:\projects\PostEX
  • 修改權限檔案
    • 到d:\projects\PostEX\conf裡,修改passwd
      • 在[users]裡,加上你們案子要用的帳號和密碼
        • 如: padsmember = padspassword
    • 修改svnserve.conf,如果你不想讓任意路人甲都可以看到你的程式,在[General]中找到一個anon-access,把它改成none
      • anon-access = none
    • 找到一行 password-db = passwd,把前面的井號去掉,這樣前面修改的passwd檔才會有啟用
  • 啟動SVN Server
    • D:\>svnserve -d -r d:\Projects --listen-port 9000
  • 所有要參與計畫的人,都裝上TortoiseSVN
  • 建立一個目錄,用來抓SVN Server上已經有寫的程式 (別人可能之前先傳上去的)
  • 做checkout,把URL of repository的protocol改成SVN
    • 如: svn://pads15.cs.nthu.edu.tw:9000/PostEX
    • 幾個主要的功能
      • checkout剛加入許畫的人,第一次去把檔案抓下來用的
      • update是已經有checkout的人,後來用來抓SVN Server上更新版用的
      • commit 是你做了更新後,要send到SVN Server上用的


Start up SVN Server command:

C:\Program Files\Subversion>
svnserve -d -r "C:\Documents and Settings\user\My Documents\SvnRepository\projects" --listen-port 9000

Source:
http://yoshiblog.blogspot.com
http://blog.roodo.com/jaceju/archives/2150759.html
http://www.blogjava.net/youxia/category/26691.html