<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    java Source

      BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
      14 Posts :: 24 Stories :: 8 Comments :: 0 Trackbacks

    2011年12月4日 #

    去除0.0.0.255和0.0.0.0
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    /**
     * 
    @author justinlei (justinlei@gmail.com)
     * @date Nov 17, 2011
     * 
    @version 1.0
     
    */
    public class InetAddressUtil {
        
    public static void main(String[] args) throws Exception {
            Inet4Address start 
    = (Inet4Address)Inet4Address.getByName("172.20.0.254");
            Inet4Address end 
    = (Inet4Address)Inet4Address.getByName("172.20.10.1");
            List
    <byte[]> list = getRangeIps(null,start.getAddress(), end.getAddress());
            
    for (byte[] bs : list) {
                System.out.println(InetAddress.getByAddress(bs).getHostAddress());
            }
        }
        
        
    public static List<byte[]> getRangeIps(List<byte[]> list,byte[] addrBytes,byte[] endBytes) throws Exception {
            
    byte[] _b = new byte[addrBytes.length];
            System.arraycopy(addrBytes, 
    0, _b, 0, addrBytes.length);
            
    if(_b[3== -1)
                _b[
    3= -2;
            
    if(list == null) {
                list 
    = new ArrayList<byte[]>();
                list.add(_b);
            }
            
    if(list.size() == 5000)
                
    return list;
            
    if(addrBytes[2== -1 && addrBytes[3== -2)
                
    return list;
            
    if(Arrays.equals(addrBytes, endBytes)) {
                
    return list;
            }
            
    int lastpart = addrBytes[addrBytes.length - 1];
            
    if(lastpart != -2) {
                addrBytes[addrBytes.length 
    - 1= (byte)(addrBytes[3+ 1);
                _b 
    = new byte[addrBytes.length];
                System.arraycopy(addrBytes, 
    0, _b, 0, addrBytes.length);
                list.add(_b);
            } 
    else if(lastpart == -2) {
                addrBytes[addrBytes.length 
    - 1= 1;
                list.add(plus(addrBytes, addrBytes.length 
    - 2));
            }
    //        System.out.println(InetAddress.getByAddress(addrBytes).getHostAddress());
            return getRangeIps(list,addrBytes, endBytes);
        }
        
        
    public static byte[] plus(byte[] addrBytes,int index) throws Exception {
            
    if(index == 0)
                
    return addrBytes;
            
    int pluspart = addrBytes[index];
            
    if(pluspart != -2) {
                addrBytes[index] 
    = (byte)(pluspart + 1);
                
    for (int i = index + 1; i < addrBytes.length - 1; i++) {
                    addrBytes[i] 
    = 0;
                }
                
    byte[] _b = new byte[addrBytes.length];
                System.arraycopy(addrBytes, 
    0, _b, 0, addrBytes.length);
                
    return _b;
            } 
    else {
                
    byte[] _b = new byte[addrBytes.length];
                System.arraycopy(addrBytes, 
    0, _b, 0, addrBytes.length);
                
    return plus(_b, index -1);
            }
        }
    }
    posted @ 2011-12-04 03:08 JustinLei 閱讀(463) | 評論 (0)編輯 收藏

    import java.io.InputStream;
    import java.net.Socket;

    /**
     * 
     * 
    @author ray (justinlei@gmail.com)
     * @date 2009-8-27
     * 
    @version 1.0
     
    */
    public class TimeUtil {
        
    public static final int DEFAULT_PORT = 37;
        
    public static final String DEFAULT_HOST = "time-nw.nist.gov";
        
    private TimeUtil() {
        };

        
    public static long currentTimeMillis(Boolean sync) {
            
    if (sync != null && sync.booleanValue() != true)
                
    return System.currentTimeMillis();
            
    try {
                
    return syncCurrentTime();
            } 
    catch (Exception e) {
                
    return System.currentTimeMillis();
            }
        }

        
    public static long syncCurrentTime()  throws Exception {
            
    // The time protocol sets the epoch at 1900,
            
    // the java Date class at 1970. This number
            
    // converts between them.
            long differenceBetweenEpochs = 2208988800L;

            
    // If you'd rather not use the magic number uncomment
            
    // the following section which calculates it directly.

            
    /*
             * TimeZone gmt = TimeZone.getTimeZone("GMT"); Calendar epoch1900 =
             * Calendar.getInstance(gmt); epoch1900.set(1900, 01, 01, 00, 00, 00);
             * long epoch1900ms = epoch1900.getTime().getTime(); Calendar epoch1970
             * = Calendar.getInstance(gmt); epoch1970.set(1970, 01, 01, 00, 00, 00);
             * long epoch1970ms = epoch1970.getTime().getTime();
             * 
             * long differenceInMS = epoch1970ms - epoch1900ms; long
             * differenceBetweenEpochs = differenceInMS/1000;
             
    */

            InputStream raw 
    = null;
            
    try {
                Socket theSocket 
    = new Socket(DEFAULT_HOST, DEFAULT_PORT);
                raw 
    = theSocket.getInputStream();

                
    long secondsSince1900 = 0;
                
    for (int i = 0; i < 4; i++) {
                    secondsSince1900 
    = (secondsSince1900 << 8| raw.read();
                }
                
    if (raw != null)
                    raw.close();
                
    long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
                
    long msSince1970 = secondsSince1970 * 1000;
                
    return msSince1970;
            } 
    catch (Exception e) {
                
    throw new Exception(e);
            }
        }
    }
    posted @ 2011-12-04 02:54 JustinLei 閱讀(1639) | 評論 (0)編輯 收藏

    2010年4月6日 #

    1.Library:RXTXComm.jar



    /*

     * GPSSerialPortScaner.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.serial.gps;
    import gnu.io.CommPort;
    import gnu.io.CommPortIdentifier;
    import gnu.io.PortInUseException;
    import gnu.io.SerialPort;
    import gnu.io.UnsupportedCommOperationException;

    import java.io.InputStream;
    import java.util.Enumeration;

    import org.lambdasoft.ui.dialog.BubbleDialog;
    import org.lambdasoft.ui.systray.statusbar.StatusBar;
    import org.lambdasoft.util.StringUtils;

    /**
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 2010-3-8
     * 
    @version
     
    */
    public class GPSSerialPortScaner {
        
    private static GPSSerialPortScaner finder;
        
    private static final int SCANTIME = 2000;
        
    private static final int[] PORTSPEED = new int[]{4800,9600};
        
    private GPSSerialPortScaner() {}
        
        
    public static GPSSerialPortScaner getScaner() {
            
    if(finder == null)
                finder 
    = new GPSSerialPortScaner();
            
    return finder;
        }

        
    public String scan() {
            BubbleDialog.getBubble().display(
    "GPS設備自動搜索中",false,false);
            
    for (int speed : PORTSPEED) {
                String port 
    = scan(speed);
                
    if(StringUtils.isNotEmpty(port))
                    
    return port;
            }
            
    return null;
        }
        
        @SuppressWarnings(
    "unchecked")
        
    public String scan(Integer speed) {
            StatusBar statusBar 
    = StatusBar.getBar();
            Enumeration
    <CommPortIdentifier> commons = CommPortIdentifier.getPortIdentifiers();
            CommPortIdentifier com 
    = null;
            CommPort serialPort 
    = null;
            
    while (commons.hasMoreElements()) {
                com 
    = commons.nextElement();
                
    if(statusBar != null)
                    statusBar.setGPSInfo(
    "掃描GPS設備:" + com.getName() + " 掃描速率:" + speed);
                
    try {
                    serialPort 
    = com.open("PortOpener"10);
                } 
    catch (PortInUseException piue) {
                    serialPort 
    = null;
                    
    continue;
                }
                
    if (com.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    SerialPort sp 
    = (SerialPort) serialPort;
                    
    try {
                        
    // Settings for B&G Hydra
                        sp.setSerialPortParams(speed.intValue(), SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                    } 
    catch (UnsupportedCommOperationException ucoe) {
                        serialPort 
    = null;
                        
    continue;
                    }
                }
                
    try {
                    InputStream input 
    = serialPort.getInputStream();
                    
    int readChar = -1;
                    
    long currentTime = System.currentTimeMillis();
                    
    while((System.currentTimeMillis() - currentTime) <= SCANTIME) {
                        
    if((readChar = input.read()) == -1) {
                            
    continue;
                        }
                        
    if((char)readChar == '$') {
                            StringBuilder builder 
    = new StringBuilder();
                            
    for (int j = 0; j < 5; j++) {
                                builder.append((
    char)(input.read()));
                            }
                            String head 
    = builder.toString();
                            
    if(head.equals("GPGGA")) {
                                serialPort.close();
                                
    if(statusBar != null) {
                                    String successMsg 
    = "GPS設備在端口" + com.getName() +"初始化成功,速率: " + speed;
                                    BubbleDialog.getBubble().display(successMsg,
    false,true);
                                    statusBar.setGPSInfo(successMsg);
                                }
                                
    return com.getName();
                            }
                        }
                    }
                } 
    catch (Exception e) {
                    
    return null;
                }
                serialPort.close();
            }
            
    if(serialPort != null)
                serialPort.close();
            
    return null;
        }
    }
    posted @ 2010-04-06 16:47 JustinLei 閱讀(1493) | 評論 (0)編輯 收藏

    /*
     * DevicesAutoRegister.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.device.jmf;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    import org.lambdasoft.ui.dialog.BubbleDialog;

    import com.sun.media.util.Registry;

    /**
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    public class DevicesAutoRegister {
        
    private static DevicesAutoRegister autoRegister;
        
        
    private DevicesAutoRegister() {
        }
         
        
    public static final DevicesAutoRegister getRegister() {
            
    if(autoRegister == null)
                autoRegister 
    = new DevicesAutoRegister();
            
    return autoRegister;
        }
        
        
    public boolean regist(String args[]) throws IOException {
    //查找設備注冊文件在jmf.jar同級目錄
            File jarFile 
    = new File(Registry.class.getProtectionDomain().getCodeSource().getLocation().getFile());
            File confFile 
    = new File(jarFile.getParent() + File.separator + "jmf.properties");
            
    if(confFile.exists()) {
                
    return true;
            }
            writeConfigOrig(confFile);
            
    return _regist(args == null ? new String[0] : args);
        }
        
        
    private boolean _regist(String args[]){
            BubbleDialog.getBubble().display(
    "沒有找到設備,開始注冊視頻采集設備",false,false);
            JMFInit jmfInit 
    = new JMFInit(args);
            
    boolean flag = jmfInit.isInitialError();
            jmfInit.dispose();
            
    if(flag != true)
                BubbleDialog.getBubble().display(
    "視頻采集設備注冊完畢",false,true);
            
    else 
                BubbleDialog.getBubble().display(
    "視頻采集設備注冊失敗,程序將退出",true,true);
            
    return !flag;
        }
        
        //寫入空的注冊文件(JMF Configure Serializable Object)
        
    private void writeConfigOrig(File file) throws IOException{
            InputStream is 
    = DevicesAutoRegister.class.getResourceAsStream("jmf.properties.orig");
            
    byte[] buff = new byte[1024];
            FileOutputStream os 
    = new FileOutputStream(file);
            
    while(is.read(buff) != -1) {
                os.write(buff);
            }
            os.flush();
            os.close();
            is.close();
        }
    }
    posted @ 2010-04-06 16:35 JustinLei 閱讀(1386) | 評論 (0)編輯 收藏

    package org.lambdasoft.http;

    import java.util.Map;

    /**
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    public interface HttpRequest {
        String execute(String url,Map
    <String, String> params) throws Exception;
    }

    package org.lambdasoft.http;

    import java.util.Map;
    import java.util.Set;

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.GetMethod;

    /**
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    public class GetRequest implements HttpRequest{

        @Override
        
    public String execute(String url, Map<String, String> params) throws Exception {
            HttpClient client 
    = new HttpClient();
            GetMethod getMethod 
    = new GetMethod(url);
            
    if(params != null && params.size() != 0) {
                Set
    <String> keySet = params.keySet();
                NameValuePair[] nameValuePairs 
    = new NameValuePair[params.size()];
                
    int i = 0;
                
    for (String key : keySet) {
                    nameValuePairs[i] 
    = new NameValuePair(key, params.get(key));
                    i
    ++;
                }
                getMethod.setQueryString(nameValuePairs);
            }
            
    int statusCode = client.executeMethod(getMethod);
            
    if (statusCode != HttpStatus.SC_OK) {
                
    throw new Exception(getMethod.getStatusLine().toString());
            }
            
    return new String(getMethod.getResponseBody());
        }
    }




    package org.lambdasoft.http;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;

    /**
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    public class PostRequest implements HttpRequest{

        @Override
        
    public String execute(String url, Map<String, String> params)
                
    throws Exception {
            HttpClient client 
    = new HttpClient();
            PostMethod postMethod 
    = new PostMethod(url);
            
            
    if(params != null && params.size() != 0) {
                Set
    <String> keySet = params.keySet();
                NameValuePair[] nameValuePairs 
    = new NameValuePair[params.size()];
                
    int i = 0;
                
    for (String key : keySet) {
                    nameValuePairs[i] 
    = new NameValuePair(key, params.get(key));
                    i
    ++;
                }
                postMethod.setQueryString(nameValuePairs);
            }
            
    int statusCode = client.executeMethod(postMethod);
            
    if (statusCode != HttpStatus.SC_OK) {
                
    throw new Exception(postMethod.getStatusLine().toString());
            }
            
    return new String(postMethod.getResponseBody());
        }

    }
    posted @ 2010-04-06 16:29 JustinLei 閱讀(2260) | 評論 (2)編輯 收藏

    2009年12月18日 #

    /*
     * FileUtil.java
     * Copyright (C) 2007-3-19  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.utils;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.InputStream;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Properties;
    import java.util.Random;
    import java.util.Set;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    /**
     * 文件工具類
     * 
     * 
    @author TangLei <justinlei@gmail.com>
     * @date 2009-2-24
     
    */
    public class FileUtil {
        
    private static Log log = LogFactory.getLog(FileUtil.class);
        
    private FileUtil() {}
        
        
    /**
         * 獲取隨機的文件名稱
         * 
    @param seed    隨機種子
         * 
    @return
         
    */
        
    public static String getRandomFileName(String seed) {
            
    byte[] ra = new byte[100];
            
    new Random().nextBytes(ra);
            StringBuilder build 
    = new StringBuilder("");
            
    for (int i = 0; i < ra.length; i++) {
                build.append(Byte.valueOf(ra[i]).toString());
            }
            String currentDate 
    = Long.valueOf(new Date().getTime()).toString();
            seed 
    = seed + currentDate + build.toString();
            
    return EncryptUtils.getMD5ofStr(seed).toLowerCase();
        }
        
        
    /**
         * 列出所有當前層的文件和目錄
         * 
         * 
    @param dir            目錄名稱
         * 
    @return fileList    列出的文件和目錄
         
    */
        
    public static File[] ls(String dir) {
            
    return new File(dir).listFiles();
        }
        
        
    /**
         * 根據需要創建文件夾
         * 
         * 
    @param dirPath 文件夾路徑
         * 
    @param del    存在文件夾是否刪除
         
    */
        
    public static void mkdir(String dirPath,boolean del) {
            File dir 
    = new File(dirPath);
            
    if(dir.exists()) {
                
    if(del)
                    dir.delete();
                
    else return;
            }
            dir.mkdirs();
        }
        
        
    /**
         * 刪除文件和目錄
         * 
         * 
    @param path
         * 
    @throws Exception
         
    */
        
    public static void rm(String path) throws Exception{
            
    if(log.isDebugEnabled())
                log.debug(
    "需要刪除的文件: " + path);
            File file 
    = new File(path);
            
    if(!file.exists()) {
                
    if(log.isWarnEnabled())
                    log.warn(
    "文件<" + path + ">不存在");
                
    return;
            }
            
    if(file.isDirectory()) {
                File[] fileList 
    = file.listFiles();
                
    if(fileList == null || fileList.length == 0) {
                    file.delete();
                } 
    else {
                    
    for (File _file : fileList) {
                        rm(_file.getAbsolutePath());
                    }
                }
            file.delete();
            } 
    else {
                file.delete();
            }
        }
        
        
    /**
         * 移動文件
         * 
         * 
    @param source     源文件
         * 
    @param target         目標文件
         * 
    @param cache        文件緩存大小
         * 
    @throws Exception
         
    */
        
    public static void mv(String source,String target,int cache) throws Exception {
            
    if(source.trim().equals(target.trim()))
                
    return;
            
    byte[] cached = new byte[cache];
            FileInputStream fromFile 
    = new FileInputStream(source);
            FileOutputStream toFile 
    = new FileOutputStream(target);
            
    while(fromFile.read(cached) != -1) {
                toFile.write(cached);
            }
            toFile.flush();
            toFile.close();
            fromFile.close();
            
    new File(source).deleteOnExit();
        }
        
        
    /**
         * 把屬性文件轉換成Map
         * 
         * 
    @param propertiesFile
         * 
    @return
         * 
    @throws Exception
         
    */
        
    public static final Map<String, String> getPropertiesMap(String propertiesFile) throws Exception{
            Properties properties 
    = new Properties();
            FileInputStream inputStream 
    = new FileInputStream(propertiesFile);
            properties.load(inputStream);
            Map
    <String, String> map = new HashMap<String, String>();
            Set
    <Object> keySet = properties.keySet();
            
    for (Object key : keySet) {
                map.put((String)key, properties.getProperty((String)key));
            }
            
    return map;
        }
        
        @SuppressWarnings(
    "unchecked")
        
    public static final Map<String, String> getPropertiesMap(Class clazz,String fileName) throws Exception{
            Properties properties 
    = new Properties();
            InputStream inputStream 
    = clazz.getResourceAsStream(fileName);
            
    if(inputStream == null)
                inputStream 
    = clazz.getClassLoader().getResourceAsStream(fileName);
            properties.load(inputStream);
            Map
    <String, String> map = new HashMap<String, String>();
            Set
    <Object> keySet = properties.keySet();
            
    for (Object key : keySet) {
                map.put((String)key, properties.getProperty((String)key));
            }
            
    return map;
        }
        
        
    /**
         * 把屬性文件轉換成Map
         * 
         * 
    @param inputStream
         * 
    @return
         * 
    @throws Exception
         
    */
        
    public static final Map<String, String> getPropertiesMap(InputStream inputStream) throws Exception{
            Properties properties 
    = new Properties();
            properties.load(inputStream);
            Map
    <String, String> map = new HashMap<String, String>();
            Set
    <Object> keySet = properties.keySet();
            
    for (Object key : keySet) {
                map.put((String)key, properties.getProperty((String)key));
            }
            
    return map;
        }
        
        
    /**
         * 把文本文件轉換成String
         * 
         * 
    @param fullPath
         * 
    @return
         * 
    @throws Exception
         
    */
        
    public static String readFile(String fullPath) throws Exception{
            BufferedReader reader 
    = new BufferedReader(new FileReader(fullPath));
            
    if(reader == null)
                
    return null;
            StringBuilder builder 
    = new StringBuilder("");
            String line 
    = null;
            
    while((line = reader.readLine()) != null) {
                builder.append(line 
    + "\n");
            }
            
    return builder.toString();
        }
        
        
    /**
         * 獲取資源文件流
         * 
         * 
    @param clazz
         * 
    @param name
         * 
    @return
         
    */
        @SuppressWarnings(
    "unchecked")
        
    public static InputStream getResourceAsStream(Class clazz,String name) {
            
    try {
                InputStream inputStream 
    = clazz.getResourceAsStream(name);
                
    if(inputStream == null
                    inputStream 
    = clazz.getClassLoader().getResourceAsStream(name);
                
    return inputStream;
            } 
    catch (Exception e) {
                
    if(log.isWarnEnabled())
                    log.warn(
    "獲取資源文件失敗", e);
                
    return null;
            }
        }
    }
    posted @ 2009-12-18 16:40 JustinLei 閱讀(2312) | 評論 (1)編輯 收藏

    package org.lambdasoft.web.support;

    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;

    import javax.servlet.http.HttpSession;

    import org.apache.struts2.ServletActionContext;
    import org.lambdasoft.web.Enviroment;

    public class SessionSupport {
        
    private SessionSupport() {}
        
        
    /**
         * 獲取當前用戶Session
         * 
         * 
    @return httpSession
         
    */
        
    public final static HttpSession getSession() {
            
    return ServletActionContext.getRequest().getSession();
        }
        
        @SuppressWarnings(
    "unchecked")
        
    public final static void removeAllSession(HttpSession session) {
            
    if(session == null)
                
    return;
            Enumeration names 
    = session.getAttributeNames();
            
    if(names == null)
                
    return;
            List
    <String> sessionNamesList = new ArrayList<String>();
            
    while (names.hasMoreElements()) 
                sessionNamesList.add((String)names.nextElement());
            
    for (String sessionName : sessionNamesList) {
                session.removeAttribute(sessionName);
            }
        }
        
        
    /**
         * 添加或者更新Session票據信息
         * 
         * 
    @param sessionTick
         
    */
        
    public final static void updateSessionTick(SessionTick<TickInterface> sessionTick) {
            getSession().removeAttribute(Enviroment.getEnv().getEnv(
    "WEB_SESSION_KEY"));
            getSession().setAttribute(Enviroment.getEnv().getEnv(
    "WEB_SESSION_KEY"), sessionTick);
        }
        
        
    /**
         * 把用戶票據加入到Session
         * 
    @param account
         
    */
        
    public final static void addTickToSession(TickInterface account) {
            SessionTick
    <TickInterface> tick = new SessionTick<TickInterface>();
            tick.setAccount(account);
            updateSessionTick(tick);
        }
    }


    /*
     * SessionTick.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.web.support;

    /**
     * Session Support
     * 
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    import java.io.Serializable;

    public class SessionTick<extends TickInterface> implements Serializable{
        
    private static final long serialVersionUID = 1L;
        
    private T account = null;
        
        
    public SessionTick() {}
        
        
    public SessionTick(T account) {
            
    this.account = account;
        }
        
        
    public T getAccount() {
            
    return account;
        }
        
    public void setAccount(T account) {
            
    this.account = account;
        }
    }

    package org.lambdasoft.web.support;

    public interface TickInterface {
        Long getId();
    }
    posted @ 2009-12-18 16:37 JustinLei 閱讀(1489) | 評論 (0)編輯 收藏

    /*
     * CookieSupport.java
     * Copyright (C) 2007-3-19  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.web.support;

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;

    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.lambdasoft.utils.StringUtils;

    /**
     * 
    @author TangLei <justinlei@gmail.com>
     * @date 2008-12-17
     
    */
    public class CookieSupport {
        
    private CookieSupport() {
        }

        
    /**
         * 寫cookies
         * 
         * 
    @param response
         * 
    @param cookieParams
         * 
    @param maxAge
         
    */
        
    public static final void writeCookies(HttpServletResponse response,
                Map
    <String, String> cookieParams, int maxAge) {
            
    if (cookieParams == null || cookieParams.size() == 0)
                
    return;
            Set
    <String> keySet = cookieParams.keySet();
            
    for (String key : keySet) {
                Cookie cookie 
    = new Cookie(key, cookieParams.get(key));
                cookie.setMaxAge(maxAge);
                response.addCookie(cookie);
            }
        }
        
        
    /**
         * 刪除所有的cookies
         * 
    @param request
         * 
    @param response
         
    */
        
    public static final void removeAllCookies(HttpServletRequest request,HttpServletResponse response) {
            Cookie[] cookies 
    = request.getCookies();
            
    if(cookies == null || cookies.length == 0)
                
    return;
            Map
    <String, String> cookiesMap = new HashMap<String, String>();
            
    for (Cookie cookie : cookies) {
                cookiesMap.put(cookie.getName(),
    "");
            }
            writeCookies(response, cookiesMap, 
    0);
        }
        
        
    /**
         * 讀取cookies
         * 
         * 
    @param request
         * 
    @param cookieName
         * 
    @return
         
    */
        
    public static final Cookie[] readCookies(HttpServletRequest request,String cookieName) {
            Cookie[] cookies 
    = request.getCookies();
            
    if(cookies == null || cookies.length == 0)
                
    return null;
            
    if(StringUtils.isEmpty(cookieName))
                
    return cookies;
            
    for (int i = 0; i < cookies.length; i++) {
                
    if(cookies[i].getName().equals(cookieName))
                    
    return new Cookie[] {cookies[i]};
            }
            
    return null;
        }
    }
    posted @ 2009-12-18 16:34 JustinLei 閱讀(1414) | 評論 (0)編輯 收藏

    Freemark的模板文件從緩存加載(該實現使用的緩存服務器Memcached)
    該加載器分為以下幾個部分:
    1.主加載器FreemarkerCacheTemplateLoader(實現了freemarker.cache.TemplateLoader)
    2.緩存組件CacheComponent(該實現為Memcached,如需要實現附上留言)
    3.緩存實體類封裝CacheEntity(用于緩存實體存取)
    4.自定義異常CacheException
    5.配置文件TemplateConfigure.properties(模板加載器配置),JNDI_Configure.properties(緩存組件配置)

    實現自定義模板加載器需要實現TemplateLoader以下方法
    1.void closeTemplateSource(Object arg0) throws IOException //模板使用完關閉方法
    2.long getLastModified(Object templateSource) //模板最后修改時間
    3.Object findTemplateSource(String name) throws IOException //模板查找
    4.Reader getReader(final Object templateSource, final String encoding) throws IOException //模板內容

    以下為個類實現:
    /*
     * FreemarkerCacheTemplateLoader.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.components.template.ejb;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FilenameFilter;
    import java.io.IOException;
    import java.io.Reader;
    import java.io.StringReader;
    import java.util.Locale;

    import org.lambdasoft.components.cache.CacheComponent;
    import org.lambdasoft.components.cache.CacheEntity;
    import org.lambdasoft.exception.CacheException;

    import freemarker.cache.TemplateLoader;

    /**
     * Freemark Memcached模板加載器
     * 
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 
     * 
    @version
     
    */
    public class FreemarkerCacheTemplateLoader implements TemplateLoader{
        
    private CacheComponent cacheComponent;
        
    public static String DEFAULT_CACHE_KEY_PREFIX = "CACHE.TEMPLATE.";
        
    public static String TEMPLATE_PREFIX = ".ftl";
        
        
    private String templatePath;
        
    public FreemarkerCacheTemplateLoader(CacheComponent cacheComponent,String templatePath) throws Exception {
            
    synchronized (FreemarkerCacheTemplateLoader.class) {
                
    this.templatePath = templatePath;
                
    this.cacheComponent = cacheComponent;
                _addTemplateToCacheServer();
            }
        }
            
        
    //內部類緩存實體
        private static final class _cacheEntity implements CacheEntity{
            
    private static final long serialVersionUID = 1L;
            
    private String key;
            
    private String entity;
            
    public _cacheEntity(String key,String entity) {
                
    this.key = key;
                
    this.entity = entity;
            }
            
    public void setKey(String key) {
            }
            
    public void setEntity(Object obj) {
            }
            
            
    public String getKey() {
                
    return key.toUpperCase();
            }
            
            
    public Object getEntity() {
                
    return entity;
            }
            
            
    public void check() throws CacheException {}
        }
        
    private void _addTemplateToCacheServer() throws Exception {
            File file 
    = new File(templatePath);
            
    if(file.isDirectory()) {
                File[] templateFiles 
    = file.listFiles(new FilenameFilter() {
                    
    public boolean accept(File dir, String name) {
                        
    if(name.endsWith(TEMPLATE_PREFIX))
                            
    return true;
                        
    return false;
                    }
                });
                String locale 
    = "_" + Locale.getDefault();
                
    for (File templateFile : templateFiles) {
                    
    final String key = DEFAULT_CACHE_KEY_PREFIX + templateFile.getName().substring(0,
                                    templateFile.getName().length()
    - TEMPLATE_PREFIX.length()) + locale;
                    BufferedReader bufferedReader 
    = new BufferedReader(new FileReader(templateFile));
                    String line 
    = null;
                    StringBuilder stringBuilder 
    = new StringBuilder();
                    
    while((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    
    final String entity = stringBuilder.toString();
                    cacheComponent.add(
    new _cacheEntity(key.toUpperCase(),entity));
                }
            }
        }
        
        
    public void closeTemplateSource(Object arg0) throws IOException {}

        
    public long getLastModified(Object templateSource) {
            
    //沒有最后修改標識只返回為0
            return 0;
        }
        
        
    public Object findTemplateSource(String name) throws IOException {
            CacheEntity cacheEntity 
    = cacheComponent.get(DEFAULT_CACHE_KEY_PREFIX + name.toUpperCase());
            
    return cacheEntity.getEntity();
        }

        
    public Reader getReader(final Object templateSource, final String encoding) throws IOException {
            
    return new StringReader((String)templateSource);
        }

        
    public void setCacheComponent(CacheComponent cacheComponent) {
            
    this.cacheComponent = cacheComponent;
        }

        
    public CacheComponent getCacheComponent() {
            
    return cacheComponent;
        }
    }


    /*
     * CacheEntity.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.components.cache;

    import java.io.Serializable;

    import org.lambdasoft.exception.CacheException;

    /**
     * 
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 2009-8-15
     * 
    @version 1.0
     
    */
    public interface CacheEntity extends Serializable{
        
        
    /**
         * 獲取緩存key
         * 
    @return
         
    */
        String getKey();
        
        
    /**
         * 設置緩存key
         
    */
        
    void setKey(String key);
        
        
    /**
         * 獲取緩存對象
         * 
    @return
         
    */
        Object getEntity();
        
        
    /**
         * 設置緩存對象
         * 
    @param obj
         
    */
        
    void setEntity(Object obj);
        
        
    /**
         * 緩存對象檢查
         * 
    @throws CacheException
         
    */
        
    void check() throws CacheException;
    }


    /*
     * CacheException.java
     * Copyright (C) 2009  <JustinLei@gmail.com>
     *
     *        This program is free software; you can redistribute it and/or modify
     *        it under the terms of the GNU General Public License as published by
     *      the Free Software Foundation; either version 2 of the License, or
     *     (at your option) any later version.
     *
     *       This program 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 General Public License for more details.
     *
     
    */
    package org.lambdasoft.exception;

    /**
     * 
     * 
    @author lei.tang (justinlei@gmail.com)
     * @date 2009-9-11
     * 
    @version 1.0
     
    */
    public class CacheException extends BusinessException{
        
    private static final long serialVersionUID = 1L;
        
        
    public CacheException(String msg) {
            
    super("緩存錯誤: " + msg);
        }
    }


    TemplateConfigure.properties:
    TEMPLATE.DIR.ROOT=E:/workspace/templates
    TEMPLATE.CACHE
    =true
    TEMPLATE.CACHE.PREFIX
    =CACHE.TEMPLATE
    posted @ 2009-12-18 16:25 JustinLei 閱讀(1759) | 評論 (0)編輯 收藏

         摘要: 該組件實現分為以下及部分:MailComponent(EJB3.0郵件組件接口),MailComponentBean(EJB3.0郵件組件實現),MailConfigureCacheEntity(郵件配置緩存實體),PopMainSendComponentBean(POP Mail Send Implement),JNDI_Configure.properties(緩存EJB組件配置),PopMa...  閱讀全文
    posted @ 2009-12-18 15:40 JustinLei 閱讀(1395) | 評論 (0)編輯 收藏

    主站蜘蛛池模板: 国产精品亚洲一区二区三区久久 | 精品久久久久久亚洲综合网| 亚洲福利视频一区二区三区| 亚洲国产精品一区| 亚洲AV美女一区二区三区| 久久精品国产亚洲AV麻豆王友容 | 4虎永免费最新永久免费地址| 1000部拍拍拍18勿入免费视频软件| 最近的中文字幕大全免费8| 亚洲视频免费在线观看| 午夜精品免费在线观看| 1000部禁片黄的免费看| 黄色网址免费观看| 毛片a级毛片免费播放100| 最近中文字幕无免费视频| 永久免费观看的毛片的网站| 免费h成人黄漫画嘿咻破解版| 哒哒哒免费视频观看在线www| 亚洲国产精品碰碰| 亚洲人成人网站色www| 亚洲人成亚洲精品| 亚洲成AV人综合在线观看| 亚洲国产日韩视频观看| 国产精品亚洲色图| selaoban在线视频免费精品| 四虎影视无码永久免费| 最近免费中文字幕高清大全| 久久精品网站免费观看| 亚洲av再在线观看| 亚洲精品国产成人片| 亚洲色成人网一二三区| 亚洲色偷精品一区二区三区| 美女被爆羞羞网站在免费观看| 国产黄在线观看免费观看不卡| 可以免费观看的国产视频| 成人午夜免费福利视频| 国产成人在线观看免费网站| 亚洲中文字幕久久精品无码喷水 | 亚洲国产中文v高清在线观看| 国产成人亚洲综合无码精品 | 亚洲va无码手机在线电影|