2009年12月18日
#
去除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); } } }
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); } } }
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;
}
}
/*
* 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();
}
}
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());
}
}
/*
* 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;
}
}
}
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<T 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();
}
/*
* 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;
}
}
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
摘要: 该组件实现分为以下及部分:MailComponent(EJB3.0邮件组件接口),MailComponentBean(EJB3.0邮件组件实现),MailConfigureCacheEntity(邮件配置缓存实体),PopMainSendComponentBean(POP Mail Send Implement),JNDI_Configure.properties(缓存EJB组件配置),PopMa... 阅读全文
该组件实现分为以下几个部分ChannelEItem,ChannelItem,RssBuildFactory,RssComponentBean
/*
* ChannelEItem.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.rss.ejb;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public class ChannelEItem extends ChannelItem{
private static final long serialVersionUID = 1L;
private String enclosure;// 流媒体文件
public String getEnclosure() {
return enclosure;
}
public void setEnclosure(String enclosure) {
this.enclosure = enclosure;
}
}
/*
* ChannelItem.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.rss.ejb;
import java.io.Serializable;
import java.util.Date;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public class ChannelItem implements Serializable{
private static final long serialVersionUID = 1L;
private String title;// Rss文件中Item的标题
private String link;// Rss文件中Item对应的连接
private String description;// Item的描述
private Date pubDate;// Item发布的时间
private String author;// Item作者
private String category;// Item所属的频道范畴
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getPubDate() {
return pubDate;
}
public void setPubDate(Date pubDate) {
this.pubDate = pubDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
/*
* RssBuildFactory.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.rss.ejb;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.sun.syndication.feed.synd.SyndCategory;
import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEnclosureImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public class RssBuildFactory {
private SyndFeed feed;
@SuppressWarnings("unchecked")
private List entries;
private SyndEntry entry;
@SuppressWarnings("unchecked")
public RssBuildFactory() {
feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
entries = new ArrayList();
}
/**
* 创建一个频道
*
* @param title 频道标题
* @param link 频道对应的连接
* @param description 频道描述
* @param language 频道所用语言
* @param pubDate 频道发布时期
* @param copyright 版权所有
* @throws Exception
*/
public void buildChannel(String title, String link, String description,
String language, Date pubDate, String copyright)
throws RuntimeException {
feed.setTitle(title);
feed.setLink(link);
feed.setDescription(description);
feed.setLanguage(language);
feed.setPublishedDate(pubDate);
feed.setCopyright(copyright);
}
/**
* 添加频道的子内容
*
* @param item
* [email={@link]{@link[/email] ChannelItem}
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void buildItems(ChannelItem item) throws RuntimeException {
entry = new SyndEntryImpl();
// 设置新闻标题
entry.setTitle(item.getTitle());
// 设置新闻的连接地址
entry.setLink(item.getLink());
// 设置新闻简介
SyndContent content = new SyndContentImpl();
content.setType("text/plain");
content.setValue(item.getDescription());
entry.setDescription(content);
// 设置发布时间
entry.setPublishedDate(item.getPubDate());
// 设置频道所属的范围
SyndCategory cate = new SyndCategoryImpl();
cate.setName(item.getCategory());
List cateList = new ArrayList();
cateList.add(cate);
entry.setCategories(cateList);
// 设置作者
entry.setAuthor(item.getAuthor());
// 将新闻项添加至数组中
entries.add(entry);
}
/**
* 添加频道的内容项
*
* @param item
* [email={@link]{@link[/email] ChannelEItem}此类继承自ChannelItem类
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void buildItems(ChannelEItem item) throws RuntimeException {
entry = new SyndEntryImpl();
// 设置新闻标题
entry.setTitle(item.getTitle());
// 设置新闻的连接地址
entry.setLink(item.getLink());
// 设置新闻简介
SyndContent content = new SyndContentImpl();
content.setValue(item.getDescription());
entry.setDescription(content);
// 设置发布时间
entry.setPublishedDate(item.getPubDate());
// 设置频道所属的范围
SyndCategory cate = new SyndCategoryImpl();
cate.setName(item.getCategory());
List cateList = new ArrayList();
cateList.add(cate);
entry.setCategories(cateList);
// 设置作者
entry.setAuthor(item.getAuthor());
// 设置流媒体播放文件
SyndEnclosure en = new SyndEnclosureImpl();
en.setUrl(item.getEnclosure());
List enList = new ArrayList();
enList.add(en);
entry.setEnclosures(enList);
// 将新闻项添加至数组中
entries.add(entry);
}
/**
* 生成XML文件
*
* @param outputStream
* @throws Exception
*/
public String buildChannel() throws IOException {
feed.setEntries(entries);
SyndFeedOutput output = new SyndFeedOutput();
Writer writer;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
writer = new OutputStreamWriter(outputStream, "UTF-8");
try {
output.output(feed, writer);
return new String(outputStream.toByteArray());
} catch (FeedException e) {
throw new IOException();
}
}
}
/*
* RssComponentBean.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.rss.ejb;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import org.lambdasoft.components.application.RssComponent;
import org.lambdasoft.components.application.param.RssBuildParam;
import org.lambdasoft.ejb.interceptors.EjbCheckParamInterceptor;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
@Stateless
@Remote
@Interceptors({EjbCheckParamInterceptor.class})
public class RssComponentBean implements RssComponent{
public String buildChannel(RssBuildParam rssBuildParam) throws Exception{
if(rssBuildParam.getChannelEItems() == null)
return null;
RssBuildFactory builder = new RssBuildFactory();
for (ChannelEItem channelEItem : rssBuildParam.getChannelEItems()) {
builder.buildItems(channelEItem);
}
builder.buildChannel(rssBuildParam.getTitle(),rssBuildParam.getLink(), rssBuildParam.getDescription(),
rssBuildParam.getLanguage(), rssBuildParam.getPubDate(), rssBuildParam.getCopyright());
return builder.buildChannel();
}
}
/*
* LogMessageBean.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.mdb;
import java.util.Map;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.naming.InitialContext;
import org.lambdasoft.components.log.BaseLogSendInterface;
import org.lambdasoft.components.log.OperateType;
import org.lambdasoft.components.log.param.LogParam;
import org.lambdasoft.utils.FileUtil;
/**
* 日志添加消息
*
* @author lei.tang (justinlei@gmail.com)
* @date 2009-9-17
* @version 1.0
*/
@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = MessageConstant.DESTINATIONTYPE_QUEUE),
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = MessageConstant.ACKNOWLEDGEMODE_AUTO),
@ActivationConfigProperty(propertyName = "destination", propertyValue = MessageConstant.DESTINATION_LOG) })
public class LogMessageBean implements MessageListener{
public static final String LOG_PREFIX = "LOG.TYPE.BEAN.";
private Map<String, String> logConfigure;
public void onMessage(Message message) {
if(!(message instanceof ObjectMessage))
return;
ObjectMessage objectMessage = (ObjectMessage)message;
try {
if(!(objectMessage.getObject() instanceof LogParam))
return;
LogParam logParam = (LogParam)objectMessage.getObject();
InitialContext context = new InitialContext();
for (Object level : logParam.getOperateTypes()) {
OperateType operateType = (OperateType)level;
String ejbName = getConfigure().get(LOG_PREFIX + (operateType.toString()));
Object sendComponent = context.lookup(ejbName);
if (sendComponent != null
&& (sendComponent instanceof BaseLogSendInterface)) {
((BaseLogSendInterface) sendComponent).log(logParam);
}
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private Map<String, String> getConfigure() {
String propertiesName = "/org/lambdasoft/components/log/ejb/logConfigure.properties";
try {
logConfigure = FileUtil.getPropertiesMap(LogMessageBean.class,propertiesName);
return logConfigure;
} catch (Exception e) {
return null;
}
}
}
/*
* MessageConstant.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.mdb;
/**
* 消息驱动bean定义
*
* @author lei.tang (justinlei@gmail.com)
* @date 2009-9-18
* @version 1.0
*/
public class MessageConstant {
public static final String DESTINATIONTYPE_QUEUE = "javax.jms.Queue";
public static final String ACKNOWLEDGEMODE_AUTO = "Auto-acknowledge";//会话确认模式
public static final String DESTINATION_CACHE = "queue/AO_CACHE";
public static final String DESTINATION_LOG = "queue/AO_LOG";
public static final String DESTINATION_MAIL = "queue/AO_MAIL";
public static final String DESTINATION_CACHE_REFLASH = "queue/AO_CACHE_REFLASH";
private MessageConstant() {}
}
/*
* LogMessage.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.mdb;
import java.io.Serializable;
/**
*
* @author lei.tang (justinlei@gmail.com)
* @date 2009-9-17
* @version 1.0
*/
public interface LogMessage extends Serializable{
String getType();
String getLevel();
String getLog();
}
摘要: 1/**//*
2 * StringUtils.java
3 * Copyright (C) 2007-3-19 <JustinLei@gmail.com>
4 *
5... 阅读全文
摘要: span {
font-family: 'Courier New';
font-size: 10pt;
color: #000000;
}
.sc0 {
}
.sc1 {
color: #008000;
}
.sc2 {
color: #008000;
}
.sc3 {
color: #008080;
}
.sc4 {
color: #FF8000;
}
.s... 阅读全文
|