1.java 基于HTTP2
package com.linkedkeeper.apns.application;
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import com.linkedkeeper.apns.service.ApnsHttp2Service;
@SuppressWarnings("serial")
public class ApplicationStartUI extends Frame {
public ApplicationStartUI(String str) {
super(str);
}
static ApplicationStartUI fr = new ApplicationStartUI("ButtonFrame");
public static void main(String[] args) {
fr.setSize(500, 500);
fr.setLocation(200, 200);
fr.setBackground(null);
fr.setLayout(null);
Button button = new Button("StartMonitorException");
button.setSize(150, 30);
button.setLocation(12, 35);
button.addActionListener(new ActionListener() {
// 单击按钮执行的方法
public void actionPerformed(ActionEvent e) {
// closeThis();
JOptionPane pane = new JOptionPane("Successfully!");
JDialog dialog = pane.createDialog(fr, "Alert!");
dialog.show();
TimerPushNotification();
}
});
fr.add(button);
fr.setVisible(true);
fr.addWindowListener(new WindowAdapter() // 为了关闭窗口
{
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void closeThis() {
fr.dispose();
}
public static void TimerPushNotification() { // per Minute to getData.
Timer timer = new Timer(true);
timer.schedule(new TimerTask() {
public void run() {
Date captureTime = new Date();
SimpleDateFormat formatTime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println("Run Timer: " + formatTime.format(new Date()));
OracleDao oracleDao = new OracleDao();
List<Map<String, Object>> listExceptions = oracleDao.getIsThereExceptionsP();
System.out.println("Exceptions:" + listExceptions.size());
if (listExceptions.size() > 0) {
for (Map<String, Object> mapException : listExceptions) {
try {
captureTime = formatTime.parse(formatTime.format(mapException.get("GETDATATIME")));
System.out.println("EXCEPTIONFLOOR:" + mapException.get("EFLOOR").toString());
} catch (ParseException e) {
e.printStackTrace();
}
List<Map<String, Object>> listUsers = oracleDao
.getUsersByFloorP(mapException.get("EFLOOR").toString());
if (listUsers.size() > 0) {
for (Map<String, Object> mapUser : listUsers) {
System.out.println("username:" + mapUser.get("USERNAME").toString());
List<Map<String, Object>> UserExceptions = oracleDao
.getUserExceptionsP(mapUser.get("USERNAME").toString(), captureTime);
System.out.println("UserExceptions11:" + UserExceptions.size());
List<Map<String, Object>> listDeviceTokens = oracleDao
.getUserDeviceTokenP(mapUser.get("USERNAME").toString());
System.out.println("DeviceTokens:" + listDeviceTokens.size());
for (Map<String, Object> mapUserException : UserExceptions) {
ApnsHttp2Service service = new ApnsHttp2Service();
System.out.println(mapUserException);
System.out.println(listDeviceTokens.get(0).get("DEVICETOKENNAME"));
service.pushNotification(mapUserException, listDeviceTokens);
}
}
}
}
}
}
}, 1, 60000);
}
}
2.apns-C# pushsharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using System.Data.Common;
//using System.Data.OracleClient;
using Oracle.DataAccess.Client;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Threading;
using System.Collections;
using System.Security.Cryptography;
using PushSharp.Tests;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string prag = Request["parameter"];
string getCid = Request["cid"];
string ID = Request["id"];
string IDT = Request["idtime"];
string Fail = Request["F"];
string TIME = Request["FT"];
string FLOOR = Request["FF"];
string DUST = Request["dust"];
string LOG = Request["login"];
string fun = Request["function"];
string layout1 = Request["layout"];
string AVG = Request["avg"];
string date = Request["DATE"];
string key = Request["Sign"];
string location = Request["location"];
string getlocation = Request["getlocation"];
string geterrcode = Request["geterrcode"];
//Login action
string action = Request["Action"];
string username = Request["AccountNo"];
string password = Request["Pwd"];
string deviceToken = Request["DeviceToken"];
string loginTime = Request["LoginTime"];
string eFloor = Request["ErrFloor"];
string exceptionTime = Request["ErrCutOffTime"];
//string test = Request["ApnsRealTest"];
if (action != null)
{
#region 1.App Login insert deviceToken
if (action.Equals("Loginin"))
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_DEVICETOKEN_INSERT", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PUSERNAME", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PPASSWORD", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PDEVICETOKENNAME", OracleDbType.Varchar2,100));
cmd.Parameters.Add(new OracleParameter("@PLOGINTIME", OracleDbType.Date));
cmd.Parameters["@PUSERNAME"].Value = username;
cmd.Parameters["@PPASSWORD"].Value = password;
cmd.Parameters["@PDEVICETOKENNAME"].Value = deviceToken;
cmd.Parameters["@PLOGINTIME"].Value = Convert.ToDateTime(loginTime);
int status = cmd.ExecuteNonQuery();
if (status >-1 )
{
Dictionary<string, string> D = new Dictionary<string, string>();
D.Add("STATUS", "FAIL!");
Dictionary<string, string>[] A = { D };
string Convent1 = JsonConvert.SerializeObject(A);
Response.Write(Convent1);
}
else
{
Dictionary<string, string> D = new Dictionary<string, string>();
D.Add("STATUS", "SUCCESS!");
Dictionary<string, string>[] A = { D };
string Convent1 = JsonConvert.SerializeObject(A);
Response.Write(Convent1);
}
}
finally
{
conn.Close();
}
}
#endregion 1.App Login insert deviceToken
#region 2.Get total number by floor
if (action.Equals("ExpTTL"))
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_EXCEPTIONS_TOTAL", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PUSERNAME", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PDEVICETOKENNAME", OracleDbType.Varchar2, 100));
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@PUSERNAME"].Value = username;
cmd.Parameters["@PDEVICETOKENNAME"].Value = deviceToken;
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
cmd.Connection = conn;
//cmd.Connection = conn;
//cmd.CommandText = "HERMES_EXCEPTIONS_TOTAL";
//OracleParameter[] parms ={
// new OracleParameter("PUSERNAME",OracleDbType.Varchar2,50),
// new OracleParameter("PDEVICETOKENNAME",OracleDbType.Varchar2,100),
// new OracleParameter("PRESULTOUTPUT",OracleDbType.RefCursor)
// };
//parms[0].Value = username;
//parms[1].Value = deviceToken;
//parms[2].Direction = ParameterDirection.Output;
//cmd.CommandType = CommandType.StoredProcedure;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
//把字典存放到數組中;
if (dt.Rows.Count <= 0)
{
Dictionary<string, string> D = new Dictionary<string, string>();
D.Add("STATUS", "沒有異常!");
Dictionary<string, string>[] A = { D };
string Convent1 = JsonConvert.SerializeObject(A);
Response.Write(Convent1);
}
else
{
//string.Format("{0:yyyy/MM/dd HH:mm:ss}",dt.Columns["UPDATE_TIME"].ToString());
string DateTimeFormat = "yyyy/MM/dd HH:mm:ss";
IsoDateTimeConverter formatTime = new IsoDateTimeConverter();
formatTime.DateTimeFormat = DateTimeFormat;
string C = JsonConvert.SerializeObject(dt,Formatting.Indented,formatTime);
Response.Write(C);
}
}
finally
{
conn.Close();
}
}
#endregion 2.Get total number by floor
#region 3.Get detail info of exceptions
if (action.Equals("ExpDetail"))
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_EXCEPTIONS_DETAIL", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@VFLOOR", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@VEXCEPTIONTIME", OracleDbType.Date));
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@VFLOOR"].Value = eFloor;
cmd.Parameters["@VEXCEPTIONTIME"].Value = Convert.ToDateTime(exceptionTime);
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
//把字典存放到數組中;
if (dt.Rows.Count <= 0)
{
Dictionary<string, string> D = new Dictionary<string, string>();
D.Add("STATUS", "沒有詳細異常信息!");
Dictionary<string, string>[] A = { D };
string Convent1 = JsonConvert.SerializeObject(A);
Response.Write(Convent1);
}
else
{
string DateTimeFormat = "yyyy/MM/dd HH:mm:ss";
IsoDateTimeConverter formatTime = new IsoDateTimeConverter();
formatTime.DateTimeFormat = DateTimeFormat;
string C = JsonConvert.SerializeObject(dt, Formatting.Indented, formatTime);
Response.Write(C);
}
}
finally
{
conn.Close();
}
}
#endregion 3.Get detail info of exceptions
}
#region ApnsRealTest
//if (test != null)
//{
// if (test.Equals("ApnsRealTest"))
// {
// DataTable deviceTokens = getDeviceTokens(username);
// ApnsRealTest apnsTest = new ApnsRealTest();
// apnsTest.APNS_Send_Single(deviceTokens);
// Console.Read();
// }
//}
#endregion ApnsRealTest
System.Timers.Timer timer = new System.Timers.Timer(60000);//实例化Timer类,设置时间间隔60000毫秒(1min)
timer.Elapsed += new System.Timers.ElapsedEventHandler(pushNotification);//到达时间执行事件
timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true)
timer.Enabled = true;//是否执行
}
}
public OracleConnection OracleConn()
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["AUTO"].ToString();
return conn;
}
public static string SHA256(string str)
{
//如果str有中文,不同Encoding的sha是不同的
byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
SHA256Managed Sha256 = new SHA256Managed();
byte[] by = Sha256.ComputeHash(SHA256Data);
return BitConverter.ToString(by).Replace("-", "").ToLower(); //64
//return Convert.ToBase64String(by); //44
}
public void pushNotification(object source,System.Timers.ElapsedEventArgs e)
{
DataTable dtExceptions = getIsThereExs();
if (dtExceptions.Rows.Count>0)
{
//根据异常信息楼层关联找到对应的用户
for (int i = 0; i < dtExceptions.Rows.Count;i++ )
{
DateTime captureTime = Convert.ToDateTime(dtExceptions.Rows[0]["GETDATATIME"].ToString());
DataTable dtUsers = getUsersByFloor(dtExceptions.Rows[i]["EFLOOR"].ToString());
for (int j = 0; j < dtUsers.Rows.Count; j++)
{
DataTable userExceptions = getUserExceptions(dtUsers.Rows[j]["USERNAME"].ToString(),captureTime);
if (userExceptions.Rows.Count>0)
{
DataTable deviceTokens = getDeviceTokens(dtUsers.Rows[j]["USERNAME"].ToString());
for(int k =0;k<userExceptions.Rows.Count;k++)
{
ApnsRealTest apnsTest = new ApnsRealTest();
apnsTest.APNS_Send_Single(deviceTokens, userExceptions.Rows[k]);
}
}
}
}
}
}
public DataTable getDeviceTokens(string username)
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_DEVICETOKEN_GETBYUSER", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PUSERNAME", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@PUSERNAME"].Value = username;
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
}
finally
{
conn.Close();
}
return dt;
}
public DataTable getIsThereExs()
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_ISTHEREEXCEPTIONS", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
}
finally
{
conn.Close();
}
return dt;
}
public DataTable getUsersByFloor(string floor)
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_EXS_GETUSERBYFLOOR", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PFLOOR", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@PFLOOR"].Value = floor;
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
}
finally
{
conn.Close();
}
return dt;
}
public DataTable getUserExceptions(string username, DateTime captureTime)
{
OracleConnection conn = OracleConn();
DataTable dt = new DataTable();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand("HERMES_EXCEPTIONS_BYUSER", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("@PUSERNAME", OracleDbType.Varchar2, 50));
cmd.Parameters.Add(new OracleParameter("@PGETDATATIME", OracleDbType.Date));
cmd.Parameters.Add(new OracleParameter("@PRESULTOUTPUT", OracleDbType.RefCursor));
cmd.Parameters["@PUSERNAME"].Value = username;
cmd.Parameters["@PGETDATATIME"].Value = Convert.ToDateTime(captureTime);
cmd.Parameters["@PRESULTOUTPUT"].Direction = ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
}
finally
{
conn.Close();
}
return dt;
}
}
ApnsRealTest.cs
public void APNS_Send_Single(DataTable devicesTokens,DataRow exceptionsRow)
{
var succeeded = 0;
var failed = 0;
var attempted = 0;
//var config = new ApnsConfiguration (ApnsConfiguration.ApnsServerEnvironment.Sandbox, Settings.Instance.ApnsCertificateFile, Settings.Instance.ApnsCertificatePassword);
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "Certificates.p12", "MLBAEIOS");
var broker = new ApnsServiceBroker (config);
broker.OnNotificationFailed += (notification, exception) => {
failed++;
};
broker.OnNotificationSucceeded += (notification) => {
succeeded++;
};
broker.Start ();
foreach (var dt in devicesTokens.Rows)
//foreach (var dt in Settings.Instance.ApnsDeviceTokens)
{
attempted++;
Dictionary<string, Dictionary<string, string>> A = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> B = new Dictionary<string, string>();
Dictionary<string, string> C = new Dictionary<string, string>();
B.Add("alert", "Floor:" + exceptionsRow["EFLOOR"].ToString()
+ ",ExceptionDevices:" + exceptionsRow["DEVICETOTAL"].ToString()
+ ",ExceptionsTotal:" + exceptionsRow["EXSTOTAL"].ToString()+".");
C.Add("floor", exceptionsRow["EFLOOR"].ToString());
C.Add("time", exceptionsRow["CAPTURETIME"].ToString());
A.Add("aps", B);
A.Add("info", C);
string output = JsonConvert.SerializeObject(A);
broker.QueueNotification(new ApnsNotification
{
DeviceToken = dt.ToString(),
Payload = JObject.Parse(output)
});
}
broker.Stop ();
//Assert.AreEqual (attempted, succeeded);
//Assert.AreEqual (0, failed);
}