Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- import java.security.*;
- import javax.net.ssl.*;
- import java.sql.*;
- import org.json.*;
- import java.util.Collection;
- import java.util.Iterator;
- import java.util.Map;
- import java.io.StringWriter;
- public class APNSServer {
- static int port = 2195;
- static String hostname = "gateway.sandbox.push.apple.com";
- static KeyStore ts;
- static char []passwKey = "heyyou31".toCharArray();
- static String URL_DATABASE = "jdbc:mysql://localhost:3306/clipping";
- static String USER_DATABASE = "clipping";
- static String PASS_DATABASE = "cp";
- static SSLSocket socket;
- static InputStream in;
- static OutputStream out;
- static ByteArrayOutputStream baos;
- static Connection databaseConnection;
- static Statement stmt;
- static String query =
- "select " +
- " n.id_device id_device, " +
- " device_token, " +
- " n.id_notificacao id_notificacao, " +
- " tipo, " +
- " n.id_post_rss, " +
- " trim(p.titulo) titulo, " +
- " trim(r.titulo) titulo_rss, " +
- " p.link link, " +
- " exists( " +
- " select 1 from tb_periodo_silencio ps " +
- " where " +
- " (n.id_device = ps.id_device) and " +
- " ( (60*hour(now()) + minute(now())) between ps.inicio and ps.fim) " +
- " ) periodo_silencio "+
- "from " +
- " tb_notificacao n, " +
- " tb_post_rss p, " +
- " tb_rss r, " +
- " tb_usuario u " +
- "where " +
- " n.id_post_rss = p.id_post_rss and " +
- " p.id_rss = r.id_rss and " +
- " u.id_device = n.id_device and " +
- " data_envio is NULL and " +
- " n.id_notificacao in (" +
- " select min(id_notificacao) " +
- " from tb_notificacao " +
- " where data_envio is NULL " +
- " group by id_device " +
- " ) and " +
- " n.id_device not in (" +
- " select id_device " +
- " from tb_notificacao " +
- " where " +
- " data_envio > date_add(now(), " +
- " interval -20 second)" +
- " ) ";
- public static void main(String args[]) throws Exception {
- System.out.print(query);
- ts = KeyStore.getInstance("PKCS12");
- JSONStringer jj;
- int t = 0;
- try {
- startSocket();
- startConnectionDatabase();
- while (true) {
- System.out.print("\n t = " + (t++));
- try {
- baos = new ByteArrayOutputStream();
- ResultSet pendentNotificationResultSet = getPendentNotificationResultaSet();
- String idNotificacaoEnviada = "";
- while (pendentNotificationResultSet.next()) {
- String tokenDevice = pendentNotificationResultSet.getString("device_token");
- if (tokenDevice == null) continue;
- baos.write(0); //The command
- baos.write(0); //The first byte of the deviceId length
- baos.write(32); //The deviceId length
- baos.write(hexStringToByteArray(tokenDevice.toUpperCase()));
- String mensagem = null;
- if (pendentNotificationResultSet.getString("tipo").equals("RSS")) {
- if (pendentNotificationResultSet.getString("titulo").indexOf(":") == -1)
- mensagem = (pendentNotificationResultSet.getString("titulo_rss") + ": " + pendentNotificationResultSet.getString("titulo"));
- else
- mensagem = (pendentNotificationResultSet.getString("titulo_rss") + " | " + pendentNotificationResultSet.getString("titulo"));
- if (mensagem.length() > 150) mensagem = mensagem.substring(0,150);
- }
- if (mensagem != null) {
- jj = new JSONStringer();
- String payload = jj
- .object()
- .key("aps")
- .object()
- .key("alert")
- .value(mensagem)
- .key("sound")
- .value("0.caf")
- .endObject()
- .key("id")
- .value(pendentNotificationResultSet.getInt("id_notificacao"))
- .key("l")
- .value(pendentNotificationResultSet.getString("link"))
- .endObject()
- .toString();
- byte bPayload[] = payload.getBytes("UTF-8");
- if (bPayload.length > 250) {
- jj = new JSONStringer();
- payload = jj
- .object()
- .key("aps")
- .object()
- .key("alert")
- .value(mensagem)
- .key("sound")
- .value("0.caf")
- .endObject()
- .key("id")
- .value(pendentNotificationResultSet.getInt("id_notificacao"))
- .endObject()
- .toString();
- bPayload = payload.getBytes("UTF-8");
- }
- System.out.print("\n"+ pendentNotificationResultSet.getString("titulo_rss"));
- System.out.println("Sending payload: " + payload + " (" + bPayload.length + ")");
- if (pendentNotificationResultSet.getInt("periodo_silencio") == 0) {
- baos.write(0); //First byte of payload length;
- baos.write(bPayload.length);
- baos.write(bPayload);
- } else {
- System.out.print("\nPeriodo de Silencio - nao envia notificacao");
- }
- idNotificacaoEnviada += (pendentNotificationResultSet.getInt("id_notificacao") + ", ");
- }
- }
- out.write(baos.toByteArray());
- out.flush();
- pendentNotificationResultSet.close();
- stmt.close();
- idNotificacaoEnviada += " -1";
- atualizaStatusNotificacaoEnvidada(idNotificacaoEnviada);
- } catch (Exception e1) {
- System.out.print("\n" + stack2string(e1));
- try {
- closeConnectionDatabase();
- closeSocket();
- } catch (Exception e2) {
- System.out.print("\n" + stack2string(e2));
- }
- try {
- startSocket();
- startConnectionDatabase();
- } catch (Exception e3) {
- System.out.print("\n" + stack2string(e3));
- }
- }
- Thread.sleep(1000);
- }
- } catch (Exception e4) {
- System.out.print("\nErro no envio da notificacao: " + stack2string(e4));
- } finally {
- closeConnectionDatabase();
- closeSocket();
- }
- }
- public static void startSocket() throws Exception {
- for (; true;) {
- try {
- ts.load(new FileInputStream("Certificates.p12"), passwKey);
- KeyManagerFactory tmf = KeyManagerFactory.getInstance("SunX509");
- tmf.init(ts,passwKey);
- SSLContext sslContext = SSLContext.getInstance("TLS");
- sslContext.init(tmf.getKeyManagers(), null, null);
- SSLSocketFactory factory =sslContext.getSocketFactory();
- socket = (SSLSocket) factory.createSocket(hostname,port); // Create the ServerSocket
- String[] suites = socket.getSupportedCipherSuites();
- socket.setEnabledCipherSuites(suites);
- socket.startHandshake();
- in = socket.getInputStream();
- out = socket.getOutputStream();
- return;
- } catch(Exception e){
- System.out.print("Erro ao inicializar conexao com Apple: " + stack2string(e));
- }
- Thread.sleep(5000);
- }
- }
- public static void closeSocket() throws Exception {
- in.close();
- out.close();
- }
- public static void startConnectionDatabase() throws Exception {
- Class.forName("com.mysql.jdbc.Driver");
- String url = URL_DATABASE;
- for (; true;) {
- try {
- databaseConnection = DriverManager.getConnection(url, USER_DATABASE, PASS_DATABASE);
- stmt = databaseConnection.createStatement();
- ResultSet rs = stmt.executeQuery("select now() from tb_notificacao limit 1");
- rs.close();
- stmt.close();
- return;
- } catch (Exception e) {
- System.out.print("Erro ao inicializar conexao com base de dados: " + stack2string(e));
- }
- Thread.sleep(5000);
- }
- }
- public static void closeConnectionDatabase() throws Exception {
- databaseConnection.close();
- }
- public static ResultSet getPendentNotificationResultaSet() throws Exception {
- stmt = databaseConnection.createStatement();
- ResultSet rs = stmt.executeQuery(query);
- return rs;
- }
- public static void atualizaStatusNotificacaoEnvidada(String idNotificacaoEnviada) throws Exception {
- stmt = databaseConnection.createStatement();
- stmt.executeUpdate("update tb_notificacao set data_envio = now() where id_notificacao in (" + idNotificacaoEnviada + ")");
- stmt.close();
- }
- public static byte[] hexStringToByteArray(String s) {
- byte[] b = new byte[s.length() / 2];
- for (int i = 0; i < b.length; i++){
- int index = i * 2;
- int v = Integer.parseInt(s.substring(index, index + 2), 16);
- b[i] = (byte)v;
- }
- return b;
- }
- public static String stack2string(Exception e) {
- try {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw);
- e.printStackTrace(pw);
- return "------\r\n" + sw.toString() + "------\r\n";
- }
- catch(Exception e2) {
- return "bad stack2string";
- }
- }
- }
Add Comment
Please, Sign In to add comment