⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smsserver.java

📁 使用smslib和GSP modem 发送和接收手机短息
💻 JAVA
字号:
// SMSLib for Java v3
// A Java API library for sending and receiving SMS via a GSM modem
// or other supported gateways.
// Web Site: http://www.smslib.org
//
// Copyright (C) 2002-2008, Thanasis Delenikas, Athens/GREECE.
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.smslib.smsserver;

import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.smslib.MessagePriorities;

/**
 * SMSServer Application.
 * <p>
 * The latest SMSServer introduction and documentation can be found on <a
 * href="http://smslib.org">http://smslib.org</a>
 */
public class SMSServer
{
	public org.smslib.Service srv;

	private Properties props;

	private boolean shutdown = false;

	private List infList;

	public OutboundNotification outboundNotification;

	public CallNotification callNotification;

	private boolean optRunOnce = false;

	public SMSServer()
	{
		srv = new org.smslib.Service();
		infList = new ArrayList();
		Runtime.getRuntime().addShutdownHook(new Shutdown());
		outboundNotification = new OutboundNotification();
		callNotification = new CallNotification();
	}

	private class Shutdown extends Thread
	{
		public void run()
		{
			srv.getLogger().info("SMSServer shutting down, please wait...");
			shutdown = true;
			try
			{
				srv.stopService();
			}
			catch (Exception e)
			{
				srv.getLogger().error(e);
				e.printStackTrace();
			}
		}
	}

	private void loadConfiguration() throws Exception
	{
		FileInputStream f;
		props = new Properties();
		if (System.getProperty("smsserver.configdir") != null) f = new FileInputStream(System.getProperty("smsserver.configdir") + "SMSServer.conf");
		else if (System.getProperty("smsserver.configfile") != null) f = new FileInputStream(System.getProperty("smsserver.configfile"));
		else throw new org.smslib.SMSLibException("Cannot find SMSServer configuration file!");
		props.load(f);
		f.close();
		for (int i = 0; i < Integer.MAX_VALUE; i++)
		{
			try
			{
				String propName = "gateway." + i;
				String propValue = props.getProperty(propName, "");
				if (propValue.length() == 0) break;
				StringTokenizer tokens = new StringTokenizer(propValue, ",");
				String gtwId = tokens.nextToken().trim();
				String gtwClass = tokens.nextToken().trim();
				Object[] args = new Object[] { gtwId, props, this };
				Class[] argsClass = new Class[] { String.class, Properties.class, SMSServer.class };
				Class c = Class.forName("org.smslib.smsserver.gateways." + gtwClass);
				java.lang.reflect.Constructor constructor = c.getConstructor(argsClass);
				org.smslib.smsserver.AGateway gtw = (AGateway) constructor.newInstance(args);
				srv.addGateway(gtw.create());
				srv.getLogger().info("SMSServer: added gateway " + gtwId + " / " + gtw.getDescription());
			}
			catch (Exception e)
			{
				srv.getLogger().error("SMSServer: Unknown Gateway in configuration file!");
			}
		}
		for (int i = 0; i < Integer.MAX_VALUE; i++)
		{
			try
			{
				String propName = "interface." + i;
				String propValue = props.getProperty(propName, "");
				if (propValue.length() == 0) break;
				StringTokenizer tokens = new StringTokenizer(propValue, ",");
				String infId = tokens.nextToken().trim();
				String infClass = tokens.nextToken().trim();
				InterfaceTypes infType = null;
				String sinfType = tokens.hasMoreTokens() ? tokens.nextToken() : "inoutbound";
				sinfType = sinfType.trim();
				if ("inbound".equalsIgnoreCase(sinfType))
				{
					infType = InterfaceTypes.INBOUND;
				}
				else if ("outbound".equalsIgnoreCase(sinfType))
				{
					infType = InterfaceTypes.OUTBOUND;
				}
				else
				{ // NULL or other crap
					infType = InterfaceTypes.INOUTBOUND;
				}
				Object[] args = new Object[] { infId, props, this, infType };
				Class[] argsClass = new Class[] { String.class, Properties.class, SMSServer.class, InterfaceTypes.class };
				Class c = Class.forName("org.smslib.smsserver.interfaces." + infClass);
				java.lang.reflect.Constructor constructor = c.getConstructor(argsClass);
				org.smslib.smsserver.AInterface inf = (AInterface) constructor.newInstance(args);
				infList.add(inf);
				srv.getLogger().info("SMSServer: added interface " + infId + " / " + inf.getDescription() + " / " + inf.getType());
			}
			/* Check for exceptions thrown by the constructor itself */
			catch (InvocationTargetException e)
			{
				srv.getLogger().error("SMSServer: Illegal Interface configuration: " + e.getCause().getMessage());
			}
			catch (Exception e)
			{
				srv.getLogger().error("SMSServer: Unknown Interface in configuration file!");
			}
		}
	}

	private void process() throws Exception
	{
		while (true)
		{
			srv.getLogger().info("SMSServer: Processing @ " + new java.util.Date());
			srv.logDebug("** GATEWAY STATISTICS **");
			for (int i = 0; i < srv.getGatewayList().size(); i++)
			{
				org.smslib.AGateway gtw = (org.smslib.AGateway) srv.getGatewayList().get(i);
				srv.logDebug("Gateway: " + gtw.getGatewayId() + ", Load: " + srv.getGatewayQueueLoad(gtw.getGatewayId()));
			}
			srv.logDebug("** GATEWAY STATISTICS **");
			if (!shutdown) readMessages();
			if (!shutdown) sendMessages();
			if (optRunOnce) break;
			if (!shutdown) Thread.sleep(Integer.parseInt(props.getProperty("settings.poll_interval", "60")) * 1000);
			if (shutdown) break;
		}
	}

	private void startInterfaces() throws Exception
	{
		for (int i = 0; i < infList.size(); i++)
			((AInterface) infList.get(i)).start();
	}

	private void stopInterfaces() throws Exception
	{
		for (int i = 0; i < infList.size(); i++)
			((AInterface) infList.get(i)).stop();
	}

	private void run() throws Exception
	{
		loadConfiguration();
		try
		{
			startInterfaces();
			srv.startService();
			process();
		}
		finally
		{
			srv.stopService();
			stopInterfaces();
		}
	}

	private void readMessages() throws Exception
	{
		List msgList;
		msgList = new ArrayList();
		srv.readMessages(msgList, org.smslib.MessageClasses.ALL);
		if (msgList.size() > 0)
		{
			for (int i = 0; i < infList.size(); i++)
			{
				AInterface inf = (AInterface) infList.get(i);
				if (inf.isInbound()) inf.MessagesReceived(msgList);
			}
		}
		if (props.getProperty("settings.delete_after_processing", "no").equalsIgnoreCase("yes"))
		{
			for (int i = 0, n = msgList.size(); i < n; i++)
				srv.deleteMessage((org.smslib.InboundMessage) msgList.get(i));
		}
	}

	private void sendMessages() throws Exception
	{
		List msgList = new ArrayList();
		for (int i = 0; i < infList.size(); i++)
		{
			AInterface inf = (AInterface) infList.get(i);
			if (inf.isOutbound()) msgList.addAll(inf.getMessagesToSend());
		}
		if (msgList.size() > 0)
		{
			if (props.getProperty("settings.send_mode", "sync").equalsIgnoreCase(("sync")))
			{
				srv.logInfo("SMSServer: sending synchronously...");
				srv.sendMessages(msgList);
				for (int i = 0; i < infList.size(); i++)
				{
					AInterface inf = (AInterface) infList.get(i);
					if (inf.isOutbound()) inf.markMessages(msgList);
				}
			}
			else
			{
				srv.logInfo("SMSServer: sending asynchronously...");
				srv.queueMessages(msgList);
			}
		}
	}

	private class OutboundNotification implements org.smslib.IOutboundMessageNotification
	{
		public void process(String gatewayId, org.smslib.OutboundMessage msg)
		{
			try
			{
				for (int i = 0; i < infList.size(); i++)
				{
					AInterface inf = (AInterface) infList.get(i);
					if (inf.isOutbound()) inf.markMessage(msg);
				}
			}
			catch (Exception e)
			{
				srv.getLogger().fatal(e);
			}
		}
	}

	private class CallNotification implements org.smslib.ICallNotification
	{
		public void process(String gtwId, String callerId)
		{
			try
			{
				for (int i = 0; i < infList.size(); i++)
				{
					AInterface inf = (AInterface) infList.get(i);
					inf.CallReceived(gtwId, callerId);
				}
			}
			catch (Exception e)
			{
				srv.getLogger().fatal(e);
			}
		}
	}

	public boolean checkPriorityTimeFrame(MessagePriorities priority)
	{
		String timeFrame;
		String from, to, current;
		Calendar cal = Calendar.getInstance();
		if (priority == MessagePriorities.LOW) timeFrame = props.getProperty("settings.timeframe.low", "0000-2359");
		else if (priority == MessagePriorities.NORMAL) timeFrame = props.getProperty("settings.timeframe.normal", "0000-2359");
		else if (priority == MessagePriorities.HIGH) timeFrame = props.getProperty("settings.timeframe.high", "0000-2359");
		else timeFrame = "0000-2359";
		from = timeFrame.substring(0, 4);
		to = timeFrame.substring(5, 9);
		cal.setTime(new java.util.Date());
		current = cal.get(Calendar.HOUR_OF_DAY) < 10 ? "0" + cal.get(Calendar.HOUR_OF_DAY) : "" + cal.get(Calendar.HOUR_OF_DAY);
		current += cal.get(Calendar.MINUTE) < 10 ? "0" + cal.get(Calendar.MINUTE) : "" + cal.get(Calendar.MINUTE);
		if ((Integer.parseInt(current) >= Integer.parseInt(from)) && (Integer.parseInt(current) < Integer.parseInt(to))) return true;
		else return false;
	}

	public static void main(String[] args)
	{
		SMSServer app = new SMSServer();
		for (int i = 0; i < args.length; i++)
		{
			if (args[i].equalsIgnoreCase("-runonce")) app.optRunOnce = true;
			else System.out.println("Invalid argument: " + args[i]);
		}
		try
		{
			app.run();
			app.srv.getLogger().info("SMSServer exiting normally.");
		}
		catch (Exception e)
		{
			app.srv.getLogger().fatal("SMSServer Error: ", e);
			try
			{
				app.srv.stopService();
			}
			catch (Exception e1)
			{
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -