Refactor PSK Credential retrieval interface
[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                                                             jint responseValue)
652 {
653     LOGI("selectedNetwork - %d", selectedNetwork);
654     if (!env || !obj)
655     {
656         LOGI("Invalid input parameter");
657         return;
658     }
659
660     if (!payload)
661     {
662         LOGE("payload is NULL");
663     }
664
665     if (!uri)
666     {
667         LOGE("Invalid input parameter : uri");
668         return;
669     }
670
671     CAResult_t res = get_network_type(selectedNetwork);
672     if (CA_STATUS_OK != res)
673     {
674         LOGE("Not supported network type");
675         return;
676     }
677
678     const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
679     LOGI("RMSendNotification - %s", strUri);
680
681     CATransportFlags_t flags;
682     addressSet_t address = {{0}, 0};
683     parsing_coap_uri(strUri, &address, &flags);
684
685     //create remote endpoint
686     CAEndpoint_t* endpoint = NULL;
687     if (CA_STATUS_OK != CACreateEndpoint(flags, g_selectedNwType,
688                                          (const char*)address.ipAddress,
689                                          address.port, &endpoint))
690     {
691         //ReleaseStringUTFChars for strUri
692         (*env)->ReleaseStringUTFChars(env, uri, strUri);
693         LOGE("Could not create remote end point");
694         return;
695     }
696
697     char resourceURI[RESOURCE_URI_LENGTH + 1] = { 0 };
698     get_resource_uri(strUri, resourceURI, RESOURCE_URI_LENGTH);
699
700     //ReleaseStringUTFChars for strUri
701     (*env)->ReleaseStringUTFChars(env, uri, strUri);
702
703     CAMessageType_t messageType = msgType;
704
705     // create token
706     CAToken_t token = NULL;
707     uint8_t tokenLength = CA_MAX_TOKEN_LEN;
708
709     res = CAGenerateToken(&token, tokenLength);
710     if ((CA_STATUS_OK != res) || (!token))
711     {
712         LOGE("token generate error!");
713         CADestroyEndpoint(endpoint);
714         return;
715     }
716
717     CAInfo_t responseData = { 0 };
718     responseData.token = token;
719     responseData.tokenLength = tokenLength;
720     responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
721     if (NULL == responseData.resourceUri)
722     {
723         LOGE("Memory allocation failed!");
724         // destroy token
725         CADestroyToken(token);
726         // destroy remote endpoint
727         CADestroyEndpoint(endpoint);
728         return;
729     }
730     memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
731
732     if (1 == isSecured)
733     {
734         uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
735         responseData.payload = (CAPayload_t) malloc(length);
736         if (NULL == responseData.payload)
737         {
738             LOGE("Memory allocation failed!");
739             // destroy token
740             CADestroyToken(token);
741             // destroy remote endpoint
742             CADestroyEndpoint(endpoint);
743
744             free(responseData.resourceUri);
745             return;
746         }
747         snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
748         responseData.payloadSize = length;
749     }
750     else
751     {
752         uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
753         responseData.payload = (CAPayload_t) malloc(length);
754         if (NULL == responseData.payload)
755         {
756             LOGE("Memory allocation failed!");
757             // destroy token
758             CADestroyToken(token);
759             // destroy remote endpoint
760             CADestroyEndpoint(endpoint);
761
762             free(responseData.resourceUri);
763             return;
764         }
765         snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
766         responseData.payloadSize = length;
767     }
768
769     responseData.type = messageType;
770
771     CAResponseInfo_t responseInfo = { 0 };
772     responseInfo.result = responseValue;
773     responseInfo.info = responseData;
774
775     // send notification
776     if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
777     {
778         LOGE("Could not send notification");
779     }
780
781     LOGI("Send Notification");
782
783     // destroy token
784     CADestroyToken(token);
785
786     // destroy remote endpoint
787     CADestroyEndpoint(endpoint);
788
789     free(responseData.payload);
790     free(responseData.resourceUri);
791 }
792
793 JNIEXPORT void JNICALL
794 Java_org_iotivity_ca_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
795                                                          jint networkType)
796 {
797     LOGI("RMSelectNetwork Type : %d", networkType);
798     if (!env || !obj)
799     {
800         LOGI("Invalid input parameter");
801         return;
802     }
803
804     if (CA_STATUS_OK != CASelectNetwork(networkType))
805     {
806         LOGE("Could not select network");
807     }
808 }
809
810 JNIEXPORT void JNICALL
811 Java_org_iotivity_ca_service_RMInterface_RMUnSelectNetwork(JNIEnv *env, jobject obj,
812                                                            jint networkType)
813 {
814     LOGI("RMUnSelectNetwork Type : %d", networkType);
815     if (!env || !obj)
816     {
817         LOGI("Invalid input parameter");
818         return;
819     }
820
821     if (CA_STATUS_OK != CAUnSelectNetwork(networkType))
822     {
823         LOGE("Could not unselect network");
824     }
825 }
826
827 JNIEXPORT void JNICALL
828 Java_org_iotivity_ca_service_RMInterface_RMGetNetworkInfomation(JNIEnv *env, jobject obj)
829 {
830     LOGI("RMGetNetworkInfomation");
831     if (!env || !obj)
832     {
833         LOGI("Invalid input parameter");
834         return;
835     }
836
837     CAEndpoint_t *tempInfo = NULL;
838     uint32_t tempSize = 0;
839
840     CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
841     if (CA_STATUS_OK != res)
842     {
843         LOGE("Could not start get network information");
844         free(tempInfo);
845         return;
846     }
847
848     LOGI("################## Network Information #######################");
849     callback("######## Network Information", "#######");
850     LOGI("Network info total size is %d", tempSize);
851
852     uint32_t index;
853     for (index = 0; index < tempSize; index++)
854     {
855         res = get_remote_address(tempInfo[index].addr);
856         if (CA_STATUS_OK != res)
857         {
858             free(tempInfo);
859             return;
860         }
861         if (NULL != g_responseListenerObject)
862         {
863             char networkInfo[NETWORK_INFO_LENGTH];
864             LOGI("Type: %d", tempInfo[index].adapter);
865             sprintf(networkInfo, "%d",tempInfo[index].adapter);
866             callback("Type :", networkInfo);
867             if (CA_ADAPTER_IP == tempInfo[index].adapter)
868             {
869                 LOGI("Port: %d", tempInfo[index].port);
870                 sprintf(networkInfo, "%d",tempInfo[index].port);
871                 callback("Port: ", networkInfo);
872             }
873             LOGI("Secured: %d", (tempInfo[index].flags & CA_SECURE));
874             LOGI("Address: %s", g_remoteAddress);
875             callback("Address: ", g_remoteAddress);
876             free(g_remoteAddress);
877         }
878         if (tempInfo[index].flags & CA_SECURE)
879         {
880             g_localSecurePort = tempInfo[index].port;
881         }
882     }
883
884     // free
885     free(tempInfo);
886
887     LOGI("##############################################################");
888 }
889
890 JNIEXPORT void JNICALL
891 Java_org_iotivity_ca_service_RMInterface_RMHandleRequestResponse(JNIEnv *env, jobject obj)
892 {
893     LOGI("RMHandleRequestResponse");
894     if(!env || !obj)
895     {
896         LOGI("Invalid input parameter");
897         return;
898     }
899
900     if (CA_STATUS_OK != CAHandleRequestResponse())
901     {
902         LOGE("Could not handle request and response");
903     }
904 }
905
906 void request_handler(const CAEndpoint_t* object, const CARequestInfo_t* requestInfo)
907 {
908
909     if (!object)
910     {
911         LOGE("Remote endpoint is NULL!");
912         return;
913     }
914
915     if (!requestInfo)
916     {
917         LOGE("Request info is NULL!");
918         return;
919     }
920
921     if ((NULL != g_lastRequestToken) && (NULL != requestInfo->info.token) &&
922             (strncmp(g_lastRequestToken, requestInfo->info.token,
923                      requestInfo->info.tokenLength) == 0))
924     {
925         LOGI("token is same. received request of it's own. skip.. ");
926         return;
927     }
928
929     CAResult_t res = get_remote_address(object->addr);
930     if (CA_STATUS_OK != res)
931     {
932         return;
933     }
934
935     LOGI("##########received request from remote device #############");
936     LOGI("Remote Address: %s", g_remoteAddress);
937     LOGI("Remote Port: %d", object->port);
938     LOGI("Uri: %s", requestInfo->info.resourceUri);
939     LOGI("Data: %s", requestInfo->info.payload);
940     LOGI("Token: %s", requestInfo->info.token);
941     LOGI("Code: %d", requestInfo->method);
942     LOGI("MessageType: %d", requestInfo->info.type);
943
944     if (NULL != g_responseListenerObject)
945     {
946         char *cloneUri = NULL;
947         uint32_t len = 0;
948
949         if (NULL != requestInfo->info.resourceUri)
950         {
951             len = strlen(requestInfo->info.resourceUri);
952             cloneUri = (char *)malloc(sizeof(char) * (len + 1));
953
954             if (NULL == cloneUri)
955             {
956                 LOGE("cloneUri Out of memory");
957                 free(g_remoteAddress);
958                 return;
959             }
960
961             memcpy(cloneUri, requestInfo->info.resourceUri, len + 1);
962             callback("Uri: ", cloneUri);
963         }
964
965         len = strlen(g_remoteAddress);
966         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
967
968         if (NULL == cloneRemoteAddress)
969         {
970             LOGE("cloneRemoteAddress Out of memory");
971             free(g_remoteAddress);
972             free(cloneUri);
973             return;
974         }
975
976         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
977
978         callback("Remote Address: ", cloneRemoteAddress);
979         free(cloneRemoteAddress);
980         free(g_remoteAddress);
981
982         char portInfo[PORT_LENGTH] = { 0, };
983         sprintf(portInfo, "%d", object->port);
984         callback("Remote Port: ", portInfo);
985
986         //clone g_clientEndpoint
987         g_clientEndpoint = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
988         if (NULL == g_clientEndpoint)
989         {
990             LOGE("g_clientEndpoint Out of memory");
991             free(cloneUri);
992             return;
993         }
994         memcpy(g_clientEndpoint, object, sizeof(CAEndpoint_t));
995
996         if (NULL != cloneUri)
997         {
998             len = strlen(cloneUri);
999             g_resourceUri = (char *) malloc(sizeof(char) * (len + 1));
1000             if (NULL == g_resourceUri)
1001             {
1002                 LOGE("g_clientEndpoint->resourceUri Out of memory");
1003                 free(g_clientEndpoint);
1004                 free(cloneUri);
1005                 return;
1006             }
1007             memcpy(g_resourceUri, cloneUri, len + 1);
1008             free(cloneUri);
1009         }
1010         //clone g_clientToken
1011         len = requestInfo->info.tokenLength;
1012
1013         g_clientToken = (char *) malloc(sizeof(char) * len);
1014         if (NULL == g_clientToken)
1015         {
1016             LOGE("g_clientToken Out of memory");
1017             free(g_clientEndpoint);
1018             return;
1019         }
1020
1021         if (NULL != requestInfo->info.token)
1022         {
1023             memcpy(g_clientToken, requestInfo->info.token, len);
1024             g_clientTokenLength = len;
1025
1026         }
1027
1028         //clone g_clientMsgId
1029         g_clientMsgId = requestInfo->info.messageId;
1030
1031         if (NULL != requestInfo->info.payload && requestInfo->info.payloadSize > 0)
1032         {
1033             len = requestInfo->info.payloadSize;
1034             char *clonePayload = (char *) malloc(len + 1);
1035             if (NULL == clonePayload)
1036             {
1037                 LOGE("clonePayload Out of memory");
1038                 free(g_clientEndpoint);
1039                 return;
1040             }
1041
1042             memcpy(clonePayload, requestInfo->info.payload, len);
1043             clonePayload[len] = '\0';
1044
1045             if (len > BIG_PAYLOAD_LENGTH)
1046             {
1047                 saveFile(clonePayload, len);
1048             }
1049             else
1050             {
1051                 callback("Data: ", clonePayload);
1052             }
1053             free(clonePayload);
1054         }
1055     }
1056
1057     if (requestInfo->info.options)
1058     {
1059         uint32_t len = requestInfo->info.numOptions;
1060         uint32_t i;
1061
1062         LOGI("Option count: %d", requestInfo->info.numOptions);
1063
1064         for (i = 0; i < len; i++)
1065         {
1066             LOGI("Option %d", i + 1);
1067             LOGI("ID : %d", requestInfo->info.options[i].optionID);
1068             LOGI("Data[%d]: %s", requestInfo->info.options[i].optionLength,
1069                  requestInfo->info.options[i].optionData);
1070
1071             if (NULL != g_responseListenerObject)
1072             {
1073                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1074                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1075                         requestInfo->info.options[i].optionID,
1076                         requestInfo->info.options[i].optionLength);
1077
1078                 callback("Option info: ", optionInfo);
1079
1080                 size_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
1081                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1082                 if (NULL == cloneOptionData)
1083                 {
1084                     LOGE("cloneOptionData Out of memory");
1085                     free(g_clientEndpoint);
1086                     return;
1087                 }
1088
1089                 memcpy(cloneOptionData, requestInfo->info.options[i].optionData,
1090                        optionDataLen + 1);
1091
1092                 callback("Option Data: ", cloneOptionData);
1093                 free(cloneOptionData);
1094             }
1095         }
1096     }
1097     LOGI("############################################################");
1098
1099     //Check if this has secure communication information
1100     if (requestInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1101     {
1102         uint32_t securePort = get_secure_information(requestInfo->info.payload);
1103         if (0 < securePort) //Set the remote endpoint secure details and send response
1104         {
1105             LOGI("This is secure resource...");
1106
1107             CAEndpoint_t *endpoint = NULL;
1108             if (CA_STATUS_OK != CACreateEndpoint(CA_SECURE,
1109                         object->adapter, object->addr, securePort, &endpoint))
1110             {
1111                 LOGE("Failed to create duplicate of remote endpoint!");
1112                 return;
1113             }
1114             object = endpoint;
1115         }
1116     }
1117 }
1118
1119 void response_handler(const CAEndpoint_t* object, const CAResponseInfo_t* responseInfo)
1120 {
1121     if (!object || !responseInfo)
1122     {
1123         LOGE("Invalid input parameter");
1124         return;
1125     }
1126
1127     CAResult_t res = get_remote_address(object->addr);
1128     if (CA_STATUS_OK != res)
1129     {
1130         return;
1131     }
1132
1133     LOGI("##########Received response from remote device #############");
1134     LOGI("Uri: %s", responseInfo->info.resourceUri);
1135     LOGI("Remote Address: %s", g_remoteAddress);
1136     LOGI("Remote Port: %d", object->port);
1137     LOGI("response result: %d", responseInfo->result);
1138     LOGI("Data: %s", responseInfo->info.payload);
1139     LOGI("Token: %s", responseInfo->info.token);
1140     LOGI("MessageType: %d", responseInfo->info.type);
1141
1142     if (NULL != g_responseListenerObject)
1143     {
1144         uint32_t len = 0;
1145
1146         if (NULL != responseInfo->info.resourceUri)
1147         {
1148             len = strlen(responseInfo->info.resourceUri);
1149             char *cloneUri = (char *) malloc(sizeof(char) * (len + 1));
1150
1151             if (NULL == cloneUri)
1152             {
1153                 LOGE("cloneUri Out of memory");
1154                 free(g_remoteAddress);
1155                 return;
1156             }
1157
1158             memcpy(cloneUri, responseInfo->info.resourceUri, len + 1);
1159
1160             callback("Uri: ", cloneUri);
1161             free(cloneUri);
1162         }
1163
1164         len = strlen(g_remoteAddress);
1165         char *cloneRemoteAddress = (char *) malloc(sizeof(char) * (len + 1));
1166
1167         if (NULL == cloneRemoteAddress)
1168         {
1169             LOGE("cloneRemoteAddress Out of memory");
1170             free(g_remoteAddress);
1171             return;
1172         }
1173
1174         memcpy(cloneRemoteAddress, g_remoteAddress, len + 1);
1175
1176         callback("Remote Address: ", cloneRemoteAddress);
1177         free(cloneRemoteAddress);
1178         free(g_remoteAddress);
1179
1180         char portInfo[PORT_LENGTH] = { 0, };
1181         sprintf(portInfo, "%d", object->port);
1182         callback("Remote Port: ", portInfo);
1183
1184         if (NULL != responseInfo->info.payload && responseInfo->info.payloadSize)
1185         {
1186             len = responseInfo->info.payloadSize;
1187             char *clonePayload = (char *) malloc(len + 1);
1188             if (NULL == clonePayload)
1189             {
1190                 LOGE("clonePayload Out of memory");
1191                 return;
1192             }
1193
1194             memcpy(clonePayload, responseInfo->info.payload, len);
1195             clonePayload[len] = '\0';
1196
1197             if (len > BIG_PAYLOAD_LENGTH)
1198             {
1199                 saveFile(clonePayload, len);
1200             }
1201             else
1202             {
1203                 callback("Data: ", clonePayload);
1204             }
1205             free(clonePayload);
1206         }
1207     }
1208
1209     if (responseInfo->info.options)
1210     {
1211         uint32_t len = responseInfo->info.numOptions;
1212         uint32_t i;
1213         for (i = 0; i < len; i++)
1214         {
1215             LOGI("Option %d", i + 1);
1216             LOGI("ID : %d", responseInfo->info.options[i].optionID);
1217             LOGI("Data[%d]: %s", responseInfo->info.options[i].optionLength,
1218                  responseInfo->info.options[i].optionData);
1219
1220             if (NULL != g_responseListenerObject)
1221             {
1222                 char optionInfo[OPTION_INFO_LENGTH] = { 0, };
1223                 sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i + 1,
1224                         responseInfo->info.options[i].optionID,
1225                         responseInfo->info.options[i].optionLength);
1226
1227                 callback("Option info: ", optionInfo);
1228
1229                 size_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
1230                 char *cloneOptionData = (char *) malloc(sizeof(char) * (optionDataLen + 1));
1231                 if (NULL == cloneOptionData)
1232                 {
1233                     LOGE("cloneOptionData Out of memory");
1234                     return;
1235                 }
1236                 memcpy(cloneOptionData, responseInfo->info.options[i].optionData,
1237                        optionDataLen + 1);
1238                 callback("Option Data: ", cloneOptionData);
1239                 free(cloneOptionData);
1240             }
1241         }
1242     }
1243     LOGI("############################################################");
1244
1245     //Check if this has secure communication information
1246     if (responseInfo->info.payload && CA_ADAPTER_IP == object->adapter)
1247     {
1248         uint32_t securePort = get_secure_information(responseInfo->info.payload);
1249         if (0 < securePort) //Set the remote endpoint secure details and send response
1250         {
1251             LOGI("This is secure resource...");
1252         }
1253     }
1254 }
1255
1256 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1257 {
1258     LOGI("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++");
1259
1260     if (rep)
1261     {
1262         LOGI("Error Handler, Adapter Type : %d", rep->adapter);
1263         LOGI("Error Handler, Adapter Type : %s", rep->addr);
1264     }
1265
1266     if (errorInfo)
1267     {
1268         const CAInfo_t *info = &errorInfo->info;
1269         LOGI("Error Handler, ErrorInfo :");
1270         LOGI("Error Handler result    : %d", errorInfo->result);
1271         LOGI("Error Handler token     : %s", info->token);
1272         LOGI("Error Handler messageId : %d", (uint16_t) info->messageId);
1273         LOGI("Error Handler resourceUri : %s", info->resourceUri);
1274         LOGI("Error Handler type      : %d", info->type);
1275         LOGI("Error Handler payload   : %s", info->payload);
1276
1277         if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1278         {
1279             LOGE("CA_ADAPTER_NOT_ENABLED, enable the adapter");
1280         }
1281         else if(CA_SEND_FAILED == errorInfo->result)
1282         {
1283             LOGE("CA_SEND_FAILED, unable to send the message, check parameters");
1284         }
1285         else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1286         {
1287             LOGE("CA_MEMORY_ALLOC_FAILED, insufficient memory");
1288         }
1289         else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1290         {
1291             LOGE("CA_SOCKET_OPERATION_FAILED, socket operation failed");
1292         }
1293         else if(CA_STATUS_FAILED == errorInfo->result)
1294         {
1295             LOGE("CA_STATUS_FAILED, message could not be delivered, internal error");
1296         }
1297     }
1298     LOGI("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++");
1299
1300     return;
1301 }
1302
1303 void get_resource_uri(const char *URI, char *resourceURI, int32_t length)
1304 {
1305     const char *startPos = URI;
1306     const char *temp = strstr(URI, "://");
1307     if (NULL != temp)
1308     {
1309         startPos = strchr(temp + 3, '/');
1310         if (!startPos)
1311         {
1312             LOGE("Resource URI is missing");
1313             return;
1314         }
1315     }
1316
1317     const char *endPos = strchr(startPos, '?');
1318     if (!endPos)
1319     {
1320         endPos = URI + strlen(URI);
1321     }
1322     --endPos;
1323
1324     if (endPos - startPos <= length)
1325     {
1326         memcpy(resourceURI, startPos + 1, endPos - startPos);
1327     }
1328
1329     LOGI("URI: %s, ResourceURI: %s", URI, resourceURI);
1330 }
1331
1332 uint32_t get_secure_information(CAPayload_t payLoad)
1333 {
1334     LOGI("entering get_secure_information");
1335
1336     if (!payLoad)
1337     {
1338         LOGE("Payload is NULL");
1339         return -1;
1340     }
1341
1342     const char *subString = NULL;
1343     if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1344     {
1345         LOGE("This is not secure resource");
1346         return -1;
1347     }
1348
1349     if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1350     {
1351         LOGE("This secure resource does not have port information");
1352         return -1;
1353     }
1354
1355     const char *startPos = strstr(subString, ":");
1356     if (!startPos)
1357     {
1358         LOGE("Parsing failed !");
1359         return -1;
1360     }
1361
1362     const char *endPos = strstr(startPos, "}");
1363     if (!endPos)
1364     {
1365         LOGE("Parsing failed !");
1366         return -1;
1367     }
1368
1369     char portStr[6] = { 0 };
1370     memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1371
1372     LOGI("secured port is: %s", portStr);
1373     return atoi(portStr);
1374 }
1375
1376 CAResult_t get_network_type(uint32_t selectedNetwork)
1377 {
1378
1379     uint32_t number = selectedNetwork;
1380
1381     if (!(number & 0xf))
1382     {
1383         return CA_NOT_SUPPORTED;
1384     }
1385     if (number & CA_ADAPTER_IP)
1386     {
1387         g_selectedNwType = CA_ADAPTER_IP;
1388         return CA_STATUS_OK;
1389     }
1390     if (number & CA_ADAPTER_RFCOMM_BTEDR)
1391     {
1392         g_selectedNwType = CA_ADAPTER_RFCOMM_BTEDR;
1393         return CA_STATUS_OK;
1394     }
1395     if (number & CA_ADAPTER_GATT_BTLE)
1396     {
1397         g_selectedNwType = CA_ADAPTER_GATT_BTLE;
1398         return CA_STATUS_OK;
1399     }
1400
1401     return CA_NOT_SUPPORTED;
1402 }
1403
1404 void callback(char *subject, char *receivedData)
1405 {
1406     bool isAttached = false;
1407     JNIEnv* env;
1408
1409     if (!g_responseListenerObject)
1410     {
1411         LOGE("g_responseListenerObject is NULL, cannot have callback");
1412         return;
1413     }
1414
1415     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
1416     if (JNI_OK != res)
1417     {
1418         LOGI("Could not get JNIEnv pointer");
1419         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
1420
1421         if (JNI_OK != res)
1422         {
1423             LOGE("AttachCurrentThread has failed");
1424             return;
1425         }
1426         isAttached = true;
1427     }
1428
1429     jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
1430     if (!cls)
1431     {
1432         LOGE("could not get class");
1433         goto detach_thread;
1434     }
1435
1436     jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
1437                                         "(Ljava/lang/String;Ljava/lang/String;)V");
1438     if (!mid)
1439     {
1440         LOGE("could not get Method ID");
1441         goto detach_thread;
1442     }
1443
1444     jstring jsubject = (*env)->NewStringUTF(env, (char*) subject);
1445     if (!jsubject)
1446     {
1447         LOGE("NewStringUTF failed");
1448         goto detach_thread;
1449     }
1450
1451     jstring jreceivedData = (*env)->NewStringUTF(env, (char*) receivedData);
1452     if (!jreceivedData)
1453     {
1454         LOGE("NewStringUTF failed");
1455         goto detach_thread;
1456     }
1457
1458     (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
1459
1460 detach_thread :
1461     if (isAttached)
1462     {
1463         (*g_jvm)->DetachCurrentThread(g_jvm);
1464         LOGI("DetachCurrentThread");
1465     }
1466 }
1467
1468 CAResult_t get_remote_address(const char *address)
1469 {
1470     uint32_t len = strlen(address);
1471
1472     g_remoteAddress = (char *)malloc(sizeof (char) * (len + 1));
1473     if (NULL == g_remoteAddress)
1474     {
1475         LOGE("g_remoteAddress Out of memory");
1476         return CA_MEMORY_ALLOC_FAILED;
1477     }
1478
1479     memcpy(g_remoteAddress, address, len + 1);
1480
1481     return CA_STATUS_OK;
1482 }
1483
1484
1485 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1486 {
1487     if (NULL == uri || NULL == address)
1488     {
1489         LOGE("parameter is null");
1490         return;
1491     }
1492
1493     // parse uri
1494     // #1. check prefix
1495     uint8_t startIndex = 0;
1496     if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1497     {
1498         LOGI("uri has '%s' prefix", COAPS_PREFIX);
1499         startIndex = COAPS_PREFIX_LEN;
1500         *flags = CA_SECURE;
1501     }
1502     else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1503     {
1504         LOGI("uri has '%s' prefix", COAP_PREFIX);
1505         startIndex = COAP_PREFIX_LEN;
1506         *flags = CA_IPV4;
1507     }
1508
1509     // #2. copy uri for parse
1510     size_t len = strlen(uri) - startIndex;
1511
1512     if (len <= 0)
1513     {
1514         LOGE("uri length is 0!");
1515         return;
1516     }
1517
1518     char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1519     if (NULL == cloneUri)
1520     {
1521         LOGE("Out of memory");
1522         return;
1523     }
1524
1525     OICStrcpy(cloneUri, len+1, &uri[startIndex]);
1526
1527     char *pstr = NULL;
1528     //filter out the resource uri
1529     char *pUrl = strtok_r(cloneUri, "/", &pstr);
1530
1531     if (pUrl)
1532     {
1533         LOGI("pAddress : %s", pUrl);
1534         int res = get_address_set(pUrl, address);
1535         if (res == -1)
1536         {
1537             LOGE("address parse error");
1538
1539             return;
1540         }
1541     }
1542     else
1543     {
1544         LOGE("strtok_r error, could not get the address");
1545     }
1546
1547     return;
1548 }
1549
1550 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1551 {
1552     if (NULL == pAddress || NULL == outAddress)
1553     {
1554         LOGE("parameter is null");
1555         return -1;
1556     }
1557
1558     size_t len = strlen(pAddress);
1559     int isIp = 0;
1560     size_t ipLen = 0;
1561
1562     for (size_t i = 0; i < len; i++)
1563     {
1564         if (pAddress[i] == '.')
1565         {
1566             isIp = 1;
1567         }
1568
1569         // found port number start index
1570         if (isIp && pAddress[i] == ':')
1571         {
1572             ipLen = i;
1573             break;
1574         }
1575     }
1576
1577     if (isIp)
1578     {
1579         if(ipLen && (ipLen <  sizeof(outAddress->ipAddress)))
1580         {
1581             strncpy(outAddress->ipAddress, pAddress, ipLen);
1582             outAddress->ipAddress[ipLen] = '\0';
1583         }
1584         else if (!ipLen && (len <  sizeof(outAddress->ipAddress)))
1585         {
1586             strncpy(outAddress->ipAddress, pAddress, len);
1587             outAddress->ipAddress[len] = '\0';
1588         }
1589         else
1590         {
1591             LOGE("IP Address too long: %d", ipLen==0 ? len : ipLen);
1592             return -1;
1593         }
1594
1595         if (ipLen > 0)
1596         {
1597             outAddress->port = atoi(pAddress + ipLen + 1);
1598         }
1599     }
1600     else
1601     {
1602         strncpy(outAddress->ipAddress, pAddress, len);
1603         outAddress->ipAddress[len] = '\0';
1604     }
1605
1606     return isIp;
1607 }
1608
1609 void delete_global_references(JNIEnv *env, jobject obj)
1610 {
1611     LOGI("delete_global_references");
1612     if (!env || !obj )
1613     {
1614         LOGI("Invalid input parameter");
1615         return;
1616     }
1617
1618     (*env)->DeleteGlobalRef(env, g_responseListenerObject);
1619 }
1620
1621
1622 bool read_file(const char* name, char** bytes, size_t* length)
1623 {
1624     if (NULL == name)
1625     {
1626         LOGE("parameter is null");
1627         return false;
1628     }
1629
1630     FILE* file;
1631     char* buffer;
1632     size_t fileLen;
1633
1634     // Open file
1635     file = fopen(name, "rt");
1636     if (!file)
1637     {
1638         fprintf(stderr, "Unable to open file %s", name);
1639         return false;
1640     }
1641
1642     // Get file length
1643     fseek(file, 0, SEEK_END);
1644     fileLen = ftell(file);
1645     fseek(file, 0, SEEK_SET);
1646
1647     LOGI("file size: %d", fileLen);
1648
1649     // Allocate memory
1650     buffer = calloc(1, sizeof(char) * fileLen + 1);
1651     if (!buffer)
1652     {
1653         fprintf(stderr, "Memory error!");
1654         fclose(file);
1655         return false;
1656     }
1657
1658     // Read file contents into buffer
1659     size_t ret = fread(buffer, fileLen, 1, file);
1660     if (ret != 1)
1661     {
1662         printf("Failed to read data from file, %s\n", name);
1663         fclose(file);
1664         free(buffer);
1665         return false;
1666     }
1667
1668     fclose(file);
1669
1670     LOGI("file bytes: %s", buffer);
1671
1672     *bytes = buffer;
1673     *length = fileLen;
1674
1675     return true;
1676 }
1677
1678 void saveFile(const char *payload, size_t payloadSize)
1679 {
1680     // 1. get day
1681     uint32_t day = gettodaydate();
1682
1683     // 2. get time
1684     time_t current_time;
1685     struct tm * time_info;
1686     char timeString[RECEIVED_FILE_NAME_PREFIX_LENGTH];
1687
1688     time(&current_time);
1689     time_info = localtime(&current_time);
1690
1691     strftime(timeString, sizeof(timeString), "%H%M%S", time_info);
1692
1693     uint32_t path_length = strlen(RECEIVED_FILE_PATH) + RECEIVED_FILE_NAME_LENGTH + 1;
1694     char* path = calloc(1, sizeof(char) * path_length);
1695     if (path != NULL)
1696     {
1697         sprintf(path, RECEIVED_FILE_PATH, day, timeString);
1698         LOGI("received file path: %s", path);
1699
1700         FILE *fp = fopen(path, "wt");
1701         fwrite(payload, 1, payloadSize, fp);
1702         fclose(fp);
1703
1704         callback("File Path: ", path);
1705     }
1706     else
1707     {
1708         LOGE("path Out of memory");
1709     }
1710 }
1711
1712 uint32_t gettodaydate()
1713 {
1714     uint32_t ldate;
1715     time_t clock;
1716     struct tm *date;
1717
1718     clock = time(0);
1719     date = localtime(&clock);
1720     ldate = date->tm_year * 100000;
1721     ldate += (date->tm_mon + 1) * 1000;
1722     ldate += date->tm_mday * 10;
1723     ldate += date->tm_wday;
1724     ldate += 190000000;
1725     ldate /= 10;
1726
1727     return(ldate);
1728 }