📄 clickatellhttpgateway.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
//
// SMSLib is distributed under the terms of the Apache License version 2.0
//
// Copyright (C) 2002-2007, Thanasis Delenikas, Athens/GREECE
// Portions Copyright:
// Davide Bettoni, Clusone/ITALY, dbettoni@users.sourceforge.net
// Tomek Cejner, Polland, heretique@users.sourceforge.net
//
// 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.gateway;
import java.util.*;
import java.net.*;
import org.apache.log4j.*;
import org.smslib.*;
public class ClickatellHTTPGateway extends AbstractGateway
{
private String apiId, username, password;
private String sessionId;
private KeepAlive keepAlive;
Object SYNC_Commander;
public ClickatellHTTPGateway(String id, String apiId, String username, String password, Logger logger)
{
super(id, logger);
started = false;
this.apiId = apiId;
this.username = username;
this.password = password;
this.sessionId = null;
this.from = null;
SYNC_Commander = new Object();
attributes = AbstractGateway.Attributes.SEND |
AbstractGateway.Attributes.WAPSI |
AbstractGateway.Attributes.CUSTOMFROM |
AbstractGateway.Attributes.BIGMESSAGES |
AbstractGateway.Attributes.FLASHSMS;
}
public void startGateway() throws Exception
{
logger.info("Starting Gateway: " + gatewayId);
connect();
super.startGateway();
}
public void stopGateway() throws Exception
{
logger.info("Stopping Gateway: " + gatewayId);
super.stopGateway();
sessionId = null;
if (keepAlive != null)
{
keepAlive.interrupt();
keepAlive.join();
keepAlive = null;
}
}
public void readMessages(LinkedList<InboundMessage> msgList, InboundMessage.MessageClass msgClass) throws Exception
{
throw new UnsupportedOperationException("Unsupported Gateway operation!");
}
public InboundMessage readMessage(String memLoc, int memIndex) throws Exception
{
throw new UnsupportedOperationException("Unsupported Gateway operation!");
}
public void deleteMessage(InboundMessage msg) throws Exception
{
throw new UnsupportedOperationException("Unsupported Gateway operation!");
}
public float queryBalance() throws Exception
{
URL url;
LinkedList<HttpHeader> request = new LinkedList<HttpHeader>();
LinkedList<String> response;
if (sessionId == null) throw new NotConnectedException();
url = new URL("http://api.clickatell.com/http/getbalance");
request.add(new HttpHeader("session_id", sessionId, false));
synchronized (SYNC_Commander) { response = HttpDriver.HttpPost(url, request); }
if (response.get(0).indexOf("Credit:") == 0) return Float.parseFloat(response.get(0).substring(response.get(0).indexOf(':') + 1));
else return -1;
}
public boolean queryCoverage(OutboundMessage msg) throws Exception
{
URL url;
LinkedList<HttpHeader> request = new LinkedList<HttpHeader>();
LinkedList<String> response;
if (sessionId == null) throw new NotConnectedException();
url = new URL("http://api.clickatell.com/utils/routeCoverage.php");
request.add(new HttpHeader("session_id", sessionId, false));
request.add(new HttpHeader("msisdn", msg.getRecipient().substring(1), false));
synchronized (SYNC_Commander) { response = HttpDriver.HttpPost(url, request); }
System.out.println(response.get(0));
if (response.get(0).indexOf("OK") == 0) return true;
else return false;
}
private void connect() throws Exception
{
if (!authenticate()) throw new IncorrectCredentialsException();
keepAlive = new KeepAlive();
}
private boolean authenticate() throws Exception
{
URL url;
LinkedList<HttpHeader> request = new LinkedList<HttpHeader>();
LinkedList<String> response;
logger.debug("Clickatell: authenticate().");
url = new URL("http://api.clickatell.com/http/auth");
request.add(new HttpHeader("api_id", apiId, false));
request.add(new HttpHeader("user", username, false));
request.add(new HttpHeader("password", password, false));
synchronized (SYNC_Commander) { response = HttpDriver.HttpPost(url, request); }
if (response.get(0).indexOf("ERR:") == 0)
{
sessionId = null;
return false;
}
else
{
sessionId = response.get(0).substring(4);
return true;
}
}
private boolean ping() throws Exception
{
URL url;
LinkedList<HttpHeader> request = new LinkedList<HttpHeader>();
LinkedList<String> response;
logger.debug("Clickatell: ping().");
url = new URL("http://api.clickatell.com/http/ping");
request.add(new HttpHeader("session_id", sessionId, false));
synchronized (SYNC_Commander)
{
response = HttpDriver.HttpPost(url, request);
}
if (response.get(0).indexOf("ERR:") == 0) return false;
else return true;
}
public void sendMessage(OutboundMessage msg) throws Exception
{
sendMessage(msg, Priority.NORMAL);
}
public void sendMessage(OutboundMessage msg, Priority priority) throws Exception
{
URL url;
LinkedList<HttpHeader> request = new LinkedList<HttpHeader>();
LinkedList<String> response;
int requestFeatures = 0;
if (sessionId == null) throw new NotConnectedException();
logger.debug("Clickatell: sendMessage().");
switch (msg.getType())
{
case OUTBOUND:
url = new URL("http://api.clickatell.com/http/sendmsg");
break;
case WAPSI:
url = new URL("http://api.clickatell.com/mms/si_push");
break;
default:
throw new OopsException("Are you sending an InboundMessage object???");
}
request.add(new HttpHeader("session_id", sessionId, false));
request.add(new HttpHeader("to", msg.getRecipient().substring(1), false));
request.add(new HttpHeader("concat", "3", false));
switch (priority)
{
case LOW:
request.add(new HttpHeader("queue", "3", false));
break;
case NORMAL:
request.add(new HttpHeader("queue", "2", false));
break;
case HIGH:
request.add(new HttpHeader("queue", "1", false));
break;
}
if (msg.getFrom() != null) request.add(new HttpHeader("from", msg.getFrom(), false));
else if (from != null) request.add(new HttpHeader("from", from, false));
if (msg.getFlashSms()) request.add(new HttpHeader("msg_type", "SMS_FLASH", false));
switch (msg.getType())
{
case OUTBOUND:
switch (msg.getEncoding())
{
case ENC7BIT:
request.add(new HttpHeader("text", msg.getText(), false));
break;
case ENCUCS2:
request.add(new HttpHeader("unicode", "1", false));
request.add(new HttpHeader("text", msg.getText(), true));
}
break;
case WAPSI:
request.add(new HttpHeader("si_id", "123456", false));
request.add(new HttpHeader("si_created", formatDateUTC(((OutboundWapSIMessage) msg).getCreateDate()), false));
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", msg.getText(), false));
break;
}
if ((from != null) || (msg.getFrom() != null)) requestFeatures =+ 16 + 32;
if (msg.getFlashSms()) requestFeatures += 512;
request.add(new HttpHeader("req_feat", "" + requestFeatures, false));
synchronized (SYNC_Commander) { response = HttpDriver.HttpPost(url, request); }
if (response.get(0).indexOf("ID:") == 0)
{
msg.setRefNo(response.get(0).substring(4));
msg.setDispatchDate(new Date());
msg.setGatewayId(gatewayId);
msg.setMessageStatus(OutboundMessage.MessageStatus.SENT);
}
}
private 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;
}
private String formatSignal(OutboundWapSIMessage.Signal signal)
{
switch (signal)
{
case None:
return "signal-none";
case Low:
return "signal-low";
case Medium:
return "signal-medium";
case High:
return "signal-high";
case Delete:
return "signal-delete";
default:
return "signal-none";
}
}
private class KeepAlive extends Thread
{
public KeepAlive()
{
setPriority(MIN_PRIORITY);
start();
logger.debug("ClickatellHTTPGateway: KeepAlive thread started.");
}
public void run()
{
while (true)
{
try
{
sleep(10 * 60 * 1000);
if (sessionId == null) break;
logger.debug("ClickatellHTTPGateway: Pinging Clickatell...");
synchronized (SYNC_Commander)
{
ping();
}
}
catch (InterruptedException e)
{
if (sessionId == null) break;
}
catch (Exception e)
{
}
}
logger.debug("ClickatellHTTPGateway: KeepAlive thread ended.");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -