Guest User

Untitled

a guest
Jul 12th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.82 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4. import java.security.*;
  5. import javax.net.ssl.*;
  6. import java.sql.*;
  7. import org.json.*;
  8. import java.util.Collection;
  9. import java.util.Iterator;
  10. import java.util.Map;
  11. import java.io.StringWriter;
  12.  
  13. public class APNSServer {
  14. static int port = 2195;
  15. static String hostname = "gateway.sandbox.push.apple.com";
  16. static KeyStore ts;
  17. static char []passwKey = "heyyou31".toCharArray();
  18. static String URL_DATABASE = "jdbc:mysql://localhost:3306/clipping";
  19. static String USER_DATABASE = "clipping";
  20. static String PASS_DATABASE = "cp";
  21. static SSLSocket socket;
  22. static InputStream in;
  23. static OutputStream out;
  24. static ByteArrayOutputStream baos;
  25. static Connection databaseConnection;
  26. static Statement stmt;
  27. static String query =
  28. "select " +
  29. " n.id_device id_device, " +
  30. " device_token, " +
  31. " n.id_notificacao id_notificacao, " +
  32. " tipo, " +
  33. " n.id_post_rss, " +
  34. " trim(p.titulo) titulo, " +
  35. " trim(r.titulo) titulo_rss, " +
  36. " p.link link, " +
  37. " exists( " +
  38. " select 1 from tb_periodo_silencio ps " +
  39. " where " +
  40. " (n.id_device = ps.id_device) and " +
  41. " ( (60*hour(now()) + minute(now())) between ps.inicio and ps.fim) " +
  42. " ) periodo_silencio "+
  43. "from " +
  44. " tb_notificacao n, " +
  45. " tb_post_rss p, " +
  46. " tb_rss r, " +
  47. " tb_usuario u " +
  48. "where " +
  49. " n.id_post_rss = p.id_post_rss and " +
  50. " p.id_rss = r.id_rss and " +
  51. " u.id_device = n.id_device and " +
  52. " data_envio is NULL and " +
  53. " n.id_notificacao in (" +
  54. " select min(id_notificacao) " +
  55. " from tb_notificacao " +
  56. " where data_envio is NULL " +
  57. " group by id_device " +
  58. " ) and " +
  59. " n.id_device not in (" +
  60. " select id_device " +
  61. " from tb_notificacao " +
  62. " where " +
  63. " data_envio > date_add(now(), " +
  64. " interval -20 second)" +
  65. " ) ";
  66.  
  67. public static void main(String args[]) throws Exception {
  68.  
  69. System.out.print(query);
  70.  
  71. ts = KeyStore.getInstance("PKCS12");
  72.  
  73. JSONStringer jj;
  74.  
  75. int t = 0;
  76. try {
  77. startSocket();
  78. startConnectionDatabase();
  79. while (true) {
  80. System.out.print("\n t = " + (t++));
  81. try {
  82. baos = new ByteArrayOutputStream();
  83. ResultSet pendentNotificationResultSet = getPendentNotificationResultaSet();
  84. String idNotificacaoEnviada = "";
  85. while (pendentNotificationResultSet.next()) {
  86. String tokenDevice = pendentNotificationResultSet.getString("device_token");
  87. if (tokenDevice == null) continue;
  88. baos.write(0); //The command
  89. baos.write(0); //The first byte of the deviceId length
  90. baos.write(32); //The deviceId length
  91.  
  92. baos.write(hexStringToByteArray(tokenDevice.toUpperCase()));
  93. String mensagem = null;
  94. if (pendentNotificationResultSet.getString("tipo").equals("RSS")) {
  95. if (pendentNotificationResultSet.getString("titulo").indexOf(":") == -1)
  96. mensagem = (pendentNotificationResultSet.getString("titulo_rss") + ": " + pendentNotificationResultSet.getString("titulo"));
  97. else
  98. mensagem = (pendentNotificationResultSet.getString("titulo_rss") + " | " + pendentNotificationResultSet.getString("titulo"));
  99.  
  100. if (mensagem.length() > 150) mensagem = mensagem.substring(0,150);
  101. }
  102. if (mensagem != null) {
  103. jj = new JSONStringer();
  104. String payload = jj
  105. .object()
  106. .key("aps")
  107. .object()
  108. .key("alert")
  109. .value(mensagem)
  110. .key("sound")
  111. .value("0.caf")
  112. .endObject()
  113. .key("id")
  114. .value(pendentNotificationResultSet.getInt("id_notificacao"))
  115. .key("l")
  116. .value(pendentNotificationResultSet.getString("link"))
  117. .endObject()
  118. .toString();
  119. byte bPayload[] = payload.getBytes("UTF-8");
  120. if (bPayload.length > 250) {
  121. jj = new JSONStringer();
  122. payload = jj
  123. .object()
  124. .key("aps")
  125. .object()
  126. .key("alert")
  127. .value(mensagem)
  128. .key("sound")
  129. .value("0.caf")
  130. .endObject()
  131. .key("id")
  132. .value(pendentNotificationResultSet.getInt("id_notificacao"))
  133. .endObject()
  134. .toString();
  135. bPayload = payload.getBytes("UTF-8");
  136. }
  137. System.out.print("\n"+ pendentNotificationResultSet.getString("titulo_rss"));
  138. System.out.println("Sending payload: " + payload + " (" + bPayload.length + ")");
  139. if (pendentNotificationResultSet.getInt("periodo_silencio") == 0) {
  140. baos.write(0); //First byte of payload length;
  141. baos.write(bPayload.length);
  142. baos.write(bPayload);
  143. } else {
  144. System.out.print("\nPeriodo de Silencio - nao envia notificacao");
  145. }
  146. idNotificacaoEnviada += (pendentNotificationResultSet.getInt("id_notificacao") + ", ");
  147. }
  148. }
  149. out.write(baos.toByteArray());
  150. out.flush();
  151. pendentNotificationResultSet.close();
  152. stmt.close();
  153. idNotificacaoEnviada += " -1";
  154. atualizaStatusNotificacaoEnvidada(idNotificacaoEnviada);
  155. } catch (Exception e1) {
  156. System.out.print("\n" + stack2string(e1));
  157. try {
  158. closeConnectionDatabase();
  159. closeSocket();
  160. } catch (Exception e2) {
  161. System.out.print("\n" + stack2string(e2));
  162. }
  163. try {
  164. startSocket();
  165. startConnectionDatabase();
  166. } catch (Exception e3) {
  167. System.out.print("\n" + stack2string(e3));
  168. }
  169. }
  170. Thread.sleep(1000);
  171. }
  172. } catch (Exception e4) {
  173. System.out.print("\nErro no envio da notificacao: " + stack2string(e4));
  174. } finally {
  175. closeConnectionDatabase();
  176. closeSocket();
  177. }
  178. }
  179.  
  180. public static void startSocket() throws Exception {
  181. for (; true;) {
  182. try {
  183. ts.load(new FileInputStream("Certificates.p12"), passwKey);
  184. KeyManagerFactory tmf = KeyManagerFactory.getInstance("SunX509");
  185. tmf.init(ts,passwKey);
  186. SSLContext sslContext = SSLContext.getInstance("TLS");
  187. sslContext.init(tmf.getKeyManagers(), null, null);
  188. SSLSocketFactory factory =sslContext.getSocketFactory();
  189. socket = (SSLSocket) factory.createSocket(hostname,port); // Create the ServerSocket
  190. String[] suites = socket.getSupportedCipherSuites();
  191. socket.setEnabledCipherSuites(suites);
  192. socket.startHandshake();
  193. in = socket.getInputStream();
  194. out = socket.getOutputStream();
  195. return;
  196. } catch(Exception e){
  197. System.out.print("Erro ao inicializar conexao com Apple: " + stack2string(e));
  198. }
  199. Thread.sleep(5000);
  200. }
  201. }
  202.  
  203. public static void closeSocket() throws Exception {
  204. in.close();
  205. out.close();
  206. }
  207.  
  208. public static void startConnectionDatabase() throws Exception {
  209. Class.forName("com.mysql.jdbc.Driver");
  210. String url = URL_DATABASE;
  211. for (; true;) {
  212. try {
  213. databaseConnection = DriverManager.getConnection(url, USER_DATABASE, PASS_DATABASE);
  214. stmt = databaseConnection.createStatement();
  215. ResultSet rs = stmt.executeQuery("select now() from tb_notificacao limit 1");
  216. rs.close();
  217. stmt.close();
  218. return;
  219. } catch (Exception e) {
  220. System.out.print("Erro ao inicializar conexao com base de dados: " + stack2string(e));
  221. }
  222. Thread.sleep(5000);
  223. }
  224. }
  225.  
  226. public static void closeConnectionDatabase() throws Exception {
  227. databaseConnection.close();
  228. }
  229.  
  230. public static ResultSet getPendentNotificationResultaSet() throws Exception {
  231. stmt = databaseConnection.createStatement();
  232. ResultSet rs = stmt.executeQuery(query);
  233. return rs;
  234. }
  235.  
  236. public static void atualizaStatusNotificacaoEnvidada(String idNotificacaoEnviada) throws Exception {
  237. stmt = databaseConnection.createStatement();
  238. stmt.executeUpdate("update tb_notificacao set data_envio = now() where id_notificacao in (" + idNotificacaoEnviada + ")");
  239. stmt.close();
  240. }
  241.  
  242. public static byte[] hexStringToByteArray(String s) {
  243. byte[] b = new byte[s.length() / 2];
  244. for (int i = 0; i < b.length; i++){
  245. int index = i * 2;
  246. int v = Integer.parseInt(s.substring(index, index + 2), 16);
  247. b[i] = (byte)v;
  248. }
  249. return b;
  250. }
  251.  
  252. public static String stack2string(Exception e) {
  253. try {
  254. StringWriter sw = new StringWriter();
  255. PrintWriter pw = new PrintWriter(sw);
  256. e.printStackTrace(pw);
  257. return "------\r\n" + sw.toString() + "------\r\n";
  258. }
  259. catch(Exception e2) {
  260. return "bad stack2string";
  261. }
  262. }
  263.  
  264. }
Add Comment
Please, Sign In to add comment