[JIRA IOT-778] fixed the jira issue related to CASendNotification API.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / samples / android / casample / sampleService / src / main / jni / ResourceModel.c
1 #include <jni.h>
2 #include <android/log.h>
3 #include <stdio.h>
4 #include <dlfcn.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <time.h>
8
9 #include "cainterface.h"
10 #include "cacommon.h"
11 #include "caadapterutils.h"
12 #include "oic_string.h"
13
14 #include "org_iotivity_ca_service_RMInterface.h"
15
16 #define  LOG_TAG   "JNI_INTERFACE_SAMPLE"
17 #define  LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
18 #define  LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
19
20 // Iotivity Device Identity.
21 const unsigned char IDENTITY[] = ("1111111111111111");
22
23 // PSK between this device and peer device.
24 const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
25
26 #define PORT_LENGTH 5
27 #define SECURE_DEFAULT_PORT 5684
28 #define RESOURCE_URI_LENGTH 14
29 #define OPTION_INFO_LENGTH 1024
30 #define NETWORK_INFO_LENGTH 1024
31 #define BIG_PAYLOAD_LENGTH 1024
32 #define RECEIVED_FILE_NAME_PREFIX_LENGTH 7
33 #define RECEIVED_FILE_NAME_LENGTH 14
34
35 typedef struct
36 {
37     char ipAddress[CA_IPADDR_SIZE];
38     uint16_t port;
39 } addressSet_t;
40
41 static void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo);
42 static void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo);
43 static void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
44 static void get_resource_uri(const char *URI, char *resourceURI, int32_t length);
45 static uint32_t get_secure_information(CAPayload_t payLoad);
46 static CAResult_t get_network_type(uint32_t selectedNetwork);
47 static void callback(char *subject, char *receivedData);
48 static CAResult_t get_remote_address(const char *address);
49 static void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
50 static void delete_global_references(JNIEnv *env, jobject obj);
51 static int get_address_set(const char *pAddress, addressSet_t* outAddress);
52 bool read_file(const char* name, char** bytes, size_t* length);
53 uint32_t gettodaydate();
54 void saveFile(const char *payload, size_t payloadSize);
55
56 uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
57 CATransportAdapter_t g_selectedNwType = CA_ADAPTER_IP;
58 static CAToken_t g_lastRequestToken = NULL;
59 static uint8_t g_lastRequestTokenLength = 0;
60
61 static const char COAP_PREFIX[] =  "coap://";
62 static const char COAPS_PREFIX[] = "coaps://";
63 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
64 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
65
66 static const char RECEIVED_FILE_PATH[] = "/storage/emulated/0/Download/%d%s.txt";
67
68 static const char SECURE_INFO_DATA[]
69                                    = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
70                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
71                                      "%d}}]}";
72 static const char NORMAL_INFO_DATA[]
73                                    = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
74                                      "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
75
76 static jobject g_responseListenerObject = NULL;
77 static JavaVM *g_jvm;
78
79 static CAEndpoint_t *g_clientEndpoint = NULL;
80 static char *g_resourceUri = NULL;
81 static CAToken_t g_clientToken = NULL;
82 static uint8_t g_clientTokenLength = 0;
83
84 static uint16_t g_clientMsgId = 0;
85 static char *g_remoteAddress = NULL;
86
87 // init
88 JNIEXPORT void JNICALL
89 Java_org_iotivity_ca_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj,
90                                                                    jobject listener)
91 {
92     LOGI("setNativeResponseListener");
93     if (!env || !obj || !listener)
94     {
95         LOGI("Invalid input parameter");
96         return;
97     }
98
99     g_responseListenerObject = (*env)->NewGlobalRef(env, listener);
100 }
101
102 #ifdef __WITH_DTLS__
103 // Internal API. Invoked by OC stack to retrieve credentials from this module
104 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
105               const unsigned char *desc, size_t desc_len,
106               unsigned char *result, size_t result_length)
107 {
108     LOGI("CAGetDtlsPskCredentials IN");
109
110     int32_t ret = -1;
111
112     if (NULL == result)
113     {
114         return ret;
115     }
116
117     switch (type)
118     {
119         case CA_DTLS_PSK_HINT:
120         case CA_DTLS_PSK_IDENTITY:
121
122             if (result_length < sizeof(IDENTITY))
123             {
124                 LOGE("ERROR : Wrong value for result for storing IDENTITY");
125                 return ret;
126             }
127
128             memcpy(result, IDENTITY, sizeof(IDENTITY));
129             ret = sizeof(IDENTITY);
130             break;
131
132         case CA_DTLS_PSK_KEY:
133
134             if ((desc_len == sizeof(IDENTITY)) &&
135                 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
136             {
137                 if (result_length < sizeof(RS_CLIENT_PSK))
138                 {
139                     LOGE("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
140                     return ret;
141                 }
142
143                 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
144                 ret = sizeof(RS_CLIENT_PSK);
145             }
146             break;
147
148         default:
149
150             LOGE("Wrong value passed for PSK_CRED_TYPE.");
151             ret = -1;
152     }
153
154     LOGI("CAGetDtlsPskCredentials OUT\n");
155     return ret;
156 }
157
158 #endif
159
160 JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
161 {
162     LOGI("JNI_OnLoad");
163     (void)reserved;
164
165     JNIEnv* env;
166     if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
167     {
168         return -1;
169     }
170     g_jvm = jvm; /* cache the JavaVM pointer */
171
172     CANativeJNISetJavaVM(g_jvm);
173
174     return JNI_VERSION_1_6;
175 }
176
177 void JNI_OnUnload(JavaVM *jvm, void *reserved)
178 {
179     LOGI("JNI_OnUnload");
180     (void)reserved;
181
182     JNIEnv* env;
183     if (JNI_OK != (*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6))
184     {
185         return;
186     }
187     g_jvm = 0;
188     return;
189 }
190
191 JNIEXPORT void JNICALL
192 Java_org_iotivity_ca_service_RMInterface_RMInitialize(JNIEnv *env, jobject obj, jobject context)
193 {
194     LOGI("RMInitialize");
195     if (!env || !obj || !context)
196     {
197         LOGI("Invalid input parameter");
198         return;
199     }
200
201     //Currently set context for Android Platform
202     CANativeJNISetContext(env, context);
203
204     CAResult_t res = CAInitialize();
205
206     if (CA_STATUS_OK != res)
207     {
208         LOGE("Could not Initialize");
209     }
210
211 #ifdef __WITH_DTLS__
212     res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
213     if(CA_STATUS_OK != res)
214     {
215         LOGE("Set credential handler fail");
216         return;
217     }
218 #endif
219 }
220
221 JNIEXPORT void JNICALL
222 Java_org_iotivity_ca_service_RMInterface_RMTerminate(JNIEnv *env, jobject obj)
223 {
224     LOGI("RMTerminate");
225     if (!env || !obj)
226     {
227         LOGI("Invalid input parameter");
228         return;
229     }
230
231     CADestroyToken(g_lastRequestToken);
232     CATerminate();
233     delete_global_references(env, obj);
234 }
235
236 JNIEXPORT void JNICALL
237 Java_org_iotivity_ca_service_RMInterface_RMStartListeningServer(JNIEnv *env, jobject obj)
238 {
239     LOGI("RMStartListeningServer");
240     if (!env || !obj)
241     {
242         LOGI("Invalid input parameter");
243         return;
244     }
245
246     if (CA_STATUS_OK != CAStartListeningServer())
247     {
248         LOGE("Could not start Listening server");
249     }
250 }
251
252 JNIEXPORT void JNICALL
253 Java_org_iotivity_ca_service_RMInterface_RMStartDiscoveryServer(JNIEnv *env, jobject obj)
254 {
255     LOGI("RMStartDiscoveryServer");
256     if (!env || !obj)
257     {
258         LOGI("Invalid input parameter");
259         return;
260     }
261
262     if (CA_STATUS_OK != CAStartDiscoveryServer())
263     {
264         LOGE("Could not start discovery server");
265     }
266 }
267
268 JNIEXPORT void JNICALL
269 Java_org_iotivity_ca_service_RMInterface_RMRegisterHandler(JNIEnv *env, jobject obj)
270 {
271     LOGI("RMRegisterHandler");
272     if(!env || !obj)
273     {
274         LOGI("Invalid input parameter");
275         return;
276     }
277
278     CARegisterHandler(request_handler, response_handler, error_handler);
279 }
280
281 JNIEXPORT void JNICALL
282 Java_org_iotivity_ca_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj, jstring uri,
283                                                        jstring payload, jint selectedNetwork,
284                                                        jint isSecured, jint msgType,
285                                                        jboolean isBigData)
286 {
287     LOGI("selectedNetwork - %d", selectedNetwork);
288     if (!env || !obj)
289     {
290         LOGI("Invalid input parameter");
291         return;
292     }
293
294     if (!uri)
295     {
296         LOGE("Invalid input parameter : uri");
297         return;
298     }
299
300     CAResult_t res = get_network_type(selectedNetwork);
301     if (CA_STATUS_OK != res)
302     {
303         return;
304     }
305
306     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
307     LOGI("RMSendRequest - %s", strUri);
308
309     CATransportFlags_t flags;
310     addressSet_t address = {{0}, 0};
311     parsing_coap_uri(strUri, &address, &flags);
312
313     //create remote endpoint
314     CAEndpoint_t* endpoint = NULL;
315     res = CACreateEndpoint(flags, g_selectedNwType, (const char*)(address.ipAddress),
316                            address.port, &endpoint);
317     if (CA_STATUS_OK != res)
318     {
319         LOGE("Could not create remote end point");
320         (*env)->ReleaseStringUTFChars(env, uri, strUri);
321         return;
322     }
323
324     CAMessageType_t messageType = msgType;
325
326     // create token
327     CAToken_t token = NULL;
328     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
329
330     res = CAGenerateToken(&token, tokenLength);
331     if ((CA_STATUS_OK != res) || (!token))
332     {
333         LOGE("token generate error!!");
334         // destroy remote endpoint
335         CADestroyEndpoint(endpoint);
336         (*env)->ReleaseStringUTFChars(env, uri, strUri);
337         return;
338     }
339
340     char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
341
342     get_resource_uri((const CAURI_t) strUri, resourceURI, RESOURCE_URI_LENGTH);
343     (*env)->ReleaseStringUTFChars(env, uri, strUri);
344
345     CAInfo_t requestData = { 0 };
346     requestData.token = token;
347     requestData.tokenLength = tokenLength;
348
349     size_t payloadLength = 0;
350     if (isBigData)
351     {
352         const char* path = NULL;
353         if (payload)
354         {
355             path = (*env)->GetStringUTFChars(env, payload, NULL);
356             if(path)
357             {
358                 char* bigData = NULL;
359                 bool result = read_file(path, &bigData, &payloadLength);
360                 if (!result)
361                 {
362                     LOGE("read has failed");
363                     (*env)->ReleaseStringUTFChars(env, payload, path);
364                     CADestroyToken(token);
365                     CADestroyEndpoint(endpoint);
366                     return;
367                 }
368                 (*env)->ReleaseStringUTFChars(env, payload, path);
369
370                 requestData.payload = (CAPayload_t) malloc(payloadLength);
371                 if (NULL == requestData.payload)
372                 {
373                     LOGE("Memory allocation failed!");
374                     // destroy token
375                     CADestroyToken(token);
376                     // destroy remote endpoint
377                     CADestroyEndpoint(endpoint);
378                     return;
379                 }
380                 memcpy(requestData.payload, bigData, payloadLength);
381                 requestData.payloadSize = payloadLength;
382             }
383         }
384     }
385     else
386     {
387         if (isSecured)
388         {
389             payloadLength = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
390             requestData.payload = (CAPayload_t) malloc(payloadLength);
391             if (NULL == requestData.payload)
392             {
393                 LOGE("Memory allocation failed!");
394                 // destroy token
395                 CADestroyToken(token);
396                 // destroy remote endpoint
397                 CADestroyEndpoint(endpoint);
398                 return;
399             }
400             snprintf((char *) requestData.payload, payloadLength, SECURE_INFO_DATA,
401                      resourceURI, g_localSecurePort);
402             requestData.payloadSize = payloadLength;
403         }
404         else
405         {
406             payloadLength = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
407             requestData.payload = (CAPayload_t) malloc(payloadLength);
408             if (NULL == requestData.payload)
409             {
410                 LOGE("Memory allocation failed!");
411                 // destroy token
412                 CADestroyToken(token);
413                 // destroy remote endpoint
414                 CADestroyEndpoint(endpoint);
415                 return;
416             }
417             snprintf((char *) requestData.payload, payloadLength, NORMAL_INFO_DATA, resourceURI);
418             requestData.payloadSize = payloadLength;
419         }
420     }
421
422     requestData.type = messageType;
423     requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
424     if (NULL == requestData.resourceUri)
425     {
426         LOGE("Memory allocation failed!");
427         // destroy token
428         CADestroyToken(token);
429         // destroy remote endpoint
430         CADestroyEndpoint(endpoint);
431         free(requestData.payload);
432         return;
433     }
434     memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
435
436     CARequestInfo_t requestInfo = { 0 };
437     requestInfo.method = CA_GET;
438     requestInfo.isMulticast = false;
439     requestInfo.info = requestData;
440
441     // send request
442     if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
443     {
444         LOGE("Could not send request");
445     }
446
447     // destroy token
448     CADestroyToken(token);
449
450     // destroy remote endpoint
451     CADestroyEndpoint(endpoint);
452
453     free(requestData.payload);
454     free(requestData.resourceUri);
455 }
456
457 JNIEXPORT void JNICALL
458 Java_org_iotivity_ca_service_RMInterface_RMSendReqestToAll(JNIEnv *env, jobject obj, jstring uri,
459                                                            jint selectedNetwork)
460 {
461     LOGI("selectedNetwork - %d", selectedNetwork);
462     if (!env || !obj)
463     {
464         LOGI("Invalid input parameter");
465         return;
466     }
467
468     CAResult_t res = get_network_type(selectedNetwork);
469     if (CA_STATUS_OK != res)
470     {
471         return;
472     }
473
474     // create remote endpoint
475     CAEndpoint_t *endpoint = NULL;
476     res = CACreateEndpoint(CA_IPV4, g_selectedNwType, NULL, 0, &endpoint);
477
478     if (CA_STATUS_OK != res)
479     {
480         LOGE("create remote endpoint error, error code: %d", res);
481         return;
482     }
483
484     // create token
485     CAToken_t token = NULL;
486     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
487
488     res = CAGenerateToken(&token, tokenLength);
489     if ((CA_STATUS_OK != res) || (!token))
490     {
491         LOGE("token generate error!!");
492         // destroy remote endpoint
493         CADestroyEndpoint(endpoint);
494         return;
495     }
496
497     LOGI("generated token %s", token);
498
499     CAInfo_t requestData = { 0 };
500     requestData.token = token;
501     requestData.tokenLength = tokenLength;
502     requestData.payload = (CAPayload_t) "TempJsonPayload";
503     requestData.payloadSize = strlen((const char *) requestData.payload);
504     requestData.type = CA_MSG_NONCONFIRM;
505
506     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
507     LOGI("resourceUri - %s", strUri);
508     requestData.resourceUri = (CAURI_t)strUri;
509
510     uint8_t optionNum = 2;
511     CAHeaderOption_t *headerOpt = (CAHeaderOption_t*) calloc(1,
512                                                              sizeof(CAHeaderOption_t) * optionNum);
513     if (NULL == headerOpt)
514     {
515         LOGE("Memory allocation failed");
516         // destroy remote endpoint
517         CADestroyEndpoint(endpoint);
518         return;
519     }
520
521     char* FirstOptionData = "Hello";
522     headerOpt[0].optionID = 3000;
523     memcpy(headerOpt[0].optionData, FirstOptionData, strlen(FirstOptionData));
524     headerOpt[0].optionLength = (uint16_t) strlen(FirstOptionData);
525
526     char* SecondOptionData2 = "World";
527     headerOpt[1].optionID = 3001;
528     memcpy(headerOpt[1].optionData, SecondOptionData2, strlen(SecondOptionData2));
529     headerOpt[1].optionLength = (uint16_t) strlen(SecondOptionData2);
530
531     requestData.numOptions = optionNum;
532     requestData.options = headerOpt;
533
534     CARequestInfo_t requestInfo = { 0 };
535     requestInfo.method = CA_GET;
536     requestInfo.isMulticast = true;
537     requestInfo.info = requestData;
538
539     // send request to all
540     res = CASendRequest(endpoint, &requestInfo);
541     if (CA_STATUS_OK != res)
542     {
543         LOGE("Could not send request to all");
544         //destroy token
545         CADestroyToken(token);
546     }
547     else
548     {
549         CADestroyToken(g_lastRequestToken);
550         g_lastRequestToken = token;
551         g_lastRequestTokenLength = tokenLength;
552     }
553
554     //ReleaseStringUTFChars for strUri
555     (*env)->ReleaseStringUTFChars(env, uri, strUri);
556
557     free(headerOpt);
558
559     // destroy remote endpoint
560     CADestroyEndpoint(endpoint);
561 }
562
563 JNIEXPORT void JNICALL
564 Java_org_iotivity_ca_service_RMInterface_RMSendResponse(JNIEnv *env, jobject obj,
565                                                         jint selectedNetwork,
566                                                         jint isSecured, jint msgType,
567                                                         jint responseValue)
568 {
569     LOGI("RMSendResponse");
570     if (!env || !obj)
571     {
572         LOGI("Invalid input parameter");
573         return;
574     }
575
576     LOGI("selectedNetwork - %d", selectedNetwork);
577
578     CAResult_t res = get_network_type(selectedNetwork);
579     if (CA_STATUS_OK != res)
580     {
581         LOGE("Not supported network type");
582         return;
583     }
584
585     if (NULL == g_clientEndpoint)
586     {
587         LOGE("No Request received");
588         return;
589     }
590
591     CAMessageType_t messageType = msgType;
592
593     CAInfo_t responseData = { 0 };
594     responseData.type = messageType;
595     responseData.messageId = g_clientMsgId;
596     responseData.resourceUri = (CAURI_t)g_resourceUri;
597
598     CAResponseInfo_t responseInfo = { 0 };
599
600     if (msgType != CA_MSG_RESET)
601     {
602         responseData.token = g_clientToken;
603         responseData.tokenLength = g_clientTokenLength;
604         responseInfo.result = responseValue;
605
606         if (1 == isSecured)
607         {
608             uint32_t length = strlen(SECURE_INFO_DATA) + strlen(g_resourceUri) + 1;
609             responseData.payload = (CAPayload_t) malloc(length);
610             sprintf((char *) responseData.payload, SECURE_INFO_DATA, g_resourceUri,
611                     g_localSecurePort);
612             responseData.payloadSize = length;
613         }
614         else
615         {
616             uint32_t length = strlen(NORMAL_INFO_DATA) + strlen(g_resourceUri) + 1;
617             responseData.payload = (CAPayload_t) malloc(length);
618             sprintf((char *) responseData.payload, NORMAL_INFO_DATA, g_resourceUri);
619             responseData.payloadSize = length;
620         }
621     }
622     //msgType is RESET
623     else
624     {
625         responseInfo.result = CA_EMPTY;
626     }
627
628     responseInfo.info = responseData;
629
630     // send response
631     res = CASendResponse(g_clientEndpoint, &responseInfo);
632     if (CA_STATUS_OK != res)
633     {
634         LOGE("Could not send response");
635     }
636
637     // destroy token
638     CADestroyToken(g_clientToken);
639     g_clientToken = NULL;
640     g_clientTokenLength = 0;
641
642     // destroy remote endpoint
643     CADestroyEndpoint(g_clientEndpoint);
644     g_clientEndpoint = NULL;
645 }
646
647 JNIEXPORT void JNICALL
648 Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
649                                                             jstring payload, jint selectedNetwork,
650                                                             jint isSecured, jint msgType)
651 {
652     LOGI("selectedNetwork - %d", selectedNetwork);
653     if (!env || !obj)
654     {
655         LOGI("Invalid input parameter");
656         return;
657     }
658
659     if (!payload)
660     {
661         LOGE("payload is NULL");
662     }
663
664     if (!uri)
665     {
666         LOGE("Invalid input parameter : uri");
667         return;
668     }
669
670     CAResult_t res = get_network_type(selectedNetwork);
671     if (CA_STATUS_OK != res)
672     {
673         LOGE("Not supported network type");
674         return;
675     }
676
677     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
678     LOGI("RMSendNotification - %s", strUri);
679
680     CATransportFlags_t flags;
681     addressSet_t address = {{0}, 0};
682     parsing_coap_uri(strUri, &address, &flags);
683
684     //create remote endpoint
685     CAEndpoint_t* endpoint = NULL;
686     if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
687                                          (const char*)address.ipAddress,
688                                          address.port, &endpoint))
689     {
690         //ReleaseStringUTFChars for strUri
691         (*env)->ReleaseStringUTFChars(env, uri, strUri);
692         LOGE("Could not create remote end point");
693         return;
694     }
695
696     char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
697     get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
698
699     //ReleaseStringUTFChars for strUri
700     (*env)->ReleaseStringUTFChars(env, uri, strUri);
701
702     CAMessageType_t messageType = msgType;
703
704     // create token
705     CAToken_t token = NULL;
706     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
707
708     res = CAGenerateToken(&token, tokenLength);
709     if ((CA_STATUS_OK != res) || (!token))
710     {
711         LOGE("token generate error!");
712         CADestroyEndpoint(endpoint);
713         return;
714     }
715
716     CAInfo_t requestData = { 0 };
717     requestData.token = token;
718     requestData.tokenLength = tokenLength;
719     requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
720     if (NULL == requestData.resourceUri)
721     {
722         LOGE("Memory allocation failed!");
723         // destroy token
724         CADestroyToken(token);
725         // destroy remote endpoint
726         CADestroyEndpoint(endpoint);
727         return;
728     }
729     memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
730
731     if (1 == isSecured)
732     {
733         uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
734         requestData.payload = (CAPayload_t) malloc(length);
735         if (NULL == requestData.payload)
736         {
737             LOGE("Memory allocation failed!");
738             // destroy token
739             CADestroyToken(token);
740             // destroy remote endpoint
741             CADestroyEndpoint(endpoint);
742
743             free(requestData.resourceUri);
744             return;
745         }
746         snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
747         requestData.payloadSize = length;
748     }
749     else
750     {
751         uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
752         requestData.payload = (CAPayload_t) malloc(length);
753         if (NULL == requestData.payload)
754         {
755             LOGE("Memory allocation failed!");
756             // destroy token
757             CADestroyToken(token);
758             // destroy remote endpoint
759             CADestroyEndpoint(endpoint);
760
761             free(requestData.resourceUri);
762             return;
763         }
764         snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
765         requestData.payloadSize = length;
766     }
767
768     requestData.type = messageType;
769
770     CARequestInfo_t requestInfo = { 0 };
771     requestInfo.method = CA_GET;
772     requestInfo.info = requestData;
773
774     // send notification
775     if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
776     {
777         LOGE("Could not send notification");
778     }
779
780     LOGI("Send Notification");
781
782     // destroy token
783     CADestroyToken(token);
784
785     // destroy remote endpoint
786     CADestroyEndpoint(endpoint);
787
788     free(requestData.payload);
789     free(requestData.resourceUri);
790 }
791
792 JNIEXPORT void JNICALL
793 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
794                                                          jint networkType)
795 {
796     LOGI("RMSelectNetwork Type : %d", networkType);
797     if (!env || !obj)
798     {
799         LOGI("Invalid input parameter");
800         return;
801     }
802
803     if (CA_STATUS_OK != CASelectNetwork(networkType))
804     {
805         LOGE("Could not select network");
806     }
807 }
808
809 JNIEXPORT void JNICALL
810 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
811                                                            jint networkType)
812 {
813     LOGI("RMUnSelectNetwork Type : %d", networkType);
814     if (!env || !obj)
815     {
816         LOGI("Invalid input parameter");
817         return;
818     }
819
820     if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
821     {
822         LOGE("Could not unselect network");
823     }
824 }
825
826 JNIEXPORT void JNICALL
827 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
828 {
829     LOGI("RMGetNetworkInfomation");
830     if (!env || !obj)
831     {
832         LOGI("Invalid input parameter");
833         return;
834     }
835
836     CAEndpoint_t *tempInfo = NULL;
837     uint32_t tempSize = 0;
838
839     CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
840     if (CA_STATUS_OK != res)
841     {
842         LOGE("Could not start get network information");
843         free(tempInfo);
844         return;
845     }
846
847     LOGI("################## Network Information #######################");
848     callback("######## Network Information", "#######");
849     LOGI("Network info total size is %d", tempSize);
850
851     uint32_t index;
852     for (index = 0; index < tempSize; index++)
853     {
854         res = get_remote_address(tempInfo[index].addr);
855         if (CA_STATUS_OK != res)
856         {
857             free(tempInfo);
858             return;
859         }
860         if (NULL != g_responseListenerObject)
861         {
862             char networkInfo[NETWORK_INFO_LENGTH];
863             LOGI("Type: %d", tempInfo[index].adapter);
864             sprintf(networkInfo, "%d",tempInfo[index].adapter);
865             callback("Type :", networkInfo);
866             if (CA_ADAPTER_IP == tempInfo[index].adapter)
867             {
868                 LOGI("Port: %d", tempInfo[index].port);
869                 sprintf(networkInfo, "%d",tempInfo[index].port);
870                 callback("Port: ", networkInfo);
871             }
872             LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
873             LOGI("Address: %s", g_remoteAddress);
874             callback("Address: ", g_remoteAddress);
875             free(g_remoteAddress);
876         }
877         if (tempInfo[index].flags & CA_SECURE)
878         {
879             g_localSecurePort = tempInfo[index].port;
880         }
881     }
882
883     // free
884     free(tempInfo);
885
886     LOGI("##############################################################");
887 }
888
889 JNIEXPORT void JNICALL
890 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
891 {
892     LOGI("RMHandleRequestResponse");
893     if(!env || !obj)
894     {
895         LOGI("Invalid input parameter");
896         return;
897     }
898
899     if (CA_STATUS_OK != CAHandleRequestResponse())
900     {
901         LOGE("Could not handle request and response");
902     }
903 }
904
905 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
906 {
907
908     if (!object)
909     {
910         LOGE("Remote endpoint is NULL!");
911         return;
912     }
913
914     if (!requestInfo)
915     {
916         LOGE("Request info is NULL!");
917         return;
918     }
919
920     if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
921             (strncmp(g_lastRequestToken, requestInfo->info.token,
922                      requestInfo->info.tokenLength) == 0))
923     {
924         LOGI("token is same. received request of it's own. skip.. ");
925         return;
926     }
927
928     CAResult_t res = get_remote_address(object->addr);
929     if (CA_STATUS_OK != res)
930     {
931         return;
932     }
933
934     LOGI("##########received request from remote device #############");
935     LOGI("Remote Address: %s", g_remoteAddress);
936     LOGI("Remote Port: %d", object->port);
937     LOGI("Uri: %s", requestInfo->info.resourceUri);
938     LOGI("Data: %s", requestInfo->info.payload);
939     LOGI("Token: %s", requestInfo->info.token);
940     LOGI("Code: %d", requestInfo->method);
941     LOGI("MessageType: %d", requestInfo->info.type);
942
943     if (NULL != g_responseListenerObject)
944     {
945         char *cloneUri = NULL;
946         uint32_t len = 0;
947
948         if (NULL != requestInfo->info.resourceUri)
949         {
950             len = strlen(requestInfo->info.resourceUri);
951             cloneUri = (char *)malloc(sizeof(char) * (len + 1));
952
953             if (NULL == cloneUri)
954             {
955                 LOGE("cloneUri Out of memory");
956                 free(g_remoteAddress);
957                 return;
958             }
959
960             memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
961             callback("Uri: ", cloneUri);
962         }
963
964         len = strlen(g_remoteAddress);
965         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
966
967         if (NULL == cloneRemoteAddress)
968         {
969             LOGE("cloneRemoteAddress Out of memory");
970             free(g_remoteAddress);
971             free(cloneUri);
972             return;
973         }
974
975         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
976
977         callback("Remote Address: ", cloneRemoteAddress);
978         free(cloneRemoteAddress);
979         free(g_remoteAddress);
980
981         char portInfo[PORT_LENGTH] = { 0, };
982         sprintf(portInfo, "%d", object->port);
983         callback("Remote Port: ", portInfo);
984
985         //clone g_clientEndpoint
986         g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
987         if (NULL == g_clientEndpoint)
988         {
989             LOGE("g_clientEndpoint Out of memory");
990             free(cloneUri);
991             return;
992         }
993         memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
994
995         if (NULL != cloneUri)
996         {
997             len = strlen(cloneUri);
998             g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
999             if (NULL == g_resourceUri)
1000             {
1001                 LOGE("g_clientEndpoint->resourceUri Out of memory");
1002                 free(g_clientEndpoint);
1003                 free(cloneUri);
1004                 return;
1005             }
1006             memcpy(g_resourceUri, cloneUri, len + 1);
1007             free(cloneUri);
1008         }
1009         //clone g_clientToken
1010         len = requestInfo->info.tokenLength;
1011
1012         g_clientToken = (char *) malloc(sizeof(char) * len);
1013         if (NULL == g_clientToken)
1014         {
1015             LOGE("g_clientToken Out of memory");
1016             free(g_clientEndpoint);
1017             return;
1018         }
1019
1020         if (NULL != requestInfo->info.token)
1021         {
1022             memcpy(g_clientToken, requestInfo->info.token, len);
1023             g_clientTokenLength = len;
1024
1025         }
1026
1027         //clone g_clientMsgId
1028         g_clientMsgId = requestInfo->info.messageId;
1029
1030         if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1031         {
1032             len = requestInfo->info.payloadSize;
1033             char *clonePayload = (char *) malloc(len + 1);
1034             if (NULL == clonePayload)
1035             {
1036                 LOGE("clonePayload Out of memory");
1037                 free(g_clientEndpoint);
1038                 return;
1039             }
1040
1041             memcpy(clonePayload, requestInfo->info.payload, len);
1042             clonePayload[len] = '\0';
1043
1044             if (len > BIG_PAYLOAD_LENGTH)
1045             {
1046                 saveFile(clonePayload, len);
1047             }
1048             else
1049             {
1050                 callback("Data: ", clonePayload);
1051             }
1052             free(clonePayload);
1053         }
1054     }
1055
1056     if (requestInfo->info.options)
1057     {
1058         uint32_t len = requestInfo->info.numOptions;
1059         uint32_t i;
1060
1061         LOGI("Option count: %d", requestInfo->info.numOptions);
1062
1063         for (i = 0; i < len; i++)
1064         {
1065             LOGI("Option %d", i + 1);
1066             LOGI("ID : %d", requestInfo->info.options[i].optionID);
1067             LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1068                  requestInfo->info.options[i].optionData);
1069
1070             if (NULL != g_responseListenerObject)
1071             {
1072                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1073                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1074                         requestInfo->info.options[i].optionID,
1075                         requestInfo->info.options[i].optionLength);
1076
1077                 callback("Option info: ", optionInfo);
1078
1079                 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1080                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1081                 if (NULL == cloneOptionData)
1082                 {
1083                     LOGE("cloneOptionData Out of memory");
1084                     free(g_clientEndpoint);
1085                     return;
1086                 }
1087
1088                 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1089                        optionDataLen + 1);
1090
1091                 callback("Option Data: ", cloneOptionData);
1092                 free(cloneOptionData);
1093             }
1094         }
1095     }
1096     LOGI("############################################################");
1097
1098     //Check if this has secure communication information
1099     if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1100     {
1101         uint32_t securePort = get_secure_information(requestInfo->info.payload);
1102         if (0 < securePort) //Set the remote endpoint secure details and send response
1103         {
1104             LOGI("This is secure resource...");
1105
1106             CAEndpoint_t *endpoint = NULL;
1107             if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1108                         object->adapter, object->addr, securePort, &endpoint))
1109             {
1110                 LOGE("Failed to create duplicate of remote endpoint!");
1111                 return;
1112             }
1113             object = endpoint;
1114         }
1115     }
1116 }
1117
1118 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1119 {
1120     if (!object || !responseInfo)
1121     {
1122         LOGE("Invalid input parameter");
1123         return;
1124     }
1125
1126     CAResult_t res = get_remote_address(object->addr);
1127     if (CA_STATUS_OK != res)
1128     {
1129         return;
1130     }
1131
1132     LOGI("##########Received response from remote device #############");
1133     LOGI("Uri: %s", responseInfo->info.resourceUri);
1134     LOGI("Remote Address: %s", g_remoteAddress);
1135     LOGI("Remote Port: %d", object->port);
1136     LOGI("response result: %d", responseInfo->result);
1137     LOGI("Data: %s", responseInfo->info.payload);
1138     LOGI("Token: %s", responseInfo->info.token);
1139     LOGI("MessageType: %d", responseInfo->info.type);
1140
1141     if (NULL != g_responseListenerObject)
1142     {
1143         uint32_t len = 0;
1144
1145         if (NULL != responseInfo->info.resourceUri)
1146         {
1147             len = strlen(responseInfo->info.resourceUri);
1148             char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1149
1150             if (NULL == cloneUri)
1151             {
1152                 LOGE("cloneUri Out of memory");
1153                 free(g_remoteAddress);
1154                 return;
1155             }
1156
1157             memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1158
1159             callback("Uri: ", cloneUri);
1160             free(cloneUri);
1161         }
1162
1163         len = strlen(g_remoteAddress);
1164         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1165
1166         if (NULL == cloneRemoteAddress)
1167         {
1168             LOGE("cloneRemoteAddress Out of memory");
1169             free(g_remoteAddress);
1170             return;
1171         }
1172
1173         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1174
1175         callback("Remote Address: ", cloneRemoteAddress);
1176         free(cloneRemoteAddress);
1177         free(g_remoteAddress);
1178
1179         char portInfo[PORT_LENGTH] = { 0, };
1180         sprintf(portInfo, "%d", object->port);
1181         callback("Remote Port: ", portInfo);
1182
1183         if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1184         {
1185             len = responseInfo->info.payloadSize;
1186             char *clonePayload = (char *) malloc(len + 1);
1187             if (NULL == clonePayload)
1188             {
1189                 LOGE("clonePayload Out of memory");
1190                 return;
1191             }
1192
1193             memcpy(clonePayload, responseInfo->info.payload, len);
1194             clonePayload[len] = '\0';
1195
1196             if (len > BIG_PAYLOAD_LENGTH)
1197             {
1198                 saveFile(clonePayload, len);
1199             }
1200             else
1201             {
1202                 callback("Data: ", clonePayload);
1203             }
1204             free(clonePayload);
1205         }
1206     }
1207
1208     if (responseInfo->info.options)
1209     {
1210         uint32_t len = responseInfo->info.numOptions;
1211         uint32_t i;
1212         for (i = 0; i < len; i++)
1213         {
1214             LOGI("Option %d", i + 1);
1215             LOGI("ID : %d", responseInfo->info.options[i].optionID);
1216             LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1217                  responseInfo->info.options[i].optionData);
1218
1219             if (NULL != g_responseListenerObject)
1220             {
1221                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1222                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1223                         responseInfo->info.options[i].optionID,
1224                         responseInfo->info.options[i].optionLength);
1225
1226                 callback("Option info: ", optionInfo);
1227
1228                 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1229                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1230                 if (NULL == cloneOptionData)
1231                 {
1232                     LOGE("cloneOptionData Out of memory");
1233                     return;
1234                 }
1235                 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1236                        optionDataLen + 1);
1237                 callback("Option Data: ", cloneOptionData);
1238                 free(cloneOptionData);
1239             }
1240         }
1241     }
1242     LOGI("############################################################");
1243
1244     //Check if this has secure communication information
1245     if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1246     {
1247         uint32_t securePort = get_secure_information(responseInfo->info.payload);
1248         if (0 < securePort) //Set the remote endpoint secure details and send response
1249         {
1250             LOGI("This is secure resource...");
1251         }
1252     }
1253 }
1254
1255 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1256 {
1257     LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1258
1259     if (rep)
1260     {
1261         LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1262         LOGI("Error Handler, Adapter Type : %s", rep->addr);
1263     }
1264
1265     if (errorInfo)
1266     {
1267         const CAInfo_t *info = &errorInfo->info;
1268         LOGI("Error Handler, ErrorInfo :");
1269         LOGI("Error Handler result    : %d", errorInfo->result);
1270         LOGI("Error Handler token     : %s", info->token);
1271         LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1272         LOGI("Error Handler resourceUri : %s", info->resourceUri);
1273         LOGI("Error Handler type      : %d", info->type);
1274         LOGI("Error Handler payload   : %s", info->payload);
1275
1276         if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1277         {
1278             LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1279         }
1280         else if(CA_SEND_FAILED == errorInfo->result)
1281         {
1282             LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1283         }
1284         else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1285         {
1286             LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1287         }
1288         else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1289         {
1290             LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1291         }
1292         else if(CA_STATUS_FAILED == errorInfo->result)
1293         {
1294             LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1295         }
1296     }
1297     LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1298
1299     return;
1300 }
1301
1302 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1303 {
1304     const char *startPos = URI;
1305     const char *temp = strstr(URI, "://");
1306     if (NULL != temp)
1307     {
1308         startPos = strchr(temp + 3, '/');
1309         if (!startPos)
1310         {
1311             LOGE("Resource URI is missing");
1312             return;
1313         }
1314     }
1315
1316     const char *endPos = strchr(startPos, '?');
1317     if (!endPos)
1318     {
1319         endPos = URI + strlen(URI);
1320     }
1321     --endPos;
1322
1323     if (endPos - startPos <= length)
1324     {
1325         memcpy(resourceURI, startPos + 1, endPos - startPos);
1326     }
1327
1328     LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1329 }
1330
1331 uint32_t get_secure_information(CAPayload_t payLoad)
1332 {
1333     LOGI("entering get_secure_information");
1334
1335     if (!payLoad)
1336     {
1337         LOGE("Payload is NULL");
1338         return -1;
1339     }
1340
1341     const char *subString = NULL;
1342     if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1343     {
1344         LOGE("This is not secure resource");
1345         return -1;
1346     }
1347
1348     if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1349     {
1350         LOGE("This secure resource does not have port information");
1351         return -1;
1352     }
1353
1354     const char *startPos = strstr(subString, ":");
1355     if (!startPos)
1356     {
1357         LOGE("Parsing failed !");
1358         return -1;
1359     }
1360
1361     const char *endPos = strstr(startPos, "}");
1362     if (!endPos)
1363     {
1364         LOGE("Parsing failed !");
1365         return -1;
1366     }
1367
1368     char portStr[6] = { 0 };
1369     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1370
1371     LOGI("secured port is: %s", portStr);
1372     return atoi(portStr);
1373 }
1374
1375 CAResult_t get_network_type(uint32_t selectedNetwork)
1376 {
1377
1378     uint32_t number = selectedNetwork;
1379
1380     if (!(number & 0xf))
1381     {
1382         return CA_NOT_SUPPORTED;
1383     }
1384     if (number & CA_ADAPTER_IP)
1385     {
1386         g_selectedNwType = CA_ADAPTER_IP;
1387         return CA_STATUS_OK;
1388     }
1389     if (number & CA_ADAPTER_RFCOMM_BTEDR)
1390     {
1391         g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1392         return CA_STATUS_OK;
1393     }
1394     if (number & CA_ADAPTER_GATT_BTLE)
1395     {
1396         g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1397         return CA_STATUS_OK;
1398     }
1399
1400     return CA_NOT_SUPPORTED;
1401 }
1402
1403 void callback(char *subject, char *receivedData)
1404 {
1405     bool isAttached = false;
1406     JNIEnv* env;
1407
1408     if (!g_responseListenerObject)
1409     {
1410         LOGE("g_responseListenerObject is NULL, cannot have callback");
1411         return;
1412     }
1413
1414     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1415     if (JNI_OK != res)
1416     {
1417         LOGI("Could not get JNIEnv pointer");
1418         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1419
1420         if (JNI_OK != res)
1421         {
1422             LOGE("AttachCurrentThread has failed");
1423             return;
1424         }
1425         isAttached = true;
1426     }
1427
1428     jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1429     if (!cls)
1430     {
1431         LOGE("could not get class");
1432         goto detach_thread;
1433     }
1434
1435     jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1436                                         "(Ljava/lang/String;Ljava/lang/String;)V");
1437     if (!mid)
1438     {
1439         LOGE("could not get Method ID");
1440         goto detach_thread;
1441     }
1442
1443     jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1444     if (!jsubject)
1445     {
1446         LOGE("NewStringUTF failed");
1447         goto detach_thread;
1448     }
1449
1450     jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1451     if (!jreceivedData)
1452     {
1453         LOGE("NewStringUTF failed");
1454         goto detach_thread;
1455     }
1456
1457     (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1458
1459 detach_thread :
1460     if (isAttached)
1461     {
1462         (*g_jvm)->DetachCurrentThread(g_jvm);
1463         LOGI("DetachCurrentThread");
1464     }
1465 }
1466
1467 CAResult_t get_remote_address(const char *address)
1468 {
1469     uint32_t len = strlen(address);
1470
1471     g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1472     if (NULL == g_remoteAddress)
1473     {
1474         LOGE("g_remoteAddress Out of memory");
1475         return CA_MEMORY_ALLOC_FAILED;
1476     }
1477
1478     memcpy(g_remoteAddress, address, len + 1);
1479
1480     return CA_STATUS_OK;
1481 }
1482
1483
1484 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1485 {
1486     if (NULL == uri || NULL == address)
1487     {
1488         LOGE("parameter is null");
1489         return;
1490     }
1491
1492     // parse uri
1493     // #1. check prefix
1494     uint8_t startIndex = 0;
1495     if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1496     {
1497         LOGI("uri has '%s' prefix", COAPS_PREFIX);
1498         startIndex = COAPS_PREFIX_LEN;
1499         *flags = CA_SECURE;
1500     }
1501     else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1502     {
1503         LOGI("uri has '%s' prefix", COAP_PREFIX);
1504         startIndex = COAP_PREFIX_LEN;
1505         *flags = CA_IPV4;
1506     }
1507
1508     // #2. copy uri for parse
1509     size_t len = strlen(uri) - startIndex;
1510
1511     if (len <= 0)
1512     {
1513         LOGE("uri length is 0!");
1514         return;
1515     }
1516
1517     char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1518     if (NULL == cloneUri)
1519     {
1520         LOGE("Out of memory");
1521         return;
1522     }
1523
1524     OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1525
1526     char *pstr = NULL;
1527     //filter out the resource uri
1528     char *pUrl = strtok_r(cloneUri, "/", &pstr);
1529
1530     if (pUrl)
1531     {
1532         LOGI("pAddress : %s", pUrl);
1533         int res = get_address_set(pUrl, address);
1534         if (res == -1)
1535         {
1536             LOGE("address parse error");
1537
1538             return;
1539         }
1540     }
1541     else
1542     {
1543         LOGE("strtok_r error, could not get the address");
1544     }
1545
1546     return;
1547 }
1548
1549 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1550 {
1551     if (NULL == pAddress || NULL == outAddress)
1552     {
1553         LOGE("parameter is null");
1554         return -1;
1555     }
1556
1557     size_t len = strlen(pAddress);
1558     int isIp = 0;
1559     size_t ipLen = 0;
1560
1561     for (size_t i = 0; i < len; i++)
1562     {
1563         if (pAddress[i] == '.')
1564         {
1565             isIp = 1;
1566         }
1567
1568         // found port number start index
1569         if (isIp && pAddress[i] == ':')
1570         {
1571             ipLen = i;
1572             break;
1573         }
1574     }
1575
1576     if (isIp)
1577     {
1578         if(ipLen && (ipLen <  sizeof(outAddress->ipAddress)))
1579         {
1580             strncpy(outAddress->ipAddress, pAddress, ipLen);
1581             outAddress->ipAddress[ipLen] = '\0';
1582         }
1583         else if (!ipLen && (len <  sizeof(outAddress->ipAddress)))
1584         {
1585             strncpy(outAddress->ipAddress, pAddress, len);
1586             outAddress->ipAddress[len] = '\0';
1587         }
1588         else
1589         {
1590             LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1591             return -1;
1592         }
1593
1594         if (ipLen > 0)
1595         {
1596             outAddress->port = atoi(pAddress + ipLen + 1);
1597         }
1598     }
1599     else
1600     {
1601         strncpy(outAddress->ipAddress, pAddress, len);
1602         outAddress->ipAddress[len] = '\0';
1603     }
1604
1605     return isIp;
1606 }
1607
1608 void delete_global_references(JNIEnv *env, jobject obj)
1609 {
1610     LOGI("delete_global_references");
1611     if (!env || !obj )
1612     {
1613         LOGI("Invalid input parameter");
1614         return;
1615     }
1616
1617     (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1618 }
1619
1620
1621 bool read_file(const char* name, char** bytes, size_t* length)
1622 {
1623     if (NULL == name)
1624     {
1625         LOGE("parameter is null");
1626         return false;
1627     }
1628
1629     FILE* file;
1630     char* buffer;
1631     size_t fileLen;
1632
1633     // Open file
1634     file = fopen(name, "rt");
1635     if (!file)
1636     {
1637         fprintf(stderr, "Unable to open file %s", name);
1638         return false;
1639     }
1640
1641     // Get file length
1642     fseek(file, 0, SEEK_END);
1643     fileLen = ftell(file);
1644     fseek(file, 0, SEEK_SET);
1645
1646     LOGI("file size: %d", fileLen);
1647
1648     // Allocate memory
1649     buffer = calloc(1, sizeof(char) * fileLen + 1);
1650     if (!buffer)
1651     {
1652         fprintf(stderr, "Memory error!");
1653         fclose(file);
1654         return false;
1655     }
1656
1657     // Read file contents into buffer
1658     size_t ret = fread(buffer, fileLen, 1, file);
1659     if (ret != 1)
1660     {
1661         printf("Failed to read data from file, %s\n", name);
1662         fclose(file);
1663         free(buffer);
1664         return false;
1665     }
1666
1667     fclose(file);
1668
1669     LOGI("file bytes: %s", buffer);
1670
1671     *bytes = buffer;
1672     *length = fileLen;
1673
1674     return true;
1675 }
1676
1677 void saveFile(const char *payload, size_t payloadSize)
1678 {
1679     // 1. get day
1680     uint32_t day = gettodaydate();
1681
1682     // 2. get time
1683     time_t current_time;
1684     struct tm * time_info;
1685     char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1686
1687     time(&current_time);
1688     time_info = localtime(&current_time);
1689
1690     strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1691
1692     uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1693     char* path = calloc(1, sizeof(char) * path_length);
1694     if (path != NULL)
1695     {
1696         sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1697         LOGI("received file path: %s", path);
1698
1699         FILE *fp = fopen(path, "wt");
1700         fwrite(payload, 1, payloadSize, fp);
1701         fclose(fp);
1702
1703         callback("File Path: ", path);
1704     }
1705     else
1706     {
1707         LOGE("path Out of memory");
1708     }
1709 }
1710
1711 uint32_t gettodaydate()
1712 {
1713     uint32_t ldate;
1714     time_t clock;
1715     struct tm *date;
1716
1717     clock = time(0);
1718     date = localtime(&clock);
1719     ldate = date->tm_year * 100000;
1720     ldate += (date->tm_mon + 1) * 1000;
1721     ldate += date->tm_mday * 10;
1722     ldate += date->tm_wday;
1723     ldate += 190000000;
1724     ldate /= 10;
1725
1726     return(ldate);
1727 }