public class Frame {
private final int COMMAND_NOTIFICATION = 2;
private final short ITEM_ID_DEVICE_TOKEN = 1;
private final short ITEM_ID_PAYLOAD = 2;
private final short ITEM_ID_NOTIFICATION_ID = 3;
private final short ITEM_ID_EXPIRATION_DATE = 4;
private final short ITEM_ID_PRIORITY = 5;
private final int MAX_PAYLOAD_BYTES = 2048; /// 2048 크기 이상 pay 로드에 싣을수 없음.
private String device_token;
private int frame_length;
private byte[] frame_data;
public Frame(String device_token) {
this.device_token = device_token;
}
public byte[] getFrame_data() {
return frame_data;
}
public int getFrame_length() {
return frame_length;
}
public int getCommandNotification() {
return COMMAND_NOTIFICATION;
}
public void pack() {
// payload Data를 담는다.
String payload = get_jsonData();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(ITEM_ID_DEVICE_TOKEN);
baos.write(intTo2ByteArray(32));
baos.write(DatatypeConverter.parseHexBinary(device_token));
baos.write(ITEM_ID_PAYLOAD);
baos.write(intTo2ByteArray(payload.getBytes().length));
baos.write(payload.getBytes("UTF-8"));
baos.write(ITEM_ID_NOTIFICATION_ID);
baos.write(intTo2ByteArray(4));
baos.write(intTo4ByteArray(5));
baos.write(ITEM_ID_EXPIRATION_DATE);
baos.write(intTo2ByteArray(4));
baos.write(intTo4ByteArray(5));
baos.write(ITEM_ID_PRIORITY);
baos.write(intTo2ByteArray(1));
baos.write((byte)10);
frame_length = baos.size();
frame_data = new byte[baos.size()];
frame_data = baos.toByteArray();
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// json 데이터를 가져오는 과정
public String get_jsonData() {
JSONParser parser = new JSONParser();
JSONObject jObj = new JSONObject();
Object obj = null;
try {
String path = Main.class.getResource("").getPath();
obj = parser.parse(new FileReader(path));
jObj = (JSONObject) obj;
System.out.println("payLoad:" + jObj.toJSONString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj.toString();
}
private static final byte[] intTo4ByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();
}
private static final byte[] intTo2ByteArray(int value) {
int s1 = (value & 0xFF00) >> 8;
int s2 = value & 0xFF;
return new byte[] { (byte) s1, (byte) s2 };
}
}