短信发送
<!-- 短信猫服务,容器加载 -->
<bean id="SMSServiceTask" class="com.comname.smp.config.util.SMSServiceTask" />
<bean id="SMSServiceTaskJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="name" value="job_SMSServiceTask"/>
<!--false表示等上一个任务执行完后再开启新的任务-->
<property name="concurrent" value="false"/>
<property name="targetObject" ref="SMSServiceTask" />
<property name="targetMethod" value="sendSMS" />
</bean>
<bean id="SMSServiceTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="SMSServiceTaskJob" />
<property name="startDelay" value="10000" />
<!-- 每10分钟执行一次 -->
<property name="cronExpression" value="0 */50 * * * ?" />
</bean>
package com.comname.smp.config.util;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import com.comname.common.SystemMessage;
import com.comname.common.sms.MessageSender;
import com.comname.common.sms.SMSInfo;
import com.comname.common.sms.SMSInfoQueueService;
import com.comname.common.util.StringUtil;
/**
* 启动发送短信程序,每10分钟执行一次
* @author
*/
public class SMSServiceTask
{
private static final Logger logger = Logger.getLogger(SMSServiceTask.class);
// 短信队列
BlockingQueue<SMSInfo> smsInfoQueue = SMSInfoQueueService.getSMSInfoQueue();
private static final int THREA_COUNT = 20;
private ExecutorService pool = null;
public SMSServiceTask()
{
pool = Executors.newFixedThreadPool(THREA_COUNT);
}
public void sendSMS()
{
logger.info("sendSMS [SMS_STATUS:" + SystemMessage.SMS_STATUS + "]");
if (SystemMessage.SMS_STATUS.equals("1"))
{
long st = System.currentTimeMillis();
String date = StringUtil.date2String(new Date());
logger.info("sendSMS start [Date:" + date + "][Queue size:" + smsInfoQueue.size() + "]");
MessageSender sender = MessageSender.getInstance();
try
{
// 初始化短信猫服务
sender.initMessageSender();
if (sender != null)
{
while (true)
{
SMSInfo sms = smsInfoQueue.poll();
if (sms != null)
{
logger.info("sendSMS [Date:" + date + "][" + sms + "]");
SendMsgThread thread = new SendMsgThread();
thread.setSender(sender);
thread.setSms(sms);
pool.execute(thread);
}
else
{
break;
}
}
}
}
catch (Exception e)
{
logger.error("sendSMS error. [Date:" + date + "]", e);
}
long et = System.currentTimeMillis();
logger.info("sendSMS end [Date:" + date + "][execute time:" + (et - st) + "(ms)]");
}
}
}
package com.comname.common;
/**
* @author
*
*/
public interface SystemMessage
{
// 短信猫服务
String SMS_STATUS = SystemInfo.getInfoMessage("sms_status").trim();
String SMS_SERVER_ID = SystemInfo.getInfoMessage("sms_server_id").trim();
String SMS_COM_PORT = SystemInfo.getInfoMessage("sms_com_port").trim();
String SMS_BAUD_RATE = SystemInfo.getInfoMessage("sms_baud_rate").trim();
String SMS_MANUFACTURER = SystemInfo.getInfoMessage("sms_manufacturer").trim();
String SMS_MODEL = SystemInfo.getInfoMessage("sms_model").trim();
String SMS_SIM_PIN = SystemInfo.getInfoMessage("sms_sim_pin").trim();
String SMS_SMSC_NUMBER = SystemInfo.getInfoMessage("sms_smsc_number").trim();
}
/**
* @Title: SystemInfo.java
* @Package com.comname.tms.common
* @Description: TODO(用一句话描述该文件做什么)
* @author 蔡龙
* @date 2012-9-1 下午6:50:13
* @version V1.0
*/
package com.comname.common;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.comname.common.util.ResourcesUtil;
/**
* @Description: TODO(用一句话描述该文件做什么)
* @author
* @date
*/
public class SystemInfo
{
static String FILE_NAME = "conf/system_"+LanguageInfo.getInfoMessage()+".properties";//system_zh_CN.properties
private static Properties properties;
private static Logger log = Logger.getLogger(SystemInfo.class);
static
{
try
{
properties = ResourcesUtil.getResourceAsProperties(FILE_NAME);
}
catch (IOException e)
{
log.error("Load Error Information Failed " + FILE_NAME);
}
}
public static String getInfoMessage(String errorCode)
{
return properties.getProperty(errorCode, "Unkonw Error:" + errorCode);
}
public static String getInfoMessage(String errorCode, Object... args)
{
String msg = properties.getProperty(errorCode, "Unkonw Error:" + errorCode);
return MessageFormat.format(msg, args);
}
/**
* @param key 主键
* @return
*/
public static int getInt(String key)
{
int value = 0;
Object obj = properties.get(key);
if (obj != null)
{
try
{
value = Integer.valueOf((String)obj);
}
catch (Exception e)
{
log.error("getInt error [key:" + key + "]", e);
}
}
return value;
}
}
package com.comname.common;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.comname.common.util.ResourcesUtil;
public class LanguageInfo {
static String FILE_NAME = "conf/language.properties";
private static Properties properties;
private static Logger log = Logger.getLogger(SystemInfo.class);
static
{
try
{
properties = ResourcesUtil.getResourceAsProperties(FILE_NAME);
}
catch (IOException e)
{
log.error("Load Error Information Failed " + FILE_NAME);
}
}
public static String getInfoMessage()
{
String infoCode = "language";
return properties.getProperty(infoCode);
}
public static void main(String args[]){
System.out.print( getInfoMessage());
}
}
package com.comname.common.util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Properties;
import com.comname.common.Constants;
/**
* 此类来自于ibatis2.3 通过classloader获取资源
*
* @author
*/
public class ResourcesUtil
{
// private static final String DEFAULT_CHARSET = Constants.CHAR_SET;
/**
* 字符编码格式
*/
public static final String CHAR_SET = "UTF-8";
private static ClassLoader defaultClassLoader;
/**
* Charset to use when calling getResourceAsReader. null means use the system default.
*/
private static Charset charset;
// private ResourcesUtil()
// {
// }
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader()
{
return defaultClassLoader;
}
/**
* Sets the default classloader
*
* @param defaultClassLoader
* - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader)
{
ResourcesUtil.defaultClassLoader = defaultClassLoader;
}
/**
* Returns the URL of the resource on the classpath
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException
{
return getResourceURL(getClassLoader(), resource);
}
/**
* Returns the URL of the resource on the classpath
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException
{
URL url = null;
if (loader != null)
{
url = loader.getResource(resource);
}
if (url == null)
{
url = ClassLoader.getSystemResource(resource);
}
if (url == null)
{
throw new IOException("Could not find resource " + resource);
}
return url;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(String resource) throws IOException
{
return getResourceAsStream(getClassLoader(), resource);
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(ClassLoader loader, String resource)
throws IOException
{
InputStream in = null;
if (loader != null)
{
in = loader.getResourceAsStream(resource);
}
if (in == null)
{
in = ClassLoader.getSystemResourceAsStream(resource);
}
if (in == null)
{
throw new IOException("Could not find resource " + resource);
}
return in;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource) throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(ClassLoader loader, String resource)
throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException
{
Reader reader;
if (charset == null)
{
reader = new InputStreamReader(getResourceAsStream(resource), DEFAULT_CHARSET);
}
else
{
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource)
throws IOException
{
Reader reader;
if (charset == null)
{
reader = new InputStreamReader(getResourceAsStream(loader, resource), DEFAULT_CHARSET);
}
else
{
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a File object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static File getResourceAsFile(String resource) throws IOException
{
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param loader
* - the classloader used to load the resource
* @param resource
* - the resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException
{
return new File(getResourceURL(loader, resource).getFile());
}
/**
* Gets a URL as an input stream
*
* @param urlString
* - the URL to get
* @return An input stream with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getUrlAsStream(String urlString) throws IOException
{
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
/**
* Gets a URL as a Reader
*
* @param urlString
* - the URL to get
* @return A Reader with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getUrlAsReader(String urlString) throws IOException
{
return new InputStreamReader(getUrlAsStream(urlString), DEFAULT_CHARSET);
}
/**
* Gets a URL as a Properties object
*
* @param urlString
* - the URL to get
* @return A Properties object with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getUrlAsProperties(String urlString) throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = urlString;
in = getUrlAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Loads a class
*
* @param className
* - the class to load
* @return The loaded class
* @throws ClassNotFoundException
* If the class cannot be found (duh!)
*/
public static Class classForName(String className)
{
Class clazz = null;
try
{
clazz = Class.forName(className);
}
catch (ClassNotFoundException e)
{
}
return clazz;
}
private static ClassLoader getClassLoader()
{
if (defaultClassLoader != null)
{
return defaultClassLoader;
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
public static Charset getCharset()
{
return charset;
}
/**
* Use this method to set the Charset to be used when calling the getResourceAsReader methods.
* This will allow iBATIS to function properly when the system default encoding doesn't deal
* well with unicode (IBATIS-340, IBATIS-349)
*
* @param charset
*/
public static void setCharset(Charset charset)
{
ResourcesUtil.charset = charset;
}
}
package com.comname.common.sms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.Message.MessageEncodings;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
import org.springframework.beans.factory.annotation.Autowired;
import com.comname.common.SystemMessage;
import com.comname.smp.config.dao.IRemindDao;
import com.comname.smp.config.entity.Remind;
/**
*
* Description:短信发送器<br>
*
*/
public class MessageSender
{
private static final Logger logger = LoggerFactory.getLogger(MessageSender.class);
@Autowired
private IRemindDao remindDao;
private static MessageSender sender;
private Service srv;
private MessageSender()
{
OutboundNotification outboundNotification = new OutboundNotification();
logger.info("Send message from a serial gsm modem.");
logger.info("Library Description:" + Library.getLibraryDescription());
logger.info("Version: " + Library.getLibraryVersion());
srv = Service.getInstance();
srv.setOutboundMessageNotification(outboundNotification);
}
public synchronized static MessageSender getInstance()
{
if (sender == null)
{
sender = new MessageSender();
}
return sender;
}
public synchronized void initMessageSender() throws Exception
{
srv = Service.getInstance();
// 短信服务未关闭则关闭服务并清空所有短信网关
if (srv.getServiceStatus() != Service.ServiceStatus.STOPPED)
{
srv.stopService();
srv.getGateways().clear();
}
// 加入新短信网关
/* SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 9600, "SIEMENS", "TC35"); */
// SerialModemGateway gateway = new SerialModemGateway(SystemMessage.SMS_SERVER_ID, SystemMessage.SMS_COM_PORT,
// Integer.parseInt(SystemMessage.SMS_BAUD_RATE), SystemMessage.SMS_MANUFACTURER, SystemMessage.SMS_MODEL);
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 19200, "SIEMENS", "TC35");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(SystemMessage.SMS_SIM_PIN);// SIM卡密码
gateway.setSmscNumber(SystemMessage.SMS_SMSC_NUMBER);// 短信中心号码
srv.addGateway(gateway);
// 启动短信服务
srv.startService();
}
public boolean sendMessage(String mbNum, String content)
{
logger.info("发短信:" + mbNum + ", " + content);
boolean success = false;
try
{
OutboundMessage msg = new OutboundMessage(mbNum, content);
msg.setEncoding(MessageEncodings.ENCUCS2);
msg.setStatusReport(true);
srv.sendMessage(msg);
success = true;
}
catch (Exception e)
{
logger.error(e.getMessage());
}
return success;
}
/**
* 销毁对象
*/
public synchronized void stopServer()
{
try
{
srv.getGateways().clear();
srv.stopService();
}
catch (Exception e)
{
logger.error(e.getMessage());
}
}
/**
* 短信发送成功后,调用该接口。并将发送短信的网关和短信内容对象传给process接口
*/
public class OutboundNotification implements IOutboundMessageNotification
{
public void process(AGateway gateway, OutboundMessage msg)
{
logger.info("Outbound handler called from Gateway: " + gateway.getGatewayId() + ",MSG:" + msg);
}
}
public static void main(String args[])
{
MessageSender sender = getInstance();
try
{
long begin = System.currentTimeMillis();// 取开始时间 单位是毫秒
// "modem.com1", "COM1", 9600, "SIEMENS", "TC35"
Remind remind = new Remind();
remind.setSmsId("modem.com1");
remind.setSmsComPort("COM1");
remind.setSmsBaudRate(19200);
remind.setSmsManufacturer("SIEMENS");
remind.setSmsModel("TC35");
remind.setSimPin("0000");
remind.setSmscNumber("+8613800270500");
sender.initMessageSender();
sender.sendMessage("15071054326", "测试短信告警1111111");
sender.sendMessage("15071054326", "测试短信告警1111111");
sender.stopServer();
long end = System.currentTimeMillis();// 取开始时间 单位是毫秒
System.out.println(begin - end);
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
package com.comname.smp.config.dao;
import com.comname.smp.config.entity.Remind;
import com.comname.smp.config.entity.RemindHistory;
public interface IRemindDao
{
/**
* 更新
* @param remind
* @return
*/
int updateRemind(Remind remind);
/**
* 保存
* @param remind
* @return
*/
int saveRemind(Remind remind);
/**
* 查询
* @return
*/
Remind getRemind();
/**
* 保存提醒记录
* @param remindHistory
*/
void saveRemindHistory(RemindHistory remindHistory);
/**
* 删除半小时前记录
*/
void delRemindHistory();
/**
* 获得半小时内记录条数
* @param remindHistory
* @return
*/
int getRemindHistory(RemindHistory remindHistory);
/**
* 更新
* @param remind
* @return
*/
int updateReportConf(Remind remind);
/**
* 保存
* @param remind
* @return
*/
int saveReportConf(Remind remind);
/**
* 查询
* @return
*/
Remind getReportConf();
}
package com.comname.smp.config.entity;
import java.util.List;
import com.comname.common.EntityBase;
import com.comname.common.util.StringUtil;
public class Remind extends EntityBase
{
private int id;
private int mailStatus; // 邮件开启状态
private String smtpHost; // SMTP域名
private String smtpPort; // SMTP端口
private String sendAccount;// 发送方邮件账号
private String sendPwd;// 发送方邮件密码
private String mailReceiver;// 接收的邮件地址 用逗号隔开
private List<String> mailReceiverList;// 接收的邮件地址
private String mailLevel;// 邮件发送级别
private int smsStatus;// 短信开启状态
private String smsReceiver;// 短信号码, 逗号隔开
private String smsId;//modem.com1:网关ID(即短信猫端口编号)
private String smsComPort;//短信猫串口 如:COM4
private int smsBaudRate;//串口每秒发送数据的bit位数 如:115200
private String smsManufacturer;//短信猫生产厂商 如:Huawei
private String smsModel;//短信类型
private String simPin;//SIM卡密码 通常为:0000或1234
private String smscNumber;//短信中心号码
private String smsLevel;// 短信发送级别
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public int getMailStatus()
{
return mailStatus;
}
public void setMailStatus(int mailStatus)
{
this.mailStatus = mailStatus;
}
public String getSmtpHost()
{
return smtpHost;
}
public void setSmtpHost(String smtpHost)
{
this.smtpHost = smtpHost;
}
public String getSmtpPort()
{
return smtpPort;
}
public void setSmtpPort(String smtpPort)
{
this.smtpPort = smtpPort;
}
public String getSendAccount()
{
return sendAccount;
}
public void setSendAccount(String sendAccount)
{
this.sendAccount = sendAccount;
}
public String getSendPwd()
{
return sendPwd;
}
public void setSendPwd(String sendPwd)
{
this.sendPwd = sendPwd;
}
public String getMailReceiver()
{
return mailReceiver;
}
public void setMailReceiver(String mailReceiver)
{
this.mailReceiver = mailReceiver;
}
public List<String> getMailReceiverList()
{
this.mailReceiverList = StringUtil.stringToList(mailReceiver);
return mailReceiverList;
}
public void setMailReceiverList(List<String> mailReceiverList)
{
this.mailReceiverList = mailReceiverList;
}
public int getSmsStatus()
{
return smsStatus;
}
public void setSmsStatus(int smsStatus)
{
this.smsStatus = smsStatus;
}
public String getSmsReceiver()
{
return smsReceiver;
}
public void setSmsReceiver(String smsReceiver)
{
this.smsReceiver = smsReceiver;
}
public String getMailLevel()
{
return mailLevel;
}
public void setMailLevel(String mailLevel)
{
this.mailLevel = mailLevel;
}
public String getSmsLevel()
{
return smsLevel;
}
public void setSmsLevel(String smsLevel)
{
this.smsLevel = smsLevel;
}
public String getSmsId()
{
return smsId;
}
public void setSmsId(String smsId)
{
this.smsId = smsId;
}
public String getSmsComPort()
{
return smsComPort;
}
public void setSmsComPort(String smsComPort)
{
this.smsComPort = smsComPort;
}
public int getSmsBaudRate()
{
return smsBaudRate;
}
public void setSmsBaudRate(int smsBaudRate)
{
this.smsBaudRate = smsBaudRate;
}
public String getSmsManufacturer()
{
return smsManufacturer;
}
public void setSmsManufacturer(String smsManufacturer)
{
this.smsManufacturer = smsManufacturer;
}
public String getSmsModel()
{
return smsModel;
}
public void setSmsModel(String smsModel)
{
this.smsModel = smsModel;
}
public String getSimPin()
{
return simPin;
}
public void setSimPin(String simPin)
{
this.simPin = simPin;
}
public String getSmscNumber()
{
return smscNumber;
}
public void setSmscNumber(String smscNumber)
{
this.smscNumber = smscNumber;
}
}
/**
*
*/
package com.comname.common;
/**
* @author
*
*/
public class EntityBase
{
private Integer beginIndex;
private Integer endIndex;
private Integer pageSize;
public Integer getBeginIndex()
{
return beginIndex;
}
public void setBeginIndex(Integer beginIndex)
{
this.beginIndex = beginIndex;
}
public Integer getEndIndex()
{
if (endIndex != null)
{
return endIndex;
}
else
{
if (beginIndex != null && pageSize != null)
{
return beginIndex + pageSize - 1;
}
}
return endIndex;
}
public void setEndIndex(Integer endIndex)
{
this.endIndex = endIndex;
}
public Integer getPageSize()
{
if (pageSize != null)
{
return pageSize;
}
else
{
if(endIndex != null && beginIndex != null)
{
return endIndex - beginIndex + 1;
}
}
return pageSize;
}
public void setPageSize(Integer pageSize)
{
this.pageSize = pageSize;
}
}
/**
* StringUtil.java, Created on
* Title: TMS <br/>
* Description: <br/>
* Copyright: Copyright (c) 2012 <br/>
* @author
* @version Revision: 1.0
*/
package com.comname.common.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.comname.common.Constants;
/**
* @author
*
*/
public class StringUtil
{
private static final Logger logger = Logger.getLogger(StringUtil.class);
/**
* <p>
* 检查字符串是否为空 ("") 或者为null
* </p>
*
* <pre>
* StringUtil.isEmpty(null) = true
* StringUtil.isEmpty("") = true
* StringUtil.isEmpty(" ") = false
* StringUtil.isEmpty("bob") = false
* StringUtil.isEmpty(" bob ") = false
* </pre>
*
* @param str
* 待检查的字符串,可能为null
* @return <code>true</code> 如果字符串为空或null
*/
public static boolean isEmpty(String str)
{
if (str == null || str.length() == 0)
{
return true;
}
return false;
}
public static String getMachine(String machine)
{
if (isEmpty(machine))
{
return "default";
}
return machine;
}
/**
*
* @title: isEmptyArray
* @description: 判断数组是否为空
* @param str
* @return
* @throws:
* @author:
* @date:
*/
public static boolean isEmptyArray(String[] str)
{
if (str == null || str.length == 0)
{
return true;
}
return false;
}
/**
* <p>
* 检查字符串是否为空格(" "), 空 ("") 或者 null.
* </p>
*
* <pre>
* StringUtil.isBlank(null) = true
* StringUtil.isBlank("") = true
* StringUtil.isBlank(" ") = true
* StringUtil.isBlank("bob") = false
* StringUtil.isBlank(" bob ") = false
* </pre>
*
* @param str
* 待检查的字符串,可能为null
* @return <code>true</code> 如果字符串是空格(" "), 空 ("") 或者 null
*/
public static boolean isBlank(String str)
{
if (str == null || "".equals(str.trim()))
{
return true;
}
return false;
}
/**
* <p>
* 将字符串用MD5算法加密
* </p>
*
* @param str
* 待加密的字符串
* @return MD5加密后的字符串
*/
public static String md5(String str)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes("UTF-8"));
byte[] b = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++)
{
int v = (int) b[i];
v = v < 0 ? 0x100 + v : v;
String cc = Integer.toHexString(v);
if (cc.length() == 1)
sb.append('0');
sb.append(cc);
}
return sb.toString();
}
catch (Exception e)
{
logger.error("call md5 is invalid [str:" + str + "]", e);
}
return "";
}
/**
* <p>
* 将字符串(yyyy-MM-dd格式)转化为Date类型
* </p>
*
* @param strDate
* 日期字符串
* @return "yyyy-MM-dd HH:mm:ss"格式的日期
*/
public static Date string2Date(String strDate)
{
return string2Date(strDate, FORMAT_DEFAULT);
}
/**
* <p>
* 将字符串按指定格式转换成日期
* </p>
*
* @param strDate
* 要转换的字符串
* @param strFormat
* 字符串的格式
* @return 字符串所代表的日期
*/
public static Date string2Date(String strDate, String strFormat)
{
if (isBlank(strDate) || isBlank(strFormat))
{
return null;
}
try
{
SimpleDateFormat sf = new SimpleDateFormat(strFormat);
Date date = sf.parse(strDate);
return date;
}
catch (Exception ex)
{
logger.error("string2Date [strDate:" + strDate + "][strFormat:" + strFormat + "]", ex);
}
return null;
}
/**
* Date对象转换成字符串
*
* @param date
* @param strFormat
* @return date或strFormat参数为空时返回null
*/
public static String date2String(Date date, String strFormat)
{
try
{
if (date != null)
{
SimpleDateFormat sf = new SimpleDateFormat(strFormat);
return sf.format(date);
}
}
catch (Exception e)
{
logger.error("date2String [date:" + date + "][format:" + strFormat + "]", e);
}
return null;
}
public static String convertArray(String[] str)
{
if (str == null)
{
return null;
}
String result = "";
StringBuffer res = new StringBuffer();
res.append("[");
for (int i = 0; i < str.length; i++)
{
res.append(str[i]);
res.append(",");
}
if (str.length > 0)
{
result = res.substring(0, res.length() - 1);
}
result = result + "]";
return result;
}
private static final String FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
private static final String FORMAT_ZT = "yyyyMMdd hhmmss";
private static final String FORMAT_BATCHID = "yyyyMMddHHmmss";
/**
* Date对象转换成yyyy-MM-dd HH:mm:ss格式的时间字符串
*
* @param date
* @return date参数为空时返回null
*/
public static String date2String(Date date)
{
return date2String(date, FORMAT_DEFAULT);
}
/**
* Date对象转换成yyyyMMddThhmmssZ格式的时间字符串
*
* @param date
* @return date参数为空时返回null
*/
public static String date2ZTString(Date date)
{
String str = date2String(date, FORMAT_ZT);
str = str.replace(' ', 'T') + "Z";
return str;
}
public static String data2Batchid(Date date)
{
return date2String(date, FORMAT_BATCHID);
}
/**
* 字符串转换成整型数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Integer parseInt(String value, Integer defaultVal)
{
Integer v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Integer.parseInt(value);
}
}
catch (Exception e)
{
logger.error("parseInt [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成整型数字
*
* @param value
* @return 转换出错时返回null
*/
public static Integer parseInt(String value)
{
return parseInt(value, null);
}
/**
* 字符串转换成长整型数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Long parseLong(String value, Long defaultVal)
{
Long v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Long.parseLong(value);
}
}
catch (Exception e)
{
logger.error("parseLong [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
public static Integer parseInteger(String value, Integer defaultVal)
{
Integer v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Integer.parseInt(value);
}
}
catch (Exception e)
{
logger.error("parseInteger [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成长整型数字
*
* @param value
* @return 转换出错时返回null
*/
public static Long parseLong(String value)
{
return parseLong(value, null);
}
public static Integer parseInteger(String value)
{
return parseInteger(value, null);
}
/**
*
* @Title:
* @Description: 字符串转换成数字型数组
* @param @param value
* @param @return 设定文件
* @author
* @return 返回类型
* @throws
*/
public static long[] parseArrayLong(String value)
{
if (value != null && value.length() > 0)
{
String strs[] = value.split(",");
long rs[] = new long[strs.length];
for (int i = 0; i < strs.length; i++)
{
rs[i] = parseLong(strs[i]);
}
return rs;
}
return null;
}
public static int[] parseArrayInt(String value)
{
if (value != null && value.length() > 0)
{
String strs[] = value.split(",");
int rs[] = new int[strs.length];
for (int i = 0; i < strs.length; i++)
{
rs[i] = parseInteger(strs[i]);
}
return rs;
}
return null;
}
/**
* 字符串转换成单精度浮点数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Float parseFloat(String value, Float defaultVal)
{
Float v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Float.parseFloat(value);
}
}
catch (Exception e)
{
logger.error("parseFloat [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成单精度浮点数字
*
* @param value
* @return 转换出错时返回null
*/
public static Float parseFloat(String value)
{
return parseFloat(value, null);
}
/**
* 字符串转换成双精度浮点数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Double parseDouble(String value, Double defaultVal)
{
Double v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Double.parseDouble(value);
}
}
catch (Exception e)
{
logger.error("parseDouble [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成双精度浮点数字
*
* @param value
* @return 转换出错时返null
*/
public static Double parseDouble(String value)
{
return parseDouble(value, null);
}
/**
* 字符串转换成布尔型对象
*
* @param value
* @return 转换出错时返回null
*/
public static Boolean parseBoolean(String value)
{
return Boolean.parseBoolean(value);
}
/**
*
* @Title:
* @Description: 对mysql的查询中,有特殊字符:_ % ' \ 都需要调用该方法转义
* @param @param str
* @param @return 设定文件
* @author
* @return 返回类型
* @throws
*/
public static String mysqlConvertStr(String str)
{
if (!StringUtils.isBlank(str))
{
str = StringUtils.deleteWhitespace(str);
if (StringUtils.contains(str, '\\'))
{
str = StringUtils.replace(str, "\\", "\\\\");
}
if (StringUtils.contains(str, '_'))
{
str = StringUtils.replace(str, "_", "\\_");
}
if (StringUtils.contains(str, "'"))
{
str = StringUtils.replace(str, "'", "\\'");
}
return str;
}
return null;
}
/*
* 获得当天的凌晨时间
*/
public static Date getTodayMorning()
{
Calendar calendar = Calendar.getInstance(Locale.CHINA);
calendar.add(Calendar.DATE, -1);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
int nDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, month - 1, nDay, 23, 59, 59);
Date dateInfo = calendar.getTime();
return dateInfo;
}
/*
* 除法运算
*/
public static double divide(double firstNum, double secondNum)
{
double result = 0;
if (firstNum != 0 && secondNum != 0)
{
BigDecimal first = new BigDecimal(firstNum);
BigDecimal second = new BigDecimal(secondNum);
result = first.divide(second, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
return result;
}
/*
* 进行单位的换算
*/
public static String selectUnit(double num, String type)
{
final double radix = 1024;
int index = -1;
String[] unit = { "B", "K", "M", "G", "T", "P", "E" };
for (int i = 0; i < unit.length; i++)
{
if (type.trim().equalsIgnoreCase(unit[i]))
index = i;
}
if (index == -1)
{
return num + type;
}
String result = num + unit[index];
while (num >= radix && index < 6)
{
num = divide(num, radix);
index++;
result = num + unit[index];
}
return result;
}
public static String selectDate(String str, String type)
{
double num = Double.valueOf(str);
final double radix = 60;
int index = -1;
String[] unit = { "s", "m", "h" };
for (int i = 0; i < unit.length; i++)
{
if (type.trim().equalsIgnoreCase(unit[i]))
index = i;
}
if (index == -1)
{
return num + type;
}
String time = num + unit[index];
while (num >= radix && index < 2)
{
num = divide(num, radix);
index++;
time = num + unit[index];
}
return time;
}
// 把字符串转换为数字
public static int parse2Int(String value)
{
value = value.replaceAll("[^0-9]", "").trim();
if (value.equals(""))
{
return 0;
}
return Integer.valueOf(value).intValue();
}
public static float parset2Float(String value)
{
if (value == null || "".equals(value))
{
return 0;
}
try
{
value = value.replaceAll("[^0-9.]", "");
return Float.parseFloat(value);
}
catch (Exception e)
{
logger.error("parset2Float [value:" + value + "]", e);
return 0;
}
}
/**
* 验证邮箱地址是否正确
* @param email
* @return
*/
public static boolean checkEmail(String email)
{
boolean flag = false;
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
return flag;
}
/**
* 验证手机号码
* @param mobiles
* @return [0-9]{5,9}
*/
public static boolean isMobileNO(String mobiles)
{
boolean flag = false;
Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
flag = m.matches();
return flag;
}
public static String getStringNull(String str)
{
if (str == null)
{
return "";
}
return str;
}
public static boolean isIndexOfTtl(String line)
{
if (line.toLowerCase().indexOf("ttl") != -1)
{
return true;
}
return false;
}
/**
* @title: checkResult
* @description:
* @param result
* @return
* @throws:
* @author:
* @date:
*/
public static String checkResult(String[] result)
{
if (result.length >= 3)
{
return "false";
}
else
{
return "true";
}
}
// 判断是数字
public static boolean isNum(String str)
{
for (int i = 0; i < str.length(); i++)
{
if (!Character.isDigit(str.charAt(i)))
{
return false;
}
}
return true;
}
public static int getCountOrTen(int count, int start)
{
if ((count - start) < 10)
{
return (count - start);
}
return 10;
}
public static List<String> stringToList(String str)
{
if (str == null || str.length() < 1)
{
return null;
}
String[] array = str.split(",");
if (array == null || array.length < 1)
{
return null;
}
List<String> resultList = new ArrayList<String>();
for (String item : array)
{
if (item != null)
{
resultList.add(item);
}
}
return resultList;
}
/**
* 将ID字符串转换成,ID List
* @param idStr 例子:2,3,4,5,6
* @return
*/
public static List<Integer> getIDList(String idStr)
{
try
{
if (idStr == null || idStr.length() < 1)
{
return null;
}
String[] array = idStr.split(",");
if (array == null || array.length < 1)
{
return null;
}
List<Integer> resultList = new ArrayList<Integer>();
Integer temp = null;
for (String item : array)
{
temp = parseInt(item);
if (temp != null)
{
resultList.add(temp);
}
}
return resultList;
}
catch (Exception e)
{
logger.error("getIDList [idStr:" + idStr + "]", e);
}
return null;
}
public static String stream2String(InputStream is)
throws UnsupportedEncodingException, IOException
{
Writer sbuf = new StringWriter();
IOUtils.copy(new InputStreamReader(is, Constants.CHAR_SET), sbuf);
return sbuf.toString();
}
/**
* 将字符串转码为utf-8,按字节截取字符串
* @param s 字符串
* @param maxLength 字符串转为字节时可保留的最大长度
* @return
*/
public static String cut(String s, int maxLength)
{
logger.debug("cut [string:" + s + "][maxLength:" + maxLength + "]");
String result = s;
try
{
if (!StringUtil.isEmpty(s))
{
byte[] srcBytes = s.getBytes(Constants.CHAR_SET);
if (srcBytes.length > maxLength && maxLength > 3)
{
// 保留3位给 "..."
maxLength = maxLength - 3;
StringBuffer buf = new StringBuffer();
char c;
int count = 0;
for (int i = 0; i < maxLength; i++)
{
if (count >= maxLength)
{
break;
}
c = s.charAt(i);
buf.append(c);
count += charLength(c);
}
buf.append("...");
result = buf.toString();
}
}
}
catch (UnsupportedEncodingException e)
{
logger.error("cut [string:" + s + "]", e);
}
return result;
}
/**
* 字符长度,UTF-8编码
* @param c 字符
* @return
* @throws UnsupportedEncodingException
*/
public static int charLength(char c) throws UnsupportedEncodingException
{
// 中文字符长度为3
return String.valueOf(c).getBytes(Constants.CHAR_SET).length;
}
}
package com.comname.smp.config.entity;
import java.util.Date;
import com.comname.common.util.StringUtil;
public class RemindHistory
{
private int id;
private int resourceId;// 资源ID
private Date sendTime;// 发送时间
private int sendType;// 发送类型 1 邮件 2 短信
private int remindTime;//提醒发送频率
public RemindHistory()
{
}
public RemindHistory(int resId, int sendType)
{
this.resourceId = resId;
this.sendType = sendType;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public int getResourceId()
{
return resourceId;
}
public void setResourceId(int resourceId)
{
this.resourceId = resourceId;
}
public Date getSendTime()
{
return sendTime;
}
public void setSendTime(Date sendTime)
{
this.sendTime = sendTime;
}
public String getSendTimeStr()
{
return StringUtil.date2String(sendTime);
}
public int getSendType()
{
return sendType;
}
public void setSendType(int sendType)
{
this.sendType = sendType;
}
public int getRemindTime()
{
return remindTime;
}
public void setRemindTime(int remindTime)
{
this.remindTime = remindTime;
}
}
package com.comname.common.sms;
/**
*
* Description:短信类<br>
* Class Name: SMSInfo.java<br>
* Project Name: OSM<br>
* Author: <br>
* Date: <br>
*
*/
public class SMSInfo
{
/**
* 手机号码
*/
private String phoneNum;
/**
* 短信内容
*/
private String content;
public SMSInfo()
{
}
public SMSInfo(String phoneNum, String content)
{
this.phoneNum = phoneNum;
this.content = content;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString()
{
return "SMSInfo [phoneNum=" + phoneNum + ", content=" + content + "]";
}
}
package com.comname.common.sms;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class SMSInfoQueueService
{
// 等待发送的短信队列
private static BlockingQueue<SMSInfo> SMSInfo = new ArrayBlockingQueue<SMSInfo>(100);
public static BlockingQueue<SMSInfo> getSMSInfoQueue()
{
return SMSInfo;
}
}
system_zh_CN.properties
##############\u77ed\u4fe1\u732b\u670d\u52a1\u914d\u7f6e##################
#\u662f\u5426\u5f00\u542f\u77ed\u4fe1\u732b\u670d\u52a1 1\u5f00\u542f
sms_status=1
#\u7f51\u7ba1ID
sms_server_id=modem.com1
#\u77ed\u4fe1\u732b\u4e32\u53e3
sms_com_port=/dev/ttyS0
#\u4e32\u53e3\u6bcf\u79d2\u53d1\u9001\u6570\u636e\u7684bit\u4f4d\u6570
sms_baud_rate=115200
#\u77ed\u4fe1\u732b\u751f\u4ea7\u5382\u5546
sms_manufacturer=SIEMENS
#\u77ed\u4fe1\u7c7b\u578b
sms_model=TC35
#SIM\u5361\u5bc6\u7801
sms_sim_pin=1234
#\u77ed\u4fe1\u4e2d\u5fc3\u53f7\u7801
sms_smsc_number=+8613800270500
#\u90ae\u4ef6\u3001\u77ed\u4fe1\u53d1\u9001\u9891\u7387\uff0c\u6bcf\u5206\u949f\u7684\u503c\u4e3a100
remind_time=1000
###############\u4e2a\u6570###############
Number=\u4e2a
language.properties
language = zh_CN
<!-- 短信猫服务,容器加载 -->
<bean id="SMSServiceTask" class="com.comname.smp.config.util.SMSServiceTask" />
<bean id="SMSServiceTaskJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="name" value="job_SMSServiceTask"/>
<!--false表示等上一个任务执行完后再开启新的任务-->
<property name="concurrent" value="false"/>
<property name="targetObject" ref="SMSServiceTask" />
<property name="targetMethod" value="sendSMS" />
</bean>
<bean id="SMSServiceTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="SMSServiceTaskJob" />
<property name="startDelay" value="10000" />
<!-- 每10分钟执行一次 -->
<property name="cronExpression" value="0 */50 * * * ?" />
</bean>
package com.comname.smp.config.util;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import com.comname.common.SystemMessage;
import com.comname.common.sms.MessageSender;
import com.comname.common.sms.SMSInfo;
import com.comname.common.sms.SMSInfoQueueService;
import com.comname.common.util.StringUtil;
/**
* 启动发送短信程序,每10分钟执行一次
* @author
*/
public class SMSServiceTask
{
private static final Logger logger = Logger.getLogger(SMSServiceTask.class);
// 短信队列
BlockingQueue<SMSInfo> smsInfoQueue = SMSInfoQueueService.getSMSInfoQueue();
private static final int THREA_COUNT = 20;
private ExecutorService pool = null;
public SMSServiceTask()
{
pool = Executors.newFixedThreadPool(THREA_COUNT);
}
public void sendSMS()
{
logger.info("sendSMS [SMS_STATUS:" + SystemMessage.SMS_STATUS + "]");
if (SystemMessage.SMS_STATUS.equals("1"))
{
long st = System.currentTimeMillis();
String date = StringUtil.date2String(new Date());
logger.info("sendSMS start [Date:" + date + "][Queue size:" + smsInfoQueue.size() + "]");
MessageSender sender = MessageSender.getInstance();
try
{
// 初始化短信猫服务
sender.initMessageSender();
if (sender != null)
{
while (true)
{
SMSInfo sms = smsInfoQueue.poll();
if (sms != null)
{
logger.info("sendSMS [Date:" + date + "][" + sms + "]");
SendMsgThread thread = new SendMsgThread();
thread.setSender(sender);
thread.setSms(sms);
pool.execute(thread);
}
else
{
break;
}
}
}
}
catch (Exception e)
{
logger.error("sendSMS error. [Date:" + date + "]", e);
}
long et = System.currentTimeMillis();
logger.info("sendSMS end [Date:" + date + "][execute time:" + (et - st) + "(ms)]");
}
}
}
package com.comname.common;
/**
* @author
*
*/
public interface SystemMessage
{
// 短信猫服务
String SMS_STATUS = SystemInfo.getInfoMessage("sms_status").trim();
String SMS_SERVER_ID = SystemInfo.getInfoMessage("sms_server_id").trim();
String SMS_COM_PORT = SystemInfo.getInfoMessage("sms_com_port").trim();
String SMS_BAUD_RATE = SystemInfo.getInfoMessage("sms_baud_rate").trim();
String SMS_MANUFACTURER = SystemInfo.getInfoMessage("sms_manufacturer").trim();
String SMS_MODEL = SystemInfo.getInfoMessage("sms_model").trim();
String SMS_SIM_PIN = SystemInfo.getInfoMessage("sms_sim_pin").trim();
String SMS_SMSC_NUMBER = SystemInfo.getInfoMessage("sms_smsc_number").trim();
}
/**
* @Title: SystemInfo.java
* @Package com.comname.tms.common
* @Description: TODO(用一句话描述该文件做什么)
* @author 蔡龙
* @date 2012-9-1 下午6:50:13
* @version V1.0
*/
package com.comname.common;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.comname.common.util.ResourcesUtil;
/**
* @Description: TODO(用一句话描述该文件做什么)
* @author
* @date
*/
public class SystemInfo
{
static String FILE_NAME = "conf/system_"+LanguageInfo.getInfoMessage()+".properties";//system_zh_CN.properties
private static Properties properties;
private static Logger log = Logger.getLogger(SystemInfo.class);
static
{
try
{
properties = ResourcesUtil.getResourceAsProperties(FILE_NAME);
}
catch (IOException e)
{
log.error("Load Error Information Failed " + FILE_NAME);
}
}
public static String getInfoMessage(String errorCode)
{
return properties.getProperty(errorCode, "Unkonw Error:" + errorCode);
}
public static String getInfoMessage(String errorCode, Object... args)
{
String msg = properties.getProperty(errorCode, "Unkonw Error:" + errorCode);
return MessageFormat.format(msg, args);
}
/**
* @param key 主键
* @return
*/
public static int getInt(String key)
{
int value = 0;
Object obj = properties.get(key);
if (obj != null)
{
try
{
value = Integer.valueOf((String)obj);
}
catch (Exception e)
{
log.error("getInt error [key:" + key + "]", e);
}
}
return value;
}
}
package com.comname.common;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.comname.common.util.ResourcesUtil;
public class LanguageInfo {
static String FILE_NAME = "conf/language.properties";
private static Properties properties;
private static Logger log = Logger.getLogger(SystemInfo.class);
static
{
try
{
properties = ResourcesUtil.getResourceAsProperties(FILE_NAME);
}
catch (IOException e)
{
log.error("Load Error Information Failed " + FILE_NAME);
}
}
public static String getInfoMessage()
{
String infoCode = "language";
return properties.getProperty(infoCode);
}
public static void main(String args[]){
System.out.print( getInfoMessage());
}
}
package com.comname.common.util;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Properties;
import com.comname.common.Constants;
/**
* 此类来自于ibatis2.3 通过classloader获取资源
*
* @author
*/
public class ResourcesUtil
{
// private static final String DEFAULT_CHARSET = Constants.CHAR_SET;
/**
* 字符编码格式
*/
public static final String CHAR_SET = "UTF-8";
private static ClassLoader defaultClassLoader;
/**
* Charset to use when calling getResourceAsReader. null means use the system default.
*/
private static Charset charset;
// private ResourcesUtil()
// {
// }
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader()
{
return defaultClassLoader;
}
/**
* Sets the default classloader
*
* @param defaultClassLoader
* - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader)
{
ResourcesUtil.defaultClassLoader = defaultClassLoader;
}
/**
* Returns the URL of the resource on the classpath
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException
{
return getResourceURL(getClassLoader(), resource);
}
/**
* Returns the URL of the resource on the classpath
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException
{
URL url = null;
if (loader != null)
{
url = loader.getResource(resource);
}
if (url == null)
{
url = ClassLoader.getSystemResource(resource);
}
if (url == null)
{
throw new IOException("Could not find resource " + resource);
}
return url;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(String resource) throws IOException
{
return getResourceAsStream(getClassLoader(), resource);
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(ClassLoader loader, String resource)
throws IOException
{
InputStream in = null;
if (loader != null)
{
in = loader.getResourceAsStream(resource);
}
if (in == null)
{
in = ClassLoader.getSystemResourceAsStream(resource);
}
if (in == null)
{
throw new IOException("Could not find resource " + resource);
}
return in;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource) throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(ClassLoader loader, String resource)
throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException
{
Reader reader;
if (charset == null)
{
reader = new InputStreamReader(getResourceAsStream(resource), DEFAULT_CHARSET);
}
else
{
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param loader
* The classloader used to load the resource
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource)
throws IOException
{
Reader reader;
if (charset == null)
{
reader = new InputStreamReader(getResourceAsStream(loader, resource), DEFAULT_CHARSET);
}
else
{
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a File object
*
* @param resource
* The resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static File getResourceAsFile(String resource) throws IOException
{
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param loader
* - the classloader used to load the resource
* @param resource
* - the resource to find
* @return The resource
* @throws IOException
* If the resource cannot be found or read
*/
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException
{
return new File(getResourceURL(loader, resource).getFile());
}
/**
* Gets a URL as an input stream
*
* @param urlString
* - the URL to get
* @return An input stream with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static InputStream getUrlAsStream(String urlString) throws IOException
{
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
/**
* Gets a URL as a Reader
*
* @param urlString
* - the URL to get
* @return A Reader with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static Reader getUrlAsReader(String urlString) throws IOException
{
return new InputStreamReader(getUrlAsStream(urlString), DEFAULT_CHARSET);
}
/**
* Gets a URL as a Properties object
*
* @param urlString
* - the URL to get
* @return A Properties object with the data from the URL
* @throws IOException
* If the resource cannot be found or read
*/
public static Properties getUrlAsProperties(String urlString) throws IOException
{
Properties props = new Properties();
InputStream in = null;
String propfile = urlString;
in = getUrlAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Loads a class
*
* @param className
* - the class to load
* @return The loaded class
* @throws ClassNotFoundException
* If the class cannot be found (duh!)
*/
public static Class classForName(String className)
{
Class clazz = null;
try
{
clazz = Class.forName(className);
}
catch (ClassNotFoundException e)
{
}
return clazz;
}
private static ClassLoader getClassLoader()
{
if (defaultClassLoader != null)
{
return defaultClassLoader;
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
public static Charset getCharset()
{
return charset;
}
/**
* Use this method to set the Charset to be used when calling the getResourceAsReader methods.
* This will allow iBATIS to function properly when the system default encoding doesn't deal
* well with unicode (IBATIS-340, IBATIS-349)
*
* @param charset
*/
public static void setCharset(Charset charset)
{
ResourcesUtil.charset = charset;
}
}
package com.comname.common.sms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.Message.MessageEncodings;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
import org.springframework.beans.factory.annotation.Autowired;
import com.comname.common.SystemMessage;
import com.comname.smp.config.dao.IRemindDao;
import com.comname.smp.config.entity.Remind;
/**
*
* Description:短信发送器<br>
*
*/
public class MessageSender
{
private static final Logger logger = LoggerFactory.getLogger(MessageSender.class);
@Autowired
private IRemindDao remindDao;
private static MessageSender sender;
private Service srv;
private MessageSender()
{
OutboundNotification outboundNotification = new OutboundNotification();
logger.info("Send message from a serial gsm modem.");
logger.info("Library Description:" + Library.getLibraryDescription());
logger.info("Version: " + Library.getLibraryVersion());
srv = Service.getInstance();
srv.setOutboundMessageNotification(outboundNotification);
}
public synchronized static MessageSender getInstance()
{
if (sender == null)
{
sender = new MessageSender();
}
return sender;
}
public synchronized void initMessageSender() throws Exception
{
srv = Service.getInstance();
// 短信服务未关闭则关闭服务并清空所有短信网关
if (srv.getServiceStatus() != Service.ServiceStatus.STOPPED)
{
srv.stopService();
srv.getGateways().clear();
}
// 加入新短信网关
/* SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 9600, "SIEMENS", "TC35"); */
// SerialModemGateway gateway = new SerialModemGateway(SystemMessage.SMS_SERVER_ID, SystemMessage.SMS_COM_PORT,
// Integer.parseInt(SystemMessage.SMS_BAUD_RATE), SystemMessage.SMS_MANUFACTURER, SystemMessage.SMS_MODEL);
SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 19200, "SIEMENS", "TC35");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin(SystemMessage.SMS_SIM_PIN);// SIM卡密码
gateway.setSmscNumber(SystemMessage.SMS_SMSC_NUMBER);// 短信中心号码
srv.addGateway(gateway);
// 启动短信服务
srv.startService();
}
public boolean sendMessage(String mbNum, String content)
{
logger.info("发短信:" + mbNum + ", " + content);
boolean success = false;
try
{
OutboundMessage msg = new OutboundMessage(mbNum, content);
msg.setEncoding(MessageEncodings.ENCUCS2);
msg.setStatusReport(true);
srv.sendMessage(msg);
success = true;
}
catch (Exception e)
{
logger.error(e.getMessage());
}
return success;
}
/**
* 销毁对象
*/
public synchronized void stopServer()
{
try
{
srv.getGateways().clear();
srv.stopService();
}
catch (Exception e)
{
logger.error(e.getMessage());
}
}
/**
* 短信发送成功后,调用该接口。并将发送短信的网关和短信内容对象传给process接口
*/
public class OutboundNotification implements IOutboundMessageNotification
{
public void process(AGateway gateway, OutboundMessage msg)
{
logger.info("Outbound handler called from Gateway: " + gateway.getGatewayId() + ",MSG:" + msg);
}
}
public static void main(String args[])
{
MessageSender sender = getInstance();
try
{
long begin = System.currentTimeMillis();// 取开始时间 单位是毫秒
// "modem.com1", "COM1", 9600, "SIEMENS", "TC35"
Remind remind = new Remind();
remind.setSmsId("modem.com1");
remind.setSmsComPort("COM1");
remind.setSmsBaudRate(19200);
remind.setSmsManufacturer("SIEMENS");
remind.setSmsModel("TC35");
remind.setSimPin("0000");
remind.setSmscNumber("+8613800270500");
sender.initMessageSender();
sender.sendMessage("15071054326", "测试短信告警1111111");
sender.sendMessage("15071054326", "测试短信告警1111111");
sender.stopServer();
long end = System.currentTimeMillis();// 取开始时间 单位是毫秒
System.out.println(begin - end);
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
package com.comname.smp.config.dao;
import com.comname.smp.config.entity.Remind;
import com.comname.smp.config.entity.RemindHistory;
public interface IRemindDao
{
/**
* 更新
* @param remind
* @return
*/
int updateRemind(Remind remind);
/**
* 保存
* @param remind
* @return
*/
int saveRemind(Remind remind);
/**
* 查询
* @return
*/
Remind getRemind();
/**
* 保存提醒记录
* @param remindHistory
*/
void saveRemindHistory(RemindHistory remindHistory);
/**
* 删除半小时前记录
*/
void delRemindHistory();
/**
* 获得半小时内记录条数
* @param remindHistory
* @return
*/
int getRemindHistory(RemindHistory remindHistory);
/**
* 更新
* @param remind
* @return
*/
int updateReportConf(Remind remind);
/**
* 保存
* @param remind
* @return
*/
int saveReportConf(Remind remind);
/**
* 查询
* @return
*/
Remind getReportConf();
}
package com.comname.smp.config.entity;
import java.util.List;
import com.comname.common.EntityBase;
import com.comname.common.util.StringUtil;
public class Remind extends EntityBase
{
private int id;
private int mailStatus; // 邮件开启状态
private String smtpHost; // SMTP域名
private String smtpPort; // SMTP端口
private String sendAccount;// 发送方邮件账号
private String sendPwd;// 发送方邮件密码
private String mailReceiver;// 接收的邮件地址 用逗号隔开
private List<String> mailReceiverList;// 接收的邮件地址
private String mailLevel;// 邮件发送级别
private int smsStatus;// 短信开启状态
private String smsReceiver;// 短信号码, 逗号隔开
private String smsId;//modem.com1:网关ID(即短信猫端口编号)
private String smsComPort;//短信猫串口 如:COM4
private int smsBaudRate;//串口每秒发送数据的bit位数 如:115200
private String smsManufacturer;//短信猫生产厂商 如:Huawei
private String smsModel;//短信类型
private String simPin;//SIM卡密码 通常为:0000或1234
private String smscNumber;//短信中心号码
private String smsLevel;// 短信发送级别
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public int getMailStatus()
{
return mailStatus;
}
public void setMailStatus(int mailStatus)
{
this.mailStatus = mailStatus;
}
public String getSmtpHost()
{
return smtpHost;
}
public void setSmtpHost(String smtpHost)
{
this.smtpHost = smtpHost;
}
public String getSmtpPort()
{
return smtpPort;
}
public void setSmtpPort(String smtpPort)
{
this.smtpPort = smtpPort;
}
public String getSendAccount()
{
return sendAccount;
}
public void setSendAccount(String sendAccount)
{
this.sendAccount = sendAccount;
}
public String getSendPwd()
{
return sendPwd;
}
public void setSendPwd(String sendPwd)
{
this.sendPwd = sendPwd;
}
public String getMailReceiver()
{
return mailReceiver;
}
public void setMailReceiver(String mailReceiver)
{
this.mailReceiver = mailReceiver;
}
public List<String> getMailReceiverList()
{
this.mailReceiverList = StringUtil.stringToList(mailReceiver);
return mailReceiverList;
}
public void setMailReceiverList(List<String> mailReceiverList)
{
this.mailReceiverList = mailReceiverList;
}
public int getSmsStatus()
{
return smsStatus;
}
public void setSmsStatus(int smsStatus)
{
this.smsStatus = smsStatus;
}
public String getSmsReceiver()
{
return smsReceiver;
}
public void setSmsReceiver(String smsReceiver)
{
this.smsReceiver = smsReceiver;
}
public String getMailLevel()
{
return mailLevel;
}
public void setMailLevel(String mailLevel)
{
this.mailLevel = mailLevel;
}
public String getSmsLevel()
{
return smsLevel;
}
public void setSmsLevel(String smsLevel)
{
this.smsLevel = smsLevel;
}
public String getSmsId()
{
return smsId;
}
public void setSmsId(String smsId)
{
this.smsId = smsId;
}
public String getSmsComPort()
{
return smsComPort;
}
public void setSmsComPort(String smsComPort)
{
this.smsComPort = smsComPort;
}
public int getSmsBaudRate()
{
return smsBaudRate;
}
public void setSmsBaudRate(int smsBaudRate)
{
this.smsBaudRate = smsBaudRate;
}
public String getSmsManufacturer()
{
return smsManufacturer;
}
public void setSmsManufacturer(String smsManufacturer)
{
this.smsManufacturer = smsManufacturer;
}
public String getSmsModel()
{
return smsModel;
}
public void setSmsModel(String smsModel)
{
this.smsModel = smsModel;
}
public String getSimPin()
{
return simPin;
}
public void setSimPin(String simPin)
{
this.simPin = simPin;
}
public String getSmscNumber()
{
return smscNumber;
}
public void setSmscNumber(String smscNumber)
{
this.smscNumber = smscNumber;
}
}
/**
*
*/
package com.comname.common;
/**
* @author
*
*/
public class EntityBase
{
private Integer beginIndex;
private Integer endIndex;
private Integer pageSize;
public Integer getBeginIndex()
{
return beginIndex;
}
public void setBeginIndex(Integer beginIndex)
{
this.beginIndex = beginIndex;
}
public Integer getEndIndex()
{
if (endIndex != null)
{
return endIndex;
}
else
{
if (beginIndex != null && pageSize != null)
{
return beginIndex + pageSize - 1;
}
}
return endIndex;
}
public void setEndIndex(Integer endIndex)
{
this.endIndex = endIndex;
}
public Integer getPageSize()
{
if (pageSize != null)
{
return pageSize;
}
else
{
if(endIndex != null && beginIndex != null)
{
return endIndex - beginIndex + 1;
}
}
return pageSize;
}
public void setPageSize(Integer pageSize)
{
this.pageSize = pageSize;
}
}
/**
* StringUtil.java, Created on
* Title: TMS <br/>
* Description: <br/>
* Copyright: Copyright (c) 2012 <br/>
* @author
* @version Revision: 1.0
*/
package com.comname.common.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.comname.common.Constants;
/**
* @author
*
*/
public class StringUtil
{
private static final Logger logger = Logger.getLogger(StringUtil.class);
/**
* <p>
* 检查字符串是否为空 ("") 或者为null
* </p>
*
* <pre>
* StringUtil.isEmpty(null) = true
* StringUtil.isEmpty("") = true
* StringUtil.isEmpty(" ") = false
* StringUtil.isEmpty("bob") = false
* StringUtil.isEmpty(" bob ") = false
* </pre>
*
* @param str
* 待检查的字符串,可能为null
* @return <code>true</code> 如果字符串为空或null
*/
public static boolean isEmpty(String str)
{
if (str == null || str.length() == 0)
{
return true;
}
return false;
}
public static String getMachine(String machine)
{
if (isEmpty(machine))
{
return "default";
}
return machine;
}
/**
*
* @title: isEmptyArray
* @description: 判断数组是否为空
* @param str
* @return
* @throws:
* @author:
* @date:
*/
public static boolean isEmptyArray(String[] str)
{
if (str == null || str.length == 0)
{
return true;
}
return false;
}
/**
* <p>
* 检查字符串是否为空格(" "), 空 ("") 或者 null.
* </p>
*
* <pre>
* StringUtil.isBlank(null) = true
* StringUtil.isBlank("") = true
* StringUtil.isBlank(" ") = true
* StringUtil.isBlank("bob") = false
* StringUtil.isBlank(" bob ") = false
* </pre>
*
* @param str
* 待检查的字符串,可能为null
* @return <code>true</code> 如果字符串是空格(" "), 空 ("") 或者 null
*/
public static boolean isBlank(String str)
{
if (str == null || "".equals(str.trim()))
{
return true;
}
return false;
}
/**
* <p>
* 将字符串用MD5算法加密
* </p>
*
* @param str
* 待加密的字符串
* @return MD5加密后的字符串
*/
public static String md5(String str)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes("UTF-8"));
byte[] b = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++)
{
int v = (int) b[i];
v = v < 0 ? 0x100 + v : v;
String cc = Integer.toHexString(v);
if (cc.length() == 1)
sb.append('0');
sb.append(cc);
}
return sb.toString();
}
catch (Exception e)
{
logger.error("call md5 is invalid [str:" + str + "]", e);
}
return "";
}
/**
* <p>
* 将字符串(yyyy-MM-dd格式)转化为Date类型
* </p>
*
* @param strDate
* 日期字符串
* @return "yyyy-MM-dd HH:mm:ss"格式的日期
*/
public static Date string2Date(String strDate)
{
return string2Date(strDate, FORMAT_DEFAULT);
}
/**
* <p>
* 将字符串按指定格式转换成日期
* </p>
*
* @param strDate
* 要转换的字符串
* @param strFormat
* 字符串的格式
* @return 字符串所代表的日期
*/
public static Date string2Date(String strDate, String strFormat)
{
if (isBlank(strDate) || isBlank(strFormat))
{
return null;
}
try
{
SimpleDateFormat sf = new SimpleDateFormat(strFormat);
Date date = sf.parse(strDate);
return date;
}
catch (Exception ex)
{
logger.error("string2Date [strDate:" + strDate + "][strFormat:" + strFormat + "]", ex);
}
return null;
}
/**
* Date对象转换成字符串
*
* @param date
* @param strFormat
* @return date或strFormat参数为空时返回null
*/
public static String date2String(Date date, String strFormat)
{
try
{
if (date != null)
{
SimpleDateFormat sf = new SimpleDateFormat(strFormat);
return sf.format(date);
}
}
catch (Exception e)
{
logger.error("date2String [date:" + date + "][format:" + strFormat + "]", e);
}
return null;
}
public static String convertArray(String[] str)
{
if (str == null)
{
return null;
}
String result = "";
StringBuffer res = new StringBuffer();
res.append("[");
for (int i = 0; i < str.length; i++)
{
res.append(str[i]);
res.append(",");
}
if (str.length > 0)
{
result = res.substring(0, res.length() - 1);
}
result = result + "]";
return result;
}
private static final String FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
private static final String FORMAT_ZT = "yyyyMMdd hhmmss";
private static final String FORMAT_BATCHID = "yyyyMMddHHmmss";
/**
* Date对象转换成yyyy-MM-dd HH:mm:ss格式的时间字符串
*
* @param date
* @return date参数为空时返回null
*/
public static String date2String(Date date)
{
return date2String(date, FORMAT_DEFAULT);
}
/**
* Date对象转换成yyyyMMddThhmmssZ格式的时间字符串
*
* @param date
* @return date参数为空时返回null
*/
public static String date2ZTString(Date date)
{
String str = date2String(date, FORMAT_ZT);
str = str.replace(' ', 'T') + "Z";
return str;
}
public static String data2Batchid(Date date)
{
return date2String(date, FORMAT_BATCHID);
}
/**
* 字符串转换成整型数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Integer parseInt(String value, Integer defaultVal)
{
Integer v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Integer.parseInt(value);
}
}
catch (Exception e)
{
logger.error("parseInt [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成整型数字
*
* @param value
* @return 转换出错时返回null
*/
public static Integer parseInt(String value)
{
return parseInt(value, null);
}
/**
* 字符串转换成长整型数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Long parseLong(String value, Long defaultVal)
{
Long v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Long.parseLong(value);
}
}
catch (Exception e)
{
logger.error("parseLong [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
public static Integer parseInteger(String value, Integer defaultVal)
{
Integer v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Integer.parseInt(value);
}
}
catch (Exception e)
{
logger.error("parseInteger [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成长整型数字
*
* @param value
* @return 转换出错时返回null
*/
public static Long parseLong(String value)
{
return parseLong(value, null);
}
public static Integer parseInteger(String value)
{
return parseInteger(value, null);
}
/**
*
* @Title:
* @Description: 字符串转换成数字型数组
* @param @param value
* @param @return 设定文件
* @author
* @return 返回类型
* @throws
*/
public static long[] parseArrayLong(String value)
{
if (value != null && value.length() > 0)
{
String strs[] = value.split(",");
long rs[] = new long[strs.length];
for (int i = 0; i < strs.length; i++)
{
rs[i] = parseLong(strs[i]);
}
return rs;
}
return null;
}
public static int[] parseArrayInt(String value)
{
if (value != null && value.length() > 0)
{
String strs[] = value.split(",");
int rs[] = new int[strs.length];
for (int i = 0; i < strs.length; i++)
{
rs[i] = parseInteger(strs[i]);
}
return rs;
}
return null;
}
/**
* 字符串转换成单精度浮点数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Float parseFloat(String value, Float defaultVal)
{
Float v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Float.parseFloat(value);
}
}
catch (Exception e)
{
logger.error("parseFloat [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成单精度浮点数字
*
* @param value
* @return 转换出错时返回null
*/
public static Float parseFloat(String value)
{
return parseFloat(value, null);
}
/**
* 字符串转换成双精度浮点数字
*
* @param value
* @param defaultVal
* @return 转换出错时返回默认值
*/
public static Double parseDouble(String value, Double defaultVal)
{
Double v = defaultVal;
try
{
if (!StringUtil.isEmpty(value))
{
v = Double.parseDouble(value);
}
}
catch (Exception e)
{
logger.error("parseDouble [value:" + value + "][defaultVal:" + defaultVal + "]", e);
}
return v;
}
/**
* 字符串转换成双精度浮点数字
*
* @param value
* @return 转换出错时返null
*/
public static Double parseDouble(String value)
{
return parseDouble(value, null);
}
/**
* 字符串转换成布尔型对象
*
* @param value
* @return 转换出错时返回null
*/
public static Boolean parseBoolean(String value)
{
return Boolean.parseBoolean(value);
}
/**
*
* @Title:
* @Description: 对mysql的查询中,有特殊字符:_ % ' \ 都需要调用该方法转义
* @param @param str
* @param @return 设定文件
* @author
* @return 返回类型
* @throws
*/
public static String mysqlConvertStr(String str)
{
if (!StringUtils.isBlank(str))
{
str = StringUtils.deleteWhitespace(str);
if (StringUtils.contains(str, '\\'))
{
str = StringUtils.replace(str, "\\", "\\\\");
}
if (StringUtils.contains(str, '_'))
{
str = StringUtils.replace(str, "_", "\\_");
}
if (StringUtils.contains(str, "'"))
{
str = StringUtils.replace(str, "'", "\\'");
}
return str;
}
return null;
}
/*
* 获得当天的凌晨时间
*/
public static Date getTodayMorning()
{
Calendar calendar = Calendar.getInstance(Locale.CHINA);
calendar.add(Calendar.DATE, -1);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
int nDay = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, month - 1, nDay, 23, 59, 59);
Date dateInfo = calendar.getTime();
return dateInfo;
}
/*
* 除法运算
*/
public static double divide(double firstNum, double secondNum)
{
double result = 0;
if (firstNum != 0 && secondNum != 0)
{
BigDecimal first = new BigDecimal(firstNum);
BigDecimal second = new BigDecimal(secondNum);
result = first.divide(second, 2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
return result;
}
/*
* 进行单位的换算
*/
public static String selectUnit(double num, String type)
{
final double radix = 1024;
int index = -1;
String[] unit = { "B", "K", "M", "G", "T", "P", "E" };
for (int i = 0; i < unit.length; i++)
{
if (type.trim().equalsIgnoreCase(unit[i]))
index = i;
}
if (index == -1)
{
return num + type;
}
String result = num + unit[index];
while (num >= radix && index < 6)
{
num = divide(num, radix);
index++;
result = num + unit[index];
}
return result;
}
public static String selectDate(String str, String type)
{
double num = Double.valueOf(str);
final double radix = 60;
int index = -1;
String[] unit = { "s", "m", "h" };
for (int i = 0; i < unit.length; i++)
{
if (type.trim().equalsIgnoreCase(unit[i]))
index = i;
}
if (index == -1)
{
return num + type;
}
String time = num + unit[index];
while (num >= radix && index < 2)
{
num = divide(num, radix);
index++;
time = num + unit[index];
}
return time;
}
// 把字符串转换为数字
public static int parse2Int(String value)
{
value = value.replaceAll("[^0-9]", "").trim();
if (value.equals(""))
{
return 0;
}
return Integer.valueOf(value).intValue();
}
public static float parset2Float(String value)
{
if (value == null || "".equals(value))
{
return 0;
}
try
{
value = value.replaceAll("[^0-9.]", "");
return Float.parseFloat(value);
}
catch (Exception e)
{
logger.error("parset2Float [value:" + value + "]", e);
return 0;
}
}
/**
* 验证邮箱地址是否正确
* @param email
* @return
*/
public static boolean checkEmail(String email)
{
boolean flag = false;
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
return flag;
}
/**
* 验证手机号码
* @param mobiles
* @return [0-9]{5,9}
*/
public static boolean isMobileNO(String mobiles)
{
boolean flag = false;
Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
flag = m.matches();
return flag;
}
public static String getStringNull(String str)
{
if (str == null)
{
return "";
}
return str;
}
public static boolean isIndexOfTtl(String line)
{
if (line.toLowerCase().indexOf("ttl") != -1)
{
return true;
}
return false;
}
/**
* @title: checkResult
* @description:
* @param result
* @return
* @throws:
* @author:
* @date:
*/
public static String checkResult(String[] result)
{
if (result.length >= 3)
{
return "false";
}
else
{
return "true";
}
}
// 判断是数字
public static boolean isNum(String str)
{
for (int i = 0; i < str.length(); i++)
{
if (!Character.isDigit(str.charAt(i)))
{
return false;
}
}
return true;
}
public static int getCountOrTen(int count, int start)
{
if ((count - start) < 10)
{
return (count - start);
}
return 10;
}
public static List<String> stringToList(String str)
{
if (str == null || str.length() < 1)
{
return null;
}
String[] array = str.split(",");
if (array == null || array.length < 1)
{
return null;
}
List<String> resultList = new ArrayList<String>();
for (String item : array)
{
if (item != null)
{
resultList.add(item);
}
}
return resultList;
}
/**
* 将ID字符串转换成,ID List
* @param idStr 例子:2,3,4,5,6
* @return
*/
public static List<Integer> getIDList(String idStr)
{
try
{
if (idStr == null || idStr.length() < 1)
{
return null;
}
String[] array = idStr.split(",");
if (array == null || array.length < 1)
{
return null;
}
List<Integer> resultList = new ArrayList<Integer>();
Integer temp = null;
for (String item : array)
{
temp = parseInt(item);
if (temp != null)
{
resultList.add(temp);
}
}
return resultList;
}
catch (Exception e)
{
logger.error("getIDList [idStr:" + idStr + "]", e);
}
return null;
}
public static String stream2String(InputStream is)
throws UnsupportedEncodingException, IOException
{
Writer sbuf = new StringWriter();
IOUtils.copy(new InputStreamReader(is, Constants.CHAR_SET), sbuf);
return sbuf.toString();
}
/**
* 将字符串转码为utf-8,按字节截取字符串
* @param s 字符串
* @param maxLength 字符串转为字节时可保留的最大长度
* @return
*/
public static String cut(String s, int maxLength)
{
logger.debug("cut [string:" + s + "][maxLength:" + maxLength + "]");
String result = s;
try
{
if (!StringUtil.isEmpty(s))
{
byte[] srcBytes = s.getBytes(Constants.CHAR_SET);
if (srcBytes.length > maxLength && maxLength > 3)
{
// 保留3位给 "..."
maxLength = maxLength - 3;
StringBuffer buf = new StringBuffer();
char c;
int count = 0;
for (int i = 0; i < maxLength; i++)
{
if (count >= maxLength)
{
break;
}
c = s.charAt(i);
buf.append(c);
count += charLength(c);
}
buf.append("...");
result = buf.toString();
}
}
}
catch (UnsupportedEncodingException e)
{
logger.error("cut [string:" + s + "]", e);
}
return result;
}
/**
* 字符长度,UTF-8编码
* @param c 字符
* @return
* @throws UnsupportedEncodingException
*/
public static int charLength(char c) throws UnsupportedEncodingException
{
// 中文字符长度为3
return String.valueOf(c).getBytes(Constants.CHAR_SET).length;
}
}
package com.comname.smp.config.entity;
import java.util.Date;
import com.comname.common.util.StringUtil;
public class RemindHistory
{
private int id;
private int resourceId;// 资源ID
private Date sendTime;// 发送时间
private int sendType;// 发送类型 1 邮件 2 短信
private int remindTime;//提醒发送频率
public RemindHistory()
{
}
public RemindHistory(int resId, int sendType)
{
this.resourceId = resId;
this.sendType = sendType;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public int getResourceId()
{
return resourceId;
}
public void setResourceId(int resourceId)
{
this.resourceId = resourceId;
}
public Date getSendTime()
{
return sendTime;
}
public void setSendTime(Date sendTime)
{
this.sendTime = sendTime;
}
public String getSendTimeStr()
{
return StringUtil.date2String(sendTime);
}
public int getSendType()
{
return sendType;
}
public void setSendType(int sendType)
{
this.sendType = sendType;
}
public int getRemindTime()
{
return remindTime;
}
public void setRemindTime(int remindTime)
{
this.remindTime = remindTime;
}
}
package com.comname.common.sms;
/**
*
* Description:短信类<br>
* Class Name: SMSInfo.java<br>
* Project Name: OSM<br>
* Author: <br>
* Date: <br>
*
*/
public class SMSInfo
{
/**
* 手机号码
*/
private String phoneNum;
/**
* 短信内容
*/
private String content;
public SMSInfo()
{
}
public SMSInfo(String phoneNum, String content)
{
this.phoneNum = phoneNum;
this.content = content;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString()
{
return "SMSInfo [phoneNum=" + phoneNum + ", content=" + content + "]";
}
}
package com.comname.common.sms;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class SMSInfoQueueService
{
// 等待发送的短信队列
private static BlockingQueue<SMSInfo> SMSInfo = new ArrayBlockingQueue<SMSInfo>(100);
public static BlockingQueue<SMSInfo> getSMSInfoQueue()
{
return SMSInfo;
}
}
system_zh_CN.properties
##############\u77ed\u4fe1\u732b\u670d\u52a1\u914d\u7f6e##################
#\u662f\u5426\u5f00\u542f\u77ed\u4fe1\u732b\u670d\u52a1 1\u5f00\u542f
sms_status=1
#\u7f51\u7ba1ID
sms_server_id=modem.com1
#\u77ed\u4fe1\u732b\u4e32\u53e3
sms_com_port=/dev/ttyS0
#\u4e32\u53e3\u6bcf\u79d2\u53d1\u9001\u6570\u636e\u7684bit\u4f4d\u6570
sms_baud_rate=115200
#\u77ed\u4fe1\u732b\u751f\u4ea7\u5382\u5546
sms_manufacturer=SIEMENS
#\u77ed\u4fe1\u7c7b\u578b
sms_model=TC35
#SIM\u5361\u5bc6\u7801
sms_sim_pin=1234
#\u77ed\u4fe1\u4e2d\u5fc3\u53f7\u7801
sms_smsc_number=+8613800270500
#\u90ae\u4ef6\u3001\u77ed\u4fe1\u53d1\u9001\u9891\u7387\uff0c\u6bcf\u5206\u949f\u7684\u503c\u4e3a100
remind_time=1000
###############\u4e2a\u6570###############
Number=\u4e2a
language.properties
language = zh_CN