Merge "Fix re-entrancy issue" into tizen_2.2
[platform/framework/native/appfw.git] / src / app / FApp_SqlDataControlImpl.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Apache License, Version 2.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 /**
18  * @file        FApp_SqlDataControlImpl.cpp
19  * @brief       This is the implementation for the %_SqlDataControlImpl class.
20  */
21
22 #include <typeinfo>
23 #include <unique_ptr.h>
24
25 #include <appsvc/appsvc.h>
26
27 #include <FBaseInteger.h>
28 #include <FBaseString.h>
29 #include <FBaseLongLong.h>
30 #include <FBaseColLinkedList.h>
31 #include <FBaseColIList.h>
32 #include <FBaseColIMap.h>
33 #include <FBaseColIMapEnumerator.h>
34 #include <FBaseRtIEventArg.h>
35 #include <FBaseSysLog.h>
36 #include <FIoFile.h>
37 #include <FAppApp.h>
38 #include <FAppSqlDataControl.h>
39 #include <FAppISqlDataControlResponseListener.h>
40
41 #include <FBase_StringConverter.h>
42 #include <FIo_DataControlResultSetEnumerator.h>
43
44 #include "FApp_AppControlManager.h"
45 #include "FApp_SqlDataControlImpl.h"
46 #include "FApp_AppArg.h"
47 #include "FApp_DataControlManager.h"
48 #include "FAppPkg_PackageManagerImpl.h"
49
50 #define DATACONTROL_PROTOCOL_VER_2_1_0_2 // ver_2.1.0.2
51 #define DATACONTROL_PROTOCOL_VER_2_1_0_3 // ver_2.1.0.3
52
53 using namespace std;
54
55 using namespace Tizen::Base;
56 using namespace Tizen::Base::Collection;
57 using namespace Tizen::Base::Runtime;
58 using namespace Tizen::Io;
59 using namespace Tizen::App;
60 using namespace Tizen::App::Package;
61
62 namespace Tizen { namespace App
63 {
64
65 static const int MAX_REQUEST_COUNT = 128;
66 static const int REQUEST_THRESHOLD = 100;
67 static const int _MAX_ARGUMENT_SIZE = 16384; // 16KB
68 static const int _MAX_REQUEST_ARGUMENT_SIZE = 1048576; // 1MB
69 //static const char* _DATACONTROL_REQUEST_DIR = "/tmp/osp/DataControlRequest/\0";
70 static const char* _DATACONTROL_REQUEST_DIR = "/tmp/osp/data-control/request/\0";
71
72 class _SqlDataControlEventArg
73         : public IEventArg
74 {
75 public:
76                 _SqlDataControlEventArg(_DataControlRequestType requestType, RequestId reqId, String providerId, String dataId,
77                                 _DataControlResultSetEnumerator* pResultSetEnum, long long insertRowId, bool providerResult, String* pErrorMsg)
78                         : __requestType(requestType)
79                         , __reqId(reqId)
80                         , __providerId(providerId)
81                         , __dataId(dataId)
82                         , __pResultSetEnum(pResultSetEnum)
83                         , __insertRowId(insertRowId)
84                         , __providerResult(providerResult)
85                         , __pErrorMsg(pErrorMsg)
86                 {
87                 }
88                 ~_SqlDataControlEventArg(void)
89                 {
90                         delete __pResultSetEnum;
91                         delete __pErrorMsg;
92                 }
93
94                 _DataControlRequestType __requestType;
95                 RequestId __reqId;
96                 String __providerId;
97                 String __dataId;
98                 _DataControlResultSetEnumerator* __pResultSetEnum;
99                 long long __insertRowId;
100                 bool __providerResult;
101                 String* __pErrorMsg;
102 };
103
104 class _SqlDataControlEvent
105         : public Event
106 {
107 protected:
108         virtual void FireImpl(IEventListener& listener, const IEventArg& arg);
109 };
110
111 void
112 _SqlDataControlEvent::FireImpl(IEventListener& listener, const IEventArg& arg)
113 {
114         const _SqlDataControlEventArg* pArg = dynamic_cast<const _SqlDataControlEventArg*>(&arg);
115         if (pArg != null)
116         {
117                 ISqlDataControlResponseListener* pListener = dynamic_cast<ISqlDataControlResponseListener*> (&listener);
118                 if (pListener != null)
119                 {
120                         switch (pArg->__requestType)
121                         {
122                         case _DATACONTROL_REQUEST_TYPE_SQL_QUERY:
123                                 pListener->OnSqlDataControlSelectResponseReceived(pArg->__reqId, pArg->__providerId, pArg->__dataId,
124                                                 *(pArg->__pResultSetEnum), pArg->__providerResult, pArg->__pErrorMsg);
125                                 break;
126                         case _DATACONTROL_REQUEST_TYPE_SQL_INSERT:
127                                 pListener->OnSqlDataControlInsertResponseReceived(pArg->__reqId, pArg->__providerId, pArg->__dataId,
128                                                  pArg->__insertRowId, pArg->__providerResult, pArg->__pErrorMsg);
129                                 break;
130                         case _DATACONTROL_REQUEST_TYPE_SQL_UPDATE:
131                                 pListener->OnSqlDataControlUpdateResponseReceived(pArg->__reqId, pArg->__providerId, pArg->__dataId,
132                                                 pArg->__providerResult, pArg->__pErrorMsg);
133                                 break;
134                         case _DATACONTROL_REQUEST_TYPE_SQL_DELETE:
135                                 pListener->OnSqlDataControlDeleteResponseReceived(pArg->__reqId, pArg->__providerId, pArg->__dataId,
136                                                 pArg->__providerResult, pArg->__pErrorMsg);
137                                 break;
138                         default:
139                                 break;
140                         }
141                 }
142         }
143 }
144
145 // private
146 _SqlDataControlImpl::_SqlDataControlImpl(void)
147         : __access(_DATACONTROL_ACCESS_UNDEFINED)
148         , __pPreviousListener(null)
149         , __pSqlDataControlEvent(null)
150 {
151 }
152
153 _SqlDataControlImpl::~_SqlDataControlImpl(void)
154 {
155         delete __pSqlDataControlEvent;
156
157         _DataControlManager* pDcMgr = _DataControlManager::GetInstance();
158
159         IEnumerator* pEnum = __pRequestList->GetEnumeratorN();
160         while (pEnum->MoveNext() == E_SUCCESS)
161         {
162                 Integer* pReqId = dynamic_cast< Integer* >(pEnum->GetCurrent());
163                 if (pReqId != null)
164                 {
165                         pDcMgr->RemoveRequestInfo(*pReqId);
166                 }
167         }
168         delete __pRequestList;
169 }
170
171 _SqlDataControlImpl*
172 _SqlDataControlImpl::GetInstance(SqlDataControl& dc)
173 {
174         return dc.__pSqlDataControlImpl;
175 }
176
177 const _SqlDataControlImpl*
178 _SqlDataControlImpl::GetInstance(const SqlDataControl& dc)
179 {
180         return dc.__pSqlDataControlImpl;
181 }
182
183 result
184 _SqlDataControlImpl::StartSqlDataControl(int type, const IList* pDataList, int* pReq)
185 {
186         Integer* pReqId = null;
187         _DataControlRequestInfo* pReqInfo = null;
188         result r = E_SUCCESS;
189
190         int req = -1;
191         _DataControlManager* pDcMgr = _DataControlManager::GetInstance();
192
193         // Check the request count of DataControl operation
194         int count = pDcMgr->GetRequestCount();
195         SysLog(NID_APP, "Current launch request count: %d", count);
196
197         if (count > REQUEST_THRESHOLD)
198         {
199                 _AppManagerImpl* pImpl = _AppManagerImpl::GetInstance();
200
201                 // Clear the request queue if the provider is terminated
202                 if (!pImpl->IsRunning(__appId))
203                 {
204                         SysLog(NID_APP, "The request queue is cleared due to the invalid provider.");
205
206                         pDcMgr->RemoveAllRequests();
207                 }
208         }
209
210         SysTryReturnResult(NID_APP, count < MAX_REQUEST_COUNT, E_MAX_EXCEEDED, "The number of requests has exceeded the maximum limit.");
211
212         _AppArg* pArg = new (std::nothrow) _AppArg;  // XXX: pArg will be released in _AppManagerImpl::LaunchApp().
213         SysTryReturnResult(NID_APP, pArg != null, E_OUT_OF_MEMORY, "insufficient memory");
214
215         pArg->Construct(*this, static_cast <_DataControlRequestType>(type), pDataList);
216
217         _AppControlManager* pAppManagerImpl = _AppControlManager::GetInstance();
218
219         if (__pSqlDataControlEvent)
220         {
221                 // reqId is system-wide id because the bundle is system-wide.
222 #if 0
223                 _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pAppManagerImpl, pArg, SqlDataControlCallback, __pSqlDataControlEvent, -1);
224                 req = reqObj.GetRequestNumber();
225 #else
226                 _AppControlManager::_RequestGuard reqObj = _AppControlManager::_RequestGuard(*pAppManagerImpl, pArg, SqlDataControlCallback, pDcMgr, -1);
227                 req = reqObj.GetRequestNumber();
228 #endif
229                 pReqId = new (std::nothrow) Integer(req);
230                 SysTryCatch(NID_APP, pReqId != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
231                                 "[E_OUT_OF_MEMORY] The memory is insufficient");
232
233                 pReqInfo = new (std::nothrow) _DataControlRequestInfo(__pSqlDataControlEvent);
234                 SysTryCatch(NID_APP, pReqInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
235                                 "[E_OUT_OF_MEMORY] The memory is insufficient");
236                 pReqInfo->SetSqlDataControlImpl(this);
237
238                 r = pDcMgr->AddRequestInfo(pReqId, pReqInfo);
239                 SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to add request info", GetErrorMessage(r));
240
241                 r = pAppManagerImpl->LaunchApp(__appId, pArg, req);
242                 if (IsFailed(r))
243                 {
244                         SysPropagate(NID_APP, r);
245                         reqObj.Invalidate();
246                         pDcMgr->RemoveRequestInfo(*pReqId);
247                         return r;
248                 }
249
250                 __pRequestList->Add(new (std::nothrow) Integer(req));
251
252                 if (pReq)
253                 {
254                         *pReq = req;
255                 }
256         }
257         else
258         {
259                 r = pAppManagerImpl->LaunchApp(__appId, pArg);
260                 SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
261                 delete pArg;
262         }
263
264         return E_SUCCESS;
265
266 CATCH:
267         delete pArg;
268         delete pReqId;
269         delete pReqInfo;
270         return r;
271 }
272
273 result
274 _SqlDataControlImpl::Select(const String& dataId, const IList* pColumnList, const String* pWhere,
275                 const String *pOrder, RequestId& reqId, int pageNo, int countPerPage)
276 {
277         SysTryReturnResult(NID_APP, pageNo > 0, E_INVALID_ARG, "The specified pageNo parameter is less than 1");
278         SysTryReturnResult(NID_APP, countPerPage > 0, E_INVALID_ARG, "The specified countPerPage parameter is less than 1");
279         SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_READ) > 0, E_ILLEGAL_ACCESS,
280                         "The SELECT query is not permitted by DataControl provider.");
281
282         const String* pColumn = null;
283         int id = 0;
284         result r = E_SUCCESS;
285         SysLog(NID_APP, "[DC_CALLER_SEND] SqlDataControl SELECT");
286
287         ArrayList* pArgList = new ArrayList();
288         pArgList->Construct();
289
290         pArgList->Add(*(new String(dataId))); // list(0): data ID
291         long long argSize = dataId.GetLength() * sizeof(wchar_t);
292
293         if (pColumnList != null)
294         {
295                 int columnCount = pColumnList->GetCount();
296                 SysTryCatch(NID_APP, columnCount > 0, r = E_INVALID_ARG, E_INVALID_ARG,
297                                 "[E_INVALID_ARG] The specified pColumnList parameter is empty.");
298
299                 pArgList->Add(*(new String(Integer::ToString(columnCount)))); // list(1): selected column count
300                 SysLog(NID_APP, "[DC_CALLER_SEND] selected column count: %d", columnCount);
301
302                 int i = 0;
303                 while (i < columnCount) // list(2): column list
304                 {
305                         pColumn = dynamic_cast< const String* >(pColumnList->GetAt(i));
306                         SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG,
307                                         "[E_INVALID_ARG] The object is not String class.");
308
309                         pArgList->Add(*(new String(*pColumn)));
310                         argSize += pColumn->GetLength() * sizeof(wchar_t);
311                         SysLog(NID_APP, "[DC_CALLER_SEND] column[%d]: %ls", i, pColumn->GetPointer());
312                         i++;
313                 }
314         }
315         else
316         {
317                 pArgList->Add(*(new String(L"NULL")));
318         }
319
320         if (pWhere != null)     // list(3): where clause
321         {
322                 pArgList->Add(*(new String(*pWhere)));
323                 argSize += pWhere->GetLength() * sizeof(wchar_t);
324                 SysLog(NID_APP, "[DC_CALLER_SEND] pWhere: %ls", pWhere->GetPointer());
325         }
326         else
327         {
328                 pArgList->Add(*(new String(L"NULL")));
329         }
330
331         if (pOrder != null)     // list(4): order clause
332         {
333                 pArgList->Add(*(new String(*pOrder)));
334                 argSize += pOrder->GetLength() * sizeof(wchar_t);
335                 SysLog(NID_APP, "[DC_CALLER_SEND] pOrder: %ls", pOrder->GetPointer());
336         }
337         else
338         {
339                 pArgList->Add(*(new String(L"NULL")));
340         }
341         SysTryCatch(NID_APP, argSize <= _MAX_ARGUMENT_SIZE, r = E_MAX_EXCEEDED, E_MAX_EXCEEDED,
342                         "[E_MAX_EXCEEDED] The size of sending argument (%lld) exceeds the maximum limit.", argSize);
343
344         pArgList->Add(*(new String(Integer::ToString(pageNo)))); // list(5): page number
345
346         pArgList->Add(*(new String(Integer::ToString(countPerPage)))); // list(6): count per page
347
348         r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_QUERY, pArgList, &id);
349         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
350
351         reqId = static_cast< RequestId >(id);
352
353         SysLog(NID_APP, "[DC_CALLER_SEND] data: %ls, pColumnList: 0x%x, pWhere: 0x%x, pOrder: 0x%x, req: %d, pageNo: %d, countPerPage: %d",
354                         dataId.GetPointer(), pColumnList, pWhere, pOrder, reqId, pageNo, countPerPage);
355
356         // fall through
357 CATCH:
358         pArgList->RemoveAll(true);
359         delete pArgList;
360
361         return r;
362 }
363
364 result
365 _SqlDataControlImpl::SqlDataControlCallback(void* data, _AppArg* pArg, _AppArg* pResArg, service_result_e res, int prop, int option)
366 {
367         ArrayList* pResultList = null;
368         String* pResult = null;
369         String* pProviderId = null;
370         String* pDataId = null;
371         String* pErrorMessage = null;
372         String* pErrorMsg = null;
373         String* pTmpPath = null;
374         String* pInsertRowId = null;
375         _DataControlResultSetEnumerator* pResultSetEnum = null;
376         int requestType = 0;
377         int reqId = 0;
378         int launchReqId = 0;
379         int providerRes = 0;
380         bool providerResult = true;
381         //bundle* origBundle = null;
382         bundle* resBundle = null;
383         _SqlDataControlEventArg* pEventArg = null;
384         const char* p = null;
385         result r = E_SUCCESS;
386
387         SysTryReturnResult(NID_APP, pResArg != null, E_INVALID_ARG, "Empty result callback.");
388         SysLog(NID_APP, "appsvc result value: %d", res);
389
390         resBundle = pResArg->GetBundle();
391         if (resBundle)
392         {
393                 p = appsvc_get_data(resBundle, OSP_K_REQUEST_ID);
394                 SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle");
395                 reqId = atoi(p);
396                 Integer key(reqId);
397
398                 _DataControlManager* pDcMgr = static_cast< _DataControlManager* >(data);
399                 _DataControlRequestInfo* pReqInfo = pDcMgr->GetRequestInfo(key);
400                 if (pReqInfo == null)
401                 {
402                         SysLog(NID_APP, "No request info of reqId %d", reqId);
403                         return E_SUCCESS;
404                 }
405
406                 _SqlDataControlEvent* pSqlDataControlEvent = dynamic_cast< _SqlDataControlEvent* >(pReqInfo->GetEvent());
407                 SysTryCatch(NID_APP, pSqlDataControlEvent != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request info");
408
409                 pDcMgr->RemoveRequestInfo(key);
410
411                 _SqlDataControlImpl* pDcImpl = pReqInfo->GetSqlDataControlImpl();
412                 SysTryCatch(NID_APP, pDcImpl != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid request info");
413                 pDcImpl->__pRequestList->Remove(key);
414
415                 // Remove the request from the queue
416                 SysLog(NID_APP, "Remove the request, req: %d", reqId);
417
418                 if (pSqlDataControlEvent != null && typeid(pSqlDataControlEvent) == typeid(_SqlDataControlEvent*))
419                 {
420                         // result list
421                         pResultList = _AppArg::GetListN(resBundle, OSP_K_ARG);
422                         SysTryCatch(NID_APP, pResultList, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result");
423
424                         pResult = dynamic_cast <String*>(pResultList->GetAt(0)); // result list[0]
425                         SysTryCatch(NID_APP, pResult, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result");
426                         Integer::Parse(*pResult, providerRes);
427                         providerResult = static_cast< bool >(providerRes);
428
429                         pErrorMessage = dynamic_cast< String* >(pResultList->GetAt(1)); // result list[1]
430                         SysTryCatch(NID_APP, pErrorMessage, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result");
431                         pErrorMsg = new (std::nothrow) String(*pErrorMessage);
432                         SysTryCatch(NID_APP, pErrorMsg, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
433                                         "[E_OUT_OF_MEMORY] The memory is insufficient.");
434
435                         // request info
436                         //origBundle = pArg->GetBundle();
437
438                         p = appsvc_get_data(resBundle, OSP_K_DATACONTROL_REQUEST_TYPE);
439                         SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle");
440                         requestType = atoi(p);
441
442                         p = appsvc_get_data(resBundle, OSP_K_DATACONTROL_PROVIDER);
443                         SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle");
444                         pProviderId = new (std::nothrow) String(p);
445                         SysTryCatch(NID_APP, pProviderId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
446                                         "[E_OUT_OF_MEMORY] The memory is insufficient.");
447
448                         p = appsvc_get_data(resBundle, OSP_K_DATACONTROL_DATA);
449                         SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle");
450                         pDataId = new (std::nothrow) String(p);
451                         SysTryCatch(NID_APP, pDataId, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
452                                         "[E_OUT_OF_MEMORY] The memory is insufficient.");
453
454                         SysSecureLog(NID_APP, "[DC_CALLER_RECV] provider result: %ld, requestType: %d, req: %d, provider: %ls, data: %ls, errorMsg: %ls ",
455                                         providerRes, requestType, reqId, pProviderId->GetPointer(), pDataId->GetPointer(), pErrorMsg->GetPointer());
456
457                         switch (static_cast <_DataControlRequestType>(requestType))
458                         {
459                         case _DATACONTROL_REQUEST_TYPE_SQL_QUERY:
460                         {
461                                 pResultSetEnum = new (std::nothrow) _DataControlResultSetEnumerator;
462                                 SysTryCatch(NID_APP, pResultSetEnum, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY,
463                                                 "[E_OUT_OF_MEMORY] The memory is insufficient.");
464
465                                 if (providerResult == true)
466                                 {
467                                         pTmpPath = dynamic_cast< String* >(pResultList->GetAt(2)); // result list[2]
468                                         if (pTmpPath == null)
469                                         {
470                                                 SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] invalid result");
471                                                 delete pResultSetEnum;
472                                                 goto CATCH;
473                                         }
474
475                                         SysLog(NID_APP, "[DC_CALLER_RECV] tempPath: %ls", pTmpPath->GetPointer());
476                                         if (pTmpPath->Equals(L"NoResultSet", true) == false) // Result set exists
477                                         {
478                                                 pResultSetEnum->SetPath(*pTmpPath);
479                                         }
480                                 }
481
482                                 pEventArg = new (std::nothrow) _SqlDataControlEventArg(_DATACONTROL_REQUEST_TYPE_SQL_QUERY, static_cast <RequestId>(reqId),
483                                                 *pProviderId, *pDataId, pResultSetEnum, -1, providerResult, pErrorMsg);
484                                 SysTryCatch(NID_APP, pEventArg != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
485                                 pSqlDataControlEvent->Fire(*pEventArg);
486
487                                 if (pTmpPath)
488                                 {
489                                         r = File::Remove(*pTmpPath); // Remove temporary file after releasing _ResultSetEnumerator.
490                                         SysTryLog(NID_APP, !IsFailed(r), "Failed to remove temp file for result set: %ls", pTmpPath->GetPointer());
491                                 }
492
493                                 break;
494                         }
495                         case _DATACONTROL_REQUEST_TYPE_SQL_INSERT:
496                         {
497                                 long long insertRowId = -1;
498                                 if (providerResult == true)
499                                 {
500                                         pInsertRowId = dynamic_cast< String* >(pResultList->GetAt(2)); // result list[2]
501                                         SysTryCatch(NID_APP, pInsertRowId, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid result");
502
503                                         LongLong::Parse(*pInsertRowId, insertRowId);
504                                 }
505
506                                 pEventArg = new (std::nothrow) _SqlDataControlEventArg(_DATACONTROL_REQUEST_TYPE_SQL_INSERT, static_cast <RequestId>(reqId),
507                                                 *pProviderId, *pDataId, null, insertRowId, providerResult, pErrorMsg);
508                                 SysTryCatch(NID_APP, pEventArg != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
509                                 pSqlDataControlEvent->Fire(*pEventArg);
510                                 break;
511                         }
512                         case _DATACONTROL_REQUEST_TYPE_SQL_UPDATE:
513                         {
514                                 pEventArg = new (std::nothrow) _SqlDataControlEventArg(_DATACONTROL_REQUEST_TYPE_SQL_UPDATE, static_cast <RequestId>(reqId),
515                                                 *pProviderId, *pDataId, null, -1, providerResult, pErrorMsg);
516                                 SysTryCatch(NID_APP, pEventArg != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
517                                 pSqlDataControlEvent->Fire(*pEventArg);
518                                 break;
519                         }
520                         case _DATACONTROL_REQUEST_TYPE_SQL_DELETE:
521                         {
522                                 pEventArg = new (std::nothrow) _SqlDataControlEventArg(_DATACONTROL_REQUEST_TYPE_SQL_DELETE, static_cast <RequestId>(reqId),
523                                                 *pProviderId, *pDataId, null, -1, providerResult, pErrorMsg);
524                                 SysTryCatch(NID_APP, pEventArg != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
525                                 pSqlDataControlEvent->Fire(*pEventArg);
526                                 break;
527                         }
528                         default:
529                                 break;
530                         }
531
532                         pResultList->RemoveAll(true);
533                         delete pResultList;
534                         delete pProviderId;
535                 }
536         }
537
538         p = appsvc_get_data(pArg->GetBundle(), OSP_K_REQUEST_ID);
539         SysTryCatch(NID_APP, p, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] invalid bundle");
540         launchReqId = atoi(p);
541
542         return E_SUCCESS;
543
544 CATCH:
545         if (pResultList)
546         {
547                 pResultList->RemoveAll(true);
548                 delete pResultList;
549         }
550         delete pProviderId;
551
552         return r;
553 }
554
555 result
556 _SqlDataControlImpl::Insert(const String& dataId, const IMap& insertMap, RequestId& reqId)
557 {
558         SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS,
559                         "The INSERT query is not permitted by DataControl provider.");
560
561         int columnCount = 0;
562         int id = 0;
563         int i = 0;
564         int uniqueId = -1;
565         File request;
566         IMapEnumerator* pMapEnum = null;
567         _PackageManagerImpl* pPkgMgrImpl = null;
568         unique_ptr< String > pProviderAppId(null);
569         result r = E_SUCCESS;
570         SysLog(NID_APP, "[DC_CALLER_SEND] SqlDataControl INSERT");
571
572         columnCount = insertMap.GetCount();
573         SysTryReturnResult(NID_APP, columnCount > 0, E_INVALID_ARG, "The specified insertMap parameter is empty.");
574
575         ArrayList* pArgList = new (std::nothrow) ArrayList();
576         pArgList->Construct();
577
578         pArgList->Add(new (std::nothrow) String(dataId)); // list[0]: data ID
579         long long argSize = dataId.GetLength() * sizeof(wchar_t);
580
581         pArgList->Add(new (std::nothrow) String(Integer::ToString(columnCount))); // list[1]: inserted column count
582         SysLog(NID_APP, "[DC_CALLER_SEND] inserted column count: %d", columnCount);
583
584 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
585         String tmpPath(_DATACONTROL_REQUEST_DIR);
586         tmpPath.Append(App::GetInstance()->GetAppId());
587
588         _DataControlManager* pDcMgr = _DataControlManager::GetInstance();
589         SysTryCatch(NID_APP, pDcMgr, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get _DataControlManager instance.");
590         uniqueId = pDcMgr->GetUniqueId();
591
592         tmpPath.Append(uniqueId);
593         SysLog(NID_APP, "[DC_CALLER_SEND] request: %ls", tmpPath.GetPointer());
594
595         r = request.Construct(tmpPath, L"w+", true);
596         SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to create request (%ls).",
597                         GetErrorMessage(r), tmpPath.GetPointer());
598
599         pArgList->Add(new (std::nothrow) String(tmpPath)); // list[2]: path 
600 #endif
601
602         pMapEnum = const_cast< IMap* >(&insertMap)->GetMapEnumeratorN();
603         while (pMapEnum->MoveNext() == E_SUCCESS) // list: column-value pairs
604         {
605 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
606                 int length = 0;
607                 String* pColumn = null;
608                 String* pValue = null;
609                 unique_ptr< char[] > pData(null);
610
611                 pColumn = dynamic_cast< String* >(pMapEnum->GetKey());
612                 SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG,
613                                 "[E_INVALID_ARG] The object is not String class.");
614
615                 pData.reset(_StringConverter::CopyToCharArrayN(*pColumn));
616                 SysTryCatch(NID_APP, pData != null, r = GetLastResult(), GetLastResult(), "[%s] Invalid request value",
617                                 GetErrorMessage(GetLastResult()));
618
619                 length = strlen(pData.get());
620                 r = request.Write(&length, sizeof(int)); // data length
621                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
622
623                 r = request.Write(pData.get(), length); // data
624                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
625
626                 pValue = dynamic_cast< String* >(pMapEnum->GetValue());
627                 SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG,
628                                 "[E_INVALID_ARG] The object is not String class.");
629
630                 pData.reset(_StringConverter::CopyToCharArrayN(*pValue));
631                 SysTryCatch(NID_APP, pData != null, r = GetLastResult(), GetLastResult(), "[%s] Invalid request value",
632                                 GetErrorMessage(GetLastResult()));
633
634                 length = strlen(pData.get());
635                 r = request.Write(&length, sizeof(int)); // data length
636                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
637
638                 r = request.Write(pData.get(), length); // data
639                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
640
641                 argSize += pColumn->GetLength() * sizeof(wchar_t);
642                 argSize += pValue->GetLength() * sizeof(wchar_t);
643 #else
644                 String* pColumn = dynamic_cast< String* >(pMapEnum->GetKey());
645                 SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG,
646                                 "[E_INVALID_ARG] The object is not String class.");
647
648                 pArgList->Add(*(new String(*pColumn)));
649                 SysLog(NID_APP, "[DC_CALLER_SEND] pColumn[%d]: %ls", i, pColumn->GetPointer());
650
651                 String* pValue = dynamic_cast< String* >(pMapEnum->GetValue());
652                 SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG,
653                                 "[E_INVALID_ARG] The object is not String class.");
654
655                 pArgList->Add(*(new String(*pValue)));
656                 SysLog(NID_APP, "[DC_CALLER_SEND] pValue[%d]: %ls", i, pValue->GetPointer());
657
658                 argSize += pColumn->GetLength() * sizeof(wchar_t);
659                 argSize += pValue->GetLength() * sizeof(wchar_t);
660                 i++;
661 #endif
662         }
663         SysTryCatch(NID_APP, argSize <= _MAX_REQUEST_ARGUMENT_SIZE, r = E_MAX_EXCEEDED, E_MAX_EXCEEDED,
664                         "[E_MAX_EXCEEDED] The size of sending argument (%lld) exceeds the maximum limit.", argSize);
665
666 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
667         request.Flush();
668 #endif
669 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_3
670         pPkgMgrImpl = _PackageManagerImpl::GetInstance();
671         pProviderAppId.reset(pPkgMgrImpl->GetAppIdOfDataControlN(this->__providerId.GetPointer()));
672         SysTryCatch(NID_APP, pProviderAppId != null, r = E_SYSTEM, E_SYSTEM,
673                         "[E_SYSTEM] The method cannot proceed due to a severe system error.");
674         r = pDcMgr->AllowAccess(*(pProviderAppId.get()));
675         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
676 #endif
677
678         r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_INSERT, pArgList, &id);
679         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
680
681         reqId = static_cast< RequestId >(id);
682
683         SysLog(NID_APP, "[DC_CALLER_SEND] data: %ls, insertMap: 0x%x, req: %d", dataId.GetPointer(), &insertMap, reqId);
684
685         // fall through
686 CATCH:
687         pArgList->RemoveAll(true);
688         delete pArgList;
689         delete pMapEnum;
690
691         return r;
692 }
693
694 result
695 _SqlDataControlImpl::Update(const String& dataId, const IMap& updateMap, const String* pWhere, RequestId& reqId)
696 {
697         SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS,
698                         "The UPDATE query is not permitted by DataControl provider.");
699
700         int columnCount = 0;
701         int id = 0;
702         int i = 0;
703         int uniqueId = -1;
704         File request;
705         IMapEnumerator* pMapEnum = null;
706         _PackageManagerImpl* pPkgMgrImpl = null;
707         unique_ptr< String > pProviderAppId(null);
708         result r = E_SUCCESS;
709         SysLog(NID_APP, "[DC_CALLER_SEND] SqlDataControl UPDATE");
710
711         columnCount = updateMap.GetCount();
712         SysTryReturnResult(NID_APP, columnCount > 0, E_INVALID_ARG, "The specified insertMap parameter is empty.");
713
714         ArrayList* pArgList = new ArrayList();
715         pArgList->Construct();
716
717         pArgList->Add(new (std::nothrow) String(dataId)); // list[0]: data ID
718         long long argSize = dataId.GetLength() * sizeof(wchar_t);
719
720         pArgList->Add(new (std::nothrow) String(Integer::ToString(columnCount))); // list[1]: updated column count
721         SysLog(NID_APP, "[DC_CALLER_SEND] updated column count: %d", columnCount);
722
723 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
724         String tmpPath(_DATACONTROL_REQUEST_DIR);
725         tmpPath.Append(App::GetInstance()->GetAppId());
726
727         _DataControlManager* pDcMgr = _DataControlManager::GetInstance();
728         SysTryCatch(NID_APP, pDcMgr, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get _DataControlManager instance.");
729         uniqueId = pDcMgr->GetUniqueId();
730
731         tmpPath.Append(uniqueId);
732         SysLog(NID_APP, "[DC_CALLER_SEND] request: %ls", tmpPath.GetPointer());
733
734         r = request.Construct(tmpPath, L"w+", true);
735         SysTryCatch(NID_APP, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to create request (%ls).",
736                         GetErrorMessage(r), tmpPath.GetPointer());
737
738         pArgList->Add(new (std::nothrow) String(tmpPath)); // list[2]: path 
739 #endif
740
741         pMapEnum = const_cast< IMap* >(&updateMap)->GetMapEnumeratorN();
742         while (pMapEnum->MoveNext() == E_SUCCESS) // list: column-value pairs
743         {
744 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
745                 int length = 0;
746                 String* pColumn = null;
747                 String* pValue = null;
748                 unique_ptr< char[] > pData(null);
749
750                 pColumn = dynamic_cast< String* >(pMapEnum->GetKey());
751                 SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG,
752                                 "[E_INVALID_ARG] The object is not String class.");
753
754                 pData.reset(_StringConverter::CopyToCharArrayN(*pColumn));
755                 SysTryCatch(NID_APP, pData != null, r = GetLastResult(), GetLastResult(), "[%s] Invalid request value",
756                                 GetErrorMessage(GetLastResult()));
757
758                 length = strlen(pData.get());
759                 r = request.Write(&length, sizeof(int)); // data length
760                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
761
762                 r = request.Write(pData.get(), length); // data
763                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
764
765                 pValue = dynamic_cast< String* >(pMapEnum->GetValue());
766                 SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG,
767                                 "[E_INVALID_ARG] The object is not String class.");
768
769                 pData.reset(_StringConverter::CopyToCharArrayN(*pValue));
770                 SysTryCatch(NID_APP, pData != null, r = GetLastResult(), GetLastResult(), "[%s] Invalid request value",
771                                 GetErrorMessage(GetLastResult()));
772
773                 length = strlen(pData.get());
774                 r = request.Write(&length, sizeof(int)); // data length
775                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
776
777                 r = request.Write(pData.get(), length); // data
778                 SysTryCatch(NID_APP, !IsFailed(r), , E_SYSTEM, "[%s] Failed to send request.", GetErrorMessage(r));
779
780                 argSize += pColumn->GetLength() * sizeof(wchar_t);
781                 argSize += pValue->GetLength() * sizeof(wchar_t);
782 #else
783                 String* pColumn = dynamic_cast< String* >(pMapEnum->GetKey());
784                 SysTryCatch(NID_APP, pColumn != null, r = E_INVALID_ARG, E_INVALID_ARG,
785                                 "[E_INVALID_ARG] The object is not String class.");
786
787                 pArgList->Add(*(new String(*pColumn)));
788                 SysLog(NID_APP, "[DC_CALLER_SEND] pColumn[%d]: %ls", i, pColumn->GetPointer());
789
790                 String* pValue = dynamic_cast< String* >(pMapEnum->GetValue());
791                 SysTryCatch(NID_APP, pValue != null, r = E_INVALID_ARG, E_INVALID_ARG,
792                                 "[E_INVALID_ARG] The object is not String class.");
793
794                 pArgList->Add(*(new String(*pValue)));
795                 SysLog(NID_APP, "[DC_CALLER_SEND] pValue[%d]: %ls", i, pValue->GetPointer());
796
797                 argSize += pColumn->GetLength() * sizeof(wchar_t);
798                 argSize += pValue->GetLength() * sizeof(wchar_t);
799                 i++;
800 #endif
801         }
802
803 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_2
804         request.Flush();
805 #endif
806
807         if (pWhere != null)     // list: where clause
808         {
809                 pArgList->Add(new (std::nothrow) String(*pWhere));
810                 argSize += pWhere->GetLength() * sizeof(wchar_t);
811                 SysLog(NID_APP, "[DC_CALLER_SEND] pWhere: %ls", pWhere->GetPointer());
812         }
813         else
814         {
815                 pArgList->Add(new (std::nothrow) String(L"NULL"));
816         }
817         SysTryCatch(NID_APP, argSize <= _MAX_REQUEST_ARGUMENT_SIZE, r = E_MAX_EXCEEDED, E_MAX_EXCEEDED,
818                         "[E_MAX_EXCEEDED] The size of sending argument (%lld) exceeds the maximum limit.", argSize);
819
820 #ifdef DATACONTROL_PROTOCOL_VER_2_1_0_3
821         pPkgMgrImpl = _PackageManagerImpl::GetInstance();
822         pProviderAppId.reset(pPkgMgrImpl->GetAppIdOfDataControlN(this->__providerId.GetPointer()));
823         SysTryCatch(NID_APP, pProviderAppId != null, r = E_SYSTEM, E_SYSTEM,
824                         "[E_SYSTEM] The method cannot proceed due to a severe system error.");
825         r = pDcMgr->AllowAccess(*(pProviderAppId.get()));
826         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
827 #endif
828
829         r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_UPDATE, pArgList, &id);
830         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
831
832         reqId = static_cast< RequestId >(id);
833
834         SysLog(NID_APP, "[DC_CALLER_SEND] data: %ls, updateMap: 0x%x, pWhere: 0x%x, req: %d",
835                                 dataId.GetPointer(), &updateMap, pWhere, reqId);
836
837         // fall through
838 CATCH:
839         pArgList->RemoveAll(true);
840         delete pArgList;
841         delete pMapEnum;
842
843         return r;
844 }
845
846 result
847 _SqlDataControlImpl::Delete(const String& dataId, const String* pWhere, RequestId& reqId)
848 {
849         SysTryReturnResult(NID_APP, (__access & _DATACONTROL_ACCESS_WRITE) > 0, E_ILLEGAL_ACCESS,
850                         "The DELETE query is not permitted by DataControl provider.");
851
852         int id = 0;
853         result r = E_SUCCESS;
854         SysLog(NID_APP, "[DC_CALLER_SEND] SqlDataControl DELETE");
855
856         ArrayList* pArgList = new ArrayList();
857         pArgList->Construct();
858
859         pArgList->Add(*(new String(dataId))); // list(0): data ID
860         long long argSize = dataId.GetLength() * sizeof(wchar_t);
861
862         if (pWhere != null)     // list(1): where clause
863         {
864                 pArgList->Add(*(new String(*pWhere)));
865                 argSize += pWhere->GetLength() * sizeof(wchar_t);
866                 SysLog(NID_APP, "[DC_CALLER_SEND] pWhere: %ls", pWhere->GetPointer());
867         }
868         else
869         {
870                 pArgList->Add(*(new String(L"NULL")));
871         }
872         SysTryCatch(NID_APP, argSize <= _MAX_ARGUMENT_SIZE, r = E_MAX_EXCEEDED, E_MAX_EXCEEDED,
873                         "[E_MAX_EXCEEDED] The size of sending argument (%lld) exceeds the maximum limit.", argSize);
874
875         r = StartSqlDataControl(_DATACONTROL_REQUEST_TYPE_SQL_DELETE, pArgList, &id);
876         SysTryCatch(NID_APP, !IsFailed(r), , r, "[%s] Propagating to caller...", GetErrorMessage(r));
877
878         reqId = static_cast< RequestId >(id);
879
880         SysLog(NID_APP, "[DC_CALLER_SEND] data: %ls, pWhere: 0x%x, req: %d", dataId.GetPointer(), pWhere, reqId);
881
882         // fall through
883 CATCH:
884         pArgList->RemoveAll(true);
885         delete pArgList;
886
887         return r;
888 }
889
890 result
891 _SqlDataControlImpl::SetSqlDataControlResponseListener(ISqlDataControlResponseListener* pListener)
892 {
893         result r = E_SUCCESS;
894
895         if (__pPreviousListener != null)
896         {
897                 r =  __pSqlDataControlEvent->RemoveListener(*__pPreviousListener);
898                 SysTryReturnResult(NID_APP, !IsFailed(r), E_SYSTEM, "Remove listener failed.");
899                  __pPreviousListener = null;
900         }
901
902         if (pListener != null)
903         {
904                 r =  __pSqlDataControlEvent->AddListener(*pListener);
905                 if (IsFailed(r))
906                 {
907                         switch (r)
908                         {
909                         case E_OBJ_ALREADY_EXIST:
910                                 return E_SUCCESS;
911                         case E_INVALID_OPERATION:
912                                 SysLogException(NID_APP, E_SYSTEM, "[E_SYSTEM] The thread setting the listener is worker thread.");
913                                 return E_SYSTEM;
914                         default:
915                                 SysLogException(NID_APP, r, "[%s] Propagating to caller...", GetErrorMessage(r));
916                                 return r;
917                         }
918                 }
919         }
920
921         __pPreviousListener = pListener;
922
923         return E_SUCCESS;
924 }
925
926 // private
927 SqlDataControl*
928 _SqlDataControlImpl::CreateSqlDataControl(const String& appId, const String& providerId, const String& access)
929 {
930         unique_ptr<SqlDataControl> pDc(new (std::nothrow) SqlDataControl);
931         SysTryReturn(NID_APP, pDc != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient");
932
933         _SqlDataControlImpl* pDcImpl = _SqlDataControlImpl::GetInstance(*pDc);
934         pDcImpl->__appId = appId;
935         pDcImpl->__providerId = providerId;
936         unique_ptr<_SqlDataControlEvent> pSqlDataControlEvent(new (std::nothrow) _SqlDataControlEvent);
937         SysTryReturn(NID_IO, pSqlDataControlEvent != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
938
939         pDcImpl->__pRequestList = new (std::nothrow) LinkedList(SingleObjectDeleter);
940         SysTryReturn(NID_IO, pDcImpl->__pRequestList != null, null, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
941
942         pDcImpl->__pSqlDataControlEvent = pSqlDataControlEvent.release();
943
944         if (access == L"readonly")
945         {
946                 pDcImpl->__access = _DATACONTROL_ACCESS_READ;
947         }
948         else if (access == L"writeonly")
949         {
950                 pDcImpl->__access = _DATACONTROL_ACCESS_WRITE;
951         }
952         else if (access == L"readwrite")
953         {
954                 pDcImpl->__access = _DATACONTROL_ACCESS_READWRITE;
955         }
956         else
957         {
958                 pDcImpl->__access = _DATACONTROL_ACCESS_UNDEFINED;
959                 SysLog(NID_IO, "The accessibility of DataControl provider is invalid.");
960         }
961
962         return pDc.release();
963 }
964
965 }} // Tizen::App
966