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

📄 clickatellhttpgateway.java

📁 最近使用的java 通过串口通迅设备(手机或gsm猫)发送短信息的源码
💻 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.http;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.OutboundMessage;
import org.smslib.OutboundWapSIMessage;
import org.smslib.TimeoutException;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.OutboundMessage.FailureCauses;
import org.smslib.OutboundMessage.MessageStatuses;
import org.smslib.OutboundWapSIMessage.WapSISignals;
import org.smslib.StatusReportMessage.DeliveryStatuses;

/**
 * Gateway for Clickatell bulk operator (http://www.clickatell.com) Outbound
 * only - implements HTTP & HTTPS interface.
 */
public class ClickatellHTTPGateway extends HTTPGateway
{
	String apiId, username, password;

	String sessionId;

	KeepAlive keepAlive;

	boolean secure;

	Object SYNC_Commander;

	String HTTP = "http://";

	String HTTPS = "https://";

	String URL_BALANCE = "api.clickatell.com/http/getbalance";

	String URL_COVERAGE = "api.clickatell.com/utils/routeCoverage.php";

	String URL_QUERYMSG = "api.clickatell.com/http/querymsg";

	String URL_AUTH = "api.clickatell.com/http/auth";

	String URL_PING = "api.clickatell.com/http/ping";

	String URL_SENDMSG = "api.clickatell.com/http/sendmsg";

	String URL_SENDWAPSI = "api.clickatell.com/mms/si_push";

	public ClickatellHTTPGateway(String id, String myApiId, String myUsername, String myPassword)
	{
		super(id);
		this.apiId = myApiId;
		this.username = myUsername;
		this.password = myPassword;
		this.sessionId = null;
		this.secure = false;
		this.SYNC_Commander = new Object();
		setAttributes(AGateway.GatewayAttributes.SEND | AGateway.GatewayAttributes.WAPSI | AGateway.GatewayAttributes.CUSTOMFROM | AGateway.GatewayAttributes.BIGMESSAGES | AGateway.GatewayAttributes.FLASHSMS);
	}

	/**
	 * Sets whether the gateway works in unsecured (HTTP) or secured (HTTPS)
	 * mode. False denotes unsecured.
	 * 
	 * @param mySecure
	 *            True for HTTPS, false for plain HTTP.
	 */
	public void setSecure(boolean mySecure)
	{
		this.secure = mySecure;
	}

	/**
	 * Return the operation mode (HTTP or HTTPS).
	 * 
	 * @return True for HTTPS, false for HTTP.
	 * @see #setSecure(boolean)
	 */
	public boolean getSecure()
	{
		return this.secure;
	}

	@Override
	public void startGateway() throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		getService().getLogger().logInfo("Starting gateway.");
		connect();
		super.startGateway();
	}

	@Override
	public void stopGateway() throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		getService().getLogger().logInfo("Stopping gateway.");
		super.stopGateway();
		this.sessionId = null;
		if (this.keepAlive != null)
		{
			this.keepAlive.interrupt();
			this.keepAlive.join();
			this.keepAlive = null;
		}
	}

	@Override
	@SuppressWarnings("unused")
	public float queryBalance() throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		if (this.sessionId == null) throw new GatewayException("Internal Clickatell Gateway error.");
		url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_BALANCE);
		request.add(new HttpHeader("session_id", this.sessionId, false));
		synchronized (this.SYNC_Commander)
		{
			response = HttpPost(url, request);
		}
		if (response.get(0).indexOf("Credit:") == 0) return Float.parseFloat(response.get(0).substring(response.get(0).indexOf(':') + 1));
		return -1;
	}

	@Override
	@SuppressWarnings("unused")
	public boolean queryCoverage(OutboundMessage msg) throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		if (this.sessionId == null) throw new GatewayException("Internal Clickatell Gateway error.");
		url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_COVERAGE);
		request.add(new HttpHeader("session_id", this.sessionId, false));
		request.add(new HttpHeader("msisdn", msg.getRecipient().substring(1), false));
		synchronized (this.SYNC_Commander)
		{
			response = HttpPost(url, request);
		}
		if (response.get(0).indexOf("OK") == 0) return true;
		return false;
	}

	@Override
	@SuppressWarnings("unused")
	public DeliveryStatuses queryMessage(String refNo) throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		int pos;
		if (this.sessionId == null) throw new GatewayException("Internal Clickatell Gateway error.");
		url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_QUERYMSG);
		request.add(new HttpHeader("session_id", this.sessionId, false));
		request.add(new HttpHeader("apimsgid", refNo, false));
		synchronized (this.SYNC_Commander)
		{
			response = HttpPost(url, request);
		}
		pos = response.get(0).indexOf("Status:");
		setDeliveryErrorCode(Integer.parseInt(response.get(0).substring(pos + 7).trim()));
		switch (getDeliveryErrorCode())
		{
			case 1:
				return DeliveryStatuses.UNKNOWN;
			case 2:
			case 3:
			case 8:
			case 11:
				return DeliveryStatuses.KEEPTRYING;
			case 4:
				return DeliveryStatuses.DELIVERED;
			case 5:
			case 6:
			case 7:
				return DeliveryStatuses.ABORTED;
			case 9:
			case 10:
				return DeliveryStatuses.ABORTED;
			case 12:
				return DeliveryStatuses.ABORTED;
			default:
				return DeliveryStatuses.UNKNOWN;
		}
	}

	void connect() throws GatewayException, IOException
	{
		try
		{
			if (!authenticate()) throw new GatewayException("Cannot authenticate to Clickatell.");
			this.keepAlive = new KeepAlive();
		}
		catch (MalformedURLException e)
		{
			throw new GatewayException("Internal Clickatell Gateway error.");
		}
	}

	boolean authenticate() throws IOException, MalformedURLException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		getService().getLogger().logDebug("Authenticate().");
		url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_AUTH);
		request.add(new HttpHeader("api_id", this.apiId, false));
		request.add(new HttpHeader("user", this.username, false));
		request.add(new HttpHeader("password", this.password, false));
		synchronized (this.SYNC_Commander)
		{
			response = HttpPost(url, request);
		}
		if (response.get(0).indexOf("ERR:") == 0)
		{
			this.sessionId = null;
			return false;
		}
		this.sessionId = response.get(0).substring(4);
		return true;
	}

	boolean ping() throws IOException, MalformedURLException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		getService().getLogger().logDebug("Ping()");
		url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_PING);
		request.add(new HttpHeader("session_id", this.sessionId, false));
		synchronized (this.SYNC_Commander)
		{
			response = HttpPost(url, request);
		}
		if (response.get(0).indexOf("ERR:") == 0) return false;
		return true;
	}

	@Override
	@SuppressWarnings("unused")
	public boolean sendMessage(OutboundMessage msg) throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		URL url;
		List<HttpHeader> request = new ArrayList<HttpHeader>();
		List<String> response;
		int requestFeatures = 0;
		boolean ok = false;
		if (this.sessionId == null)
		{
			getService().getLogger().logError("No session defined.");
			msg.setFailureCause(FailureCauses.GATEWAY_FAILURE);
			return false;
		}
		getService().getLogger().logDebug("sendMessage()");
		try
		{
			if (msg.getType() == MessageTypes.OUTBOUND) url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_SENDMSG);
			else if (msg.getType() == MessageTypes.WAPSI) url = new URL((this.secure ? this.HTTPS : this.HTTP) + this.URL_SENDWAPSI);
			else
			{
				msg.setFailureCause(FailureCauses.BAD_FORMAT);
				getService().getLogger().logError("Incorrect message format.");
				return false;
			}
			request.add(new HttpHeader("session_id", this.sessionId, false));
			request.add(new HttpHeader("to", msg.getRecipient().substring(1), false));
			request.add(new HttpHeader("concat", "3", false));
			if (msg.getPriority() < 0) request.add(new HttpHeader("queue", "3", false));
			else if (msg.getPriority() == 0) request.add(new HttpHeader("queue", "2", false));
			else if (msg.getPriority() >= 0) request.add(new HttpHeader("queue", "1", false));
			if (msg.getFrom() != null && msg.getFrom().length() != 0) request.add(new HttpHeader("from", msg.getFrom(), false));
			else if (getFrom() != null && getFrom().length() != 0) request.add(new HttpHeader("from", getFrom(), false));
			if (msg.getFlashSms()) request.add(new HttpHeader("msg_type", "SMS_FLASH", false));
			if (msg.getType() == MessageTypes.OUTBOUND)
			{
				if ((msg.getSrcPort() != -1) || (msg.getDstPort() != -1)) request.add(new HttpHeader("udh", msg.getPduUserDataHeader(), false));
				if (msg.getEncoding() == MessageEncodings.ENC7BIT) request.add(new HttpHeader("text", msg.getText(), false));
				else if (msg.getEncoding() == MessageEncodings.ENCUCS2)
				{
					request.add(new HttpHeader("unicode", "1", false));
					request.add(new HttpHeader("text", msg.getText(), true));
				}
			}
			else if (msg.getType() == MessageTypes.WAPSI)
			{
				request.add(new HttpHeader("si_id", String.valueOf(msg.getId()), false));
				if (((OutboundWapSIMessage) msg).getCreateDate() != null) request.add(new HttpHeader("si_created", formatDateUTC(((OutboundWapSIMessage) msg).getCreateDate()), false));
				if (((OutboundWapSIMessage) msg).getExpireDate() != null) request.add(new HttpHeader("si_expires", formatDateUTC(((OutboundWapSIMessage) msg).getExpireDate()), false));
				request.add(new HttpHeader("si_action", formatSignal(((OutboundWapSIMessage) msg).getSignal()), false));
				request.add(new HttpHeader("si_url", ((OutboundWapSIMessage) msg).getUrl().toString(), false));
				request.add(new HttpHeader("si_text", ((OutboundWapSIMessage) msg).getIndicationText(), false));
			}
			if (msg.getStatusReport()) request.add(new HttpHeader("deliv_ack", "1", false));
			if ((getFrom() != null && getFrom().length() != 0) || (msg.getFrom() != null && msg.getFrom().length() != 0)) requestFeatures += 16 + 32;
			if (msg.getFlashSms()) requestFeatures += 512;
			if (msg.getStatusReport()) requestFeatures += 8192;
			request.add(new HttpHeader("req_feat", "" + requestFeatures, false));
			synchronized (this.SYNC_Commander)
			{
				response = HttpPost(url, request);
			}
			if (response.get(0).indexOf("ID:") == 0)
			{
				msg.setRefNo(response.get(0).substring(4));
				msg.setDispatchDate(new Date());
				msg.setGatewayId(getGatewayId());
				msg.setMessageStatus(MessageStatuses.SENT);
				incOutboundMessageCount();
				ok = true;
			}
			else if (response.get(0).indexOf("ERR:") == 0)
			{
				switch (Integer.parseInt(response.get(0).substring(5, 8)))
				{
					case 1:
					case 2:
					case 3:
					case 4:
					case 5:
					case 6:
					case 7:
						msg.setFailureCause(FailureCauses.GATEWAY_AUTH);
						break;
					case 101:
					case 102:
					case 105:
					case 106:
					case 107:
					case 112:
					case 116:
					case 120:
						msg.setFailureCause(FailureCauses.BAD_FORMAT);
						break;
					case 114:
						msg.setFailureCause(FailureCauses.NO_ROUTE);
						break;
					case 301:
					case 302:
						msg.setFailureCause(FailureCauses.NO_CREDIT);
						break;
					default:
						msg.setFailureCause(FailureCauses.UNKNOWN);
						break;
				}
				msg.setRefNo(null);
				msg.setDispatchDate(null);
				msg.setMessageStatus(MessageStatuses.FAILED);
				ok = false;
			}
		}
		catch (MalformedURLException e)
		{
			getService().getLogger().logError("Malformed URL.", e);
		}
		catch (IOException e)
		{
			getService().getLogger().logError("I/O error.", e);
		}
		return ok;
	}

	String formatDateUTC(Date d)
	{
		String strDate = "", tmp = "";
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		strDate = String.valueOf(cal.get(Calendar.YEAR));
		tmp = String.valueOf(cal.get(Calendar.MONTH) + 1);
		if (tmp.length() != 2) tmp = "0" + tmp;
		strDate += "-" + tmp;
		tmp = String.valueOf(cal.get(Calendar.DATE));
		if (tmp.length() != 2) tmp = "0" + tmp;
		strDate += "-" + tmp;
		tmp = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
		if (tmp.length() != 2) tmp = "0" + tmp;
		strDate += "T" + tmp;
		tmp = String.valueOf(cal.get(Calendar.MINUTE));
		if (tmp.length() != 2) tmp = "0" + tmp;
		strDate += ":" + tmp;
		tmp = String.valueOf(cal.get(Calendar.SECOND));
		if (tmp.length() != 2) tmp = "0" + tmp;
		strDate += ":" + tmp + "Z";
		return strDate;
	}

	String formatSignal(WapSISignals signal)
	{
		if (signal == WapSISignals.NONE) return "signal-none";
		else if (signal == WapSISignals.LOW) return "signal-low";
		else if (signal == WapSISignals.MEDIUM) return "signal-medium";
		else if (signal == WapSISignals.HIGH) return "signal-high";
		else if (signal == WapSISignals.DELETE) return "signal-delete";
		else return "signal-none";
	}

	class KeepAlive extends Thread
	{
		public KeepAlive()
		{
			setPriority(MIN_PRIORITY);
			start();
		}

		@Override
		public void run()
		{
			getService().getLogger().logDebug("KeepAlive thread started.");
			while (true)
			{
				try
				{
					sleep(10 * 60 * 1000);
					if (ClickatellHTTPGateway.this.sessionId == null) break;
					getService().getLogger().logDebug("** KeepAlive START **");
					synchronized (ClickatellHTTPGateway.this.SYNC_Commander)
					{
						ping();
					}
					getService().getLogger().logDebug("** KeepAlive END **");
				}
				catch (InterruptedException e)
				{
					if (ClickatellHTTPGateway.this.sessionId == null) break;
				}
				catch (Exception e)
				{
					// Swallow this...
				}
			}
			getService().getLogger().logDebug("KeepAlive thread ended.");
		}
	}
}

⌨️ 快捷键说明

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