Origins : http://blog.naver.com/melilyoo/140104172738
우선 이곳에서 푸시서비스를 등록해 보자.
http://ti-agile.blogspot.com/2010/01/programming-apple-push-notification.html
Device에 토큰 받아오는 부분까지 성공했다면.....
자바로 프로바이더 부분을 구현해보자.
KeyManagerFactory의 인증은 내가 가진 apple의 인증서를 넣어야 한다.
그리고 TrustManagerFactory의 인증은 공인인증된 인증서를 넣어야 한다. 그래서 java의 공인인증서를 넣은것이다.
그런다음 소켓을 연결하고 byte형식으로 토큰을 보내면 된다. ^^V
토큰은 아래와 같이 저장되었다. 알아보기 쉽게 하기 위해서 HEX값으로 표기했다. 보툥 0x를 빼고 저장하던데... 그냥 0x까지 붙여넣었다.
0x6d0x4b0x950x440x6d0xe30x650x8f0xd90xe30xab0x5c0x090xcb0x970xd20x1b0x6f0x880xfe0x810xa50xf80xf70x030xfa0xeb0x7f0xc00x130xe50xc0
====== Source ======================================================================================================
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import kr.co.confitech.girlboard.common.RowData;
public class APNSProvider{
private final String HOST = "gateway.sandbox.push.apple.com";
private final int POST = 2195;
private SSLSocket socket = null;
public void provider(String[] tokens, RowData data) throws Exception{
try{
// Apple PNS 인증
char[] password = "confitech".toCharArray();
FileInputStream fin = new FileInputStream("C:/Java/jdk1.5.0_16/jre/lib/security/pns.p12");
KeyStore ks1 = KeyStore.getInstance("PKCS12");
ks1.load(fin, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks1, password);
// 공인 인증서 인증
char[] password1 = "changeit".toCharArray();
fin = new FileInputStream("C:/Java/jdk1.5.0_16/jre/lib/security/cacerts");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fin, password1);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
fin.close();
// 소켓 연결
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory sf = ctx.getSocketFactory();
socket = (SSLSocket)sf.createSocket(HOST, POST);
if(!socket.isConnected()){
return;
}
socket.setSoTimeout(10000);
socket.startHandshake();
String msg = "{\"aps\":{\"alert\":\""+data.get("alert")+"\",\"badge\":"+data.get("badge");
if(data.get("sound") == null){
msg = msg + "}}";
}else{
msg = msg + ",\"sound\":\""+data.get("sound")+"\"}}";
}
System.out.println(msg);
OutputStream out = socket.getOutputStream();
for(int i=0; i<tokens.length; i++){
String strToken = tokens[i];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
//1. 0
bout.write((byte)0x00);
//2. 32 (token length)
bout.write(to2ByteArray(32));
//3. token
for(int j = 0; j < 32; j++){
String s = strToken.substring((j * 4) + 2, (j * 4) + 4);
int z = Integer.parseInt(s, 16);
bout.write((byte)z);
}
//4. message length
bout.write(to2ByteArray(msg.getBytes().length));
//5. message
bout.write(msg.getBytes());
// 푸시 보내기
out.write(bout.toByteArray());
out.flush();
}
out.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
/**
*
* @param i
* @return
*/
public static byte[] to2ByteArray(int i){
byte[] b = new byte[2];
b[0] = (byte)((i >>> 8) & 0xFF);
b[1] = (byte)((i >>> 0) & 0xFF);
return b;
}
}
====== end ======================================================================================================
Generating a Certificate Request

Figure 1. Generating a certificate request

Figure 2. Saving the certificate request to disk

Figure 3. Naming the certificate request
Creating an App ID

Figure 4. Launching the iPhone Developer Program Portal

Figure 5. The welcome screen of the iPhone Developer Program Portal

Figure 6. Clicking on the App ID tab
net.learn2develop.MyPushApp. Click Submit (see Figure 7).
Figure 7. Creating a new App ID

Figure 8. Viewing the newly created App ID
Configuring an App ID for Push Notifications

Figure 9. Configuring an App ID for push notification service

Figure 10. The Apple Push Notification service SSL Certificate Assistant screen

Figure 11. Generating the SSL certificate

Figure 12. The APNs SSL certificate that is generated

Figure 13. Downloading the certificate generated
aps.developer.identity.cer. Double-click on it to install it in the Keychain Access application (see Figure 14). The SSL certificate will be used by your provider application so that it can contact the APNs to send push notifications to your applications.
Figure 14. Installing the generated certificate into the Keychain Access application
Creating a Provisioning Profile

Figure 15. Selecting the Provisioning tab
MyDevicesProfile as the profile name. Select PushAppID as the App ID. Finally, check all the devices that you want to provision (you can register these devices with the iPhone Developer Program Portal through the Devices tab). Click Submit (see Figure 16).
Figure 16. Creating a new provisioning profile

Figure 17. Pending the approval of the provisioning profile
Provisioning a Device
MyDevicesProfile.mobileprovision file onto the Xcode icon on the Dock.MyDevicesProfile installed on the device (see Figure 18).
Figure 18. Viewing the installed provisioning profile
Creating the iPhone Application
beep.wav in this example) onto the Resources folder in Xcode (see Figure 19).
Figure 19. Adding a WAV file to the project

Figure 20. Entering the App ID for the application
net.learn2develop.MyPushApp.
Figure 21. Selecting the profile for code signing
ApplePushNotificationAppDelegate.m file, type the following code in bold:#import "ApplePushNotificationAppDelegate.h" #import "ApplePushNotificationViewController.h" @implementation ApplePushNotificationAppDelegate @synthesize window; @synthesize viewController; - (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:viewController.view]; [window makeKeyAndVisible]; NSLog(@"Registering for push notifications..."); [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; } - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken]; NSLog(str); } - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { NSString *str = [NSString stringWithFormat: @"Error: %@", err]; NSLog(str); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { for (id key in userInfo) { NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]); } } - (void)dealloc { [viewController release]; [window release]; [super dealloc]; } @end
Command-R to test the application on a real device. Press Shift-Command-R in Xcode to display the Debugger Console window. Observe carefully the device token that is printed (see Figure 22). In the figure below, the token is:38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b. Record down this device token (you might want to cut and paste it into a text file).
Figure 22. Viewing the device token for push notification

Figure 23. Viewing the Notifications item in the Settings application
Creating the Push Notification Provider
1. Communicate with the APNs using the SSL certificate you have created earlier.
2. Construct the payload for the message you want to send.
3. Send the push notification containing the payload to the APNs.

Figure 24. Format of a push notification message
The payload is a JSON formatted string (maximum 256 bytes) carrying the information you want to send to your application. An example of a payload looks like this:
{ "aps": { "alert" : "You got a new message!" , "badge" : 5, "sound" : "beep.wav"}, "acme1" : "bar", "acme2" : 42 }
Right-click on the Resources folder in Xcode and select Add Existing Files…. Select theaps.developer.identity.cer file that you have downloaded earlier (see Figure 25).
Figure 25. Adding the SSL certificate to the application
ApplicationDelegate.m file, modify the code as shown in bold below:- (id)init { self = [super init]; if(self != nil) { self.deviceToken = @"38c866dd bb323b39 ffa73487 5e157ee5 a85e0b7c e90d56e9 fe145bcc 6c2c594b"; self.payload = @"{\"aps\":{\"alert\":\"You got a new message!\",\"badge\":5,\"sound\":\"beep.wav\"},\"acme1\":\"bar\",\"acme2\":42}"; self.certificate = [[NSBundle mainBundle] pathForResource:@"aps_developer_identity" ofType:@"cer"]; } return self; }

Figure 26. Granting access to the SSL certificate
{ "aps": { "alert" : "You got a new message!" , "badge" : 5, "sound" : "beep.wav"}, "acme1" : "bar", "acme2" : 42 }

Figure 27. Receiving a Push Notification message
Command-R and send a push message from the PushMeBaby application, the Debugger Console window will display the following outputs:2009-11-24 21:11:49.182 ApplePushNotification[1461:207] key: acme1, value: bar
2009-11-24 21:11:49.187 ApplePushNotification[1461:207] key: aps, value: {
alert = "You got a new message!";
badge = 5;
sound = "beep.wav";
}
2009-11-24 21:11:49.191 ApplePushNotification[1461:207] key: acme2, value: 42
From http://mobiforge.com/developing/story/programming-apple-push-notification-services


