[Messaging] MessageService JS implementation
authorMaciek Blim <m.blim@samsung.com>
Wed, 10 Dec 2014 15:10:36 +0000 (16:10 +0100)
committerMaciek Blim <m.blim@samsung.com>
Sat, 13 Dec 2014 12:33:58 +0000 (21:33 +0900)
[Verification] Code compile without errors

[Feature] Example implementation of
callback manager inside node js

Change-Id: I05b463d88df6adfeebe2422942ff80efc856957b
Signed-off-by: Maciek Blim <m.blim@samsung.com>
214 files changed:
messaging/messaging.gyp [deleted file]
messaging/messaging_api.js [deleted file]
messaging/messaging_extension.cc [deleted file]
messaging/messaging_extension.h [deleted file]
messaging/messaging_instance.cc [deleted file]
messaging/messaging_instance.h [deleted file]
messaging/old/BaseFilterVisitor.cpp [deleted file]
messaging/old/CMakeLists.txt [deleted file]
messaging/old/ChangeListenerContainer.cpp [deleted file]
messaging/old/ChangeListenerContainer.h [deleted file]
messaging/old/ConversationCallbackData.cpp [deleted file]
messaging/old/ConversationCallbackData.h [deleted file]
messaging/old/ConversationsChangeCallback.cpp [deleted file]
messaging/old/ConversationsChangeCallback.h [deleted file]
messaging/old/DBus/Connection.cpp [deleted file]
messaging/old/DBus/Connection.h [deleted file]
messaging/old/DBus/EmailSignalProxy.cpp [deleted file]
messaging/old/DBus/EmailSignalProxy.h [deleted file]
messaging/old/DBus/LoadAttachmentProxy.cpp [deleted file]
messaging/old/DBus/LoadAttachmentProxy.h [deleted file]
messaging/old/DBus/LoadBodyProxy.cpp [deleted file]
messaging/old/DBus/LoadBodyProxy.h [deleted file]
messaging/old/DBus/MessageProxy.cpp [deleted file]
messaging/old/DBus/MessageProxy.h [deleted file]
messaging/old/DBus/Proxy.cpp [deleted file]
messaging/old/DBus/Proxy.h [deleted file]
messaging/old/DBus/SendProxy.cpp [deleted file]
messaging/old/DBus/SendProxy.h [deleted file]
messaging/old/DBus/SyncProxy.cpp [deleted file]
messaging/old/DBus/SyncProxy.h [deleted file]
messaging/old/EmailManager.cpp [deleted file]
messaging/old/EmailManager.h [deleted file]
messaging/old/FindMsgCallbackUserData.cpp [deleted file]
messaging/old/FindMsgCallbackUserData.h [deleted file]
messaging/old/FoldersCallbackData.cpp [deleted file]
messaging/old/FoldersCallbackData.h [deleted file]
messaging/old/FoldersChangeCallback.cpp [deleted file]
messaging/old/FoldersChangeCallback.h [deleted file]
messaging/old/JSMessage.cpp [deleted file]
messaging/old/JSMessage.h [deleted file]
messaging/old/JSMessageAttachment.cpp [deleted file]
messaging/old/JSMessageAttachment.h [deleted file]
messaging/old/JSMessageBody.cpp [deleted file]
messaging/old/JSMessageBody.h [deleted file]
messaging/old/JSMessageConversation.cpp [deleted file]
messaging/old/JSMessageConversation.h [deleted file]
messaging/old/JSMessageFolder.cpp [deleted file]
messaging/old/JSMessageFolder.h [deleted file]
messaging/old/JSMessageService.cpp [deleted file]
messaging/old/JSMessageService.h [deleted file]
messaging/old/JSMessageStorage.cpp [deleted file]
messaging/old/JSMessageStorage.h [deleted file]
messaging/old/JSMessagingManager.cpp [deleted file]
messaging/old/JSMessagingManager.h [deleted file]
messaging/old/Message.cpp [deleted file]
messaging/old/Message.h [deleted file]
messaging/old/MessageAttachment.cpp [deleted file]
messaging/old/MessageAttachment.h [deleted file]
messaging/old/MessageBody.cpp [deleted file]
messaging/old/MessageBody.h [deleted file]
messaging/old/MessageCallbackUserData.cpp [deleted file]
messaging/old/MessageCallbackUserData.h [deleted file]
messaging/old/MessageConversation.cpp [deleted file]
messaging/old/MessageConversation.h [deleted file]
messaging/old/MessageEmail.cpp [deleted file]
messaging/old/MessageEmail.h [deleted file]
messaging/old/MessageFolder.cpp [deleted file]
messaging/old/MessageFolder.h [deleted file]
messaging/old/MessageMMS.cpp [deleted file]
messaging/old/MessageMMS.h [deleted file]
messaging/old/MessageSMS.cpp [deleted file]
messaging/old/MessageSMS.h [deleted file]
messaging/old/MessageService.cpp [deleted file]
messaging/old/MessageService.h [deleted file]
messaging/old/MessageServiceEmail.cpp [deleted file]
messaging/old/MessageServiceEmail.h [deleted file]
messaging/old/MessageServiceShortMsg.cpp [deleted file]
messaging/old/MessageServiceShortMsg.h [deleted file]
messaging/old/MessageStorage.cpp [deleted file]
messaging/old/MessageStorage.h [deleted file]
messaging/old/MessageStorageEmail.cpp [deleted file]
messaging/old/MessageStorageEmail.h [deleted file]
messaging/old/MessageStorageShortMsg.cpp [deleted file]
messaging/old/MessageStorageShortMsg.h [deleted file]
messaging/old/MessagesCallbackUserData.cpp [deleted file]
messaging/old/MessagesCallbackUserData.h [deleted file]
messaging/old/MessagesChangeCallback.cpp [deleted file]
messaging/old/MessagesChangeCallback.h [deleted file]
messaging/old/MessagingDatabaseManager.cpp [deleted file]
messaging/old/MessagingDatabaseManager.h [deleted file]
messaging/old/MessagingManager.cpp [deleted file]
messaging/old/MessagingManager.h [deleted file]
messaging/old/MessagingUtil.cpp [deleted file]
messaging/old/MessagingUtil.h [deleted file]
messaging/old/ShortMsgManager.cpp [deleted file]
messaging/old/ShortMsgManager.h [deleted file]
messaging/old/TestScripts/addConversationsChangeListener_01.js [deleted file]
messaging/old/TestScripts/addFoldersChangeListener_01.js [deleted file]
messaging/old/TestScripts/addMessagesChangeListener_01.js [deleted file]
messaging/old/TestScripts/allChangeListeners_01.js [deleted file]
messaging/old/TestScripts/loadMessageAttachment_01.js [deleted file]
messaging/old/TestScripts/loadMessageBody_01.js [deleted file]
messaging/old/config.xml [deleted file]
messaging/old/plugin_config.cpp [deleted file]
messaging/old/plugin_config.h [deleted file]
messaging/old/plugin_config_impl.h [deleted file]
messaging/old/plugin_initializer.cpp [deleted file]
src/messaging/messaging.gyp [new file with mode: 0644]
src/messaging/messaging_api.js [new file with mode: 0644]
src/messaging/messaging_extension.cc [new file with mode: 0644]
src/messaging/messaging_extension.h [new file with mode: 0644]
src/messaging/messaging_instance.cc [new file with mode: 0644]
src/messaging/messaging_instance.h [new file with mode: 0644]
src/messaging/old/BaseFilterVisitor.cpp [new file with mode: 0644]
src/messaging/old/CMakeLists.txt [new file with mode: 0755]
src/messaging/old/ChangeListenerContainer.cpp [new file with mode: 0644]
src/messaging/old/ChangeListenerContainer.h [new file with mode: 0755]
src/messaging/old/ConversationCallbackData.cpp [new file with mode: 0644]
src/messaging/old/ConversationCallbackData.h [new file with mode: 0644]
src/messaging/old/ConversationsChangeCallback.cpp [new file with mode: 0644]
src/messaging/old/ConversationsChangeCallback.h [new file with mode: 0644]
src/messaging/old/DBus/Connection.cpp [new file with mode: 0644]
src/messaging/old/DBus/Connection.h [new file with mode: 0644]
src/messaging/old/DBus/EmailSignalProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/EmailSignalProxy.h [new file with mode: 0644]
src/messaging/old/DBus/LoadAttachmentProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/LoadAttachmentProxy.h [new file with mode: 0644]
src/messaging/old/DBus/LoadBodyProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/LoadBodyProxy.h [new file with mode: 0644]
src/messaging/old/DBus/MessageProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/MessageProxy.h [new file with mode: 0644]
src/messaging/old/DBus/Proxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/Proxy.h [new file with mode: 0644]
src/messaging/old/DBus/SendProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/SendProxy.h [new file with mode: 0644]
src/messaging/old/DBus/SyncProxy.cpp [new file with mode: 0644]
src/messaging/old/DBus/SyncProxy.h [new file with mode: 0644]
src/messaging/old/EmailManager.cpp [new file with mode: 0644]
src/messaging/old/EmailManager.h [new file with mode: 0644]
src/messaging/old/FindMsgCallbackUserData.cpp [new file with mode: 0644]
src/messaging/old/FindMsgCallbackUserData.h [new file with mode: 0644]
src/messaging/old/FoldersCallbackData.cpp [new file with mode: 0644]
src/messaging/old/FoldersCallbackData.h [new file with mode: 0644]
src/messaging/old/FoldersChangeCallback.cpp [new file with mode: 0644]
src/messaging/old/FoldersChangeCallback.h [new file with mode: 0644]
src/messaging/old/JSMessage.cpp [new file with mode: 0644]
src/messaging/old/JSMessage.h [new file with mode: 0644]
src/messaging/old/JSMessageAttachment.cpp [new file with mode: 0644]
src/messaging/old/JSMessageAttachment.h [new file with mode: 0755]
src/messaging/old/JSMessageBody.cpp [new file with mode: 0644]
src/messaging/old/JSMessageBody.h [new file with mode: 0755]
src/messaging/old/JSMessageConversation.cpp [new file with mode: 0644]
src/messaging/old/JSMessageConversation.h [new file with mode: 0755]
src/messaging/old/JSMessageFolder.cpp [new file with mode: 0644]
src/messaging/old/JSMessageFolder.h [new file with mode: 0755]
src/messaging/old/JSMessageService.cpp [new file with mode: 0644]
src/messaging/old/JSMessageService.h [new file with mode: 0755]
src/messaging/old/JSMessageStorage.cpp [new file with mode: 0644]
src/messaging/old/JSMessageStorage.h [new file with mode: 0755]
src/messaging/old/JSMessagingManager.cpp [new file with mode: 0755]
src/messaging/old/JSMessagingManager.h [new file with mode: 0755]
src/messaging/old/Message.cpp [new file with mode: 0644]
src/messaging/old/Message.h [new file with mode: 0644]
src/messaging/old/MessageAttachment.cpp [new file with mode: 0755]
src/messaging/old/MessageAttachment.h [new file with mode: 0755]
src/messaging/old/MessageBody.cpp [new file with mode: 0644]
src/messaging/old/MessageBody.h [new file with mode: 0644]
src/messaging/old/MessageCallbackUserData.cpp [new file with mode: 0644]
src/messaging/old/MessageCallbackUserData.h [new file with mode: 0644]
src/messaging/old/MessageConversation.cpp [new file with mode: 0644]
src/messaging/old/MessageConversation.h [new file with mode: 0644]
src/messaging/old/MessageEmail.cpp [new file with mode: 0644]
src/messaging/old/MessageEmail.h [new file with mode: 0644]
src/messaging/old/MessageFolder.cpp [new file with mode: 0644]
src/messaging/old/MessageFolder.h [new file with mode: 0644]
src/messaging/old/MessageMMS.cpp [new file with mode: 0644]
src/messaging/old/MessageMMS.h [new file with mode: 0644]
src/messaging/old/MessageSMS.cpp [new file with mode: 0644]
src/messaging/old/MessageSMS.h [new file with mode: 0644]
src/messaging/old/MessageService.cpp [new file with mode: 0644]
src/messaging/old/MessageService.h [new file with mode: 0755]
src/messaging/old/MessageServiceEmail.cpp [new file with mode: 0644]
src/messaging/old/MessageServiceEmail.h [new file with mode: 0755]
src/messaging/old/MessageServiceShortMsg.cpp [new file with mode: 0755]
src/messaging/old/MessageServiceShortMsg.h [new file with mode: 0755]
src/messaging/old/MessageStorage.cpp [new file with mode: 0644]
src/messaging/old/MessageStorage.h [new file with mode: 0644]
src/messaging/old/MessageStorageEmail.cpp [new file with mode: 0644]
src/messaging/old/MessageStorageEmail.h [new file with mode: 0644]
src/messaging/old/MessageStorageShortMsg.cpp [new file with mode: 0755]
src/messaging/old/MessageStorageShortMsg.h [new file with mode: 0644]
src/messaging/old/MessagesCallbackUserData.cpp [new file with mode: 0644]
src/messaging/old/MessagesCallbackUserData.h [new file with mode: 0644]
src/messaging/old/MessagesChangeCallback.cpp [new file with mode: 0644]
src/messaging/old/MessagesChangeCallback.h [new file with mode: 0644]
src/messaging/old/MessagingDatabaseManager.cpp [new file with mode: 0755]
src/messaging/old/MessagingDatabaseManager.h [new file with mode: 0755]
src/messaging/old/MessagingManager.cpp [new file with mode: 0755]
src/messaging/old/MessagingManager.h [new file with mode: 0755]
src/messaging/old/MessagingUtil.cpp [new file with mode: 0644]
src/messaging/old/MessagingUtil.h [new file with mode: 0644]
src/messaging/old/ShortMsgManager.cpp [new file with mode: 0644]
src/messaging/old/ShortMsgManager.h [new file with mode: 0755]
src/messaging/old/TestScripts/addConversationsChangeListener_01.js [new file with mode: 0644]
src/messaging/old/TestScripts/addFoldersChangeListener_01.js [new file with mode: 0644]
src/messaging/old/TestScripts/addMessagesChangeListener_01.js [new file with mode: 0644]
src/messaging/old/TestScripts/allChangeListeners_01.js [new file with mode: 0644]
src/messaging/old/TestScripts/loadMessageAttachment_01.js [new file with mode: 0644]
src/messaging/old/TestScripts/loadMessageBody_01.js [new file with mode: 0644]
src/messaging/old/config.xml [new file with mode: 0755]
src/messaging/old/plugin_config.cpp [new file with mode: 0755]
src/messaging/old/plugin_config.h [new file with mode: 0755]
src/messaging/old/plugin_config_impl.h [new file with mode: 0755]
src/messaging/old/plugin_initializer.cpp [new file with mode: 0644]

diff --git a/messaging/messaging.gyp b/messaging/messaging.gyp
deleted file mode 100644 (file)
index bb817aa..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-
-{
-  'includes':[
-    '../common/common.gypi',
-  ],
-  'targets': [
-    {
-      'target_name': 'tizen_messaging',
-      'type': 'loadable_module',
-      'sources': [
-        'messaging_api.js',
-        'messaging_instance.cc',
-        'messaging_instance.h',
-        'messaging_extension.cc',
-        'messaging_extension.h'
-      ],
-      'includes': [
-        '../common/pkg-config.gypi',
-      ],
-      'conditions': [
-        ['tizen == 1', {
-          'variables': {
-            'packages': [
-            ]
-          },
-        }],
-      ],
-    },
-  ],
-}
diff --git a/messaging/messaging_api.js b/messaging/messaging_api.js
deleted file mode 100644 (file)
index a6213d6..0000000
+++ /dev/null
@@ -1 +0,0 @@
-exports = {};
diff --git a/messaging/messaging_extension.cc b/messaging/messaging_extension.cc
deleted file mode 100644 (file)
index 3b42c82..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "messaging_extension.h"
-
-#include "messaging_instance.h"
-
-// This will be generated from time_api.js.
-extern const char kSource_messaging_api[];
-
-common::Extension* CreateExtension() {
-  return new MessagingExtension;
-}
-
-MessagingExtension::MessagingExtension() {
-  SetExtensionName("tizen.messaging");
-  SetJavaScriptAPI(kSource_messaging_api);
-}
-
-MessagingExtension::~MessagingExtension() {}
-
-common::Instance* MessagingExtension::CreateInstance() {
-  return new extension::messaging::MessagingInstance;
-}
diff --git a/messaging/messaging_extension.h b/messaging/messaging_extension.h
deleted file mode 100644 (file)
index ebf1691..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef MESSAGING_MESSAGING_EXTENSION_H_
-#define MESSAGING_MESSAGING_EXTENSION_H_
-
-#include "common/extension.h"
-
-class MessagingExtension : public common::Extension {
- public:
-  MessagingExtension();
-  virtual ~MessagingExtension();
-
- private:
-  virtual common::Instance* CreateInstance();
-};
-
-#endif // MESSAGING_MESSAGING_EXTENSION_H_
-
diff --git a/messaging/messaging_instance.cc b/messaging/messaging_instance.cc
deleted file mode 100644 (file)
index 275f5e9..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-
-// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "messaging_instance.h"
-
-namespace extension {
-namespace messaging {
-
-MessagingInstance::MessagingInstance() {}
-
-MessagingInstance::~MessagingInstance() {}
-
-} // namespace messaging
-} // namespace extension
-
diff --git a/messaging/messaging_instance.h b/messaging/messaging_instance.h
deleted file mode 100644 (file)
index 0b41021..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef MESSAGING_MESSAGING_INSTANCE_H_
-#define MESSAGING_MESSAGING_INSTANCE_H_
-
-#include "common/extension.h"
-
-namespace extension {
-namespace messaging {
-
-class MessagingInstance : public common::ParsedInstance {
-    public:
-        MessagingInstance();
-        virtual ~MessagingInstance();
-};
-
-} // namespace messaging
-} // namespace extension
-
-#endif // MESSAGING_MESSAGING_INSTANCE_H_
diff --git a/messaging/old/BaseFilterVisitor.cpp b/messaging/old/BaseFilterVisitor.cpp
deleted file mode 100644 (file)
index 47ab777..0000000
+++ /dev/null
@@ -1,236 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        BaseFilterVisitor.cpp
- */
-
-#include "BaseFilterVisitor.h"
-#include <Logger.h>
-#include <cstring>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-inline std::string convertToLowerCase(const std::string& input_string)
-{
-    std::string outputString=input_string;
-    outputString.reserve(input_string.length());
-    std::transform(outputString.begin(), outputString.end(), outputString.begin(),
-            ::tolower);
-    return outputString;
-}
-
-BaseFilterVisitor::BaseFilterVisitor()
-{
-}
-
-BaseFilterVisitor::~BaseFilterVisitor()
-{
-}
-
-void BaseFilterVisitor::visitPreComposite(Tizen::FilterType& type, int depth)
-{
-    LOGD("Entered");
-    m_operand_list.push_back(FCO_START);
-}
-
-void BaseFilterVisitor::visitInComposite(Tizen::FilterType& type, int depth)
-{
-    LOGD("Entered");
-    if(Tizen::UNION_FILTER == type) {
-        m_operand_list.push_back(FCO_OR);
-        LOGD("operand OR");
-    }else if(Tizen::INTERSECTION_FILTER == type) {
-        LOGD("operand AND");
-        m_operand_list.push_back(FCO_AND);
-    } else {
-        LOGE("Invalid filter type:%d", type);
-    }
-}
-
-void BaseFilterVisitor::visitPostComposite(Tizen::FilterType& type, int depth)
-{
-    LOGD("Entered");
-    LOGD("Start: numResults:%d numOperands:%d", m_result_list.size(),
-            m_operand_list.size());
-
-    while(m_operand_list.back() != FCO_START) {
-
-        const bool left =  m_result_list.back();
-        m_result_list.pop_back();
-        const bool right =  m_result_list.back();
-        m_result_list.pop_back();
-        const FilterCompositeOperand& operand = m_operand_list.back();
-        m_operand_list.pop_back();
-
-        bool result = false;
-        if(FCO_AND == operand) {
-            result = left && right;
-        } else if(FCO_OR == operand) {
-            result = left || right;
-        }
-        m_result_list.push_back(result);
-    }
-
-    m_operand_list.pop_back(); //remove FCO_START
-    LOGD("End: numResults:%d numOperands:%d", m_result_list.size(),
-            m_operand_list.size());
-}
-
-void BaseFilterVisitor::testStringMatch(const std::string& key,
-        const std::string& value,
-        Tizen::MatchFlag flag)
-{
-    m_result_list.push_back(matchString(key, value, flag));
-}
-
-void BaseFilterVisitor::testAnyStringMatch(const std::string& key,
-        const std::vector<std::string>& values,
-        Tizen::MatchFlag flag)
-{
-    m_result_list.push_back(matchStringVector(key, values, flag));
-}
-
-void BaseFilterVisitor::testTimeStampIsInRange(const time_t& timeStamp,
-            Tizen::AnyPtr& initialValue, Tizen::AnyPtr& endValue)
-{
-    m_result_list.push_back(matchTimeStampRange(timeStamp, initialValue, endValue));
-}
-
-bool BaseFilterVisitor::matchString(const std::string& key,
-        const std::string& value,
-        Tizen::MatchFlag flag)
-{
-    bool res = false;
-
-    switch(flag)
-    {
-        case Tizen::MATCH_ENDSWITH: {
-            if (key.empty()) return false;
-            if (key.size() > value.size()) return false;
-            std::string lvalue = convertToLowerCase(value);
-            std::string lkey = convertToLowerCase(key);
-            res = lvalue.substr(lvalue.size() - lkey.size(), lkey.size()) == lkey;
-        } break;
-
-        case Tizen::MATCH_EXACTLY: {
-            res = key == value;
-        } break;
-
-        case Tizen::MATCH_STARTSWITH: {
-            if (key.empty()) return false;
-            if (key.size() > value.size()) return false;
-            std::string lvalue = convertToLowerCase(value);
-            std::string lkey = convertToLowerCase(key);
-            res = lvalue.substr(0, lkey.size()) == lkey;
-        } break;
-
-        case Tizen::MATCH_CONTAINS: {
-            if (key.empty()) return false;
-            if (key.size() > value.size()) return false;
-            std::string lvalue = convertToLowerCase(value);
-            std::string lkey = convertToLowerCase(key);
-            res = lvalue.find(lkey) != std::string::npos;
-        } break;
-
-        default: {
-            LOGE("Unknown match flag");
-            res =  false;
-        } break;
-    }
-
-    LOGD("key:%s value:%s matchFlag:%d RESULT:%d", key.c_str(), value.c_str(), flag, res);
-    return res;
-}
-
-bool BaseFilterVisitor::matchStringVector(const std::string& key,
-        const std::vector<std::string>& values,
-        Tizen::MatchFlag flag)
-{
-    for(auto it = values.begin(); it != values.end(); ++it) {
-        if(matchString(key,*it,flag)) {
-            return true;
-        }
-    }
-    return false;
-}
-
-bool BaseFilterVisitor:: matchTimeStampRange(const time_t& timeStamp,
-        Tizen::AnyPtr& initialValue, Tizen::AnyPtr& endValue)
-{
-    time_t from_time;
-    time_t to_time;
-
-    if (initialValue && !initialValue->isNullOrUndefined() &&
-            initialValue->isType(DeviceAPI::Tizen::PrimitiveType_Time)) {
-        struct tm ftime = *initialValue->getDateTm();
-        from_time = mktime(&ftime);
-    } else {
-        LOGE("initialValue is not Time!");
-        throw Common::InvalidValuesException("initialValue is not Time!");
-    }
-
-    if (endValue && !endValue->isNullOrUndefined() &&
-            endValue->isType(DeviceAPI::Tizen::PrimitiveType_Time) ) {
-        struct tm ttime = *endValue->getDateTm();
-        to_time = mktime(&ttime);
-    } else {
-        LOGE("endValue is not Time!");
-        throw Common::InvalidValuesException("endValue is not Time!");
-    }
-
-    bool isInRange = isBetweenTimeRange(timeStamp, from_time, to_time);
-
-    LOGD("%d is%s in time range <%d, %d>", timeStamp, (isInRange ? "" : " NOT"),
-            from_time, to_time);
-
-    return isInRange;
-}
-
-bool BaseFilterVisitor::isMatched()
-{
-    if(m_result_list.empty()) {
-        LOGW("m_result_list is empty!");
-        return false;
-    }
-    return m_result_list.back();
-}
-
-std::string BaseFilterVisitor::formatResultListChangeLog(const size_t old_res_count)
-{
-    const size_t new_res_count = m_result_list.size();
-    const int delta = new_res_count - old_res_count;
-    std::ostringstream oss;
-
-    if(delta > 0) {
-        oss << "m_result_list added: "<< delta << " {" << std::endl;
-        std::vector<bool>::reverse_iterator rit = m_result_list.rbegin();
-        for(size_t i = 0; i < delta; ++i, ++rit) {
-            const bool result = *rit;
-            oss << "    [LAST -" << (delta - (i+1)) <<"] added: "<< result;
-        }
-        oss << "}" << std::endl;
-    } else if(delta < 0) {
-        oss <<"m_result_list removed: "<< delta;
-    }
-
-    return oss.str();
-}
-
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/CMakeLists.txt b/messaging/old/CMakeLists.txt
deleted file mode 100755 (executable)
index e9c8ec3..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-SET(TARGET_NAME ${messaging_target})
-SET(DESTINATION_NAME ${messaging_dest})
-SET(TARGET_IMPL_NAME ${messaging_impl})
-
-PKG_CHECK_MODULES(platform_pkgs_messaging REQUIRED msg-service email-service
-                  dbus-1 capi-system-info dbus-glib-1 tapi)
-
-ADD_DEFINITIONS("-fvisibility=hidden")
-
-SET(INCLUDE_DIRS
-    ${filesystem_include}
-    ${messaging_include}
-    ${tizen_include}
-    ${platform_pkgs_messaging_INCLUDE_DIRS}
-)
-
-INCLUDE_DIRECTORIES(${INCLUDE_COMMON} ${INCLUDE_DIRS})
-MESSAGE(STATUS "${TARGET_NAME} module includes: INCLUDE_COMMON ${INCLUDE_DIRS}")
-
-SET(CMAKE_INSTALL_RPATH
-    ${CMAKE_INSTALL_RPATH}
-    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${filesystem_dest}
-    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest}
-    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}
-)
-
-SET(SRCS_IMPL
-    ChangeListenerContainer.cpp
-    JSMessagingManager.cpp
-    MessagingManager.cpp
-    JSMessage.cpp
-    JSMessageAttachment.cpp
-    JSMessageBody.cpp
-    JSMessageConversation.cpp
-    JSMessageFolder.cpp
-    JSMessageService.cpp
-    MessageService.cpp
-    MessageServiceShortMsg.cpp
-    MessageServiceEmail.cpp
-    ShortMsgManager.cpp
-    EmailManager.cpp
-    MessageCallbackUserData.cpp
-    MessagesCallbackUserData.cpp
-    ConversationCallbackData.cpp
-    FoldersCallbackData.cpp
-    JSMessageStorage.cpp
-    MessageStorage.cpp
-    MessageStorageEmail.cpp
-    MessageStorageShortMsg.cpp
-    MessagingUtil.cpp
-    JSMessageAttachment.cpp
-    MessageAttachment.cpp
-    Message.cpp
-    MessageEmail.cpp
-    MessageMMS.cpp
-    MessageSMS.cpp
-    MessageConversation.cpp
-    MessageBody.cpp
-    MessageFolder.cpp
-    JSMessageFolder.cpp
-    MessagesChangeCallback.cpp
-    ConversationsChangeCallback.cpp
-    FoldersChangeCallback.cpp
-    FindMsgCallbackUserData.cpp
-    DBus/Connection.cpp
-    DBus/Proxy.cpp
-    DBus/SyncProxy.cpp
-    DBus/LoadBodyProxy.cpp
-    DBus/LoadAttachmentProxy.cpp
-    DBus/EmailSignalProxy.cpp
-    DBus/MessageProxy.cpp
-    DBus/SendProxy.cpp
-    MessagingDatabaseManager.cpp
-)
-
-ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL})
-
-SET(LINK_LIBS
-    ${LIBS_WIDGETDB}
-    ${filesystem_config}
-    ${filesystem_impl}
-    ${tizen_impl}
-    ${platform_pkgs_messaging_LIBRARIES}
-)
-
-TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} ${LIBS_COMMON} ${LINK_LIBS})
-MESSAGE(STATUS "${TARGET_NAME} module links: LIBS_COMMON ${LINK_LIBS}")
-
-SET(SRCS
-    plugin_config.cpp
-    plugin_initializer.cpp
-)
-
-ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS})
-
-TARGET_LINK_LIBRARIES(${TARGET_NAME}
-    ${TARGET_IMPL_NAME}
-    "-Wl,--no-as-needed" ${filesystem_config}
-)
-
-INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME})
-INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME})
-INSTALL(
-    DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/messaging
-    FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE
-)
diff --git a/messaging/old/ChangeListenerContainer.cpp b/messaging/old/ChangeListenerContainer.cpp
deleted file mode 100644 (file)
index ef32e51..0000000
+++ /dev/null
@@ -1,456 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "ChangeListenerContainer.h"
-
-#include <Logger.h>
-#include "EmailManager.h"
-#include "ShortMsgManager.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-ChangeListenerContainer& ChangeListenerContainer::getInstance()
-{
-    EmailManager::getInstance(); //make sure that callbacks are registered in email-service
-    ShortMsgManager::getInstance(); //make sure that callbacks are registered in msg-service
-    static ChangeListenerContainer clc;
-    return clc;
-}
-
-ChangeListenerContainer::ChangeListenerContainer():
-        m_current_id(0)
-{
-    LOGD("Entered");
-    // call getNextId() function to properly initialize static mutex inside
-    getNextId();
-}
-
-// --- Listeners registration functions ---
-long ChangeListenerContainer::addMessageChangeListener(
-        std::shared_ptr<MessagesChangeCallback> callback)
-{
-    LOGD("Entered");
-    // Check type of service for which listener should be registered
-    // and lock appropriate mutex
-    MessageType mtype = callback->getServiceType();
-    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
-    {
-        std::lock_guard<std::mutex> lock(m_short_lock);
-        int new_id = getNextId();
-        m_short_message_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
-        return new_id;
-    }
-    else if (MessageType(EMAIL) == mtype) {
-        std::lock_guard<std::mutex> lock(m_email_lock);
-        int new_id = getNextId();
-        m_email_message_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for Email, watchId: %d", new_id);
-        return new_id;
-    }
-    LOGE("Listener with invalid MessageService type - failed to register");
-    return -1;
-}
-
-long ChangeListenerContainer::addConversationChangeListener(
-        std::shared_ptr<ConversationsChangeCallback> callback)
-{
-    LOGD("Entered");
-    // Check type of service for which listener should be registered
-    // and lock appropriate mutex
-    MessageType mtype = callback->getServiceType();
-    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
-    {
-        std::lock_guard<std::mutex> lock(m_short_lock);
-        int new_id = getNextId();
-        m_short_conversation_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
-        return new_id;
-    }
-    else if (MessageType(EMAIL) == mtype) {
-        std::lock_guard<std::mutex> lock(m_email_lock);
-        int new_id = getNextId();
-        m_email_conversation_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for Email, watchId: %d", new_id);
-        return new_id;
-    }
-    LOGE("Listener with invalid MessageService type - failed to register");
-    return -1;
-}
-
-long ChangeListenerContainer::addFolderChangeListener(
-        std::shared_ptr<FoldersChangeCallback> callback)
-{
-    LOGD("Entered");
-    // Check type of service for which listener should be registered
-    // and lock appropriate mutex
-    MessageType mtype = callback->getServiceType();
-    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
-    {
-        std::lock_guard<std::mutex> lock(m_short_lock);
-        int new_id = getNextId();
-        m_short_folder_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
-        return new_id;
-    }
-    else if (MessageType(EMAIL) == mtype) {
-        std::lock_guard<std::mutex> lock(m_email_lock);
-        int new_id = getNextId();
-        m_email_folder_callbacks.insert(std::make_pair(new_id, callback));
-        LOGD("Added callback for Email, watchId: %d", new_id);
-        return new_id;
-    }
-    LOGE("Listener with invalid MessageService type - failed to register");
-    return -1;
-}
-
-// --- listeners removal ---
-void ChangeListenerContainer::removeChangeListener(JSContextRef context, long id)
-{
-    LOGD("Entered");
-    // Lock both types of collections - id does not indicate service type
-    // TODO: consider additional map<listener_id, service_type> or
-    //       map<lister_id, map<>&> to provide faster and less complicated removal
-    std::lock_guard<std::mutex> shortlock(m_short_lock);
-    std::lock_guard<std::mutex> maillock(m_email_lock);
-    LOGD("Locks done");
-    if(id<0 || id > m_current_id) {
-        LOGE("Invalid id %d given.", id);
-        return;
-    }
-    if (removeCallbackIfExists<MessagesChangeCallback>(
-            context, m_short_message_callbacks,id)) {
-        LOGD("ShortMessage message listener with id: %d removed", id);
-    }
-    else if (removeCallbackIfExists<ConversationsChangeCallback>(
-            context, m_short_conversation_callbacks, id)) {
-        LOGD("ShortMessage conversation listener with id: %d removed", id);
-    }
-    else if (removeCallbackIfExists<FoldersChangeCallback>(
-            context, m_short_folder_callbacks, id)) {
-        LOGD("ShortMessage folder listener with id: %d removed", id);
-    }
-    else if (removeCallbackIfExists<MessagesChangeCallback>(
-            context, m_email_message_callbacks, id)) {
-        LOGD("Email message listener with id: %d removed", id);
-    }
-    else if (removeCallbackIfExists<ConversationsChangeCallback>(
-            context, m_email_conversation_callbacks, id)) {
-        LOGD("Email conversation listener with id: %d removed", id);
-    }
-    else if (removeCallbackIfExists<FoldersChangeCallback>(
-            context, m_email_folder_callbacks,id)) {
-        LOGD("Email folder listener with id: %d removed", id);
-    }
-    else {
-        LOGW("WatchId %d not found", id);
-    }
-}
-
-// --- Callback invoking functions ---
-// -- for message --
-void ChangeListenerContainer::callMessageAdded(EventMessages* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling messageadded for ShortMessage");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_message_callbacks;
-        }
-        callAdded<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling messageadded for Email");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_message_callbacks;
-        }
-        callAdded<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-void ChangeListenerContainer::callMessageUpdated(EventMessages* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling messageupdated for ShortMessage");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_message_callbacks;
-        }
-        callUpdated<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling messageupdated for Email");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_message_callbacks;
-        }
-        callUpdated<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-void ChangeListenerContainer::callMessageRemoved(EventMessages* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling messageremoved for ShortMessage");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_message_callbacks;
-        }
-        callRemoved<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling messageremoved for Email");
-        MCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_message_callbacks;
-        }
-        callRemoved<MessagesChangeCallback, EventMessages>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-// -- for conversation --
-void ChangeListenerContainer::callConversationAdded(EventConversations* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling converationadded for ShortMessage");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_conversation_callbacks;
-        }
-        callAdded<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling conversationadded for Email");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_conversation_callbacks;
-        }
-        callAdded<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-void ChangeListenerContainer::callConversationUpdated(EventConversations* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling conversationupdated for ShortConversation");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_conversation_callbacks;
-        }
-        callUpdated<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling conversationupdated for Email");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_conversation_callbacks;
-        }
-        callUpdated<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-void ChangeListenerContainer::callConversationRemoved(EventConversations* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling conversationremoved for ShortConversation");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            LOGD("m_short_conversation_callbacks.size() = %d",
-                    m_short_conversation_callbacks.size());
-
-            callbacksCopy = m_short_conversation_callbacks;
-        }
-        callRemoved<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling conversationremoved for Email");
-        CCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            LOGD("m_email_conversation_callbacks.size() = %d",
-                m_email_conversation_callbacks.size());
-
-            callbacksCopy = m_email_conversation_callbacks;
-        }
-        callRemoved<ConversationsChangeCallback, EventConversations>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-// -- for folder --
-void ChangeListenerContainer::callFolderAdded(EventFolders* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling folderadded for ShortMessage");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_folder_callbacks;
-        }
-        callAdded<FoldersChangeCallback, EventFolders>(
-                m_short_folder_callbacks, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling folderadded for Email");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_folder_callbacks;
-        }
-        callAdded<FoldersChangeCallback, EventFolders>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-
-void ChangeListenerContainer::callFolderUpdated(EventFolders* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling folderupdated for ShortFolder");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_folder_callbacks;
-        }
-        callUpdated<FoldersChangeCallback, EventFolders>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling folderupdated for Email");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_folder_callbacks;
-        }
-        callUpdated<FoldersChangeCallback, EventFolders>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-void ChangeListenerContainer::callFolderRemoved(EventFolders* event)
-{
-    LOGD("Entered");
-
-    if(MessageType(SMS) == event->service_type ||
-            MessageType(MMS) == event->service_type) {
-        LOGD("Calling folderremoved for ShortFolder");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> shortlock(m_short_lock);
-            callbacksCopy = m_short_folder_callbacks;
-        }
-        callRemoved<FoldersChangeCallback, EventFolders>(
-                callbacksCopy, event);
-    }
-    else if(MessageType(EMAIL) == event->service_type) {
-        LOGD("Calling folderremoved for Email");
-        FCLmap callbacksCopy;
-        {
-            std::lock_guard<std::mutex> maillock(m_email_lock);
-            callbacksCopy = m_email_folder_callbacks;
-        }
-        callRemoved<FoldersChangeCallback, EventFolders>(
-                callbacksCopy, event);
-    }
-    else {
-        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
-    }
-}
-
-int ChangeListenerContainer::getNextId() {
-    // mutex is created only on first call (first call added to constructor
-    // to initialize mutex correctly
-    static std::mutex id_mutex;
-    std::lock_guard<std::mutex> idlock(id_mutex);
-
-    return m_current_id++;
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/ChangeListenerContainer.h b/messaging/old/ChangeListenerContainer.h
deleted file mode 100755 (executable)
index 3fd7831..0000000
+++ /dev/null
@@ -1,251 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_CHANGE_LISTENER_CONTAINER_H__
-#define __TIZEN_CHANGE_LISTENER_CONTAINER_H__
-
-#include <memory>
-#include <mutex>
-#include <vector>
-#include <map>
-#include <Logger.h>
-#include <GlobalContextManager.h>
-
-#include "Message.h"
-#include "MessageConversation.h"
-#include "MessageFolder.h"
-#include "MessagingUtil.h"
-#include "MessagesChangeCallback.h"
-#include "ConversationsChangeCallback.h"
-#include "FoldersChangeCallback.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-//! Data related to MessageChange event passed to add/update/remove callbacks
-struct EventMessages {
-    int service_id;
-    MessageType service_type;
-    MessagePtrVector items;
-    ConversationPtrVector removed_conversations;
-    // TODO: Filtering support
-};
-
-//! Data related to ConversationChange event passed to add/update/remove callbacks
-struct EventConversations {
-    int service_id;
-    MessageType service_type;
-    ConversationPtrVector items;
-    // TODO: Filtering support
-};
-
-//! Data related to FolderChange event passed to add/update/remove callbacks
-struct EventFolders {
-    int service_id;
-    MessageType service_type;
-    FolderPtrVector items;
-    // TODO: Filtering support
-};
-
-template <class T > struct CallbackDataHolder {
-    std::shared_ptr<T> ptr;
-    int operation_type;
-};
-
-//! Map that stores MessageChangeListeners
-typedef std::map<long, std::shared_ptr<MessagesChangeCallback>> MCLmap;
-//! Map that stores ConversationsChangeListeners
-typedef std::map<long, std::shared_ptr<ConversationsChangeCallback>> CCLmap;
-//! Map that stores FoldersChangeListeners
-typedef std::map<long, std::shared_ptr<FoldersChangeCallback>> FCLmap;
-
-
-/**
- * Singleton class for managing (storing and calling) ChangeListeners for
- * short message (SMS/MMS) service and email service.
- *
- * Two mutexes used to lock separately addition and searching of Short and
- * Email message related listeners. Listeneres removal functions locks access
- * to both types of listeners (havind listener id only it is not possible
- * to determine message (service) type.
- */
-class ChangeListenerContainer {
-    public:
-        static ChangeListenerContainer& getInstance();
-
-
-        // Interface for listener's manipulation (registration and removal).
-        long addMessageChangeListener(std::shared_ptr<MessagesChangeCallback> callback);
-        long addConversationChangeListener(std::shared_ptr<ConversationsChangeCallback> callback);
-        long addFolderChangeListener(std::shared_ptr<FoldersChangeCallback> callback);
-        void removeChangeListener(JSContextRef context, long id);
-
-        // Methods used to invoke registered listeners
-        void callMessageAdded(EventMessages* event);
-        void callMessageUpdated(EventMessages* event);
-        void callMessageRemoved(EventMessages* event);
-        void callConversationAdded(EventConversations* event);
-        void callConversationUpdated(EventConversations* event);
-        void callConversationRemoved(EventConversations* event);
-        void callFolderAdded(EventFolders* event);
-        void callFolderUpdated(EventFolders* event);
-        void callFolderRemoved(EventFolders* event);
-
-    private:
-        //! Highest used id (in most cases id of last registered listener)
-        long m_current_id;
-        //! Mutex for preventing race conditions on SMS/MMS callbacks collection
-        std::mutex m_short_lock;
-        //! Mutex for preventing race conditions on email callbacks collection
-        std::mutex m_email_lock;
-
-        //! Functions for listener id incrementation with thread safe mutex locking
-        int getNextId();
-
-        /* Callbacks for emails and short messages should be stored in separate
-         * collections to simplyfy adding ang searching on call */
-
-        // Callbacks for short messages service
-        MCLmap m_short_message_callbacks;
-        CCLmap m_short_conversation_callbacks;
-        FCLmap m_short_folder_callbacks;
-
-        // Callbacks for email service
-        MCLmap m_email_message_callbacks;
-        CCLmap m_email_conversation_callbacks;
-        FCLmap m_email_folder_callbacks;
-
-        ChangeListenerContainer();
-
-        template<class T> static bool removeCallbackIfExists(
-                JSContextRef context, std::map<long,std::shared_ptr<T>>& collection, long id ) {
-            LOGD("Entered");
-
-            JSContextRef g_ctx = Common::GlobalContextManager::getInstance()->
-                    getGlobalContext(context);
-            auto itr = collection.find(id);
-            if ( itr != collection.end()) {
-                if(itr->second->getContext() == g_ctx){
-                    itr->second->setActive(false);
-                    collection.erase(id);
-                    return true;
-                } else {
-                    LOGE("Removing callback which does not belong to the current context is not allowed.");
-                    throw Common::NotFoundException(
-                            "Removing callback which does not belong to the current context is not allowed.");
-                }
-            }
-            return false;
-        }
-
-        /* Templates below written for code reusage (each template is used
-         * 2 times in each callXxxx[Added | Removed | Updated] function. */
-
-        /**
-         * Template function for calling "added" callback for all listeners
-         * from given collection with given event.
-         * */
-        template<class T, class U> void callAdded(
-                std::map<long,std::shared_ptr<T>>& collection,
-                U* event) {
-            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
-            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
-            try {
-                for (; itstart != itend; ++itstart) {
-                    auto callback = (*itstart).second;
-                    if (callback->getServiceType() == event->service_type
-                            && callback->getServiceId() == event->service_id) {
-                        LOGD("Found callback for given service id (%d) and type (%d)",
-                                event->service_id, event->service_type);
-                        //@todo filter msgs
-                        callback->added(event->items);
-                    }
-                }
-            }catch (const Common::BasePlatformException &err) {
-                LOGE("callAdded failed, %s: %s", err.getName().c_str(),
-                        err.getMessage().c_str());
-            }
-            catch (...) {
-                LOGE("callAdded failed");
-            }
-        }
-
-        /**
-         * Template function for calling "updated" callback for all listeners
-         * from given collection with given event.
-         * */
-        template<class T, class U> void callUpdated(
-                std::map<long,std::shared_ptr<T>>& collection,
-                U* event) {
-            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
-            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
-            try {
-                for (; itstart != itend; ++itstart) {
-                    auto callback = (*itstart).second;
-                    if (callback->getServiceType() == event->service_type
-                            && callback->getServiceId() == event->service_id) {
-                        LOGD("Found callback for given service id (%d) and type (%d)",
-                                event->service_id, event->service_type);
-                        //@todo filter msgs
-                        callback->updated(event->items);
-                    }
-                }
-            }catch (const Common::BasePlatformException &err) {
-                LOGE("callUpdated failed, %s: %s", err.getName().c_str(),
-                        err.getMessage().c_str());
-            }
-            catch (...) {
-                LOGE("callUpdated failed");
-            }
-        }
-
-        /**
-         * Template function for calling "removed" callback for all listeners
-         * from given collection with given event.
-         * */
-
-        template<class T, class U> void callRemoved(
-                std::map<long,std::shared_ptr<T>>& collection,
-                U* event) {
-            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
-            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
-            try {
-                for (; itstart != itend; ++itstart) {
-                    auto callback = (*itstart).second;
-                    if (callback->getServiceType() == event->service_type
-                            && callback->getServiceId() == event->service_id) {
-                        LOGD("Found callback for given service id (%d) and type (%d)",
-                                event->service_id, event->service_type);
-                        //@todo filter msgs
-                        callback->removed(event->items);
-                    }
-                }
-            }catch (const Common::BasePlatformException &err) {
-                LOGE("callRemoved failed, %s: %s", err.getName().c_str(),
-                        err.getMessage().c_str());
-            }
-            catch (...) {
-                LOGE("callRemoved failed");
-            }
-        }
-};
-
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_CHANGE_LISTENER_CONTAINER_H__
diff --git a/messaging/old/ConversationCallbackData.cpp b/messaging/old/ConversationCallbackData.cpp
deleted file mode 100644 (file)
index 51d309e..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "ConversationCallbackData.h"
-#include "JSMessageConversation.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-ConversationCallbackData::ConversationCallbackData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_filter(),
-        m_sort(),
-        m_limit(0),
-        m_offset(0),
-        m_is_error(false),
-        m_account_id(0),
-        m_service_type(UNDEFINED)
-{
-}
-
-ConversationCallbackData::~ConversationCallbackData()
-{
-}
-
-void ConversationCallbackData::setFilter(Tizen::AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-void ConversationCallbackData::setSortMode(Tizen::SortModePtr sortMode)
-{
-    m_sort = sortMode;
-}
-
-void ConversationCallbackData::setLimit(long limit)
-{
-    m_limit = limit;
-}
-
-void ConversationCallbackData::setOffset(long offset)
-{
-    m_offset = offset;
-}
-
-void ConversationCallbackData::addConversation(std::shared_ptr<MessageConversation> msg)
-{
-    m_conversations.push_back(msg);
-}
-
-void ConversationCallbackData::addConversations(JSContextRef context,
-        const std::vector<JSValueRef>& jsobject_conservations)
-{
-    const size_t new_conversations_count = jsobject_conservations.size();
-    if(0 == new_conversations_count) {
-        return;
-    }
-
-    m_conversations.reserve(m_conversations.size() + new_conversations_count);
-    for (auto it = jsobject_conservations.begin();
-            it != jsobject_conservations.end();
-            ++it) {
-        m_conversations.push_back(JSMessageConversation::getPrivateObject(context, *it));
-    }
-}
-
-std::vector<std::shared_ptr<MessageConversation>> ConversationCallbackData::getConversations() const
-{
-    return m_conversations;
-}
-
-void ConversationCallbackData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool ConversationCallbackData::isError() const
-{
-    return m_is_error;
-}
-
-std::string ConversationCallbackData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string ConversationCallbackData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void ConversationCallbackData::setAccountId(int account_id){
-    m_account_id = account_id;
-}
-
-int ConversationCallbackData::getAccountId() const
-{
-    return m_account_id;
-}
-
-void ConversationCallbackData::setMessageServiceType(MessageType m_msg_type)
-{
-    m_service_type = m_msg_type;
-}
-
-MessageType ConversationCallbackData::getMessageServiceType() const
-{
-    return m_service_type;
-}
-
-Tizen::AbstractFilterPtr ConversationCallbackData::getFilter() const
-{
-    return m_filter;
-}
-
-Tizen::SortModePtr ConversationCallbackData::getSortMode() const
-{
-    return m_sort;
-}
-
-long ConversationCallbackData::getLimit() const
-{
-    return m_limit;
-}
-
-long ConversationCallbackData::getOffset() const
-{
-    return m_offset;
-}
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/ConversationCallbackData.h b/messaging/old/ConversationCallbackData.h
deleted file mode 100644 (file)
index 4bc3a38..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_CONVERSATION_CALLBACK_DATA_H__
-#define __TIZEN_CONVERSATION_CALLBACK_DATA_H__
-
-#include <CallbackUserData.h>
-#include <memory>
-#include <string>
-#include <vector>
-#include <AttributeFilter.h>
-#include <SortMode.h>
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-class MessageConversation;
-
-class ConversationCallbackData: public Common::CallbackUserData {
-public:
-    ConversationCallbackData(JSContextRef globalCtx);
-    virtual ~ConversationCallbackData();
-
-    void setFilter(Tizen::AbstractFilterPtr filter);
-    void setSortMode(Tizen::SortModePtr sortMode);
-    void setLimit(long limit);
-    void setOffset(long offset);
-    void addConversation(std::shared_ptr<MessageConversation> msg);
-    void addConversations(JSContextRef context,
-            const std::vector<JSValueRef>& jsobject_conservations);
-
-    std::vector<std::shared_ptr<MessageConversation>> getConversations() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void setAccountId(int account_id);
-    int getAccountId() const;
-
-    void setMessageServiceType(MessageType m_msg_type);
-    MessageType getMessageServiceType() const;
-    Tizen::AbstractFilterPtr getFilter() const;
-    Tizen::SortModePtr getSortMode() const;
-    long getLimit() const;
-    long getOffset() const;
-
-private:
-    Tizen::AbstractFilterPtr m_filter;
-    Tizen::SortModePtr m_sort;
-    long m_limit;
-    long m_offset;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    std::vector<std::shared_ptr<MessageConversation>> m_conversations;
-    int m_account_id;
-    MessageType m_service_type;
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif // __TIZEN_CONVERSATION_CALLBACK_DATA_H__
diff --git a/messaging/old/ConversationsChangeCallback.cpp b/messaging/old/ConversationsChangeCallback.cpp
deleted file mode 100644 (file)
index 678513c..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <PlatformException.h>
-#include <JSUtil.h>
-#include <GlobalContextManager.h>
-
-#include "MessagingUtil.h"
-#include "ConversationsChangeCallback.h"
-#include "JSMessageConversation.h"
-#include "MessagingUtil.h"
-#include <Logger.h>
-
-using namespace DeviceAPI::Common;
-using namespace DeviceAPI::Tizen;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-const char* CONVERSATIONSADDED = "conversationsadded";
-const char* CONVERSATIONSUPDATED = "conversationsupdated";
-const char* CONVERSATIONSREMOVED = "conversationsremoved";
-
-ConversationsChangeCallback::ConversationsChangeCallback(
-        JSContextRef global_ctx,
-        JSObjectRef on_added_obj,
-        JSObjectRef on_updated_obj,
-        JSObjectRef on_removed_obj,
-        int service_id,
-        MessageType service_type) :
-        m_callback_data(global_ctx),
-        m_id(service_id),
-        m_msg_type(service_type),
-        m_is_act(true)
-{
-    LOGD("Entered");
-
-    m_callback_data.setCallback(CONVERSATIONSADDED, on_added_obj);
-    m_callback_data.setCallback(CONVERSATIONSUPDATED, on_updated_obj);
-    m_callback_data.setCallback(CONVERSATIONSREMOVED, on_removed_obj);
-}
-
-ConversationsChangeCallback::~ConversationsChangeCallback()
-{
-    LOGD("Entered");
-}
-
-ConversationPtrVector ConversationsChangeCallback::filterConversations(
-        AbstractFilterPtr filter,
-        const ConversationPtrVector& source_conversations)
-{
-    if (filter) {
-        ConversationPtrVector filtered_conversations;
-        ConversationPtrVector::const_iterator it = source_conversations.begin();
-        ConversationPtrVector::const_iterator end_it = source_conversations.end();
-
-        for(int i = 0; it != end_it; ++i, ++it) {
-            const ConversationPtr& conversation = *it;
-            const bool matched = filter->isMatching(conversation.get());
-            if(matched) {
-                filtered_conversations.push_back(conversation);
-            }
-
-            LOGD("[%d] conversation id:%d", i, conversation->getConversationId());
-            LOGD("[%d] conversation subject :%s", i, conversation->getSubject().c_str());
-            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
-        }
-
-        LOGD("returning matching %d of %d conversations", filtered_conversations.size(),
-                source_conversations.size());
-
-        return filtered_conversations;
-    }
-    else {
-        return source_conversations;
-    }
-}
-
-void ConversationsChangeCallback::added(
-        const ConversationPtrVector& conversations)
-{
-    LOGD("Entered conversations.size()=%d", conversations.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
-            JSMessageConversation>(ctx, filtered);
-
-    LOGD("Calling:%s with:%d added conversations", CONVERSATIONSADDED,
-        filtered.size());
-
-    m_callback_data.invokeCallback(CONVERSATIONSADDED, js_obj);
-}
-
-void ConversationsChangeCallback::updated(
-        const ConversationPtrVector& conversations)
-{
-    LOGD("Entered conversations.size()=%d", conversations.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
-            JSMessageConversation>(ctx, filtered);
-
-    LOGD("Calling:%s with:%d updated conversations", CONVERSATIONSUPDATED,
-            filtered.size());
-
-    m_callback_data.invokeCallback(CONVERSATIONSUPDATED, js_obj);
-}
-
-void ConversationsChangeCallback::removed(
-        const ConversationPtrVector& conversations)
-{
-    LOGD("Entered conversations.size()=%d", conversations.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
-            JSMessageConversation>(ctx, filtered);
-
-    LOGD("Calling:%s with:%d removed conversations", CONVERSATIONSREMOVED,
-            filtered.size());
-
-    m_callback_data.invokeCallback(CONVERSATIONSREMOVED, js_obj);
-}
-
-void ConversationsChangeCallback::setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-DeviceAPI::Tizen::AbstractFilterPtr ConversationsChangeCallback::getFilter() const
-{
-    return m_filter;
-}
-
-int ConversationsChangeCallback::getServiceId() const
-{
-    return m_id;
-}
-
-MessageType ConversationsChangeCallback::getServiceType() const
-{
-    return m_msg_type;
-}
-
-void ConversationsChangeCallback::setActive(bool act) {
-    m_is_act = act;
-}
-
-bool ConversationsChangeCallback::isActive() {
-    return m_is_act;
-}
-
-void ConversationsChangeCallback::setItems(ConversationPtrVector& items)
-{
-    m_items = items;
-}
-ConversationPtrVector ConversationsChangeCallback::getItems()
-{
-    return m_items;
-}
-
-JSContextRef ConversationsChangeCallback::getContext() const
-{
-    return m_callback_data.getContext();
-}
-
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/ConversationsChangeCallback.h b/messaging/old/ConversationsChangeCallback.h
deleted file mode 100644 (file)
index 612db76..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
-#define __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-#include <MultiCallbackUserData.h>
-
-#include <AbstractFilter.h>
-
-#include "MessageConversation.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-extern const char* CONVERSATIONSADDED;
-extern const char* CONVERSATIONSUPDATED;
-extern const char* CONVERSATIONSREMOVED;
-
-class ConversationsChangeCallback {
-public:
-    ConversationsChangeCallback(JSContextRef globalCtx,
-            JSObjectRef on_added_obj,
-            JSObjectRef on_updated_obj,
-            JSObjectRef on_removed_obj,
-            int service_id,
-            MessageType service_type);
-    virtual ~ConversationsChangeCallback();
-
-    void added(const ConversationPtrVector& conversations);
-    void updated(const ConversationPtrVector& conversations);
-    void removed(const ConversationPtrVector& conversations);
-
-    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
-    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
-
-    int getServiceId() const;
-    MessageType getServiceType() const;
-
-    void setActive(bool act);
-    bool isActive();
-
-    void setItems(ConversationPtrVector& items);
-    ConversationPtrVector getItems();
-    JSContextRef getContext() const;
-private:
-    static ConversationPtrVector filterConversations(
-            DeviceAPI::Tizen::AbstractFilterPtr a_filter,
-            const ConversationPtrVector& a_sourceConversations);
-
-    Common::MultiCallbackUserData m_callback_data;
-    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
-    int m_id;
-    MessageType m_msg_type;
-    bool m_is_act;
-    ConversationPtrVector m_items;
-
-};
-
-} // Messaging
-} // DeviceAPI
-
-
-
-
-#endif // __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
diff --git a/messaging/old/DBus/Connection.cpp b/messaging/old/DBus/Connection.cpp
deleted file mode 100644 (file)
index 67c243c..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "Connection.h"
-#include <Logger.h>
-#include <PlatformException.h>
-#include <cstring>
-#include <email-types.h>
-#include "MessageService.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-Connection& Connection::getInstance()
-{
-    LOGD("Entered");
-    static Connection instance;
-    return instance;
-}
-
-GDBusConnection* Connection::getDBus()
-{
-    return m_dbus;
-}
-
-Connection::Connection()
-{
-    dbus_g_thread_init();
-    g_type_init();
-
-    m_dbus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &m_error);
-    if (!m_dbus || m_error) {
-        LOGE("Could not get connection");
-    }
-    LOGD("Connection set");
-}
-
-Connection::~Connection()
-{
-    g_object_unref(m_dbus);
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/Connection.h b/messaging/old/DBus/Connection.h
deleted file mode 100644 (file)
index 16afddc..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_DBUS_CONNECTION_H__
-#define __TIZEN_DBUS_CONNECTION_H__
-
-#include <dbus/dbus.h>
-#include <dbus/dbus-glib.h>
-#include <gio/gio.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-class Connection {
-public:
-    static Connection& getInstance();
-
-    GDBusConnection* getDBus();
-
-private:
-    Connection();
-    Connection(const Connection&);
-    void operator=(const Connection&);
-    virtual ~Connection();
-
-    GDBusConnection* m_dbus;
-    GError* m_error;
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif
diff --git a/messaging/old/DBus/EmailSignalProxy.cpp b/messaging/old/DBus/EmailSignalProxy.cpp
deleted file mode 100644 (file)
index a3a9702..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        EmailSignalProxy.cpp
- */
-
-#include "EmailSignalProxy.h"
-#include <Logger.h>
-#include <cstring>
-#include <PlatformException.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-EmailSignalProxy::EmailSignalProxy(const std::string& proxy_path,
-        const std::string& proxy_iface) :
-        Proxy (proxy_path,
-                      proxy_iface,
-                      Proxy::DBUS_NAME_SIGNAL_EMAIL,   //specify email signal details
-                      DBUS_PATH_NETWORK_STATUS,
-                      DBUS_IFACE_NETWORK_STATUS)
-{
-}
-
-EmailSignalProxy::~EmailSignalProxy()
-{
-
-}
-
-void EmailSignalProxy::signalCallback(GDBusConnection* connection,
-        const gchar* sender_name,
-        const gchar* object_path,
-        const gchar* interface_name,
-        const gchar* signal_name,
-        GVariant* parameters)
-{
-    int status, mail_id, op_handle, error_code;
-    char* source = NULL;
-
-    try {
-        g_variant_get(parameters, "(iisii)",
-                &status,
-                &mail_id,
-                &source,
-                &op_handle,
-                &error_code);
-
-        //It is better to log this only when subclass is responsible of handling
-        //passed signal (usually determined by status value).
-        //
-        //LOGD("email:\n  status: %d\n  mail_id: %d\n  "
-        //        "source: %s\n  op_handle: %d\n  error_code: %d",
-        //        status, mail_id, source, op_handle, error_code);
-
-        handleEmailSignal(status, mail_id, source, op_handle, error_code);
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    g_free(source);
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/EmailSignalProxy.h b/messaging/old/DBus/EmailSignalProxy.h
deleted file mode 100644 (file)
index 378076a..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        EmailSignalProxy.h
- */
-
-#ifndef __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
-#define __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
-
-#include "Proxy.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-class EmailSignalProxy;
-typedef std::shared_ptr<EmailSignalProxy> EmailSignalProxyPtr;
-
-class EmailSignalProxy : public Proxy {
-public:
-    EmailSignalProxy(const std::string& proxy_path,
-            const std::string& proxy_iface);
-    virtual ~EmailSignalProxy();
-
-protected:
-    /**
-     * Override this method in subclass to handle email signal
-     */
-    virtual void handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code) = 0;
-
-    virtual void signalCallback(GDBusConnection *connection,
-            const gchar *sender_name,
-            const gchar *object_path,
-            const gchar *interface_name,
-            const gchar *signal_name,
-            GVariant *parameters);
-
-private:
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif // __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
diff --git a/messaging/old/DBus/LoadAttachmentProxy.cpp b/messaging/old/DBus/LoadAttachmentProxy.cpp
deleted file mode 100644 (file)
index 55eac0b..0000000
+++ /dev/null
@@ -1,231 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        LoadAttachmentProxy.cpp
- */
-
-#include "LoadAttachmentProxy.h"
-#include <Logger.h>
-#include <PlatformException.h>
-#include <cstring>
-#include <email-types.h>
-#include "MessageService.h"
-#include "Message.h"
-#include "MessageBody.h"
-#include "EmailManager.h"
-#include "JSMessageAttachment.h"
-#include <email-api.h>
-#include <JSWebAPIErrorFactory.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-/**
-  * This method perform very specified task (see warning comment) so it should not be
-  * visible outside LoadAttachmentProxy class.
-  */
-void updateAttachmentDataWithEmailGetAttachmentData(
-        std::shared_ptr<MessageAttachment> attachment)
-{
-    struct ScopedEmailAttachmentData {
-        ScopedEmailAttachmentData() : data(NULL) { }
-        ~ScopedEmailAttachmentData() {
-            if(data) {
-                email_free_attachment_data(&data, 1);
-            }
-        }
-        email_attachment_data_t* operator->() { return data; }
-        email_attachment_data_t* data;
-    } attachment_data_holder;
-
-    LOGD("attachmentId = %d", attachment->getId());
-
-    /*
-     * WARNING: email_get_attachment_data seems to be getting NOT COMPLETE
-     *          email_attachment_data_t object, observed that:
-     *              mail_id is 0
-     *              account_id is 0
-     *              mailbox_id is 0
-     *          Thus currently only attachment_path and attachment_mime_type is used!
-     *
-     *          To get COMPLETE data please use: Message::convertEmailToMessageAttachment
-     *          mtehod which fetches all attachments from specified email.
-     */
-    int err = email_get_attachment_data(attachment->getId(), &attachment_data_holder.data);
-    if (EMAIL_ERROR_NONE != err ||
-        NULL == attachment_data_holder.data) {
-        LOGE("Couldn't get attachment data for attachmentId:%d", attachment->getId());
-        throw Common::UnknownException("Couldn't get attachment.");
-    }
-
-    LOGD("attachment name : %s", attachment_data_holder->attachment_name);
-
-    if(attachment_data_holder->attachment_mime_type) {
-        attachment->setMimeType(attachment_data_holder->attachment_mime_type);
-    }
-
-    bool isSaved = false;
-    if (attachment_data_holder->attachment_path) {
-        LOGD("set attachment path: %s", attachment_data_holder->attachment_path);
-        attachment->setFilePath(attachment_data_holder->attachment_path);
-
-        LOGD("save_status: %d", attachment_data_holder->save_status);
-        LOGD("attachment_size : %d", attachment_data_holder->attachment_size);
-    }
-    isSaved = attachment_data_holder->save_status;
-    attachment->setIsSaved(isSaved);
-}
-
-LoadAttachmentProxy::LoadAttachmentProxy(const std::string& path,
-        const std::string& iface) :
-        EmailSignalProxy(path, iface)
-{
-}
-
-LoadAttachmentProxy::~LoadAttachmentProxy()
-{
-}
-
-void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwned)
-{
-    if(callbackOwned->getMessageAttachment()) {
-        LOGD("Registered callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d",
-            callbackOwned->getMessageAttachment()->getId(),
-            callbackOwned->getMessageAttachment()->getMessageId(),
-            callbackOwned->getOperationHandle(),
-            callbackOwned->getNth());
-    }
-
-    m_callback_set.insert(callbackOwned);
-}
-
-void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback)
-{
-    if(callback->getMessageAttachment()) {
-        LOGD("Removed callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d",
-            callback->getMessageAttachment()->getId(),
-            callback->getMessageAttachment()->getMessageId(),
-            callback->getOperationHandle(),
-            callback->getNth());
-    }
-
-    m_callback_set.erase(callback);
-}
-
-MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth,
-        const int mail_id)
-{
-    CallbackSet::iterator it = m_callback_set.begin();
-    for (; it != m_callback_set.end(); ++it) {
-        MessageAttachmentCallbackData* callback = *it;
-        if (nth == callback->getNth() &&
-            mail_id == callback->getMessageAttachment()->getMessageId()) {
-            return callback;
-        }
-    }
-
-    LOGW("Could not find callback with nth: %d and mail_id: %d", nth, mail_id);
-    return NULL;
-}
-
-void LoadAttachmentProxy::handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code)
-{
-    if(NOTI_DOWNLOAD_ATTACH_FINISH != status &&
-            NOTI_DOWNLOAD_ATTACH_FAIL != status) {
-        return;
-    }
-
-    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
-            "source: %s\n  op_handle(nth): %d\n  error_code: %d",
-            status, mail_id, source.c_str(), op_handle, error_code);
-
-    MessageAttachmentCallbackData* callback = NULL;
-
-    //It seems that D-Bus signal op_handle is equal to nth in:
-    // int email_download_attachment(int mail_id, int nth, int *handle)
-    // and not handle returned from above call!!
-    const int nth = op_handle;
-
-    try {
-        // From old implementation it looks that op_handle(nth) is is equal to
-        // index (1 based) of attachment inside email thus it is not globally unique!
-        // Therfore we need to test if mail_id match.
-        // For details see old implementation MailSync.cp line 461
-
-        callback = findCallback(nth, mail_id);
-        if(!callback) {
-            //We should not log not found pair since it could be requested by
-            //different application.
-            return;
-        }
-
-        LOGD("Found callback for pair mailId:%d nth:%d", mail_id, nth);
-
-        if(NOTI_DOWNLOAD_ATTACH_FINISH == status) {
-            LOGD("Message attachment downloaded!");
-
-            std::shared_ptr<MessageAttachment> att = callback->getMessageAttachment();
-            updateAttachmentDataWithEmailGetAttachmentData(att);
-            LOGD("Updated Message attachment object");
-
-            try {
-                JSContextRef context = callback->getContext();
-                JSObjectRef jsMessageAtt = JSMessageAttachment::makeJSObject(context, att);
-                callback->callSuccessCallback(jsMessageAtt);
-            } catch (...) {
-                LOGW("Couldn't create JSMessageAttachment object!");
-                throw Common::UnknownException(
-                        "Couldn't create JSMessageAttachment object!");
-            }
-
-        } else if(NOTI_DOWNLOAD_ATTACH_FAIL) {
-            LOGD("Load message attachment failed!");
-            JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                    callback->getContext(),
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        }
-    } catch (const Common::BasePlatformException& e) {
-        LOGE("Exception in signal callback");
-        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                callback->getContext(), e);
-        callback->callErrorCallback(errobj);
-    } catch (...) {
-        LOGE("Exception in signal callback");
-        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                callback->getContext(),
-                Common::JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                "Handling signal callback failed");
-        callback->callErrorCallback(errobj);
-    }
-
-    if(callback) {
-        removeCallback(callback);
-        delete callback;
-    }
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/LoadAttachmentProxy.h b/messaging/old/DBus/LoadAttachmentProxy.h
deleted file mode 100644 (file)
index 06db27d..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        LoadAttachmentProxy.h
- */
-
-#ifndef __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
-#define __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
-
-#include "EmailSignalProxy.h"
-#include <set>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageAttachmentCallbackData;
-
-namespace DBus {
-
-class LoadAttachmentProxy;
-typedef std::shared_ptr<LoadAttachmentProxy> LoadAttachmentProxyPtr;
-
-class LoadAttachmentProxy : public EmailSignalProxy {
-public:
-
-    // Callback is owned by this set
-    typedef std::set<MessageAttachmentCallbackData*> CallbackSet;
-
-    LoadAttachmentProxy(const std::string& path,
-            const std::string& iface);
-    virtual ~LoadAttachmentProxy();
-
-    //Passed callback will be owned by this proxy
-    void addCallback(MessageAttachmentCallbackData* callbackOwned);
-    void removeCallback(MessageAttachmentCallbackData* callback);
-
-protected:
-    virtual void handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code);
-
-private:
-    MessageAttachmentCallbackData* findCallback(const int nth, const int mail_id);
-
-    CallbackSet m_callback_set;
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif // __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
diff --git a/messaging/old/DBus/LoadBodyProxy.cpp b/messaging/old/DBus/LoadBodyProxy.cpp
deleted file mode 100644 (file)
index 990d04f..0000000
+++ /dev/null
@@ -1,206 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        LoadBodyProxy.cpp
- */
-
-#include "LoadBodyProxy.h"
-#include <Logger.h>
-#include <PlatformException.h>
-#include <cstring>
-#include <email-types.h>
-#include "MessageService.h"
-#include "Message.h"
-#include "MessageBody.h"
-#include "EmailManager.h"
-#include "JSMessage.h"
-#include <JSWebAPIErrorFactory.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-LoadBodyProxy::LoadBodyProxy(const std::string& path,
-        const std::string& iface) :
-        EmailSignalProxy(path, iface)
-{
-
-}
-
-LoadBodyProxy::~LoadBodyProxy()
-{
-
-}
-
-void LoadBodyProxy::addCallback(MessageBodyCallbackData* callbackOwned)
-{
-    m_callback_set.insert(callbackOwned);
-}
-
-void LoadBodyProxy::removeCallback(MessageBodyCallbackData* callback)
-{
-    m_callback_set.erase(callback);
-}
-
-MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_handle)
-{
-    CallbackSet::iterator it = m_callback_set.begin();
-    for (; it != m_callback_set.end(); ++it) {
-
-        MessageBodyCallbackData* callback = *it;
-        if (op_handle == callback->getOperationHandle()) {
-            return callback;
-        }
-    }
-
-    LOGW("Could not find callback with op_handle: %d", op_handle);
-    return NULL;
-}
-
-void LoadBodyProxy::handleEmailSignal(const int status,
-        const int mail_id,
-        const std::string& source,
-        const int op_handle,
-        const int error_code)
-{
-    switch(status) {
-        //We should handle this signal since it is DOWNLOAD_BODY_*
-        case NOTI_DOWNLOAD_BODY_START:
-        case NOTI_DOWNLOAD_BODY_FINISH:
-        case NOTI_DOWNLOAD_BODY_FAIL: {
-        } break;
-
-        // This values have not been explicitly handled in old implementation
-        //  NOTI_DOWNLOAD_BODY_CANCEL
-        //  NOTI_DOWNLOAD_MULTIPART_BODY
-        //
-        // 1. I assume that NOTI_DOWNLOAD_MULTIPART_BODY is called several times
-        // before final NOTI_DOWNLOAD_BODY_FINISH is called, thus we should not
-        // remove nor delete callback.
-        //
-        // 2. I assume that NOTI_DOWNLOAD_BODY_CANCEL is called before
-        // NOTI_DOWNLOAD_BODY_FAIL so we should do the same as in point 1.
-        case NOTI_DOWNLOAD_BODY_CANCEL:
-        case NOTI_DOWNLOAD_MULTIPART_BODY:
-        default: {
-            // This signal is not related with load message body or there is nothing
-            // to do so we can return now.
-            return;
-        } break;
-    }
-
-    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
-        "source: %s\n  op_handle: %d\n  error_code: %d",
-        status, mail_id, source.c_str(), op_handle, error_code);
-
-    if(NOTI_DOWNLOAD_BODY_START == status) {
-        LOGD("Download message body started ...");
-        // There is nothing more to do so we can return now.
-        return;
-    }
-
-    MessageBodyCallbackData* callback = NULL;
-    try {
-        callback = findCallbackByOpHandle(op_handle);
-        if (!callback) {
-            LOGE("Callback is null");
-        } else {
-            if( (NOTI_DOWNLOAD_BODY_FINISH == status) ||
-                (NOTI_DOWNLOAD_BODY_FAIL == status &&
-                         EMAIL_ERROR_MAIL_IS_ALREADY_DOWNLOADED == error_code)) {
-
-                // Old implementation is not verifying whether message update failed,
-                // it just calls success callback.
-                if(callback->getMessage()) {
-                    email_mail_data_t* mail_data = EmailManager::loadMessage(
-                             callback->getMessage()->getId());
-                    if (mail_data) {
-                        callback->getMessage()->updateEmailMessage(*mail_data);
-                        EmailManager::freeMessage(mail_data);
-                        mail_data = NULL;
-                    }
-
-                    //TODO: this should be reviewed when attachments and
-                    //      loadAttachments have been completed.
-                    //TODO: see old implementation lines 608-635 in MailSync.cpp
-                    /*
-                    * This is original Messaging implementation:
-                    *
-                    * std::vector<IAttachmentPtr> attachments = mail->getAttachments();
-                    * std::vector<IAttachmentPtr> inlineAttachments = mail->getInlineAttachments();
-                    *
-                    * for (unsigned int idx = 0; idx < attachments.size() ; idx++ )
-                    * {
-                    *   LoggerD("set Attachment ID = " << attachments[idx]->getAttachmentID());
-                    *   attachments[idx]->setMessage(event->m_message);
-                    *
-                    * }
-                    * for (unsigned int idx = 0; idx < inlineAttachments.size() ; idx++ )
-                    * {
-                    *   LoggerD("set inline Attachment ID = " << inlineAttachments[idx]->getAttachmentID());
-                    *   inlineAttachments[idx]->setMessage(event->m_message);
-                    * }
-                    */
-                }
-
-                LOGD("Message body downloaded!");
-                try {
-                    JSContextRef context = callback->getContext();
-                    JSObjectRef jsMessage = JSMessage::makeJSObject(context,
-                             callback->getMessage());
-                    callback->callSuccessCallback(jsMessage);
-                } catch (...) {
-                    LOGW("Couldn't create JSMessage object!");
-                    throw Common::UnknownException(
-                            "Couldn't create JSMessage object!");
-                }
-
-            } else if(NOTI_DOWNLOAD_BODY_FAIL == status) {
-                LOGD("Load message body failed!");
-                JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                        callback->getContext(),
-                        callback->getErrorName(),
-                        callback->getErrorMessage());
-                callback->callErrorCallback(errobj);
-            }
-        }
-    }
-    catch (const Common::BasePlatformException& e) {
-        LOGE("Exception in signal callback");
-        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                callback->getContext(), e);
-        callback->callErrorCallback(errobj);
-    }
-    catch (...) {
-        LOGE("Exception in signal callback");
-        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
-                callback->getContext(),
-                Common::JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                "Handling signal callback failed");
-        callback->callErrorCallback(errobj);
-    }
-
-    if(callback) {
-        removeCallback(callback);
-        delete callback;
-    }
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/LoadBodyProxy.h b/messaging/old/DBus/LoadBodyProxy.h
deleted file mode 100644 (file)
index 2fffa37..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        LoadBodyProxy.h
- */
-
-#ifndef __TIZEN_DBUS_LOAD_BODY_PROXY_H__
-#define __TIZEN_DBUS_LOAD_BODY_PROXY_H__
-
-#include "EmailSignalProxy.h"
-#include <set>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageBodyCallbackData;
-
-namespace DBus {
-
-class LoadBodyProxy;
-typedef std::shared_ptr<LoadBodyProxy> LoadBodyProxyPtr;
-
-class LoadBodyProxy : public EmailSignalProxy {
-public:
-
-    // Callback is owned by this set
-    typedef std::set<MessageBodyCallbackData*> CallbackSet;
-
-    LoadBodyProxy(const std::string& path,
-            const std::string& iface);
-    virtual ~LoadBodyProxy();
-
-    //Passed callback will be owned by this proxy
-    void addCallback(MessageBodyCallbackData* callbackOwned);
-    void removeCallback(MessageBodyCallbackData* callback);
-
-protected:
-    virtual void handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code);
-
-private:
-    /**
-     * Find callback by operation handle returned from:
-     *  int email_download_body(..., int *handle);
-     */
-    MessageBodyCallbackData* findCallbackByOpHandle(const int op_handle);
-
-    CallbackSet m_callback_set;
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif // __TIZEN_DBUS_LOAD_BODY_PROXY_H__
diff --git a/messaging/old/DBus/MessageProxy.cpp b/messaging/old/DBus/MessageProxy.cpp
deleted file mode 100644 (file)
index 32d4782..0000000
+++ /dev/null
@@ -1,290 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "MessageProxy.h"
-#include "Connection.h"
-#include <Logger.h>
-#include <Message.h>
-#include <MessageEmail.h>
-#include <MessageConversation.h>
-#include <MessageFolder.h>
-#include <ChangeListenerContainer.h>
-#include <EmailManager.h>
-#include <PlatformException.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-MessageProxy::MessageProxy():
-        Proxy(Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE,
-                     Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE,
-                     Proxy::DBUS_NAME_SIGNAL_EMAIL,
-                     Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE,
-                     Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE)
-{
-}
-
-MessageProxy::~MessageProxy()
-{
-}
-
-void MessageProxy::signalCallback(GDBusConnection *connection,
-            const gchar *sender_name,
-            const gchar *object_path,
-            const gchar *interface_name,
-            const gchar *signal_name,
-            GVariant *parameters)
-{
-    LOGD("Enter");
-    int status, account_id, object_id, thread_id;
-    char* name;
-    g_variant_get(parameters, "(iiisi)",
-            &status,
-            &account_id,
-            &object_id,
-            &name,
-            &thread_id);
-    LOGD("status: %d", status);
-    LOGD("account_id: %d", account_id);
-    LOGD("object_id: %d", object_id);
-    LOGD("name: %s", name);
-    LOGD("thread_id: %d", thread_id);
-
-    try {
-        switch (status) {
-            case NOTI_MAIL_ADD:
-            case NOTI_MAIL_UPDATE:
-                handleEmailEvent(account_id, object_id, thread_id, status);
-                break;
-            case NOTI_MAIL_DELETE:
-                //ids of removing messages are sent with name in format:
-                //id1,id2,id3,
-                handleEmailRemoveEvent(account_id, name);
-                break;
-            case NOTI_MAIL_DELETE_FINISH:
-            case NOTI_MAIL_DELETE_FAIL:
-                //notify EmailManager, maybe it tries to delete mail
-                notifyEmailManager(name, static_cast<email_noti_on_storage_event>(status));
-                break;
-            case NOTI_THREAD_DELETE:
-                handleThreadRemoveEvent(account_id, object_id);
-                break;
-            case NOTI_MAILBOX_ADD:
-            case NOTI_MAILBOX_UPDATE:
-            case NOTI_MAILBOX_FIELD_UPDATE:
-            case NOTI_MAILBOX_RENAME:
-            case NOTI_MAILBOX_DELETE:
-                handleMailboxEvent(account_id, object_id, status);
-                break;
-            default:
-                LOGD("Unrecognized status: %d", status);
-        }
-    } catch (const Common::BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Failed to call callback");
-    }
-    g_free(name);
-}
-
-void MessageProxy::handleEmailEvent(int account_id, int mail_id, int thread_id, int event)
-{
-    LOGD("Enter");
-
-    if(NOTI_MAIL_UPDATE == event) {
-        //getting thread_id from message
-        email_mail_data_t *mail_data = NULL;
-
-        if(EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail_data)) {
-            if (mail_data) email_free_mail_data(&mail_data, 1);
-
-            LOGE("Failed to get mail data during setting conversation id in MessageProxy.");
-            return;
-        }
-
-        thread_id = mail_data->thread_id;
-
-        if(EMAIL_ERROR_NONE != email_free_mail_data(&mail_data,1)) {
-            LOGE("Failed to free mail data memory");
-        }
-    }
-
-    email_mail_data_t* mail_data = EmailManager::getInstance().loadMessage(mail_id);
-    if (mail_data == NULL) {
-        throw Common::UnknownException("Failed to load email");
-    }
-    std::shared_ptr<Message> msg = Message::convertPlatformEmailToObject(*mail_data);
-    ConversationPtr conv = MessageConversation::convertEmailConversationToObject(
-            thread_id);
-
-    EventMessages* eventMsg = new EventMessages();
-    eventMsg->service_type = MessageType::EMAIL;
-    eventMsg->service_id = account_id;
-    eventMsg->items.push_back(msg);
-    EventConversations* eventConv = new EventConversations();
-    eventConv->service_type = MessageType::EMAIL;
-    eventConv->service_id = account_id;
-    eventConv->items.push_back(conv);
-    switch (event) {
-        case NOTI_MAIL_ADD:
-            ChangeListenerContainer::getInstance().callMessageAdded(eventMsg);
-            if (conv->getMessageCount() == 1) {
-                LOGD("This thread is new, triggering conversationAdded");
-                ChangeListenerContainer::getInstance().callConversationAdded(eventConv);
-            } else {
-                LOGD("This thread is not new, but it's updated");
-                ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
-            }
-            break;
-        case NOTI_MAIL_UPDATE:
-            ChangeListenerContainer::getInstance().callMessageUpdated(eventMsg);
-            ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
-            break;
-        default:
-            LOGW("Unknown event type: %d", event);
-            break;
-
-    }
-    delete eventMsg;
-    delete eventConv;
-
-    EmailManager::getInstance().freeMessage(mail_data);
-}
-
-std::vector<int> getMailIds(const std::string& idsString)
-{
-    std::stringstream idsStream(idsString);
-    std::string item;
-    std::vector<int> ids;
-    while (std::getline(idsStream, item, ',')) {
-        if (item.length() > 0) {
-            int id;
-            std::stringstream stream(item);
-            stream >> id;
-            if (stream) {
-                LOGD("Mail delete id: %d", id);
-                ids.push_back(id);
-            }
-        }
-    }
-    return ids;
-}
-
-void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& idsString)
-{
-    LOGD("Enter");
-    std::vector<int> ids = getMailIds(idsString);
-    if (ids.empty()) {
-        LOGD("Mail id list is empty.");
-        return;
-    }
-    EventMessages* eventMsg = new EventMessages();
-    eventMsg->service_type = MessageType::EMAIL;
-    eventMsg->service_id = account_id;
-    for (auto it = ids.begin(); it != ids.end(); ++it) {
-        //it turns out that this event is triggered after messages are removed
-        //so we just create empty messages with id and type
-        std::shared_ptr<Message> msg = std::make_shared<MessageEmail>();
-        msg->setId(*it);
-        eventMsg->items.push_back(msg);
-    }
-    ChangeListenerContainer::getInstance().callMessageRemoved(eventMsg);
-    delete eventMsg;
-    eventMsg = NULL;
-}
-
-void MessageProxy::notifyEmailManager(const std::string& idsString,
-        email_noti_on_storage_event status)
-{
-    LOGD("Enter");
-    std::vector<int> ids = getMailIds(idsString);
-    if (ids.empty()) {
-        LOGD("Mail id list is empty.");
-        return;
-    }
-    EmailManager::getInstance().removeStatusCallback(ids, status);
-}
-
-void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id)
-{
-    LOGD("Enter");
-    //event is called after thread is removed, so we just set thread id
-    ConversationPtr conv = std::make_shared<MessageConversation>();
-    conv->setConversationId(thread_id);
-
-    EventConversations* eventConv = new EventConversations();
-    eventConv->service_type = MessageType::EMAIL;
-    eventConv->service_id = account_id;
-    eventConv->items.push_back(conv);
-    ChangeListenerContainer::getInstance().callConversationRemoved(eventConv);
-    delete eventConv;
-    eventConv = NULL;
-}
-
-void MessageProxy::handleMailboxEvent(int account_id, int mailbox_id, int event)
-{
-    LOGD("Enter");
-
-    EventFolders* eventFolder = new EventFolders();
-    eventFolder->service_type = MessageType::EMAIL;
-    eventFolder->service_id = account_id;
-    FolderPtr folder;
-    if (event == NOTI_MAILBOX_DELETE) {
-        //this event is triggered after mailbox is removed
-        //so we just create folder with id
-        folder.reset(new MessageFolder(std::to_string(mailbox_id),
-                "", //parent_id
-                "", //service_id
-                "", //content_type
-                "", //name
-                "", //path
-                MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD,
-                false));
-    } else {
-        email_mailbox_t* mail_box = NULL;
-        if (EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_id(mailbox_id, &mail_box)) {
-            LOGE("Mailbox not retrieved");
-            delete eventFolder;
-            throw Common::UnknownException("Failed to load mailbox");
-        }
-        folder.reset(new MessageFolder(*mail_box));
-        if (EMAIL_ERROR_NONE != email_free_mailbox(&mail_box, 1)) {
-            LOGD("Failed to free email_free_mailbox");
-        }
-    }
-    eventFolder->items.push_back(folder);
-    switch (event) {
-        case NOTI_MAILBOX_ADD:
-            ChangeListenerContainer::getInstance().callFolderAdded(eventFolder);
-            break;
-        case NOTI_MAILBOX_UPDATE:
-        case NOTI_MAILBOX_FIELD_UPDATE:
-            ChangeListenerContainer::getInstance().callFolderUpdated(eventFolder);
-            break;
-        case NOTI_MAILBOX_DELETE:
-            ChangeListenerContainer::getInstance().callFolderRemoved(eventFolder);
-            break;
-        default:
-            LOGW("Unknown event type: %d", event);
-    }
-    delete eventFolder;
-}
-
-} //DBus
-} //Messaging
-} //DeviceAPI
diff --git a/messaging/old/DBus/MessageProxy.h b/messaging/old/DBus/MessageProxy.h
deleted file mode 100644 (file)
index 7b6d456..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_PROXY_H
-#define __TIZEN_MESSAGE_PROXY_H
-
-#include <dbus/dbus.h>
-#include <dbus/dbus-glib.h>
-#include <gio/gio.h>
-#include <memory>
-#include <string>
-#include <email-types.h>
-#include "Proxy.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-class MessageProxy: public Proxy {
-public:
-    MessageProxy();
-    virtual ~MessageProxy();
-protected:
-    virtual void signalCallback(GDBusConnection *connection,
-            const gchar *sender_name,
-            const gchar *object_path,
-            const gchar *interface_name,
-            const gchar *signal_name,
-            GVariant *parameters);
-    /**
-     * Handles e-mail add and update only.
-     * @param account_id
-     * @param mail_id
-     * @param thread_id
-     * @param event
-     */
-    void handleEmailEvent(int account_id, int mail_id, int thread_id, int event);
-    void handleEmailRemoveEvent(int account_id, const std::string& idsString);
-    void notifyEmailManager(const std::string& idsString, email_noti_on_storage_event status);
-    void handleThreadRemoveEvent(int account_id, int thread_id);
-    void handleMailboxEvent(int account_id, int mailbox_id, int event);
-};
-
-typedef std::shared_ptr<MessageProxy> MessageProxyPtr;
-
-} //DBus
-} //Messaging
-} //DeviceAPI
-
-#endif /* __TIZEN_MESSAGE_PROXY_H */
-
diff --git a/messaging/old/DBus/Proxy.cpp b/messaging/old/DBus/Proxy.cpp
deleted file mode 100644 (file)
index 422ab07..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        Proxy.cpp
- */
-
-#include "Proxy.h"
-#include <Logger.h>
-#include <PlatformException.h>
-#include <cstring>
-#include <email-types.h>
-#include "MessageService.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-const char* Proxy::DBUS_PATH_NETWORK_STATUS = "/User/Email/NetworkStatus";
-const char* Proxy::DBUS_IFACE_NETWORK_STATUS = "User.Email.NetworkStatus";
-const char* Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE = "/User/Email/StorageChange";
-const char* Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE = "User.Email.StorageChange";
-const char* Proxy::DBUS_NAME_SIGNAL_EMAIL = "email";
-
-Proxy::Proxy(const std::string& proxy_path,
-            const std::string& proxy_iface,
-            const std::string& signal_name,
-            const std::string& signal_path,
-            const std::string& signal_iface) :
-                m_conn(Connection::getInstance()),
-                m_sub_id(0),
-                m_path(proxy_path),
-                m_iface(proxy_iface),
-                m_signal_name(signal_name),
-                m_signal_path(signal_path),
-                m_signal_iface(signal_iface),
-                m_error(NULL),
-                m_dbus_signal_subscribed(false)
-{
-    LOGD("Proxy:\n"
-            "  proxy_path: %s\n  proxy_iface: %s"
-            "  signal_name: %s\n signal_path:%s\n signal_iface:%s",
-            m_path.c_str(), m_iface.c_str(),
-            m_signal_name.c_str(), m_signal_path.c_str(), m_signal_iface.c_str());
-
-    const gchar* unique_name = g_dbus_connection_get_unique_name(m_conn.getDBus());
-    LOGD("Generated unique name: %d", unique_name);
-
-    // path and interface are not obligatory to receive, but
-    // they should be set to send the signals.
-    m_proxy = g_dbus_proxy_new_sync(m_conn.getDBus(),
-            G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
-            NULL, unique_name, m_path.c_str(), m_iface.c_str(), NULL, &m_error);
-    if (!m_proxy || m_error) {
-        LOGE("Could not get proxy");
-        throw Common::UnknownException("Could not get proxy");
-    }
-}
-
-Proxy::~Proxy()
-{
-    signalUnsubscribe();
-}
-
-void Proxy::signalCallbackProxy(GDBusConnection *connection,
-        const gchar *sender_name,
-        const gchar *object_path,
-        const gchar *interface_name,
-        const gchar *signal_name,
-        GVariant *parameters,
-        gpointer user_data)
-{
-    Proxy* this_ptr = static_cast<Proxy*>(user_data);
-    if (!this_ptr) {
-        LOGW("Proxy is null, nothing to do");
-        return;
-    }
-
-    try {
-        //It is better to log this only when subclass is responsible of handling
-        //passed signal. If you need it put it into your signalCallback(...) method
-        //LOGD("signal: %s from: %s path: %s interface: %s",
-        //        signal_name, sender_name, object_path, interface_name);
-
-        this_ptr->signalCallback(connection, sender_name, object_path, interface_name,
-                signal_name, parameters);
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-}
-
-void Proxy::signalSubscribe()
-{
-    if(m_dbus_signal_subscribed) {
-        LOGW("Proxy has already subscribed for listening DBus signal");
-        return;
-    }
-
-    const char* sender = NULL;
-    m_sub_id = g_dbus_connection_signal_subscribe(m_conn.getDBus(),
-            sender,
-            m_signal_iface.c_str(),
-            m_signal_name.c_str(),
-            m_signal_path.c_str(),
-            NULL,
-            G_DBUS_SIGNAL_FLAGS_NONE,
-            signalCallbackProxy,
-            static_cast<gpointer>(this),
-            NULL);
-    LOGD("g_dbus_connection_signal_subscribe returned id: %d", m_sub_id);
-
-    m_dbus_signal_subscribed = true;
-}
-
-void Proxy::signalUnsubscribe()
-{
-    if (!m_dbus_signal_subscribed) {
-        LOGW("Proxy hasn't subscribed for listening DBus signal");
-        return;
-    }
-
-    g_dbus_connection_signal_unsubscribe(m_conn.getDBus(), m_sub_id);
-    LOGD("g_dbus_connection_signal_unsubscribe finished");
-
-    m_dbus_signal_subscribed = false;
-}
-
-const std::string& Proxy::getSignalName() const
-{
-    return m_signal_name;
-}
-
-const std::string& Proxy::getSignalPath() const
-{
-    return m_signal_path;
-}
-
-const std::string& Proxy::getSignalInterfaceName() const
-{
-    return m_signal_iface;
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/Proxy.h b/messaging/old/DBus/Proxy.h
deleted file mode 100644 (file)
index f157f1e..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        Proxy.h
- */
-
-#ifndef __TIZEN_DBUS_PROXY_H__
-#define __TIZEN_DBUS_PROXY_H__
-
-#include "Connection.h"
-#include <memory>
-#include <string>
-#include <mutex>
-#include <map>
-#include <CallbackUserData.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-
-class Proxy;
-typedef std::shared_ptr<Proxy> ProxyPtr;
-
-/**
- * This is generic dbus signal listener proxy.
- */
-class Proxy {
-public:
-    /**
-     * List of Tizen path and interface names:
-     */
-    static const char* DBUS_PATH_NETWORK_STATUS;
-    static const char* DBUS_IFACE_NETWORK_STATUS;
-    static const char* DBUS_PATH_EMAIL_STORAGE_CHANGE;
-    static const char* DBUS_IFACE_EMAIL_STORAGE_CHANGE;
-    /**
-     * Name of email signal
-     */
-    static const char* DBUS_NAME_SIGNAL_EMAIL;
-
-    /**
-     * @param proxy_path - path of this proxy
-     * @param proxy_iface - interface name of this proxy
-     *
-     * @param signal_name - expected signal name
-     * @param signal_path - expected signal path
-     * @param signal_iface - expected signal interface name
-     */
-    Proxy(const std::string& proxy_path,
-            const std::string& proxy_iface,
-            const std::string& signal_name,
-            const std::string& signal_path,
-            const std::string& signal_iface);
-
-    virtual ~Proxy();
-
-    void signalSubscribe();
-    void signalUnsubscribe();
-
-    const std::string& getSignalName() const;
-    const std::string& getSignalPath() const;
-    const std::string& getSignalInterfaceName() const;
-
-protected:
-    /**
-     * Please implement this method in subclass to handle signal.
-     * Executed by static void signalCallbackProxy(...).
-     */
-    virtual void signalCallback(GDBusConnection *connection,
-            const gchar *sender_name,
-            const gchar *object_path,
-            const gchar *interface_name,
-            const gchar *signal_name,
-            GVariant *parameters) = 0;
-
-private:
-    /**
-     * This method (registered with g_dbus_connection_signal_subscribe) is executed by
-     * DBus when signal is received. It calls
-     * (static_cast<Proxy*>(user_data))->signalCallback(...)
-     */
-    static void signalCallbackProxy(GDBusConnection *connection,
-            const gchar *sender_name,
-            const gchar *object_path,
-            const gchar *interface_name,
-            const gchar *signal_name,
-            GVariant *parameters,
-            gpointer user_data);
-
-    Connection& m_conn;
-    guint m_sub_id;
-
-    std::string m_path;
-    std::string m_iface;
-
-    std::string m_signal_name;
-    std::string m_signal_path;
-    std::string m_signal_iface;
-
-    GError* m_error;
-    GDBusProxy* m_proxy;
-    bool m_dbus_signal_subscribed;
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif // __TIZEN_DBUS_PROXY_H__
diff --git a/messaging/old/DBus/SendProxy.cpp b/messaging/old/DBus/SendProxy.cpp
deleted file mode 100644 (file)
index 1e5a836..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "SendProxy.h"
-
-#include <Logger.h>
-#include <email-types.h>
-#include <EmailManager.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-SendProxy::SendProxy():
-        EmailSignalProxy(Proxy::DBUS_PATH_NETWORK_STATUS,
-                     Proxy::DBUS_IFACE_NETWORK_STATUS)
-{
-}
-
-SendProxy::~SendProxy()
-{
-}
-
-void SendProxy::handleEmailSignal(const int status,
-            const int account_id,
-            const std::string& source,
-            const int mail_id,
-            const int error_code)
-{
-    LOGD("Enter");
-    switch (status) {
-        case NOTI_SEND_FINISH:
-        case NOTI_SEND_FAIL:
-            LOGD("Recognized status for email send");
-            LOGD("received email signal with:\n  status: %d\n  account_id: %d\n  "
-                "source: %s\n  mail_id: %d\n  error_code: %d",
-                status, account_id, source.c_str(), mail_id, error_code);
-            EmailManager::getInstance().sendStatusCallback(mail_id,
-                    static_cast<email_noti_on_network_event>(status),
-                    error_code);
-            break;
-        default:
-            LOGD("Unrecognized status %d, ignoring", status);
-    }
-}
-
-
-} //DBus
-} //Messaging
-} //DeviceAPI
\ No newline at end of file
diff --git a/messaging/old/DBus/SendProxy.h b/messaging/old/DBus/SendProxy.h
deleted file mode 100644 (file)
index 1493c8e..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_SEND_PROXY_H
-#define __TIZEN_SEND_PROXY_H
-
-#include "EmailSignalProxy.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-class SendProxy: public EmailSignalProxy {
-public:
-    SendProxy();
-    virtual ~SendProxy();
-protected:
-    virtual void handleEmailSignal(const int status,
-            const int account_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code);
-
-};
-
-typedef std::shared_ptr<SendProxy> SendProxyPtr;
-
-} //DBus
-} //Messaging
-} //DeviceAPI
-
-#endif /* __TIZEN_SEND_PROXY_H */
-
diff --git a/messaging/old/DBus/SyncProxy.cpp b/messaging/old/DBus/SyncProxy.cpp
deleted file mode 100644 (file)
index 9e12d41..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        SyncProxy.cpp
- */
-
-#include "SyncProxy.h"
-#include <Logger.h>
-#include <PlatformException.h>
-#include <cstring>
-#include <email-types.h>
-#include "MessageService.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-SyncProxy::SyncProxy(const std::string& path,
-        const std::string& iface) :
-        EmailSignalProxy(path, iface)
-{
-
-}
-
-SyncProxy::~SyncProxy()
-{
-
-}
-
-void SyncProxy::addCallback(long op_id, Common::CallbackUserData* callbackOwned)
-{
-    m_callback_map.insert(std::make_pair(op_id, callbackOwned));
-}
-
-Common::CallbackUserData* SyncProxy::getCallback(long op_id)
-{
-    Common::CallbackUserData* cb = NULL;
-    CallbackMap::iterator it = m_callback_map.find(op_id);
-    if (it != m_callback_map.end()) {
-        cb = it->second;
-        return cb;
-    }
-    LOGE("Could not find callback");
-    throw Common::UnknownException("Could not find callback");
-    return cb;
-}
-
-void SyncProxy::removeCallback(long op_id){
-    CallbackMap::iterator it = m_callback_map.find(op_id);
-    if (it != m_callback_map.end()) {
-        Common::CallbackUserData* cb = it->second;
-        delete cb;
-        cb = NULL;
-        m_callback_map.erase(it);
-    }
-    else {
-        LOGE("Could not find callback");
-        throw Common::UnknownException("Could not find callback");
-    }
-}
-
-void SyncProxy::handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code)
-{
-    if( NOTI_DOWNLOAD_START != status &&
-            NOTI_DOWNLOAD_FINISH != status &&
-            NOTI_DOWNLOAD_FAIL != status ) {
-        // Nothing to do: this status is not related to sync nor syncFolder request
-        return;
-    }
-
-    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
-            "source: %s\n  op_handle: %d\n  error_code: %d",
-            status, mail_id, source.c_str(), op_handle, error_code);
-
-    if (NOTI_DOWNLOAD_START == status) {
-        LOGD("Sync started...");
-        // There is nothing more to do so we can return now.
-        return;
-    }
-
-    Common::CallbackUserData* callback = NULL;
-    CallbackMap::iterator callback_it;
-
-    try {
-        callback_it =  findSyncCallbackByOpHandle(op_handle);
-        callback = callback_it->second;
-        if (!callback) {
-            LOGE("Callback is null");
-            throw Common::UnknownException("Callback is null");
-        }
-
-        switch (status) {
-            case NOTI_DOWNLOAD_FINISH:
-                LOGD("Sync finished!");
-                callback->callSuccessCallback();
-                break;
-
-            case NOTI_DOWNLOAD_FAIL:
-                LOGD("Sync failed!");
-                callback->callErrorCallback();
-                break;
-
-            default:
-                break;
-        }
-    }
-    catch (const Common::BasePlatformException& e) {
-        // this situation may occur when there is no callback in the
-        // map with specified opId (for example stopSync() has
-        // removed it), but sync() was already started - only
-        // warning here:
-        LOGE("Exception in signal callback");
-    }
-    catch(...)
-    {
-        LOGE("Exception in signal callback");
-    }
-
-    if(callback) {
-        delete callback;
-        m_callback_map.erase(callback_it);
-    }
-}
-
-SyncProxy::CallbackMap::iterator SyncProxy::findSyncCallbackByOpHandle(
-        const int op_handle)
-{
-    CallbackMap::iterator it = m_callback_map.begin();
-    for (; it != m_callback_map.end(); ++it) {
-        SyncCallbackData* cb = dynamic_cast<SyncCallbackData*>(it->second);
-        if (!cb) continue;
-
-        if (op_handle == cb->getOperationHandle()) {
-            return it;
-        }
-    }
-    // this situation may occur when there is no callback in the
-    // map with specified opId (for example stopSync() has
-    // removed it), but sync() was already started - only
-    // warning here:
-    LOGW("Could not find callback with op_handle: %d", op_handle);
-    throw Common::UnknownException("Could not find callback");
-}
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
diff --git a/messaging/old/DBus/SyncProxy.h b/messaging/old/DBus/SyncProxy.h
deleted file mode 100644 (file)
index 4953ff3..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        SyncProxy.h
- */
-
-#ifndef __TIZEN_DBUS_SYNC_PROXY_H__
-#define __TIZEN_DBUS_SYNC_PROXY_H__
-
-#include "EmailSignalProxy.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-namespace DBus {
-
-class SyncProxy;
-typedef std::shared_ptr<SyncProxy> SyncProxyPtr;
-
-class SyncProxy : public EmailSignalProxy {
-public:
-
-    // Callback is owned by this map
-    typedef std::map<long, Common::CallbackUserData*> CallbackMap;
-
-    SyncProxy(const std::string& path,
-            const std::string& iface);
-    virtual ~SyncProxy();
-
-    //Passed callback will be owned by this proxy
-    void addCallback(long op_id, Common::CallbackUserData* callbackOwned);
-    Common::CallbackUserData* getCallback(long op_id);
-    void removeCallback(long op_id);
-
-protected:
-    virtual void handleEmailSignal(const int status,
-            const int mail_id,
-            const std::string& source,
-            const int op_handle,
-            const int error_code);
-
-private:
-    /**
-     * Find callback by operation handle returned from:
-     *  int email_sync_header(..., int *handle);
-     */
-    CallbackMap::iterator findSyncCallbackByOpHandle(const int op_handle);
-
-    CallbackMap m_callback_map;
-};
-
-} //namespace DBus
-} //namespace Messaging
-} //namespace DeviceAPI
-
-#endif // __TIZEN_DBUS_SYNC_PROXY_H__
diff --git a/messaging/old/EmailManager.cpp b/messaging/old/EmailManager.cpp
deleted file mode 100644 (file)
index 0204522..0000000
+++ /dev/null
@@ -1,1408 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file: EmailManager.cpp
- */
-
-#include <JSWebAPIErrorFactory.h>
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-#include <memory>
-#include <PlatformException.h>
-#include <sstream>
-#include <GlobalContextManager.h>
-
-#include <AbstractFilter.h>
-
-#include <email-api-network.h>
-#include <email-api-account.h>
-#include <email-api-mail.h>
-#include <email-api-mailbox.h>
-
-#include "EmailManager.h"
-#include "MessagingUtil.h"
-#include "MessageService.h"
-#include "Message.h"
-#include "MessageConversation.h"
-#include "MessageCallbackUserData.h"
-#include "MessagesCallbackUserData.h"
-#include "FindMsgCallbackUserData.h"
-#include "ConversationCallbackData.h"
-#include "MessageEmail.h"
-#include "MessagingDatabaseManager.h"
-
-#include "JSMessage.h"
-#include "JSMessageConversation.h"
-#include "JSMessageFolder.h"
-
-#include <email-api.h>
-#include <vconf.h>
-
-#include "DBus/SyncProxy.h"
-#include "DBus/LoadBodyProxy.h"
-#include "DBus/LoadAttachmentProxy.h"
-
-#include <sstream>
-#include <FilterIterator.h>
-
-using namespace DeviceAPI::Common;
-using namespace DeviceAPI::Tizen;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const int ACCOUNT_ID_NOT_INITIALIZED = -1;
-const std::string FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME  = "serviceId";
-} //anonymous namespace
-
-EmailManager& EmailManager::getInstance()
-{
-    LOGD("Entered");
-
-    static EmailManager instance;
-    return instance;
-}
-
-EmailManager::EmailManager()
-{
-    LOGD("Entered");
-    getUniqueOpId();
-    const int non_err = EMAIL_ERROR_NONE;
-
-    if(non_err != email_service_begin()){
-        LOGE("Email service failed to begin");
-        throw Common::UnknownException("Email service failed to begin");
-    }
-    if(non_err != email_open_db()){
-        LOGE("Email DB failed to open");
-        throw Common::UnknownException("Email DB failed to open");
-    }
-
-    int slot_size = -1;
-    vconf_get_int("db/private/email-service/slot_size", &(slot_size));
-    if (slot_size > 0) {
-        m_slot_size = slot_size;
-    }
-
-    m_proxy_sync = std::make_shared<DBus::SyncProxy>(
-                                      DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
-                                      DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
-    if (!m_proxy_sync) {
-        LOGE("Sync proxy is null");
-        throw Common::UnknownException("Sync proxy is null");
-    }
-    m_proxy_sync->signalSubscribe();
-
-    m_proxy_load_body = std::make_shared<DBus::LoadBodyProxy>(
-                                        DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
-                                        DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
-    if (!m_proxy_load_body) {
-        LOGE("Load body proxy is null");
-        throw Common::UnknownException("Load body proxy is null");
-    }
-    m_proxy_load_body->signalSubscribe();
-
-    m_proxy_load_attachment = std::make_shared<DBus::LoadAttachmentProxy>(
-                                        DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
-                                        DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
-    if (!m_proxy_load_attachment) {
-        LOGE("Load attachment proxy is null");
-        throw Common::UnknownException("Load attachment proxy is null");
-    }
-    m_proxy_load_attachment->signalSubscribe();
-
-    m_proxy_messageStorage = std::make_shared<DBus::MessageProxy>();
-    if (!m_proxy_messageStorage) {
-        LOGE("Message proxy is null");
-        throw Common::UnknownException("Message proxy is null");
-    }
-    m_proxy_messageStorage->signalSubscribe();
-
-    m_proxy_send = std::make_shared<DBus::SendProxy>();
-    if (!m_proxy_send) {
-        LOGE("Send proxy is null");
-        throw Common::UnknownException("Send proxy is null");
-    }
-    m_proxy_send->signalSubscribe();
-}
-
-EmailManager::~EmailManager()
-{
-    LOGD("Entered");
-}
-
-void EmailManager::addDraftMessagePlatform(int account_id,
-    std::shared_ptr<Message> message)
-{
-    addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_DRAFT);
-}
-
-void EmailManager::addOutboxMessagePlatform(int account_id,
-    std::shared_ptr<Message> message)
-{
-    addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_OUTBOX);
-}
-
-void EmailManager::addMessagePlatform(int account_id,
-    std::shared_ptr<Message> message, email_mailbox_type_e mailbox_type)
-{
-    email_mail_data_t* mail_data = NULL;
-    email_mail_data_t* mail_data_final = NULL;
-    int err = EMAIL_ERROR_NONE;
-
-    mail_data = Message::convertPlatformEmail(message);
-
-    mail_data->account_id = account_id;
-
-    //Adding "from" email address
-    email_account_t* account = NULL;
-    err = email_get_account(account_id, EMAIL_ACC_GET_OPT_FULL_DATA, &account);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("email_get_account failed. [%d]\n",err);
-        err = email_free_mail_data(&mail_data,1);
-        if(EMAIL_ERROR_NONE != err) {
-            LOGE("Failed to free mail data memory");
-        }
-        throw UnknownException("Cannot retrieve email account information");
-    }
-    LOGE("FROM %s", account->user_email_address);
-    std::stringstream ss;
-    ss << "<" << account->user_email_address << ">";
-    std::string address_from;
-    ss >> address_from;
-    mail_data->full_address_from = strdup(address_from.c_str());
-    LOGE("FROM %s", mail_data->full_address_from);
-    err = email_free_account(&account,1);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to free account data memory");
-    }
-    //Setting mailbox id
-    email_mailbox_t *mailbox_data = NULL;
-    err = email_get_mailbox_by_mailbox_type(account_id, mailbox_type,
-            &mailbox_data);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGD("email_get_mailbox_by_mailbox_type failed. [%d]\n",err);
-        err = email_free_mail_data(&mail_data,1);
-        if(EMAIL_ERROR_NONE != err) {
-            LOGE("Failed to free mail data memory");
-        }
-        throw UnknownException("Cannot retrieve draft mailbox");
-    }
-    else {
-        LOGD("email_get_mailbox_by_mailbox_type success.\n");
-        mail_data->mailbox_id = mailbox_data->mailbox_id;
-        mail_data->mailbox_type = mailbox_data->mailbox_type;
-    }
-
-    mail_data->report_status = EMAIL_MAIL_REPORT_NONE;
-    mail_data->save_status = EMAIL_MAIL_STATUS_SAVED;
-    mail_data->flags_draft_field = 1;
-
-    //adding email without attachments
-    err = email_add_mail(mail_data, NULL, 0, NULL, 0);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGD("email_add_mail failed. [%d]\n",err);
-        err = email_free_mail_data(&mail_data,1);
-        if(EMAIL_ERROR_NONE != err) {
-            LOGE("Failed to free mail data memory");
-        }
-        err = email_free_mailbox(&mailbox_data, 1);
-        if (EMAIL_ERROR_NONE != err) {
-            LOGE("Failed to destroy mailbox");
-        }
-        throw UnknownException("Couldn't add message to draft mailbox");
-    }
-    else {
-        LOGD("email_add_mail success.\n");
-    }
-
-    LOGD("saved mail without attachments id = [%d]\n", mail_data->mail_id);
-
-    message->setId(mail_data->mail_id);
-    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
-
-    //Adding attachments
-    if (message->getHasAttachment()){
-        Message::addEmailAttachments(message);
-    }
-
-    err = email_get_mail_data(message->getId(), &mail_data_final);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to retrieve added mail data");
-        throw UnknownException("Couldn't retrieve added mail data");
-    }
-
-    message->updateEmailMessage(*mail_data_final);
-
-    err = email_free_mail_data(&mail_data_final,1);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to free mail data final memory");
-    }
-
-    err = email_free_mail_data(&mail_data,1);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to free mail data memory");
-    }
-
-    err = email_free_mailbox(&mailbox_data, 1);
-    if (EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to destroy mailbox");
-    }
-}
-
-static gboolean addDraftMessageCompleteCB(void *data)
-{
-    MessageCallbackUserData* callback =
-        static_cast<MessageCallbackUserData *>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        return false;
-    }
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return false;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, err);
-        callback->callErrorCallback(errobj);
-    } catch (...) {
-        LOGE("Message add draft failed");
-        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
-        callback->callErrorCallback(errobj);
-    }
-
-    delete callback;
-    callback = NULL;
-
-    return false;
-}
-
-void EmailManager::addDraftMessage(MessageCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::shared_ptr<Message> message = callback->getMessage();
-        addDraftMessagePlatform(callback->getAccountId(), message);
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Message add draft failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
-    }
-
-    //Complete task
-    if (!g_idle_add(addDraftMessageCompleteCB, static_cast<void *>(callback))) {
-        LOGE("g_idle addition failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-
-//**** sending email ****
-static gboolean sendEmailCompleteCB(void* data)
-{
-    LOGD("Entered");
-
-    MessageRecipientsCallbackData* callback =
-            static_cast<MessageRecipientsCallbackData*>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        return false;
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return false;
-    }
-
-    try {
-        if (callback->isError()) {
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
-        }
-        else {
-            std::shared_ptr<Message> message = callback->getMessage();
-            callback->callSuccessCallback(
-                    JSUtil::toJSValueRef(context, message->getTO()));
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT);
-        }
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error when calling send message callback");
-    }
-
-    delete callback;
-    callback = NULL;
-
-    return false;
-}
-
-void EmailManager::sendMessage(MessageRecipientsCallbackData* callback)
-{
-    LOGD("Entered");
-    int err = EMAIL_ERROR_NONE;
-    email_mail_data_t *mail_data = NULL;
-
-    try{
-        if(!callback){
-            LOGE("Callback is null");
-            throw UnknownException("Callback is null");
-        }
-
-        std::shared_ptr<Message> message = callback->getMessage();
-        if(!message) {
-            LOGE("Message is null");
-            throw UnknownException("Message is null");
-        }
-
-        if(!(message->is_id_set())) {
-            addOutboxMessagePlatform(callback->getAccountId(),message);
-        }
-
-        err = email_get_mail_data(message->getId(),&mail_data);
-        if(EMAIL_ERROR_NONE != err) {
-            LOGE("email_get_mail_data failed. [%d]\n",err);
-            throw UnknownException("Failed to get platform email structure");
-        }
-
-        LOGD("email_get_mail_data success.\n");
-
-        //Sending EMAIL
-        mail_data->save_status = EMAIL_MAIL_STATUS_SENDING;
-
-        int req_id = 0;
-        err = email_send_mail(mail_data->mail_id, &req_id);
-        if (EMAIL_ERROR_NONE != err) {
-            LOGE("Failed to send message %d", err);
-            throw UnknownException("Failed to send message");
-        }
-        LOGD("req_id: %d", req_id);
-        callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENDING);
-        m_sendRequests[req_id] = callback;
-
-    } catch (const BasePlatformException& ex) {
-         LOGE("%s (%s)", (ex.getName()).c_str(), (ex.getMessage()).c_str());
-         callback->setError(ex.getName(), ex.getMessage());
-         if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
-             LOGE("g_idle addition failed");
-             delete callback;
-             callback = NULL;
-         }
-    }catch (...) {
-        LOGE("Message send failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message send failed");
-        if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
-            LOGE("g_idle addition failed");
-            delete callback;
-            callback = NULL;
-        }
-    }
-
-    err = email_free_mail_data(&mail_data,1);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Failed to free mail data memory");
-    }
-
-    return;
-}
-
-void EmailManager::sendStatusCallback(int mail_id,
-        email_noti_on_network_event status,
-        int error_code)
-{
-    LOGD("Enter");
-
-    std::lock_guard<std::mutex> lock(m_mutex);
-    //find first request for this mail_id
-    SendReqMapIterator it = getSendRequest(mail_id);
-    if (it != m_sendRequests.end()) {
-        LOGD("Found request");
-        MessageRecipientsCallbackData* callback = it->second;
-        m_sendRequests.erase(it);
-
-        if (NOTI_SEND_FAIL == status) {
-            LOGD("Failed to send message, set proper error");
-            switch (error_code) {
-                case EMAIL_ERROR_NO_SIM_INSERTED:
-                case EMAIL_ERROR_SOCKET_FAILURE:
-                case EMAIL_ERROR_CONNECTION_FAILURE:
-                case EMAIL_ERROR_CONNECTION_BROKEN:
-                case EMAIL_ERROR_NO_SUCH_HOST:
-                case EMAIL_ERROR_NETWORK_NOT_AVAILABLE:
-                case EMAIL_ERROR_INVALID_STREAM:
-                case EMAIL_ERROR_NO_RESPONSE:
-                    LOGE("Network error %d", error_code);
-                    callback->setError(JSWebAPIErrorFactory::NETWORK_ERROR,
-                            "Failed to send message");
-                    break;
-                default:
-                    LOGE("Unknown error %d", error_code);
-                    callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                            "Failed to send message");
-            }
-        } else if (NOTI_SEND_FINISH == status) {
-            LOGD("Message sent successfully");
-        }
-
-        if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
-            LOGE("g_idle addition failed");
-            delete callback;
-            callback = NULL;
-        }
-    } else {
-        LOGW("No matching request found");
-    }
-}
-
-email_mail_data_t* EmailManager::loadMessage(int msg_id)
-{
-    email_mail_data_t* mail_data = NULL;
-    int err = EMAIL_ERROR_NONE;
-    err = email_get_mail_data(msg_id, &mail_data);
-    if (EMAIL_ERROR_NONE != err) {
-        LOGE("email_get_mail_data failed. [%d]", err);
-    } else {
-        LOGD("email_get_mail_data success.");
-    }
-    return mail_data;
-}
-
-EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id)
-{
-    for (auto it = m_sendRequests.begin(); it != m_sendRequests.end(); it++) {
-        if (it->second->getMessage()->getId() == mail_id) {
-            return it;
-        }
-    }
-    return m_sendRequests.end();
-}
-
-void EmailManager::freeMessage(email_mail_data_t* mail_data)
-{
-    if(!mail_data) {
-        return;
-    }
-
-    int err = email_free_mail_data(&mail_data,1);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Could not free mail data!");
-    }
-}
-
-void EmailManager::loadMessageBody(MessageBodyCallbackData* callback)
-{
-    LOGD("Entered");
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    if(!callback->getMessage()) {
-        LOGE("Callback's message is null");
-        return;
-    }
-
-    m_proxy_load_body->addCallback(callback);
-
-    const int mailId = callback->getMessage()->getId();
-    int err = EMAIL_ERROR_NONE;
-
-    int op_handle = -1;
-    err = email_download_body(mailId, 0, &op_handle);
-    if(EMAIL_ERROR_NONE != err){
-        LOGE("Email download body failed, %d", err);
-        m_proxy_load_body->removeCallback(callback);
-        return;
-    }
-    callback->setOperationHandle(op_handle);
-}
-
-void EmailManager::loadMessageAttachment(MessageAttachmentCallbackData* callback)
-{
-    LOGD("Entered");
-    if(!callback) {
-        LOGE("Callback is null");
-        throw Common::InvalidValuesException("Callback is null");
-    }
-    if(!callback->getMessageAttachment()) {
-        LOGE("Callback's message attachment is null");
-        throw Common::InvalidValuesException("Callback's message attachment is null");
-    }
-
-    std::shared_ptr<MessageAttachment> msgAttachment = callback->getMessageAttachment();
-    LOGD("attachmentId:%d mailId:%d", msgAttachment->getId(),
-            msgAttachment->getMessageId());
-
-    struct ScopedEmailMailData {
-        ScopedEmailMailData() : data(NULL) { }
-        ~ScopedEmailMailData() { EmailManager::freeMessage(data); }
-        email_mail_data_t* data;
-    } mail_data_holder;
-
-    mail_data_holder.data = EmailManager::loadMessage(msgAttachment->getMessageId());
-    if(!mail_data_holder.data) {
-        std::stringstream err_ss;
-        err_ss << "Couldn't get email_mail_data_t for messageId:"
-                << msgAttachment->getMessageId();
-        LOGE("%s",err_ss.str().c_str());
-        throw Common::UnknownException(err_ss.str().c_str());
-    }
-
-    AttachmentPtrVector attachments = Message::convertEmailToMessageAttachment(
-            *mail_data_holder.data);
-    LOGD("Mail:%d contain:%d attachments", msgAttachment->getMessageId(),
-        attachments.size());
-
-    AttachmentPtrVector::iterator it = attachments.begin();
-    int attachmentIndex = -1;
-    for(int i = 0; it != attachments.end(); ++i, ++it) {
-        if((*it)->getId() == msgAttachment->getId()) {
-            attachmentIndex = i;
-            break;
-        }
-    }
-
-    if(attachmentIndex < 0) {
-        std::stringstream err_ss;
-        err_ss << "Attachment with id:" << msgAttachment->getId() << "not found";
-        LOGE("%s",err_ss.str().c_str());
-        throw Common::UnknownException(err_ss.str().c_str());
-    }
-
-    LOGD("Attachment with id:%d is located at index:%d", msgAttachment->getId(),
-            attachmentIndex);
-
-    int op_handle = -1;
-    const int nth = attachmentIndex + 1; //in documentation: the minimum number is "1"
-    callback->setNth(nth);
-
-    int err = email_download_attachment(msgAttachment->getMessageId(), nth, &op_handle);
-    if (EMAIL_ERROR_NONE != err) {
-        std::stringstream err_ss;
-        err_ss << "Download email attachment failed with error: " << err;
-        LOGE("%s",err_ss.str().c_str());
-        throw Common::UnknownException(err_ss.str().c_str());
-    } else  {
-        LOGD("email_download_attachment returned handle:%d",op_handle);
-        callback->setOperationHandle(op_handle);
-        m_proxy_load_attachment->addCallback(callback);
-    }
-}
-//#################################### sync: ###################################
-
-void EmailManager::sync(void* data)
-{
-    LOGD("Entered");
-    SyncCallbackData* callback = static_cast<SyncCallbackData*>(data);
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-    long op_id = callback->getOpId();
-    m_proxy_sync->addCallback(op_id, callback);
-
-    int err = EMAIL_ERROR_NONE;
-    int limit = callback->getLimit();
-    int slot_size = -1;
-    int account_id = callback->getAccountId();
-
-    if (limit < 0) {
-        slot_size = m_slot_size;
-    }
-    else {
-        slot_size = limit;
-    }
-
-    err = email_set_mail_slot_size(0, 0, slot_size);
-    if(EMAIL_ERROR_NONE != err){
-        LOGE("Email set slot size failed, %d", err);
-        m_proxy_sync->removeCallback(op_id);
-        return;
-    }
-
-    int op_handle = -1;
-    err = email_sync_header(account_id, 0, &op_handle);
-    if(EMAIL_ERROR_NONE != err){
-        LOGE("Email sync header failed, %d", err);
-        m_proxy_sync->removeCallback(op_id);
-    }
-    callback->setOperationHandle(op_handle);
-}
-
-//#################################### ^sync ###################################
-
-//################################## syncFolder: ###############################
-
-void EmailManager::syncFolder(SyncFolderCallbackData* callback)
-{
-    LOGD("Entered");
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    const long op_id = callback->getOpId();
-    m_proxy_sync->addCallback(op_id, callback);
-
-    if(!callback->getMessageFolder())
-    {
-        LOGE("Callback's messageFolder is null");
-        m_proxy_sync->removeCallback(op_id);
-        return;
-    }
-
-    int err = EMAIL_ERROR_NONE;
-
-    email_mailbox_t* mailbox = NULL;
-
-    const std::string folder_id_str = callback->getMessageFolder()->getId();
-    int folder_id = 0;
-    std::istringstream(folder_id_str) >> folder_id;
-
-    err = email_get_mailbox_by_mailbox_id(folder_id, &mailbox);
-    if (EMAIL_ERROR_NONE != err || NULL == mailbox) {
-        LOGE("Couldn't get mailbox, error code: %d", err);
-        m_proxy_sync->removeCallback(op_id);
-        return;
-    }
-
-    try {
-        const int limit = callback->getLimit();
-        int slot_size = -1;
-
-        if (limit < 0) {
-            slot_size = m_slot_size;
-        }
-        else {
-            slot_size = limit;
-        }
-
-        err = email_set_mail_slot_size(0, 0, slot_size);
-        if(EMAIL_ERROR_NONE != err){
-            LOGE("Email set slot size failed, %d", err);
-            throw UnknownException("Email set slot size failed");
-        }
-
-        int op_handle = -1;
-        const int account_id = callback->getAccountId();
-        err = email_sync_header(account_id, mailbox->mailbox_id, &op_handle);
-        if(EMAIL_ERROR_NONE != err) {
-            LOGE("Email sync header failed, %d", err);
-            m_proxy_sync->removeCallback(op_id);
-            throw UnknownException("Email sync header failed");
-        }
-        callback->setOperationHandle(op_handle);
-    }
-    catch (const BasePlatformException& e) {
-        LOGE("Exception in syncFolder");
-    }
-
-    if (NULL != mailbox)
-    {
-        err = email_free_mailbox(&mailbox , 1);
-        if  (EMAIL_ERROR_NONE !=  err) {
-            LOGD("Failed to email_free_mailbox - err:%d ", err);
-        }
-        mailbox = NULL;
-    }
-}
-
-//#################################### ^syncFolder #############################
-
-//################################## stopSync: #################################
-
-void EmailManager::stopSync(long op_id)
-{
-    LOGD("Entered");
-    SyncCallbackData* callback = NULL;
-    try {
-        callback = dynamic_cast<SyncCallbackData*>(
-                m_proxy_sync->getCallback(op_id));
-    }
-    catch (const BasePlatformException& e) {
-        LOGE("Could not get callback");
-    }
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int err = EMAIL_ERROR_NONE;
-    err = email_cancel_job(callback->getAccountId(), callback->getOperationHandle(),
-            EMAIL_CANCELED_BY_USER);
-    if(EMAIL_ERROR_NONE != err){
-        LOGE("Email cancel job failed, %d", err);
-    }
-    JSObjectRef err_obj =
-            JSWebAPIErrorFactory::makeErrorObject(callback->getContext(),
-                    JSWebAPIErrorFactory::ABORT_ERROR,
-                    "Sync aborted by user");
-    callback->callErrorCallback(err_obj);
-    m_proxy_sync->removeCallback(op_id);
-}
-
-//################################## ^stopSync #################################
-
-void removeEmailCompleteCB(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-    if (!callback) {
-        LOGE("Callback is null");
-        return;
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling removeEmail callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling removeEmail callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-EmailManager::DeleteReqVector::iterator EmailManager::getDeleteRequest(
-        const std::vector<int> &ids)
-{
-    for (auto idIt = ids.begin(); idIt != ids.end(); ++idIt) {
-        for (auto reqIt = m_deleteRequests.begin(); reqIt != m_deleteRequests.end(); ++reqIt) {
-            MessagePtrVector msgs = reqIt->callback->getMessages();
-            for (auto msgIt = msgs.begin(); msgIt != msgs.end(); ++msgIt) {
-                if ((*msgIt)->getId() == *idIt) {
-                    return reqIt;
-                }
-            }
-        }
-    }
-    return m_deleteRequests.end();
-}
-
-void EmailManager::removeStatusCallback(const std::vector<int> &ids,
-            email_noti_on_storage_event status)
-{
-    LOGD("Enter");
-    std::lock_guard<std::mutex> lock(m_mutex);
-    DeleteReqVector::iterator it = getDeleteRequest(ids);
-    if (it != m_deleteRequests.end()) {
-        LOGD("Found request");
-        if (NOTI_MAIL_DELETE_FINISH == status) {
-            LOGD("Successfully removed %d mails", ids.size());
-            it->messagesDeleted += ids.size();
-        }
-        MessagesCallbackUserData* callback = it->callback;
-        if (NOTI_MAIL_DELETE_FAIL == status) {
-            LOGD("Failed to remove mail");
-            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
-        }
-        //if one of mails failed, call error callback
-        //if all mails are deleted, call success.
-        // >= is used in case of duplicated dbus messages
-        if (NOTI_MAIL_DELETE_FAIL == status ||
-                static_cast<unsigned int>(it->messagesDeleted) >= it->callback->getMessages().size()) {
-            LOGD("Calling callback");
-            m_deleteRequests.erase(it);
-            m_mutex.unlock();
-            removeEmailCompleteCB(callback);
-        } else {
-            LOGD("Not all messages are removed, waiting for next callback");
-        }
-    } else {
-        LOGD("Request not found, ignoring");
-    }
-}
-
-void EmailManager::removeMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int error;
-    email_mail_data_t *mail = NULL;
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
-        MessageType type = callback->getMessageServiceType();
-        for(auto it = messages.begin() ; it != messages.end(); ++it) {
-            if((*it)->getType() != type) {
-                LOGE("Invalid message type");
-                throw TypeMismatchException("Error while deleting email");
-            }
-        }
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-            error = email_get_mail_data((*it)->getId(), &mail);
-            if (EMAIL_ERROR_NONE != error) {
-                LOGE("Couldn't retrieve mail data");
-                throw UnknownException("Error while deleting mail");
-            }
-
-            //This task (_EMAIL_API_DELETE_MAIL) is for async
-            error = email_delete_mail(mail->mailbox_id, &mail->mail_id, 1, 0);
-            if (EMAIL_ERROR_NONE != error) {
-                email_free_mail_data(&mail, 1);
-                LOGE("Error while deleting mail");
-                throw UnknownException("Error while deleting mail");
-            }
-            email_free_mail_data(&mail, 1);
-        }
-        //store delete request and wait for dbus response
-        DeleteReq request;
-        request.callback = callback;
-        request.messagesDeleted = 0;
-        m_deleteRequests.push_back(request);
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-        removeEmailCompleteCB(callback);
-    } catch (...) {
-        LOGE("Messages remove failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
-        removeEmailCompleteCB(callback);
-    }
-}
-
-void EmailManager::updateMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int error;
-    email_mail_data_t *mail = NULL;
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
-        MessageType type = callback->getMessageServiceType();
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-            if ((*it)->getType() != type) {
-                LOGE("Invalid message type");
-                throw TypeMismatchException("Error while updating message");
-            }
-        }
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-
-            mail = Message::convertPlatformEmail((*it));
-
-            if((*it)->getHasAttachment())
-            {
-                LOGD("Message has attachments. Workaround need to be used.");
-                //Update of mail on server using function email_update_mail() is not possible.
-                //Attachment is updated only locally (can't be later loaded from server),
-                //so use of workaround is needed:
-                //1. add new mail
-                //2. delete old mail
-
-                //adding message again after changes
-                addDraftMessagePlatform(mail->account_id, (*it));
-                LOGD("mail added - new id = [%d]\n", (*it)->getId());
-
-                //deleting old mail
-                LOGD("mail deleted = [%d]\n", mail->mail_id);
-                error = email_delete_mail(mail->mailbox_id,&mail->mail_id,1,1);
-                if (EMAIL_ERROR_NONE != error) {
-                    email_free_mail_data(&mail, 1);
-                    LOGE("Error while deleting old mail on update: %d", error);
-                    throw Common::UnknownException("Error while deleting old mail on update");
-                }
-            } else {
-                LOGD("There are no attachments, updating only email data.");
-                error = email_update_mail(mail, NULL, 0, NULL, 0);
-                if (EMAIL_ERROR_NONE != error) {
-                    email_free_mail_data(&mail, 1);
-                    LOGE("Error while updating mail");
-                    throw UnknownException("Error while updating mail");
-                }
-            }
-
-            email_free_mail_data(&mail, 1);
-        }
-
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages update failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages update failed");
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling updateEmail callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling updateEmail callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-
-void EmailManager::findMessages(FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    email_mail_data_t* mailList = NULL;
-    int mailListCount = 0;
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::pair<int, email_mail_data_t*> emails =
-                MessagingDatabaseManager::getInstance().findEmails(callback);
-        mailListCount = emails.first;
-        LOGD("Found %d mails", mailListCount);
-
-        mailList = emails.second;
-        email_mail_data_t* nth_email = mailList;
-
-        for (int i = 0; i < mailListCount; ++i) {
-            std::shared_ptr<Message> email =
-                    Message::convertPlatformEmailToObject(*nth_email);
-            callback->addMessage(email);
-            nth_email++;
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Message find failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message find failed");
-    }
-
-    if (mailListCount > 0 && mailList != NULL) {
-        if (EMAIL_ERROR_NONE != email_free_mail_data(&mailList, mailListCount)) {
-            LOGW("Failed to free mailList");
-        }
-    }
-
-    //Complete task
-    LOGD("callback: %p error:%d messages.size()=%d", callback, callback->isError(),
-            callback->getMessages().size());
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback(JSMessage::messageVectorToJSObjectArray(context,
-                    callback->getMessages()));
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling findMessages callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Failed to call findMessages callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-void EmailManager::findConversations(ConversationCallbackData* callback)
-{
-    LOGE("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int convListCount = 0;
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<EmailConversationInfo> conversationsInfo =
-                MessagingDatabaseManager::getInstance().findEmailConversations(callback);
-        convListCount = conversationsInfo.size();
-        LOGD("Found %d conversations", convListCount);
-
-        for (int i = 0; i < convListCount; ++i) {
-            std::shared_ptr<MessageConversation> conversation =
-                    MessageConversation::convertEmailConversationToObject(conversationsInfo.at(i).id);
-            conversation->setUnreadMessages(conversationsInfo.at(i).unreadMessages);
-            callback->addConversation(conversation);
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Conversation find failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Conversation find failed");
-    }
-
-    //Complete task
-    LOGD("callback: %p error:%d conversations.size()=%d", callback, callback->isError(),
-            callback->getConversations().size());
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback(
-                    MessagingUtil::vectorToJSObjectArray<ConversationPtr,
-                    JSMessageConversation>(context,
-                            callback->getConversations()));
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling findConversations callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Failed to call findConversations callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-long EmailManager::getUniqueOpId()
-{
-    // mutex is created only on first call (first call added to constructor
-    // to initialize mutex correctly)
-    static std::mutex op_id_mutex;
-    std::lock_guard<std::mutex> lock(op_id_mutex);
-    static long op_id = 0;
-    return op_id++;
-}
-
-void EmailManager::findFolders(FoldersCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int ret = EMAIL_ERROR_UNKNOWN;
-    int account_id = ACCOUNT_ID_NOT_INITIALIZED;
-    email_mailbox_t* mailboxes = NULL;
-    email_mailbox_t* nth_mailbox = NULL;
-    int mailboxes_count;
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-
-        Tizen::AbstractFilterPtr filter = callback->getFilter();
-        if (!filter) {
-            LOGE("Filter not provided");
-            throw UnknownException("Filter not provided");
-        }
-
-        for(FilterIterator it(filter); false == it.isEnd(); it++) {
-
-            if(FIS_COMPOSITE_START == it.getState()) {
-                CompositeFilterPtr cf = castToCompositeFilter((*it));
-                if(cf && INTERSECTION != cf->getType()) {
-                    LOGE("[ERROR] >>> invalid Filter type: %d", cf->getType());
-                    throw TypeMismatchException("Invalid Filter Type");
-                }
-            }
-            else if(FIS_ATTRIBUTE_FILTER == it.getState()) {
-                AttributeFilterPtr attrf = castToAttributeFilter((*it));
-                if(attrf) {
-                    const std::string attr_name = attrf->getAttributeName();
-                    if (FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME == attr_name) {
-                        account_id = static_cast<int>(attrf->getMatchValue()->toLong());
-                    } else {
-                        LOGE("The attribute name: %s is invalid", attr_name.c_str());
-                        throw InvalidValuesException("The attribute name is invalid");
-                    }
-                }
-            }
-        }
-
-        LOGD("Listing folders for account ID: %d", account_id);
-        if (account_id > 0) {
-            ret = email_get_mailbox_list(account_id,
-                    -1,
-                    &mailboxes,
-                    &mailboxes_count);
-            if (EMAIL_ERROR_NONE != ret || !mailboxes) {
-                LOGE("Cannot get folders: %d", ret);
-                throw Common::UnknownException(
-                        "Platform error, cannot get folders");
-            }
-
-            if (mailboxes_count <= 0) {
-                LOGD("Empty mailboxes");
-            }
-            else {
-                LOGD("Founded mailboxes: %d", mailboxes_count);
-
-                nth_mailbox = mailboxes;
-                for (int i = 0; i < mailboxes_count; ++i) {
-                    std::shared_ptr<MessageFolder> fd;
-                    fd = std::make_shared<MessageFolder>(*nth_mailbox);
-                    callback->addFolder(fd);
-                    nth_mailbox++;
-                }
-            }
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages update failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                "Messages update failed");
-    }
-
-    if (mailboxes != NULL) {
-        if (EMAIL_ERROR_NONE != email_free_mailbox(&mailboxes,
-                mailboxes_count)) {
-            LOGW("Free mailboxes failed: %d", ret);
-        }
-    }
-
-    //Complete task
-    LOGD("callback: %p error:%d folders.size()=%d", callback, callback->isError(),
-            callback->getFolders().size());
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,
-                    JSMessageFolder>(context, callback->getFolders());
-            callback->callSuccessCallback(js_obj);
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling findFolders callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling findFolders callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-void EmailManager::removeConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int error;
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<std::shared_ptr<MessageConversation>> conversations =
-                callback->getConversations();
-        MessageType type = callback->getMessageServiceType();
-
-        int thread_id = 0;
-        for(auto it = conversations.begin() ; it != conversations.end(); ++it) {
-            if((*it)->getType() != type) {
-                LOGE("Invalid message type");
-                throw TypeMismatchException("Error while deleting email conversation");
-            }
-        }
-
-        for (auto it = conversations.begin() ; it != conversations.end(); ++it) {
-            thread_id = (*it)->getConversationId();
-            error = email_delete_thread(thread_id, false);
-            if (EMAIL_ERROR_NONE != error) {
-                LOGE("Couldn't delete conversation data");
-                throw UnknownException("Error while deleting mail conversation");
-            }
-
-            // for now, there is no way to recognize deleting email thread job is completed.
-            // so use polling to wait the thread is removed.
-            email_mail_data_t *thread_info = NULL;
-            do {
-                usleep(300 * 1000);
-                LOGD("Waiting to delete this email thread...");
-                error = email_get_thread_information_by_thread_id(
-                    thread_id, &thread_info);
-
-                if (thread_info != NULL) {
-                    free(thread_info);
-                    thread_info = NULL;
-                }
-            } while (error != EMAIL_ERROR_MAIL_NOT_FOUND);
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages remove failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling removeConversations callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling removeConversations callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/EmailManager.h b/messaging/old/EmailManager.h
deleted file mode 100644 (file)
index 9513ce6..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file: EmailManager.h
- */
-
-#ifndef __TIZEN_EMAIL_MANAGER_H__
-#define __TIZEN_EMAIL_MANAGER_H__
-
-#include <glib.h>
-#include <mutex>
-#include <string>
-#include <map>
-#include <vector>
-
-#include "email-api-network.h"
-#include "email-api-account.h"
-#include "email-api-mail.h"
-#include "email-api-mailbox.h"
-
-#include <CallbackUserData.h>
-#include <PlatformException.h>
-
-#include "MessagingUtil.h"
-#include "MessageService.h"
-
-#include "DBus/Connection.h"
-#include "DBus/SyncProxy.h"
-#include "DBus/LoadBodyProxy.h"
-#include "DBus/LoadAttachmentProxy.h"
-#include "DBus/MessageProxy.h"
-#include "DBus/SendProxy.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-class MessageCallbackUserData;
-class FindMsgCallbackUserData;
-class SyncFolderCallbackData;
-
-class EmailManager {
-public:
-    static EmailManager& getInstance();
-
-    void addDraftMessage(MessageCallbackUserData* callback);
-    void removeMessages(MessagesCallbackUserData* callback);
-    void updateMessages(MessagesCallbackUserData* callback);
-    void findMessages(FindMsgCallbackUserData* callback);
-    void findConversations(ConversationCallbackData* callback);
-    void findFolders(FoldersCallbackData* callback);
-    void removeConversations(ConversationCallbackData* callback);
-
-    void sendMessage(MessageRecipientsCallbackData* callback);
-    void sendStatusCallback(int mail_id, email_noti_on_network_event status,
-            int error_code);
-    void removeStatusCallback(const std::vector<int> &ids,
-            email_noti_on_storage_event status);
-
-    void loadMessageBody(MessageBodyCallbackData* callback);
-    void loadMessageAttachment(MessageAttachmentCallbackData* callback);
-
-    void sync(void* data);
-    void syncFolder(SyncFolderCallbackData* callback);
-    void stopSync(long op_id);
-
-    void registerStatusCallback(msg_handle_t msg_handle);
-
-    /**
-     * Use freeMessage() to release returned email_mail_data_t object.
-     */
-    static email_mail_data_t* loadMessage(int msg_id);
-    static void freeMessage(email_mail_data_t*);
-
-    long getUniqueOpId();
-
-private:
-    EmailManager();
-    EmailManager(const EmailManager &);
-    void operator=(const EmailManager &);
-    virtual ~EmailManager();
-    void addDraftMessagePlatform(int account_id,
-        std::shared_ptr<Message> message);
-    void addOutboxMessagePlatform(int account_id,
-        std::shared_ptr<Message> message);
-    void addMessagePlatform(int account_id, std::shared_ptr<Message> message,
-        email_mailbox_type_e mailbox_type);
-
-    typedef std::map<int, MessageRecipientsCallbackData*> SendReqMap;
-    typedef SendReqMap::iterator SendReqMapIterator;
-    SendReqMapIterator getSendRequest(int mail_id);
-    SendReqMap m_sendRequests;
-    struct DeleteReq {
-        MessagesCallbackUserData* callback;
-        int messagesDeleted;
-    };
-    typedef std::vector<DeleteReq> DeleteReqVector;
-    /**
-     * Find first request containing at least one message id
-     * @param ids
-     * @return
-     */
-    DeleteReqVector::iterator getDeleteRequest(const std::vector<int> &ids);
-    DeleteReqVector m_deleteRequests;
-
-    int m_slot_size;
-
-    DBus::SyncProxyPtr m_proxy_sync;
-    DBus::LoadBodyProxyPtr m_proxy_load_body;
-    DBus::LoadAttachmentProxyPtr m_proxy_load_attachment;
-    DBus::MessageProxyPtr m_proxy_messageStorage;
-    DBus::SendProxyPtr m_proxy_send;
-
-    std::mutex m_mutex;
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_EMAIL_MANAGER_H__
diff --git a/messaging/old/FindMsgCallbackUserData.cpp b/messaging/old/FindMsgCallbackUserData.cpp
deleted file mode 100644 (file)
index ab296ff..0000000
+++ /dev/null
@@ -1,136 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file: FindMsgCallbackUserData.cpp
- */
-
-#include "FindMsgCallbackUserData.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-FindMsgCallbackUserData::FindMsgCallbackUserData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_limit(0),
-        m_offset(0),
-        m_is_error(false),
-        m_account_id(0),
-        m_service_type(UNDEFINED)
-{
-}
-
-FindMsgCallbackUserData::~FindMsgCallbackUserData()
-{
-}
-
-void FindMsgCallbackUserData::setFilter(Tizen::AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-void FindMsgCallbackUserData::setSortMode(Tizen::SortModePtr sortMode)
-{
-    m_sort = sortMode;
-}
-
-void FindMsgCallbackUserData::setLimit(long limit)
-{
-    m_limit = limit;
-}
-
-void FindMsgCallbackUserData::setOffset(long offset)
-{
-    m_offset = offset;
-}
-
-void FindMsgCallbackUserData::addMessage(std::shared_ptr<Message> msg)
-{
-    m_messages.push_back(msg);
-}
-
-std::vector<std::shared_ptr<Message>> FindMsgCallbackUserData::getMessages() const
-{
-    return m_messages;
-}
-
-void FindMsgCallbackUserData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool FindMsgCallbackUserData::isError() const
-{
-    return m_is_error;
-}
-
-std::string FindMsgCallbackUserData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string FindMsgCallbackUserData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void FindMsgCallbackUserData::setAccountId(int account_id){
-    m_account_id = account_id;
-}
-
-int FindMsgCallbackUserData::getAccountId() const
-{
-    return m_account_id;
-}
-
-void FindMsgCallbackUserData::setMessageServiceType(MessageType m_msg_type)
-{
-    m_service_type = m_msg_type;
-}
-
-MessageType FindMsgCallbackUserData::getMessageServiceType() const
-{
-    return m_service_type;
-}
-
-Tizen::AbstractFilterPtr FindMsgCallbackUserData::getFilter() const
-{
-    return m_filter;
-}
-
-Tizen::SortModePtr FindMsgCallbackUserData::getSortMode() const
-{
-    return m_sort;
-}
-
-long FindMsgCallbackUserData::getLimit() const
-{
-    return m_limit;
-}
-
-long FindMsgCallbackUserData::getOffset() const
-{
-    return m_offset;
-}
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/FindMsgCallbackUserData.h b/messaging/old/FindMsgCallbackUserData.h
deleted file mode 100644 (file)
index d434b74..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file: FindMsgCallbackUserData.h
- */
-
-#ifndef __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H
-#define __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H
-
-#include <CallbackUserData.h>
-#include <memory>
-#include <string>
-#include <vector>
-#include <AttributeFilter.h>
-#include <SortMode.h>
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-
-class FindMsgCallbackUserData: public Common::CallbackUserData {
-public:
-    FindMsgCallbackUserData(JSContextRef globalCtx);
-    virtual ~FindMsgCallbackUserData();
-
-    void setFilter(Tizen::AbstractFilterPtr filter);
-    void setSortMode(Tizen::SortModePtr sortMode);
-    void setLimit(long limit);
-    void setOffset(long offset);
-    void addMessage(std::shared_ptr<Message> msg);
-    std::vector<std::shared_ptr<Message>> getMessages() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void setAccountId(int account_id);
-    int getAccountId() const;
-
-    void setMessageServiceType(MessageType m_msg_type);
-    MessageType getMessageServiceType() const;
-    Tizen::AbstractFilterPtr getFilter() const;
-    Tizen::SortModePtr getSortMode() const;
-    long getLimit() const;
-    long getOffset() const;
-private:
-    //@TODO replace dpl shared_ptr when JSAttributeFilter is changed
-    Tizen::AbstractFilterPtr m_filter;
-    Tizen::SortModePtr m_sort;
-    long m_limit;
-    long m_offset;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    std::vector<std::shared_ptr<Message>> m_messages;
-    int m_account_id;
-    MessageType m_service_type;
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H */
diff --git a/messaging/old/FoldersCallbackData.cpp b/messaging/old/FoldersCallbackData.cpp
deleted file mode 100644 (file)
index 4f067ff..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "FoldersCallbackData.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-
-FoldersCallbackData::FoldersCallbackData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_is_error(false)
-{
-}
-
-FoldersCallbackData::~FoldersCallbackData() {
-}
-
-void FoldersCallbackData::addFolder(std::shared_ptr<MessageFolder> folder)
-{
-    m_folders.push_back(folder);
-}
-
-const std::vector<std::shared_ptr<MessageFolder>>& FoldersCallbackData::getFolders() const
-{
-    return m_folders;
-}
-
-void FoldersCallbackData::setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-DeviceAPI::Tizen::AbstractFilterPtr FoldersCallbackData::getFilter() const
-{
-    return m_filter;
-}
-
-void FoldersCallbackData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool FoldersCallbackData::isError() const
-{
-    return m_is_error;
-}
-
-std::string FoldersCallbackData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string FoldersCallbackData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/FoldersCallbackData.h b/messaging/old/FoldersCallbackData.h
deleted file mode 100644 (file)
index bf444cf..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_FOLDERS_CALLBACK_DATA_H__
-#define __TIZEN_FOLDERS_CALLBACK_DATA_H__
-
-#include <CallbackUserData.h>
-#include <memory>
-#include <vector>
-#include <string>
-
-#include <AbstractFilter.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageFolder;
-
-class FoldersCallbackData: public Common::CallbackUserData {
-public:
-    FoldersCallbackData(JSContextRef globalCtx);
-    virtual ~FoldersCallbackData();
-
-    void addFolder(std::shared_ptr<MessageFolder> folder);
-    const std::vector<std::shared_ptr<MessageFolder>>& getFolders() const;
-
-    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
-    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-private:
-    std::vector<std::shared_ptr<MessageFolder>> m_folders;
-    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_FOLDERS_CALLBACK_DATA_H__ */
diff --git a/messaging/old/FoldersChangeCallback.cpp b/messaging/old/FoldersChangeCallback.cpp
deleted file mode 100644 (file)
index 269b6b2..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <PlatformException.h>
-#include <JSUtil.h>
-#include <GlobalContextManager.h>
-
-#include "FoldersChangeCallback.h"
-#include "JSMessageFolder.h"
-#include "MessagingUtil.h"
-#include <Logger.h>
-
-using namespace DeviceAPI::Common;
-using namespace DeviceAPI::Tizen;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-const char* FOLDERSADDED = "foldersadded";
-const char* FOLDERSUPDATED = "foldersupdated";
-const char* FOLDERSREMOVED = "foldersremoved";
-
-FoldersChangeCallback::FoldersChangeCallback(JSContextRef global_ctx,
-        JSObjectRef on_added_obj,
-        JSObjectRef on_updated_obj,
-        JSObjectRef on_removed_obj,
-        int service_id,
-        MessageType service_type):
-    m_callback_data(global_ctx),
-    m_id(service_id),
-    m_msg_type(service_type),
-    m_is_act(true)
-{
-    LOGD("Entered");
-
-    m_callback_data.setCallback(FOLDERSADDED, on_added_obj);
-    m_callback_data.setCallback(FOLDERSUPDATED, on_updated_obj);
-    m_callback_data.setCallback(FOLDERSREMOVED, on_removed_obj);
-}
-
-FoldersChangeCallback::~FoldersChangeCallback()
-{
-    LOGD("Entered");
-}
-
-FolderPtrVector FoldersChangeCallback::filterFolders(
-        AbstractFilterPtr filter,
-        const FolderPtrVector& source_folders)
-{
-    if (filter) {
-        FolderPtrVector filtered_folders;
-        FolderPtrVector::const_iterator it = source_folders.begin();
-        FolderPtrVector::const_iterator end_it = source_folders.end();
-
-        for(int i = 0; it != end_it; ++i, ++it) {
-            const FolderPtr& folder = *it;
-            const bool matched = filter->isMatching(folder.get());
-            if (matched) {
-                filtered_folders.push_back(folder);
-            }
-
-            LOGD("[%d] folder id:%s", i, folder->getId().c_str());
-            LOGD("[%d] folder name:%s", i, folder->getName().c_str());
-            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
-        }
-
-        return filtered_folders;
-    }
-    else {
-        return source_folders;
-    }
-}
-
-void FoldersChangeCallback::added(const FolderPtrVector& folders)
-{
-    LOGD("Entered folders.size()=%d", folders.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    FolderPtrVector filtered = filterFolders(m_filter, folders);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
-            ctx, filtered);
-
-    LOGD("Calling:%s with:%d added folders", FOLDERSADDED,
-            filtered.size());
-
-    m_callback_data.invokeCallback(FOLDERSADDED, js_obj);
-}
-
-void FoldersChangeCallback::updated(const FolderPtrVector& folders)
-{
-    LOGD("Entered folders.size()=%d", folders.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    FolderPtrVector filtered = filterFolders(m_filter, folders);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
-            ctx, filtered);
-
-    LOGD("Calling:%s with:%d updated folders", FOLDERSUPDATED,
-            filtered.size());
-
-    m_callback_data.invokeCallback(FOLDERSUPDATED, js_obj);
-}
-
-void FoldersChangeCallback::removed(const FolderPtrVector& folders)
-{
-    LOGD("Entered folders.size()=%d", folders.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    FolderPtrVector filtered = filterFolders(m_filter, folders);
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
-            ctx, filtered);
-
-    LOGD("Calling:%s with:%d removed folders", FOLDERSREMOVED,
-            filtered.size());
-
-    m_callback_data.invokeCallback(FOLDERSREMOVED, js_obj);
-}
-
-void FoldersChangeCallback::setFilter(AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-AbstractFilterPtr FoldersChangeCallback::getFilter() const
-{
-    return m_filter;
-}
-
-int FoldersChangeCallback::getServiceId() const
-{
-    return m_id;
-}
-
-MessageType FoldersChangeCallback::getServiceType() const
-{
-    return m_msg_type;
-}
-
-void FoldersChangeCallback::setActive(bool act) {
-    m_is_act = act;
-}
-
-bool FoldersChangeCallback::isActive() {
-    return m_is_act;
-}
-
-void FoldersChangeCallback::setItems(FolderPtrVector& items)
-{
-    m_items = items;
-}
-FolderPtrVector FoldersChangeCallback::getItems()
-{
-    return m_items;
-}
-
-JSContextRef FoldersChangeCallback::getContext() const
-{
-    return m_callback_data.getContext();
-}
-
-} // Messaging
-} // DeviceAPI
-
-
diff --git a/messaging/old/FoldersChangeCallback.h b/messaging/old/FoldersChangeCallback.h
deleted file mode 100644 (file)
index fc2a888..0000000
+++ /dev/null
@@ -1,78 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
-#define __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-#include <MultiCallbackUserData.h>
-
-#include <AbstractFilter.h>
-
-#include "MessageFolder.h"
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-extern const char* FOLDERSADDED;
-extern const char* FOLDERSUPDATED;
-extern const char* FOLDERSREMOVED;
-
-class FoldersChangeCallback {
-public:
-    FoldersChangeCallback(JSContextRef global_ctx,
-            JSObjectRef on_added_obj,
-            JSObjectRef on_updated_obj,
-            JSObjectRef on_removed_obj,
-            int service_id,
-            MessageType service_type);
-    virtual ~FoldersChangeCallback();
-
-    void added(const FolderPtrVector& folders);
-    void updated(const FolderPtrVector& folders);
-    void removed(const FolderPtrVector& folders);
-
-    void setFilter(Tizen::AbstractFilterPtr filter);
-    Tizen::AbstractFilterPtr getFilter() const;
-
-    int getServiceId() const;
-    MessageType getServiceType() const;
-
-    void setActive(bool act);
-    bool isActive();
-
-    void setItems(FolderPtrVector& items);
-    FolderPtrVector getItems();
-    JSContextRef getContext() const;
-private:
-    static FolderPtrVector filterFolders(Tizen::AbstractFilterPtr filter,
-            const FolderPtrVector& source_folders);
-
-    Common::MultiCallbackUserData m_callback_data;
-    Tizen::AbstractFilterPtr m_filter;
-    int m_id;
-    MessageType m_msg_type;
-    bool m_is_act;
-    FolderPtrVector m_items;
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
diff --git a/messaging/old/JSMessage.cpp b/messaging/old/JSMessage.cpp
deleted file mode 100644 (file)
index 3325dcb..0000000
+++ /dev/null
@@ -1,923 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <PlatformException.h>
-#include <JSUtil.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-
-#include "JSMessage.h"
-#include "JSMessageBody.h"
-#include "JSMessageAttachment.h"
-
-#include "plugin_config.h"
-
-#include "MessagingUtil.h"
-#include "Message.h"
-#include "MessageSMS.h"
-#include "MessageMMS.h"
-#include "MessageEmail.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE = "Message";
-
-const char* MESSAGE_DICTIONARY_ATTRIBUTE_PLAIN_BODY = "plainBody";
-const char* MESSAGE_DICTIONARY_ATTRIBUTE_HTML_BODY = "htmlBody";
-}
-
-namespace JSMessageKeys {
-const char* MESSAGE_ATTRIBUTE_ID = "id";
-const char* MESSAGE_ATTRIBUTE_CONVERSATION_ID = "conversationId";
-const char* MESSAGE_ATTRIBUTE_FOLDER_ID = "folderId";
-const char* MESSAGE_ATTRIBUTE_TYPE = "type";
-const char* MESSAGE_ATTRIBUTE_TIMESTAMP = "timestamp";
-const char* MESSAGE_ATTRIBUTE_FROM = "from";
-const char* MESSAGE_ATTRIBUTE_TO = "to"; // used also in dictionary
-const char* MESSAGE_ATTRIBUTE_CC = "cc"; // used also in dictionary
-const char* MESSAGE_ATTRIBUTE_BCC = "bcc"; // used also in dictionary
-const char* MESSAGE_ATTRIBUTE_BODY = "body";
-const char* MESSAGE_ATTRIBUTE_IS_READ = "isRead";
-const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY = "isHighPriority"; // used also in dictionary
-const char* MESSAGE_ATTRIBUTE_SUBJECT = "subject"; // used also in dictionary
-const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO = "inResponseTo";
-const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS = "messageStatus";
-const char* MESSAGE_ATTRIBUTE_ATTACHMENTS = "attachments";
-const char* MESSAGE_ATTRIBUTE_HAS_ATTACHMENT = "hasAttachment";
-} // namespace JSMessage
-
-using namespace JSMessageKeys;
-
-JSClassRef JSMessage::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessage::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE,
-    NULL,
-    JSMessage::m_property,
-    NULL, // m_function
-    JSMessage::initialize,
-    JSMessage::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL, //callAsFunction,
-    NULL, //callAsConstructor,
-    NULL, //hasInstance,
-    NULL, //convertToType,
-};
-
-JSStaticValue JSMessage::m_property[] = {
-    { MESSAGE_ATTRIBUTE_ID, getMessageId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_CONVERSATION_ID, getConversationId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_FOLDER_ID, getFolder, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_TYPE, getMessageType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_TIMESTAMP, getTime, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_FROM, getSourceAddress, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTRIBUTE_TO, getDestinationAddress, setDestinationAddress, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_CC, getCcAddress, setCcAddress, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_BCC, getBccAddress, setBccAddress, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_BODY, getMessageBody, setMessageBody, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_IS_READ, getIsRead, setIsRead, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY, getMessagePriority, setMessagePriority, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_SUBJECT, getSubject, setSubject, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_IN_RESPONSE_TO, getInResponseTo, NULL, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_MESSAGE_STATUS, getMessageStatus, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly},
-    { MESSAGE_ATTRIBUTE_ATTACHMENTS, getAttachments, setAttachments, kJSPropertyAttributeDontDelete },
-    { MESSAGE_ATTRIBUTE_HAS_ATTACHMENT, hasAttachment, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly},
-    { 0, 0, 0, 0 }
-};
-
-const JSClassDefinition* JSMessage::getClassInfo()
-{
-    LOGD("Entered");
-    return &(m_classInfo);
-}
-
-JSClassRef DLL_EXPORT JSMessage::getClassRef()
-{
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-JSObjectRef DLL_EXPORT JSMessage::constructor(JSContextRef context,
-        JSObjectRef constructor,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-
-    ArgumentValidator validator(context, argumentCount, arguments);
-
-    JSObjectRef jsObjRef = JSObjectMake(context, JSMessage::getClassRef(), NULL);
-
-    // constructor
-    JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor");
-    JSObjectSetProperty(context, jsObjRef, ctorName, constructor,
-        kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL);
-    JSStringRelease(ctorName);
-
-    try {
-        std::shared_ptr<Message> priv;
-
-        std::string msgTypeString = validator.toString(0);
-        LOGD(" Message type : %s", msgTypeString.c_str());
-        JSObjectRef dictionary = validator.toObject(1, true);
-
-        try {
-            MessageType msgtype = MessagingUtil::stringToMessageType(msgTypeString);
-            switch(msgtype) {
-                case MessageType(SMS):
-                    priv = std::make_shared<MessageSMS>();
-                    break;
-                case MessageType(MMS):
-                    priv = std::make_shared<MessageMMS>();
-                    break;
-                case MessageType(EMAIL):
-                    priv = std::make_shared<MessageEmail>();
-                    break;
-                default:
-                    break;
-            }
-        }
-        catch(const BasePlatformException &ex) {
-            LOGE("Invalid message type given: %s.", msgTypeString.c_str());
-            throw ex;
-        }
-
-        setPrivateObject(jsObjRef, priv);
-
-        // both - dictionary and private object - have to be not NULL
-        if (dictionary != NULL && priv.get() != NULL) {
-            JSValueRef subjectData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_ATTRIBUTE_SUBJECT);
-            JSValueRef toData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_ATTRIBUTE_TO);
-            JSValueRef ccData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_ATTRIBUTE_CC);
-            JSValueRef bccData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_ATTRIBUTE_BCC);
-            JSValueRef plainBodyData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_DICTIONARY_ATTRIBUTE_PLAIN_BODY);
-            JSValueRef htmlBodyData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_DICTIONARY_ATTRIBUTE_HTML_BODY);
-            JSValueRef priorityData = JSUtil::getProperty(context, dictionary,
-                    MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY);
-
-            if (!JSValueIsUndefined(context, subjectData)) {
-                std::string subject = JSUtil::JSValueToString(context, subjectData);
-                LOGD(" Subject: %s", subject.c_str());
-                priv->setSubject(subject);
-            }
-            if (!JSValueIsUndefined(context, toData)) {
-                std::vector<std::string> to = JSUtil::JSArrayToStringVector(
-                        context, toData);
-                priv->setTO(to);
-            }
-            if (!JSValueIsUndefined(context, ccData)) {
-                std::vector<std::string> cc = JSUtil::JSArrayToStringVector(
-                        context, ccData);
-                priv->setCC(cc);
-            }
-            if (!JSValueIsUndefined(context, bccData)) {
-                std::vector<std::string> bcc = JSUtil::JSArrayToStringVector(
-                        context, bccData);
-                priv->setBCC(bcc);
-            }
-            if (!JSValueIsUndefined(context, htmlBodyData)) {
-                std::string htmlBody = JSUtil::JSValueToString(context, htmlBodyData);
-                LOGD(" htmlBody: %s", htmlBody.c_str());
-                priv->getBody()->setHtmlBody(htmlBody);
-            }
-            if (!JSValueIsUndefined(context, priorityData)) {
-                priv->setIsHighPriority(JSUtil::JSValueToBoolean(context, priorityData));
-            }
-            if (!JSValueIsUndefined(context, plainBodyData)) {
-                std::string plainBody = JSUtil::JSValueToString(context, plainBodyData);
-                LOGD(" plainBody: %s", plainBody.c_str());
-                priv->getBody()->setPlainBody(plainBody);
-            }
-        }
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Message creation failed: %s", err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Message creation failed - unsupported error.");
-    }
-
-    return jsObjRef;
-}
-
-void JSMessage::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessage::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    // Below holder is fetched from JSObject because holder
-    // with last shared_ptr instace should be removed
-    MessageHolder* priv = static_cast<MessageHolder*>(JSObjectGetPrivate(object));
-    JSObjectSetPrivate(object, NULL);
-    delete priv;
-}
-
-std::shared_ptr<Message> JSMessage::getPrivateObject(JSContextRef context,
-        JSValueRef value)
-{
-    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGE("Object type do not match");
-        throw TypeMismatchException("Object type is not Message");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-    MessageHolder* priv = static_cast<MessageHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw UnknownException("Private data holder is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessage::setPrivateObject(JSObjectRef object, std::shared_ptr<Message> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw UnknownException("NULL private data given");
-    }
-    MessageHolder* priv = static_cast<MessageHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    }
-    else {
-        priv = new(std::nothrow) MessageHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in Message");
-            throw UnknownException(
-                    "Failed to set Message private data");
-        }
-    }
-}
-
-JSObjectRef JSMessage::makeJSObject(JSContextRef context,
-        std::shared_ptr<Message> ptr)
-{
-    if (!ptr) {
-        LOGE("NULL pointer to message given");
-        throw UnknownException("NULL pointer to message given");
-    }
-
-    MessageHolder* priv = new(std::nothrow) MessageHolder();
-    if (!priv) {
-        LOGW("Failed to allocate memory for MessageHolder");
-        throw UnknownException("Priv is null");
-    }
-    priv->ptr = ptr;
-
-    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
-    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
-        LOGE("Failed to set private in Message");
-        throw UnknownException("Private data not set");
-    }
-    return obj;
-}
-
-JSObjectRef JSMessage::messageVectorToJSObjectArray(JSContextRef context,
-        const MessagePtrVector& messages)
-{
-    size_t count = messages.size();
-
-    JSObjectRef array[count];
-    for (size_t i = 0; i < count; i++) {
-        array[i] = JSMessage::makeJSObject(context, messages[i]);
-    }
-    JSObjectRef result = JSObjectMakeArray(context, count,
-            count > 0 ? array : NULL, NULL);
-    if (!result) {
-        LOGW("Failed to create Message array");
-        throw UnknownException("Message array is null");
-    }
-    return result;
-}
-
-JSValueRef JSMessage::getAttachments(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return priv->getJSMessageAttachments(
-            Common::GlobalContextManager::getInstance()
-                ->getGlobalContext(context));
-    }
-    catch(const BasePlatformException& err) {
-        LOGE("Failed to get attachments: %s", err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message attachment.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getBccAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return priv->getJSBCC(
-            Common::GlobalContextManager::getInstance()
-                ->getGlobalContext(context));
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get BCC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting BCC.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getCcAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return priv->getJSCC(
-            Common::GlobalContextManager::getInstance()
-                ->getGlobalContext(context));
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get CC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting CC.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getDestinationAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return priv->getJSTO(
-            Common::GlobalContextManager::getInstance()
-                ->getGlobalContext(context));
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get TO. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting TO.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getIsRead(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getIsRead());
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get is_read flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getMessageId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_id_set()) {
-            std::string stringid = std::to_string(priv->getId());
-            return JSUtil::toJSValueRef(context, stringid);
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get message id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting message id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getMessagePriority(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getIsHighPriority());
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get priority. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getMessageType(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context,
-                MessagingUtil::messageTypeToString(priv->getType()));
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get message type. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting message type.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getSourceAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_from_set()) {
-            return JSUtil::toJSValueRef(context, priv->getFrom());
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get source address. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting source address.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getSubject(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getSubject());
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get subject. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting subject.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getTime(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_timestamp_set()) {
-            return JSUtil::makeDateObject(context, priv->getTimestamp());
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get timestamp. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting timestamp.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getFolder(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_folder_id_set()) {
-            std::string stringid = std::to_string(priv->getFolderId());
-            return JSUtil::toJSValueRef(context, stringid);
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get folder id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting subject.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getMessageBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSMessageBody::makeJSObject(context, priv->getBody());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get MessageBody: %s", err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting BCC.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-bool JSMessage::setAttachments(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        if(!JSIsArrayValue(context,value)) {
-            return true;
-        }
-
-        auto priv = getPrivateObject(context, object);
-
-        AttachmentPtrVector atts;
-        atts = JSUtil::JSArrayToType_<std::shared_ptr<MessageAttachment>>(
-                context, value, JSMessageAttachment::getPrivateObject);
-        priv->setMessageAttachments(atts);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to set Attachments: %s", err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting Attachments.");
-    }
-    return true;
-}
-
-bool JSMessage::setBccAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        if(!JSIsArrayValue(context,value)) {
-            return true;
-        }
-
-        auto priv = getPrivateObject(context, object);
-
-        std::vector<std::string> bcc = JSUtil::JSArrayToStringVector(
-                context, value);
-        priv->setBCC(bcc);
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set BCC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting BCC.");
-    }
-    return true;
-}
-
-bool JSMessage::setCcAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        if(!JSIsArrayValue(context,value)) {
-            return true;
-        }
-
-        auto priv = getPrivateObject(context, object);
-
-        std::vector<std::string> cc = JSUtil::JSArrayToStringVector(
-                context, value);
-        priv->setCC(cc);
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set CC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting CC.");
-    }
-    return true;
-}
-
-bool JSMessage::setDestinationAddress(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef * exception)
-{
-    LOGD("Entered");
-    try {
-        if(!JSIsArrayValue(context,value)) {
-            return true;
-        }
-
-        auto priv = getPrivateObject(context, object);
-
-        std::vector<std::string> to = JSUtil::JSArrayToStringVector(
-                context, value);
-        priv->setTO(to);
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set TO. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting TO.");
-    }
-    return true;
-}
-
-bool JSMessage::setIsRead(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef * exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        priv->setIsRead(JSUtil::JSValueToBoolean(context, value));
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set isRead flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return true;
-}
-
-bool JSMessage::setMessagePriority(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef * exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        priv->setIsHighPriority(JSUtil::JSValueToBoolean(context, value));
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set priority. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return true;
-}
-
-bool JSMessage::setSubject(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef * exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        priv->setSubject(JSUtil::JSValueToString(context, value));
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("Failed to set subject. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while setting subject.");
-    }
-    return true;
-}
-
-bool JSMessage::setMessageBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    // TODO: MessageBody setting problem should be solved in spec or implementation
-    return true;
-}
-
-JSValueRef JSMessage::getConversationId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_conversation_id_set()) {
-            std::string stringid = std::to_string(priv->getConversationId());
-            return JSUtil::toJSValueRef(context, stringid);
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get conversation id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting conversation id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getInResponseTo(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_in_response_set()) {
-            std::string stringid = std::to_string(priv->getInResponseTo());
-            return JSUtil::toJSValueRef(context, stringid);
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get inResponeTo. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting inResponseTo.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::getMessageStatus(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context,
-                MessagingUtil::messageStatusToString(priv->getMessageStatus()));
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get message status. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    // Catch all exceptions not related to platform API execution failures
-    catch(...) {
-        LOGE("Unsupported error while getting message status.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessage::hasAttachment(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getHasAttachment());
-    }
-    catch(const BasePlatformException &err) {
-        LOGE("Failed to get hasAttachment flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessage.h b/messaging/old/JSMessage.h
deleted file mode 100644 (file)
index 4caa3ae..0000000
+++ /dev/null
@@ -1,253 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_H__
-#define __TIZEN_JS_MESSAGE_H__
-
-#include <JavaScriptCore/JavaScript.h>
-#include <Logger.h>
-#include "Message.h"
-// headers below needed to declare function that converts vector of
-// MessageAttachment into JSArray
-#include <vector>
-#include <memory>
-#include "MessageAttachment.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace JSMessageKeys {
-extern const char* MESSAGE_ATTRIBUTE_ID;
-extern const char* MESSAGE_ATTRIBUTE_CONVERSATION_ID;
-extern const char* MESSAGE_ATTRIBUTE_FOLDER_ID;
-extern const char* MESSAGE_ATTRIBUTE_TYPE;
-extern const char* MESSAGE_ATTRIBUTE_TIMESTAMP;
-extern const char* MESSAGE_ATTRIBUTE_FROM;
-extern const char* MESSAGE_ATTRIBUTE_TO;
-extern const char* MESSAGE_ATTRIBUTE_CC;
-extern const char* MESSAGE_ATTRIBUTE_BCC;
-extern const char* MESSAGE_ATTRIBUTE_BODY;
-extern const char* MESSAGE_ATTRIBUTE_IS_READ;
-extern const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY;
-extern const char* MESSAGE_ATTRIBUTE_SUBJECT;
-extern const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO;
-extern const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS;
-extern const char* MESSAGE_ATTRIBUTE_ATTACHMENTS;
-extern const char* MESSAGE_ATTRIBUTE_HAS_ATTACHMENT;
-} //namespace MESSAGE_ATTRIBUTE
-
-class JSMessage
-{
-public:
-    static const JSClassDefinition* getClassInfo();
-
-    static JSClassRef getClassRef();
-
-    static JSObjectRef constructor(JSContextRef ctx,
-            JSObjectRef constructor,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static std::shared_ptr<Message> getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<Message> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-            std::shared_ptr<Message> ptr);
-
-    /**
-     * Function converts vector of shared_pointers with Message into JSArray
-     */
-    static JSObjectRef messageVectorToJSObjectArray(JSContextRef context,
-            const MessagePtrVector& messages);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context,
-            JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getAttachments(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getBccAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getCcAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getDestinationAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getIsRead(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMessageId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMessagePriority(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMessageType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getSourceAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getSubject(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getTime(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getFolder(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMessageBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static bool setAttachments(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setBccAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setCcAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setDestinationAddress(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setIsRead(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setMessagePriority(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setSubject(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setMessageBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static JSValueRef getConversationId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getInResponseTo(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMessageStatus(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef hasAttachment(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSStaticFunction m_function[];
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This member variable contains the initialization values for the static properties of this class.
-     * The values are given according to the data structure JSPropertySpec
-     */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_H__
-
diff --git a/messaging/old/JSMessageAttachment.cpp b/messaging/old/JSMessageAttachment.cpp
deleted file mode 100644 (file)
index 62ee120..0000000
+++ /dev/null
@@ -1,350 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <SecurityExceptions.h>
-
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-
-#include "JSMessageAttachment.h"
-#include "MessageAttachment.h"
-
-#include "plugin_config.h"
-
-#include <JSUtil.h>
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE_ATTACHMENT = "MessageAttachment";
-
-const char* MESSAGE_ATTACHMENT_ID = "id";
-const char* MESSAGE_ATTACHMENT_MSG_ID = "messageId";
-const char* MESSAGE_ATTACHMENT_MIME_TYPE = "mimeType";
-const char* MESSAGE_ATTACHMENT_FILE_PATH = "filePath";
-}
-
-JSClassRef JSMessageAttachment::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageAttachment::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_ATTACHMENT,
-    NULL,
-    JSMessageAttachment::m_property,
-    NULL,
-    JSMessageAttachment::initialize,
-    JSMessageAttachment::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL, //callAsFunction,
-    NULL, //callAsConstructor,
-    NULL, //hasInstance,
-    NULL, //convertToType,
-};
-
-JSStaticValue JSMessageAttachment::m_property[] = {
-    { MESSAGE_ATTACHMENT_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTACHMENT_MSG_ID, getMsgId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTACHMENT_MIME_TYPE, getMimeType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_ATTACHMENT_FILE_PATH, getFilePath, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { 0, 0, 0, 0 }
-};
-
-const JSClassDefinition* JSMessageAttachment::getClassInfo()
-{
-    LOGD("Entered");
-    return &(m_classInfo);
-}
-
-JSClassRef DLL_EXPORT JSMessageAttachment::getClassRef()
-{
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-void JSMessageAttachment::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageAttachment::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    // Below holder is fetched from JSObject because holder
-    // with last shared_ptr instace should be removed
-    MessageAttachmentHolder* priv =
-            static_cast<MessageAttachmentHolder*>(JSObjectGetPrivate(object));
-    JSObjectSetPrivate(object, NULL);
-    delete priv;
-}
-
-std::shared_ptr<MessageAttachment> JSMessageAttachment::getPrivateObject(
-        JSContextRef context,
-        JSValueRef value)
-{
-    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGE("Object type do not match");
-        throw TypeMismatchException("Object type is not MessageAttachment");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-    MessageAttachmentHolder* priv = static_cast<MessageAttachmentHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw UnknownException("Private data holder is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessageAttachment::setPrivateObject(JSObjectRef object,
-        std::shared_ptr<MessageAttachment> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw UnknownException("NULL private data given");
-    }
-    MessageAttachmentHolder* priv = static_cast<MessageAttachmentHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    }
-    else {
-        priv = new(std::nothrow) MessageAttachmentHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in MessageAttachment");
-            throw UnknownException("Failed to set MessageAttachment private data");
-        }
-    }
-}
-
-JSObjectRef JSMessageAttachment::makeJSObject(JSContextRef context,
-        std::shared_ptr<MessageAttachment> native)
-{
-    if (!native) {
-        LOGE("NULL pointer to attachment given");
-        throw UnknownException("NULL pointer to attachment given");
-    }
-
-    MessageAttachmentHolder* priv = new(std::nothrow) MessageAttachmentHolder();
-    if (!priv) {
-        LOGW("Failed to allocate memory for AttachmentHolder");
-        throw UnknownException("Priv is null");
-    }
-    priv->ptr = native;
-
-    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
-    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
-        LOGE("Failed to set private in MessageAttachment");
-        throw UnknownException("Private data not set");
-    }
-    return obj;
-}
-
-JSObjectRef JSMessageAttachment::attachmentVectorToJSObjectArray(
-        JSContextRef context, const AttachmentPtrVector& atts)
-{
-    size_t count = atts.size();
-
-    JSObjectRef array[count];
-    for (size_t i = 0; i < count; i++) {
-        array[i] = JSMessageAttachment::makeJSObject(context, atts[i]);
-    }
-    JSObjectRef result = JSObjectMakeArray(context, count,
-            count > 0 ? array : NULL, NULL);
-    if (!result) {
-        LOGW("Failed to create MessageAttachment array");
-        throw UnknownException("MessageAttachment array is null");
-    }
-    return result;
-}
-
-JSObjectRef DLL_EXPORT JSMessageAttachment::constructor(JSContextRef context,
-            JSObjectRef constructor,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception)
-{
-    LOGD("Entered");
-
-    ArgumentValidator validator(context, argumentCount, arguments);
-
-    JSObjectRef jsObjRef = JSObjectMake(context, JSMessageAttachment::getClassRef(), NULL);
-
-    // constructor
-    JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor");
-    JSObjectSetProperty(context, jsObjRef, ctorName, constructor,
-        kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL);
-    JSStringRelease(ctorName);
-
-    try {
-        std::string filePath = validator.toString(0);
-        LOGD(" filePath: %s", filePath.c_str());
-
-        auto priv = std::shared_ptr<MessageAttachment>(new (std::nothrow)
-                MessageAttachment());
-        if(!priv) {
-            LOGE("Failed to allocate memory for private data");
-            throw UnknownException("Memory allocation failuer");
-        }
-
-        priv->setFilePath(filePath);
-        if (!validator.isNull(1) && !validator.isOmitted(1)) {
-            std::string mimeType = validator.toString(1, true);
-            LOGD(" mimeType: %s", mimeType.c_str());
-            priv->setMimeType(mimeType);
-        }
-
-        JSMessageAttachment::setPrivateObject(jsObjRef, priv);
-    }
-    catch (BasePlatformException &err) {
-        LOGE("MessageAttachment creation failed: %s", err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("MessageAttachment creation failed: Unknown exception.");
-    }
-
-    return jsObjRef;
-}
-
-JSValueRef JSMessageAttachment::getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception)
-{
-    LOGD("Entered");
-
-    try {
-        auto priv = JSMessageAttachment::getPrivateObject(context, object);
-
-        if (priv->isIdSet()) {
-            std::string stringid = std::to_string(priv->getId());
-            return JSUtil::toJSValueRef(context, stringid);
-        }else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("getMessageAttachmentId - unknown exception.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageAttachment::getMsgId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = JSMessageAttachment::getPrivateObject(context, object);
-
-        if (priv->isMessageIdSet()) {
-            std::string stringid = std::to_string(priv->getMessageId());
-            return JSUtil::toJSValueRef(context, stringid);
-        } else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("getMessageAttachmentMsgId - unknown exception.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageAttachment::getMimeType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = JSMessageAttachment::getPrivateObject(context, object);
-
-        if (priv->isMimeTypeSet()) {
-            return JSUtil::toJSValueRef(context, priv->getMimeType());
-        } else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("getMessageAttachmentMimeType - unknown exception.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageAttachment::getFilePath(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = JSMessageAttachment::getPrivateObject(context, object);
-
-        if (priv->isFilePathSet() && priv->isSaved()) {
-            return JSUtil::toJSValueRef(context, priv->getFilePath());
-        } else {
-            return JSValueMakeNull(context);
-        }
-
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("getMessageAttachmentFilePath - unknown exception.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessageAttachment.h b/messaging/old/JSMessageAttachment.h
deleted file mode 100755 (executable)
index cfda6c7..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_ATTACHMENT_H__
-#define __TIZEN_JS_MESSAGE_ATTACHMENT_H__
-
-#include <JavaScriptCore/JavaScript.h>
-#include <memory>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageAttachment;
-typedef std::vector<std::shared_ptr<MessageAttachment>> AttachmentPtrVector;
-
-class JSMessageAttachment
-{
-public:
-    static const JSClassDefinition* getClassInfo();
-
-    static JSClassRef getClassRef();
-
-    static JSObjectRef constructor(JSContextRef ctx,
-            JSObjectRef constructor,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static std::shared_ptr<MessageAttachment> getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<MessageAttachment> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-        std::shared_ptr<MessageAttachment> attptr);
-
-    /**
-     * Function converts vector of shared_pointers with MessageAttachment
-     * into JSArray
-     */
-    static JSObjectRef attachmentVectorToJSObjectArray(JSContextRef context,
-            const AttachmentPtrVector& atts);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context,
-            JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMsgId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMimeType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getFilePath(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    /**
-    * This structure describes a statically declared function property.
-    */
-    static JSStaticFunction m_function[];
-
-    /**
-    * This structure contains properties and callbacks that define a type of object.
-    */
-    static JSClassDefinition m_classInfo;
-
-    /**
-    * This member variable contains the initialization values for the static properties of this class.
-    * The values are given according to the data structure JSPropertySpec
-    */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_ATTACHMENT_H__
-
diff --git a/messaging/old/JSMessageBody.cpp b/messaging/old/JSMessageBody.cpp
deleted file mode 100644 (file)
index afd250c..0000000
+++ /dev/null
@@ -1,342 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <JSUtil.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-
-#include "JSMessageBody.h"
-#include "MessageBody.h"
-#include "JSMessageAttachment.h"
-
-#include "plugin_config.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE_BODY = "MessageBody";
-
-const char* MESSAGE_BODY_ID = "messageId";
-const char* MESSAGE_BODY_LOADED = "loaded";
-const char* MESSAGE_BODY_PLAIN_BODY = "plainBody";
-const char* MESSAGE_BODY_HTML_BODY = "htmlBody";
-const char* MESSAGE_BODY_INLINE_ATT = "inlineAttachments";
-}
-
-JSClassRef JSMessageBody::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageBody::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_BODY,
-    NULL,
-    JSMessageBody::m_property,
-    NULL,
-    JSMessageBody::initialize,
-    JSMessageBody::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty
-    NULL, //setProperty
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames
-    NULL, //callAsFunction,
-    NULL, //callAsConstructor,
-    NULL, //hasInstance,
-    NULL, //convertToType,
-};
-
-JSStaticValue JSMessageBody::m_property[] = {
-    { MESSAGE_BODY_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_BODY_LOADED, getLoaded, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_BODY_PLAIN_BODY, getPlainBody, setPlainBody, kJSPropertyAttributeDontDelete },
-    { MESSAGE_BODY_HTML_BODY, getHTMLBody, setHTMLBody, kJSPropertyAttributeDontDelete },
-    { MESSAGE_BODY_INLINE_ATT, getInlineAtt, setInlineAtt, kJSPropertyAttributeDontDelete },
-    { 0, 0, 0, 0 }
-};
-
-const JSClassDefinition* JSMessageBody::getClassInfo()
-{
-    return &(m_classInfo);
-}
-
-JSClassRef JSMessageBody::getClassRef()
-{
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-void JSMessageBody::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageBody::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    // Below holder is fetched and deleted from JSObject because last shared_ptr
-    // instace should be removed
-    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
-            JSObjectGetPrivate(object));
-    JSObjectSetPrivate(object, NULL);
-    delete priv;
-}
-
-std::shared_ptr<MessageBody> JSMessageBody::getPrivateObject(
-        JSContextRef context,
-        JSValueRef value)
-{
-    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGE("Object type do not match");
-        throw TypeMismatchException("Object type is not MessageBody");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw UnknownException("Private data holder is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessageBody::setPrivateObject(JSObjectRef object,
-        std::shared_ptr<MessageBody> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw UnknownException("NULL private data given");
-    }
-    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    }
-    else {
-        priv = new(std::nothrow) MessageBodyHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in MessageBody");
-            throw UnknownException(
-                    "Failed to set MessageBody private data");
-        }
-    }
-}
-
-JSObjectRef JSMessageBody::makeJSObject(JSContextRef context,
-        std::shared_ptr<MessageBody> ptr)
-{
-    if (!ptr) {
-        LOGE("NULL pointer to message body given");
-        throw UnknownException("NULL pointer to message body given");
-    }
-
-    MessageBodyHolder* priv = new(std::nothrow) MessageBodyHolder();
-    if (!priv) {
-        LOGW("Failed to allocate memory for MessageBodyHolder");
-        throw UnknownException("Priv is null");
-    }
-    priv->ptr = ptr;
-
-    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
-    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
-        LOGE("Failed to set private in MessageBody");
-        throw UnknownException("Private data not set");
-    }
-    return obj;
-}
-
-JSValueRef JSMessageBody::getId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        if(priv->is_message_id_set()) {
-            std::string stringid = std::to_string(priv->getMessageId());
-            return JSUtil::toJSValueRef(context, stringid);
-        }
-        else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageBody::getLoaded(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getLoaded());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageBody::getPlainBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getPlainBody());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageBody::getHTMLBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getHtmlBody());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageBody::getInlineAtt(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        return priv->getJSInlineAttachments(
-            Common::GlobalContextManager::getInstance()
-                ->getGlobalContext(context));
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-bool JSMessageBody::setPlainBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        std::string c_value = JSUtil::JSValueToString(context, value);
-        priv->setPlainBody(c_value);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return true;
-}
-
-bool JSMessageBody::setHTMLBody(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-
-        std::string c_value = JSUtil::JSValueToString(context, value);
-        priv->setHtmlBody(c_value);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return true;
-}
-
-bool JSMessageBody::setInlineAtt(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        if(!JSIsArrayValue(context,value)) {
-            return true;
-        }
-
-        auto priv = getPrivateObject(context, object);
-
-        AttachmentPtrVector atts;
-        atts = JSUtil::JSArrayToType_<std::shared_ptr<MessageAttachment>>(
-                context, value, JSMessageAttachment::getPrivateObject);
-        priv->setInlineAttachments(atts);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return true;
-}
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessageBody.h b/messaging/old/JSMessageBody.h
deleted file mode 100755 (executable)
index 29448ca..0000000
+++ /dev/null
@@ -1,125 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_BODY_H__
-#define __TIZEN_JS_MESSAGE_BODY_H__
-
-#include <JavaScriptCore/JavaScript.h>
-#include "MessageBody.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class JSMessageBody
-{
-public:
-    static const JSClassDefinition* getClassInfo();
-
-    static JSClassRef getClassRef();
-
-    static std::shared_ptr<MessageBody> getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<MessageBody> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-            std::shared_ptr<MessageBody> ptr);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context,
-            JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getLoaded(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getPlainBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getHTMLBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getInlineAtt(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static bool setPlainBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setHTMLBody(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setInlineAtt(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSStaticFunction m_function[];
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-    * This member variable contains the initialization values for the static properties of this class.
-    * The values are given according to the data structure JSPropertySpec
-    */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_BODY_H__
-
diff --git a/messaging/old/JSMessageConversation.cpp b/messaging/old/JSMessageConversation.cpp
deleted file mode 100644 (file)
index 360e54d..0000000
+++ /dev/null
@@ -1,444 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <SecurityExceptions.h>
-#include <PlatformException.h>
-#include <JSUtil.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-
-#include "JSMessageConversation.h"
-#include "MessageConversation.h"
-
-#include "plugin_config.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-using namespace DeviceAPI::Common;
-using namespace WrtDeviceApis::Commons;
-
-namespace {
-const char* MESSAGE_CONVERSATION = "MessageConversation";
-}
-
-namespace JSMessageConversationKeys {
-const char* MESSAGE_CONVERSATION_ID = "id";
-const char* MESSAGE_CONVERSATION_TYPE = "type";
-const char* MESSAGE_CONVERSATION_TIMESTAMP = "timestamp";
-const char* MESSAGE_CONVERSATION_MSG_COUNT = "messageCount";
-const char* MESSAGE_CONVERSATION_UNREAD_MSG = "unreadMessages";
-const char* MESSAGE_CONVERSATION_PREVIEW = "preview";
-const char* MESSAGE_CONVERSATION_SUBJECT = "subject";
-const char* MESSAGE_CONVERSATION_IS_READ = "isRead";
-const char* MESSAGE_CONVERSATION_FROM = "from";
-const char* MESSAGE_CONVERSATION_TO = "to";
-const char* MESSAGE_CONVERSATION_CC = "cc";
-const char* MESSAGE_CONVERSATION_BCC = "bcc";
-const char* MESSAGE_CONVERSATION_LAST_MSG_ID = "lastMessageId";
-}
-
-using namespace JSMessageConversationKeys;
-
-JSClassRef JSMessageConversation::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageConversation::m_classInfo =
-{
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_CONVERSATION,
-    NULL,
-    JSMessageConversation::m_property,
-    NULL,
-    JSMessageConversation::initialize,
-    JSMessageConversation::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL,
-    NULL,
-    NULL, //hasInstance,
-    NULL
-};
-
-JSStaticValue JSMessageConversation::m_property[] = {
-    { MESSAGE_CONVERSATION_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_TYPE, getType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_TIMESTAMP, getTimestamp, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_MSG_COUNT, getMsgCount, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_UNREAD_MSG, getUnreadMsg, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_PREVIEW, getPreview, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_SUBJECT, getSubject, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_IS_READ, getIsRead, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_FROM, getFrom, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_TO, getTo, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_CC, getCC, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_BCC, getBCC, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_CONVERSATION_LAST_MSG_ID, getLastMsgId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { 0, 0, 0, 0 }
-};
-
-JSClassRef DLL_EXPORT JSMessageConversation::getClassRef()
-{
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-const JSClassDefinition* JSMessageConversation::getClassInfo()
-{
-    LOGD("Entered");
-    return &m_classInfo;
-}
-
-void JSMessageConversation::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageConversation::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    MessageConversationHolder* priv =
-            static_cast<MessageConversationHolder*>(JSObjectGetPrivate(object));
-    JSObjectSetPrivate(object,NULL);
-    delete priv;
-}
-
-std::shared_ptr<MessageConversation> JSMessageConversation::getPrivateObject(
-        JSContextRef context, JSValueRef value)
-{
-    if(!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGW("Type mismatch");
-        throw TypeMismatchException("Type mismatch");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-
-    MessageConversationHolder* priv = static_cast<MessageConversationHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw UnknownException("Private data is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessageConversation::setPrivateObject(JSObjectRef object, std::shared_ptr<MessageConversation> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw UnknownException("NULL private data given");
-    }
-    MessageConversationHolder* priv = static_cast<MessageConversationHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    }
-    else {
-        priv = new(std::nothrow) MessageConversationHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in MessageConversation");
-            throw UnknownException(
-                    "Failed to set MessageConversation private data");
-        }
-    }
-}
-
-JSObjectRef JSMessageConversation::makeJSObject(JSContextRef context,
-        std::shared_ptr<MessageConversation> ptr)
-{
-    if (!ptr) {
-        LOGE("NULL pointer to message conversation given");
-        throw UnknownException("NULL pointer to message conversation given");
-    }
-
-    MessageConversationHolder* priv = new(std::nothrow) MessageConversationHolder();
-    if (!priv) {
-        LOGW("Failed to allocate memory for MessageConversationHolder");
-        throw UnknownException("Priv is null");
-    }
-    priv->ptr = ptr;
-
-    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
-    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
-        LOGE("Failed to set private in MessageConversation");
-        throw UnknownException("Private data not set");
-    }
-    return obj;
-}
-
-JSValueRef JSMessageConversation::getId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        std::string stringid = std::to_string(priv->getConversationId());
-        return JSUtil::toJSValueRef(context, stringid);
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getType(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, MessagingUtil::messageTypeToString(priv->getType()));
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation type.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getTimestamp(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::makeDateObject(context, priv->getTimestamp());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getMsgCount(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getMessageCount());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getUnreadMsg(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getUnreadMessages());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getPreview(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getPreview());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation preview.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getSubject(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getSubject());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation subject.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getIsRead(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getIsRead());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation isRead flag.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getFrom(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getFrom());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation source address.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getTo(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getTo());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting message conversation destination address.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getCC(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getCC());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting CC.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getBCC(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getBCC());
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting BCC.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageConversation::getLastMsgId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        std::string stringid = std::to_string(priv->getLastMessageId());
-        return JSUtil::toJSValueRef(context, stringid);
-    }
-    catch (const BasePlatformException &err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while getting last message id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-} //Messaging
-} //DeviceAPI
diff --git a/messaging/old/JSMessageConversation.h b/messaging/old/JSMessageConversation.h
deleted file mode 100755 (executable)
index dd2c221..0000000
+++ /dev/null
@@ -1,162 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_CONVERSATION_H__
-#define __TIZEN_JS_MESSAGE_CONVERSATION_H__
-
-#include <JavaScriptCore/JavaScript.h>
-#include "MessageConversation.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace JSMessageConversationKeys {
-extern const char* MESSAGE_CONVERSATION_ID;
-extern const char* MESSAGE_CONVERSATION_TYPE;
-extern const char* MESSAGE_CONVERSATION_TIMESTAMP;
-extern const char* MESSAGE_CONVERSATION_MSG_COUNT;
-extern const char* MESSAGE_CONVERSATION_UNREAD_MSG;
-extern const char* MESSAGE_CONVERSATION_PREVIEW;
-extern const char* MESSAGE_CONVERSATION_SUBJECT;
-extern const char* MESSAGE_CONVERSATION_IS_READ;
-extern const char* MESSAGE_CONVERSATION_FROM;
-extern const char* MESSAGE_CONVERSATION_TO;
-extern const char* MESSAGE_CONVERSATION_CC;
-extern const char* MESSAGE_CONVERSATION_BCC;
-extern const char* MESSAGE_CONVERSATION_LAST_MSG_ID;
-}
-
-class JSMessageConversation
-{
-public:
-/* @struct JSClassDefinition
- *@abstract This structure contains properties and callbacks that define a type of object.
- *@abstract All fields other than the version field are optional. Any pointer may be NULL.
- */
-    static const JSClassDefinition* getClassInfo();
-
-    static JSClassRef getClassRef();
-
-    static std::shared_ptr<MessageConversation> getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<MessageConversation> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-            std::shared_ptr<MessageConversation> ptr);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context, JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getTimestamp(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMsgCount(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getUnreadMsg(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getPreview(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getSubject(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getIsRead(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getFrom(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getTo(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getCC(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getBCC(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getLastMsgId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This member variable contains the initialization values for the static properties
-     * of this class.
-     * The values are given according to the data structure JSPropertySpec
-     */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_CONVERSATION_H__
diff --git a/messaging/old/JSMessageFolder.cpp b/messaging/old/JSMessageFolder.cpp
deleted file mode 100644 (file)
index e9c977b..0000000
+++ /dev/null
@@ -1,402 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        JSMessageFolder.cpp
- */
-
-
-#include <JSUtil.h>
-#include <SecurityExceptions.h>
-
-#include <Export.h>
-#include <Logger.h>
-
-#include "JSMessageFolder.h"
-#include "MessageFolder.h"
-#include "MessagingUtil.h"
-#include "MessageFolder.h"
-
-#include "plugin_config.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE_FOLDER = "MessageFolder";
-
-const char* MESSAGE_FOLDER_ID = "id";
-const char* MESSAGE_FOLDER_PARENT_ID = "parentId";
-const char* MESSAGE_FOLDER_SERVICE_ID = "serviceId";
-const char* MESSAGE_FOLDER_CONTENT_TYPE = "contentType";
-const char* MESSAGE_FOLDER_NAME = "name";
-const char* MESSAGE_FOLDER_PATH = "path";
-const char* MESSAGE_FOLDER_TYPE = "type";
-const char* MESSAGE_FOLDER_SYNCHRONIZABLE = "synchronizable";
-}
-
-JSClassRef JSMessageFolder::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageFolder::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_FOLDER,
-    NULL,
-    JSMessageFolder::m_property,
-    NULL,
-    JSMessageFolder::initialize,
-    JSMessageFolder::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL, //callAsFunction,
-    NULL, //callAsConstructor,
-    NULL, //hasInstance,
-    NULL, //convertToType,
-};
-
-JSStaticValue JSMessageFolder::m_property[] = {
-    { MESSAGE_FOLDER_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_PARENT_ID, getParentId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_SERVICE_ID, getServiceId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_CONTENT_TYPE, getContentType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_NAME, getName, setName, kJSPropertyAttributeDontDelete },
-    { MESSAGE_FOLDER_PATH, getPath, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_TYPE, getType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
-    { MESSAGE_FOLDER_SYNCHRONIZABLE, getSynchronizable, setSynchronizable, kJSPropertyAttributeDontDelete },
-    { 0, 0, 0, 0 }
-};
-
-JSClassRef JSMessageFolder::getClassRef() {
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-const JSClassDefinition* JSMessageFolder::getClassInfo() {
-    LOGD("Entered");
-    return &(m_classInfo);
-}
-
-void JSMessageFolder::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageFolder::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(JSObjectGetPrivate(object));
-    if(priv)
-    {
-        JSObjectSetPrivate(object,NULL);
-        delete priv;
-        priv = NULL;
-    }
-}
-
-std::shared_ptr<MessageFolder> JSMessageFolder::getPrivateObject(JSContextRef context,
-        JSValueRef value)
-{
-    if(!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGW("Type mismatch");
-        throw TypeMismatchException("Type mismatch");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-
-    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw UnknownException("Private data is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessageFolder::setPrivateObject(JSObjectRef object, std::shared_ptr<MessageFolder> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw UnknownException("NULL private data given");
-    }
-    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    }
-    else {
-        priv = new(std::nothrow) MessageFolderHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in MessageFolder");
-            throw UnknownException(
-                    "Failed to set MessageFolder private data");
-        }
-    }
-}
-
-JSObjectRef JSMessageFolder::makeJSObject(JSContextRef context,
-        std::shared_ptr<MessageFolder> ptr)
-{
-    if (!ptr) {
-        LOGE("NULL pointer to message folder given");
-        throw UnknownException("NULL pointer to message folder given");
-    }
-
-    MessageFolderHolder* priv = new(std::nothrow) MessageFolderHolder();
-    if (!priv) {
-        LOGW("Failed to allocate memory for MessageFolderHolder");
-        throw UnknownException("Priv is null");
-    }
-    priv->ptr = ptr;
-
-    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
-    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
-        LOGE("Failed to set private in MessageFolder");
-        throw UnknownException("Private data not set");
-    }
-    return obj;
-}
-
-JSValueRef JSMessageFolder::getId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getId());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder id. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getParentId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        if (priv->isParentIdSet()) {
-            return JSUtil::toJSValueRef(context, priv->getParentId());
-        } else {
-            return JSValueMakeNull(context);
-        }
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder parent id. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder parent id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getServiceId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getServiceId());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder service id. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder service id.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getContentType(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getContentType());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder content type. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder content type.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getName(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getName());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder name. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder name.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getPath(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getPath());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder path. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder path.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getType(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context,
-                MessagingUtil::messageFolderTypeToString(priv->getType()));
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder type. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while getting message folder type.");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageFolder::getSynchronizable(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        return JSUtil::toJSValueRef(context, priv->getSynchronizable());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to get message folder is synchronizable flag. %s : %s",
-                err.getName().c_str(), err.getMessage().c_str());
-    }
-    return JSValueMakeUndefined(context);
-}
-
-bool JSMessageFolder::setName(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        std::string c_value = JSUtil::JSValueToString(context, value);
-        priv->setName(c_value);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to set message folder name. %s : %s", err.getName().c_str(),
-                err.getMessage().c_str());
-    }
-    catch (...) {
-        LOGE("Unsupported error while setting message folder name.");
-    }
-    return true;
-}
-
-bool JSMessageFolder::setSynchronizable(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef value,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        auto priv = getPrivateObject(context, object);
-        bool c_value = JSUtil::JSValueToBoolean(context, value);
-        priv->setSynchronizable(c_value);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Failed to set message folder is synchronizable flag. %s : %s",
-                err.getName().c_str(), err.getMessage().c_str());
-    }
-    catch(...) {
-        LOGE("Unsupported error while setting message folder is synchronizable flag.");
-    }
-    return true;
-}
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessageFolder.h b/messaging/old/JSMessageFolder.h
deleted file mode 100755 (executable)
index 892474b..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        JSMessageFolder.h
- */
-
-
-#ifndef __TIZEN_JS_MESSAGE_FOLDER_H__
-#define __TIZEN_JS_MESSAGE_FOLDER_H__
-
-#include <JavaScriptCore/JavaScript.h>
-#include "MessageFolder.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class JSMessageFolder
-{
-public:
-    static const JSClassDefinition* getClassInfo();
-
-    static JSClassRef getClassRef();
-
-    static std::shared_ptr<MessageFolder> getPrivateObject(JSContextRef context, JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<MessageFolder> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-            std::shared_ptr<MessageFolder> ptr);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context, JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getParentId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getServiceId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getContentType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getName(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getPath(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getSynchronizable(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static bool setName(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    static bool setSynchronizable(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef value,
-            JSValueRef* exception);
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This member variable contains the initialization values for the static properties
-     * of this class.
-     * The values are given according to the data structure JSPropertySpec
-     */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_FOLDER_H__
-
diff --git a/messaging/old/JSMessageService.cpp b/messaging/old/JSMessageService.cpp
deleted file mode 100644 (file)
index 717d3d3..0000000
+++ /dev/null
@@ -1,587 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <SecurityExceptions.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <JSUtil.h>
-#include <Export.h>
-#include <Logger.h>
-#include <PlatformException.h>
-#include <TimeTracer.h>
-#include <tapi_common.h>
-
-#include "JSMessage.h"
-#include "JSMessageService.h"
-#include "MessageService.h"
-#include "MessagingUtil.h"
-
-#include "plugin_config.h"
-#include "JSMessageStorage.h"
-
-#include "JSMessageFolder.h"
-#include "JSMessageAttachment.h"
-
-#include "MessagingManager.h"
-
-using namespace std;
-using namespace DeviceAPI::Common;
-using namespace WrtDeviceApis::Commons;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE_SERVICE = "MessageService";
-
-const char* MESSAGE_SERVICE_ID = "id";
-const char* MESSAGE_SERVICE_TYPE = "type";
-const char* MESSAGE_SERVICE_NAME = "name";
-const char* MESSAGE_SERVICE_MSG_STORAGE = "messageStorage";
-}
-
-JSClassRef JSMessageService::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageService::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_SERVICE,
-    NULL,
-    JSMessageService::m_property,
-    JSMessageService::m_function,
-    JSMessageService::initialize,
-    JSMessageService::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL,
-    NULL,
-    NULL, //hasInstance,
-    NULL
-};
-
-JSStaticValue JSMessageService::m_property[] = {
-    { MESSAGE_SERVICE_ID, getId, NULL, kJSPropertyAttributeDontDelete
-            | kJSPropertyAttributeReadOnly },
-    { MESSAGE_SERVICE_TYPE, getType, NULL, kJSPropertyAttributeDontDelete
-            | kJSPropertyAttributeReadOnly },
-    { MESSAGE_SERVICE_NAME, getName, NULL, kJSPropertyAttributeDontDelete
-            | kJSPropertyAttributeReadOnly },
-    { MESSAGE_SERVICE_MSG_STORAGE, getMsgStorage, NULL, kJSPropertyAttributeDontDelete
-            | kJSPropertyAttributeReadOnly },
-    { 0, 0, 0, 0 }
-};
-
-JSStaticFunction JSMessageService::m_function[] = {
-    { MESSAGING_FUNCTION_API_SEND_MESSAGE, JSMessageService::sendMessage,
-            kJSPropertyAttributeNone },
-    { MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY, JSMessageService::loadMessageBody,
-            kJSPropertyAttributeNone },
-    { MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
-            JSMessageService::loadMessageAttachment, kJSPropertyAttributeNone },
-    { MESSAGING_FUNCTION_API_SYNC, JSMessageService::sync,
-            kJSPropertyAttributeNone },
-    { MESSAGING_FUNCTION_API_SYNC_FOLDER, JSMessageService::syncFolder,
-            kJSPropertyAttributeNone },
-    { MESSAGING_FUNCTION_API_STOP_SYNC, JSMessageService::stopSync,
-            kJSPropertyAttributeNone },
-    { 0, 0, 0 }
-};
-
-const JSClassRef JSMessageService::getClassRef()
-{
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-MessageService* JSMessageService::getPrivateObject(
-        JSContextRef context,
-        JSValueRef value)
-{
-    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGE("Object type do not match");
-        throw Common::TypeMismatchException("Object type is not MessageService");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-    MessageService* priv = static_cast<MessageService*>(JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw Common::UnknownException("Private data is null");
-    }
-
-    return priv;
-}
-
-JSObjectRef JSMessageService::createJSObject(JSContextRef context,
-        MessageService* priv)
-{
-    LOGD("Entered");
-    if (!priv) {
-        LOGE("Private data is null");
-        return NULL;
-    }
-    priv->copyAceCheckAccessFunction(MessagingManager::getInstance());
-    JSObjectRef jsObject = JSObjectMake(context, getClassRef(),
-            static_cast<void*>(priv));
-    if (NULL == jsObject) {
-        LOGE("object creation error");
-    }
-
-    return jsObject;
-}
-
-void JSMessageService::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageService::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    MessageService* priv = static_cast<MessageService*>(JSObjectGetPrivate(object));
-    if (priv) {
-        JSObjectSetPrivate(object, NULL);
-        delete priv;
-        priv = NULL;
-    }
-}
-
-JSValueRef JSMessageService::getType(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        MessageService* priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context,
-            MessagingUtil::messageTypeToString(priv->getMsgServiceType()));
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error, cannot get property");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::getName(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        MessageService* priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getMsgServiceName());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error, cannot get property");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::getId(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        MessageService* priv = getPrivateObject(context, object);
-
-        return JSUtil::toJSValueRef(context, priv->getMsgServiceIdStr());
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error, cannot get property");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::getMsgStorage(JSContextRef context,
-        JSObjectRef object,
-        JSStringRef propertyName,
-        JSValueRef* exception)
-{
-    LOGD("Entered");
-    try {
-        MessageService* priv = getPrivateObject(context, object);
-
-        std::shared_ptr<MessageStorage> storage = priv->getMsgStorage();
-        storage->copyAceCheckAccessFunction(priv);
-
-        return JSMessageStorage::makeJSObject(context, storage);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error, cannot get property");
-    }
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::sendMessage(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessageRecipientsCallbackData *callback = NULL;
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_SEND_MESSAGE);
-
-        // void sendMessage(Message message,
-        //         optional MessageRecipientsCallback successCallback,
-        //         optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
-                validator.toJSValueRef(0));
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) MessageRecipientsCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setMessage(message);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        // internally TelNetworkDefaultDataSubs_t consists of -1(unknown), 0(sim_1), 1(sim_2)
-        // but in spec, simIndex parameter starts with 1.
-        // so if user set simIndex param, then minus 1 on it.
-        long tmp = validator.toLong(3, true, 0);
-        char **cp_list = tel_get_cp_name_list();
-        int sim_count = 0;
-
-        if (cp_list) {
-            while (cp_list[sim_count]) {
-                sim_count++;
-            }
-            g_strfreev(cp_list);
-        } else {
-            LOGD("Empty cp name list");
-        }
-
-        tmp--;
-        if (tmp >= sim_count || tmp < -1) {
-            LOGE("Sim index out of bound %d : %d", tmp, sim_count);
-            Common::InvalidValuesException err("The index of sim is out of bound");
-            callback->setError(err.getName().c_str(), err.getMessage().c_str());
-            callback->callErrorCallback();
-
-            delete callback;
-            callback = NULL;
-            return JSValueMakeUndefined(context);
-        }
-
-        callback->setSimIndex(static_cast<TelNetworkDefaultDataSubs_t>(tmp));
-        priv->sendMessage(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Unknown error, cannot send message");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::loadMessageBody(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-
-    MessageBodyCallbackData *callback = NULL;
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY);
-        // void loadMessageBody(Message message,
-        //         MessageBodySuccessCallback successCallback,
-        //         optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
-                validator.toJSValueRef(0));
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) MessageBodyCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setMessage(message);
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->loadMessageBody(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        Common::UnknownException err("Cannot load message body");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::loadMessageAttachment(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessageAttachmentCallbackData *callback = NULL;
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT);
-        // void loadMessageAttachment(MessageAttachment attachment,
-        //         MessageAttachmentSuccessCallback successCallback,
-        //         optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        JSValueRef jsMsgAttachment = validator.toJSValueRef(0);
-        std::shared_ptr<MessageAttachment> attachment =
-                JSMessageAttachment::getPrivateObject(context, jsMsgAttachment);
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) MessageAttachmentCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setMessageAttachment(attachment);
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->loadMessageAttachment(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        Common::UnknownException err("Cannot load message attachment");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageService::sync(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    SyncCallbackData *callback = NULL;
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_SYNC);
-        // long sync(optional SuccessCallback? successCallback,
-        //           optional ErrorCallback? errorCallback,
-        //           optional unsigned long? limit);
-        ArgumentValidator validator(context, argumentCount, arguments);
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) SyncCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setSuccessCallback(validator.toFunction(0, true));
-        callback->setErrorCallback(validator.toFunction(1, true));
-        // if limit is not provided or is null
-        // default value is used in MessageService
-        if (!validator.isOmitted(2) && !validator.isNull(2)) {
-            callback->setLimit(validator.toULong(2));
-        }
-
-        long op_id = priv->sync(callback);
-        return JSUtil::toJSValueRef(context, op_id);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        Common::UnknownException err("Cannot sync with external mail server");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-}
-
-JSValueRef JSMessageService::syncFolder(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    SyncFolderCallbackData *callback = NULL;
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_SYNC_FOLDER);
-        // long syncFolder(MessageFolder folder,
-        //         optional SuccessCallback? successCallback,
-        //         optional ErrorCallback? errorCallback,
-        //         optional unsigned long? limit);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::shared_ptr<MessageFolder> messageFolder =
-                JSMessageFolder::getPrivateObject(context, validator.toJSValueRef(0));
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) SyncFolderCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setMessageFolder(messageFolder);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-        // if limit is not provided or is null
-        // default value is used in MessageService
-        if (!validator.isOmitted(3) && !validator.isNull(3)) {
-            callback->setLimit(validator.toULong(3));
-        }
-
-        long op_id = priv->syncFolder(callback);
-        return JSUtil::toJSValueRef(context, op_id);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        Common::UnknownException err("Cannot sync folder with external server");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-}
-
-JSValueRef JSMessageService::stopSync(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    try {
-        MessageService* priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv,
-                MESSAGING_FUNCTION_API_STOP_SYNC);
-
-        // void stopSync(long opId);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        long opId = validator.toLong(0);
-
-        priv->stopSync(opId);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        Common::UnknownException err("Cannot stop sync with external server");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessageService.h b/messaging/old/JSMessageService.h
deleted file mode 100755 (executable)
index d0c091d..0000000
+++ /dev/null
@@ -1,141 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_SERVICE_H__
-#define __TIZEN_JS_MESSAGE_SERVICE_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-#include "MessageService.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class JSMessageService
-{
-public :
-    static const JSClassDefinition* getClassInfo();
-
-    static const JSClassRef getClassRef();
-
-    static MessageService* getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static JSObjectRef createJSObject(JSContextRef context,
-            MessageService* priv);
-
-private :
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context, JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef getId(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getType(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getName(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef getMsgStorage(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName,
-            JSValueRef* exception);
-
-    static JSValueRef sendMessage(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef loadMessageBody(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef loadMessageAttachment(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef sync(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef syncFolder(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef stopSync(JSContextRef context,
-            JSObjectRef function,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This member variable contains the initialization values for the static properties of this class.
-     * The values are given according to the data structure JSPropertySpec
-     */
-    static JSStaticValue m_property[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSStaticFunction m_function[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-}; //JSMessageService
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_SERVICE_H__
-
diff --git a/messaging/old/JSMessageStorage.cpp b/messaging/old/JSMessageStorage.cpp
deleted file mode 100644 (file)
index 1ee110b..0000000
+++ /dev/null
@@ -1,882 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <SecurityExceptions.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-#include <PlatformException.h>
-#include <JSAttributeFilter.h>
-#include <JSSortMode.h>
-#include <JSUtil.h>
-#include <vector>
-#include <TimeTracer.h>
-
-
-#include "JSMessage.h"
-#include "JSMessageConversation.h"
-#include "Message.h"
-#include "MessageCallbackUserData.h"
-#include "JSMessageStorage.h"
-#include "MessagesChangeCallback.h"
-#include "ConversationsChangeCallback.h"
-#include "FoldersChangeCallback.h"
-#include "AbstractFilter.h"
-
-#include "plugin_config_impl.h"
-#include "MessagesCallbackUserData.h"
-#include "FindMsgCallbackUserData.h"
-#include "ConversationCallbackData.h"
-
-using namespace std;
-using namespace DeviceAPI::Common;
-using namespace WrtDeviceApis::Commons;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGE_STORAGE = "MessageStorage";
-}
-
-JSClassRef JSMessageStorage::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessageStorage::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGE_STORAGE,
-    NULL,
-    NULL,
-    JSMessageStorage::m_function,
-    JSMessageStorage::initialize,
-    JSMessageStorage::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-JSStaticFunction JSMessageStorage::m_function[] = {
-    { MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE, JSMessageStorage::addDraftMessage, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_FIND_MESSAGES, JSMessageStorage::findMessages, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_REMOVE_MESSAGES, JSMessageStorage::removeMessages, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_UPDATE_MESSAGES, JSMessageStorage::updateMessages, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_FIND_CONVERSATIONS, JSMessageStorage::findConversations, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS, JSMessageStorage::removeConversations, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_FIND_FOLDERS, JSMessageStorage::findFolders, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER, JSMessageStorage::addMessagesChangeListener, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER, JSMessageStorage::addConversationsChangeListener, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER, JSMessageStorage::addFoldersChangeListener, kJSPropertyAttributeDontDelete },
-    { MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER, JSMessageStorage::removeChangeListener, kJSPropertyAttributeDontDelete },
-    { 0, 0, 0 }
-};
-
-const JSClassRef JSMessageStorage::getClassRef()
-{
-    LOGD("Entered");
-    if (!m_jsClassRef)
-    {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-std::shared_ptr<MessageStorage> JSMessageStorage::getPrivateObject(
-        JSContextRef context,
-        JSValueRef value)
-{
-    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
-        LOGE("Object type do not match");
-        throw Common::TypeMismatchException("Object type is not MessageStorage");
-    }
-
-    JSObjectRef object = JSUtil::JSValueToObject(context, value);
-    MessageStorageHolder* priv = static_cast<MessageStorageHolder*>(
-            JSObjectGetPrivate(object));
-    if (!priv) {
-        LOGE("NULL private data");
-        throw Common::UnknownException("Private data holder is null");
-    }
-    if (!(priv->ptr)) {
-        LOGE("NULL shared pointer in private data");
-        throw Common::UnknownException("Private data is null");
-    }
-
-    return priv->ptr;
-}
-
-void JSMessageStorage::setPrivateObject(JSObjectRef object,
-        std::shared_ptr<MessageStorage> data)
-{
-    if (!data) {
-        LOGE("NULL shared pointer given to set as private data");
-        throw Common::UnknownException("NULL private data given");
-    }
-    MessageStorageHolder* priv = static_cast<MessageStorageHolder*>(
-            JSObjectGetPrivate(object));
-    if (priv) {
-        priv->ptr = data;
-    } else {
-        priv = new(std::nothrow) MessageStorageHolder();
-        if (!priv) {
-            LOGE("Memory allocation failure");
-            throw Common::UnknownException("Failed to allocate memory");
-        }
-        priv->ptr = data;
-        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
-            delete priv;
-            priv = NULL;
-            LOGE("Failed to set private data in MessageStorage");
-            throw Common::UnknownException(
-                    "Failed to set MessageStorage private data");
-        }
-    }
-}
-
-JSObjectRef JSMessageStorage::makeJSObject(JSContextRef context,
-    std::shared_ptr<MessageStorage> ptr)
-{
-    LOGD("Entered");
-    if (!ptr) {
-        LOGE("Private data is null");
-        throw Common::UnknownException("Private object is NULL");
-    }
-
-    MessageStorageHolder* priv = new(std::nothrow) MessageStorageHolder();
-    if (!priv) {
-        LOGE("Failed to allocate memory for MessageStorageHolder");
-        throw Common::UnknownException("Failed to allocate memory");
-    }
-    priv->ptr = ptr;
-
-    JSObjectRef jsObject = JSObjectMake(context, getClassRef(),
-            static_cast<void*>(priv));
-    if (!jsObject) {
-        LOGE("Object creation failed");
-        throw Common::UnknownException("Object creation failed");
-    }
-
-    return jsObject;
-}
-
-void JSMessageStorage::initialize(JSContextRef context, JSObjectRef object)
-{
-    LOGD("Entered");
-}
-
-void JSMessageStorage::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    MessageStorageHolder* priv =
-            static_cast<MessageStorageHolder*>(JSObjectGetPrivate(object));
-    if (priv) {
-        JSObjectSetPrivate(object, NULL);
-        delete priv;
-        priv = NULL;
-    }
-}
-
-JSValueRef JSMessageStorage::addDraftMessage(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessageCallbackUserData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE);
-
-        // void addDraftMessage(Message message,
-        //         optional SuccessCallback? successCallback,
-        //.        optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
-                validator.toJSValueRef(0));
-
-        JSContextRef g_ctx = GlobalContextManager::getInstance()
-                ->getGlobalContext(context);
-        callback = new(std::nothrow) MessageCallbackUserData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setMessage(message);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->addDraftMessage(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Unknown error, cannot add draft message");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::findMessages(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    FindMsgCallbackUserData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_FIND_MESSAGES);
-        /*
-         * void findMessages(AbstractFilter filter,
-         *          MessageArraySuccessCallback successCallback,
-         *          optional ErrorCallback? errorCallback,
-         *          optional SortMode? sort,
-         *          optional unsigned long? limit,
-         *          optional unsigned long? offset);
-         */
-        JSContextRef g_ctx = GlobalContextManager::getInstance()
-                ->getGlobalContext(context);
-        callback = new FindMsgCallbackUserData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        ArgumentValidator validator(context, argumentCount, arguments);
-
-        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                getPrivateObject(context, validator.toJSValueRef(0));
-
-        if (!filter) {
-            LOGE("Wrong filter");
-            throw Common::TypeMismatchException("Invalid filter");
-        }
-        callback->setFilter(filter);
-
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        JSObjectRef sortmodeobj = validator.toObject(3, true);
-        if(sortmodeobj != NULL){
-            DeviceAPI::Tizen::SortModePtr sortMode =
-                    Tizen::JSSortMode::getPrivateObject(context, sortmodeobj);
-            LOGD("sort mode is set");
-            callback->setSortMode(sortMode);
-        }
-
-        callback->setLimit(validator.toULong(4, true, 0));
-        callback->setOffset(validator.toULong(5, true, 0));
-        priv->findMessages(callback);
-    }
-    catch (const WrtDeviceApis::Commons::Exception& exc) {
-        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
-        Common::TypeMismatchException err(exc.GetMessage().c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }catch (...) {
-        Common::UnknownException err("Unknown error, cannot find messages");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::removeMessages(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessagesCallbackUserData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_REMOVE_MESSAGES);
-        /**
-         * void removeMessages(Message[] messages,
-         *          optional SuccessCallback? successCallback,
-         *          optional ErrorCallback? errorCallback);
-         */
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::vector<JSValueRef> messages = validator.toJSValueRefVector(0);
-        JSContextRef g_ctx = GlobalContextManager::getInstance()
-                ->getGlobalContext(context);
-        callback = new MessagesCallbackUserData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        callback->addMessages(context, messages);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->removeMessages(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Unknown error, cannot remove messages");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::updateMessages(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessagesCallbackUserData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_UPDATE_MESSAGES);
-        /**
-         * void updateMessages (Message[] messages,
-         *          optional SuccessCallback? successCallback,
-         *          optional ErrorCallback? errorCallback)
-         */
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::vector<JSValueRef> messages = validator.toJSValueRefVector(0);
-        JSContextRef g_ctx = GlobalContextManager::getInstance()
-                ->getGlobalContext(context);
-        callback = new MessagesCallbackUserData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        callback->addMessages(context, messages);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->updateMessages(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Unknown error, cannot update messages");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::findConversations(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    ConversationCallbackData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_FIND_CONVERSATIONS);
-        // void findConversations (AbstractFilter filter,
-        //         MessageConversationArraySuccessCallback successCallback,
-        //         optional ErrorCallback? errorCallback,
-        //         optional SortMode? sort,
-        //         optional unsigned long? limit,
-        //         optional unsigned long? offset)
-        ArgumentValidator validator(context, argumentCount, arguments);
-
-        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                getPrivateObject(context, validator.toJSValueRef(0));
-        if (!filter) {
-            LOGE("Wrong filter");
-            throw Common::TypeMismatchException("Invalid filter");
-        }
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new ConversationCallbackData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        callback->setFilter(filter);
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        JSObjectRef sortmodeobj = validator.toObject(3, true);
-        if(sortmodeobj != NULL){
-            DeviceAPI::Tizen::SortModePtr sortMode =
-                    Tizen::JSSortMode::getPrivateObject(context, sortmodeobj);
-            if (!sortMode) {
-                LOGE("Wrong sort mode");
-                throw Common::TypeMismatchException("Invalid sort mode");
-            }
-            LOGD("sort mode is set");
-            callback->setSortMode(sortMode);
-        }
-
-        callback->setLimit(validator.toULong(4, true, 0));
-        callback->setOffset(validator.toULong(5, true, 0));
-
-        priv->findConversations(callback);
-    }
-    catch (const WrtDeviceApis::Commons::Exception& exc) {
-        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
-        Common::TypeMismatchException err(exc.GetMessage().c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot find conversations");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::removeConversations(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    ConversationCallbackData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
-                thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS);
-        // void removeConversation(MessageConversation[] conversations,
-        //         optional SuccessCallback? successCallback,
-        //         optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        std::vector<JSValueRef> conversations = validator.toJSValueRefVector(0);
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new ConversationCallbackData(g_ctx);
-        LOGD("created new callback: %p", callback);
-
-        callback->addConversations(context, conversations);
-        callback->setSuccessCallback(validator.toFunction(1, true));
-        callback->setErrorCallback(validator.toFunction(2, true));
-
-        priv->removeConversations(callback);
-    } catch (const BasePlatformException& err) {
-        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    } catch (...) {
-        LOGE("Unknown error while removing conversation");
-        delete callback;
-        callback = NULL;
-        Common::UnknownException err("Cannot remove conversations");
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::findFolders(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    FoldersCallbackData* callback = NULL;
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_FIND_FOLDERS);
-        // void findFolders(AbstractFilter filter,
-        //         MessageFolderArraySuccessCallback successCallback,
-        //         optional ErrorCallback? errorCallback);
-        ArgumentValidator validator(context, argumentCount, arguments);
-
-        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                getPrivateObject(context, validator.toJSValueRef(0));
-        if (!filter) {
-            LOGE("Wrong filter");
-            throw Common::TypeMismatchException("Invalid filter");
-        }
-
-        JSContextRef global_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-
-        callback = new FoldersCallbackData(global_ctx);
-        LOGD("created new callback: %p", callback);
-
-        callback->setFilter(filter);
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-        priv->findFolders(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot find folders");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSValueRef JSMessageStorage::addMessagesChangeListener(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER);
-        // long addMessagesChangeListener (
-        //         MessagesChangeCallback messagesChangeCallback,
-        //         optional AbstractFilter filter)
-        ArgumentValidator validator(context, argumentCount, arguments);
-        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0, false,
-                MESSAGESADDED, MESSAGESUPDATED, MESSAGESREMOVED, NULL);
-
-        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, MESSAGESADDED);
-        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, MESSAGESUPDATED);
-        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, MESSAGESREMOVED);
-
-
-        JSContextRef global_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-
-        auto callback = std::make_shared<MessagesChangeCallback>(
-                global_ctx,
-                on_added_obj,
-                on_updateded_obj,
-                on_removed_obj,
-                priv->getMsgServiceId(),
-                priv->getMsgServiceType());
-
-        JSObjectRef filterobj = validator.toObject(1, true);
-        if (filterobj != NULL) {
-            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                    getPrivateObject(context, validator.toJSValueRef(1));
-            if (!filter) {
-                LOGE("Wrong filter");
-                throw Common::TypeMismatchException("Invalid filter");
-            }
-            LOGD("filter is set");
-            callback->setFilter(filter);
-        }
-        return JSValueMakeNumber(context, priv->addMessagesChangeListener(callback));
-    }
-    catch (const WrtDeviceApis::Commons::Exception& exc) {
-        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
-        Common::TypeMismatchException err(exc.GetMessage().c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot add listener for messages");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-}
-
-JSValueRef JSMessageStorage::addConversationsChangeListener(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
-                thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER);
-        // long addConversationsChangeListener(
-        //         MessageConversationsChangeCallback conversationsChangeCallback,
-        //         optional AbstractFilter? filter)
-        ArgumentValidator validator(context, argumentCount, arguments);
-        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0,false,
-                CONVERSATIONSADDED, CONVERSATIONSUPDATED, CONVERSATIONSREMOVED,
-                NULL);
-
-        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, CONVERSATIONSADDED);
-        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, CONVERSATIONSUPDATED);
-        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, CONVERSATIONSREMOVED);
-
-        JSContextRef global_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-
-        auto callback = std::make_shared<ConversationsChangeCallback>(
-                global_ctx,
-                on_added_obj,
-                on_updateded_obj,
-                on_removed_obj,
-                priv->getMsgServiceId(),
-                priv->getMsgServiceType());
-
-        JSObjectRef filterobj = validator.toObject(1, true);
-        if (filterobj != NULL) {
-            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                    getPrivateObject(context, validator.toJSValueRef(1));
-            if (!filter) {
-                LOGE("Wrong filter");
-                throw Common::TypeMismatchException("Invalid filter");
-            }
-            LOGD("filter is set");
-            callback->setFilter(filter);
-        }
-
-        return JSValueMakeNumber(context,
-                priv->addConversationsChangeListener(callback));
-    }
-    catch (const WrtDeviceApis::Commons::Exception& exc) {
-        LOGE("Wrong filer mode: %s", exc.GetMessage().c_str());
-        Common::TypeMismatchException err(exc.GetMessage().c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot add listener for conversations");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-}
-
-
-JSValueRef JSMessageStorage::addFoldersChangeListener(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
-                thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER);
-        // long addFoldersChangeListener(
-        //         MessageFoldersChangeCallback foldersChangeCallback,
-        //         optional AbstractFilter? filter);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0, false,
-                FOLDERSADDED, FOLDERSUPDATED, FOLDERSREMOVED, NULL);
-
-        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, FOLDERSADDED);
-        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, FOLDERSUPDATED);
-        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
-                js_callbacks_obj, FOLDERSREMOVED);
-
-        JSContextRef global_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-
-        auto callback = std::make_shared<FoldersChangeCallback>(
-                global_ctx,
-                on_added_obj,
-                on_updateded_obj,
-                on_removed_obj,
-                priv->getMsgServiceId(),
-                priv->getMsgServiceType());
-
-        JSObjectRef filterobj = validator.toObject(1, true);
-        if (filterobj != NULL) {
-            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
-                    getPrivateObject(context, validator.toJSValueRef(1));
-            if (!filter) {
-                LOGE("Wrong filter");
-                throw Common::TypeMismatchException("Invalid filter");
-            }
-            LOGD("filter is set");
-            callback->setFilter(filter);
-        }
-
-        return JSValueMakeNumber(context, priv->addFoldersChangeListener(callback));
-    }
-    catch (const WrtDeviceApis::Commons::Exception& exc) {
-        LOGE("Wrong filer mode: %s", exc.GetMessage().c_str());
-        Common::TypeMismatchException err(exc.GetMessage().c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot add listener for folders");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-}
-
-JSValueRef JSMessageStorage::removeChangeListener(JSContextRef context,
-        JSObjectRef function,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    try {
-        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
-                thisObject);
-        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
-                MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER);
-        // void removeChangeListener(long watchId);
-        ArgumentValidator validator(context, argumentCount, arguments);
-        long watchId = validator.toLong(0);
-
-        priv->removeChangeListener(context, watchId);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Cannot add listener for folders");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-JSObjectRef JSMessageStorage::getFunctionFromCallbackObj(JSContextRef context,
-        JSObjectRef obj,
-        const char* name)
-{
-    JSObjectRef function_obj = NULL;
-    JSStringRef propertyName = JSStringCreateWithUTF8CString(name);
-    bool has = JSObjectHasProperty(context, obj, propertyName);
-    JSStringRelease(propertyName);
-    if (has) {
-        JSValueRef value = JSUtil::getProperty(context, obj, name);
-        function_obj = JSUtil::JSValueToObject(context, value);
-    }
-    return function_obj;
-}
-
-} //Messaging
-} //DeviceAPI
-
diff --git a/messaging/old/JSMessageStorage.h b/messaging/old/JSMessageStorage.h
deleted file mode 100755 (executable)
index c841e08..0000000
+++ /dev/null
@@ -1,160 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGE_STORAGE_H__
-#define __TIZEN_JS_MESSAGE_STORAGE_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-#include <memory>
-
-#include "MessageStorage.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class JSMessageStorage
-{
-public:
-// @struct JSClassDefinition
-// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
-    static const JSClassDefinition* getClassInfo();
-
-    static const JSClassRef getClassRef();
-
-    static std::shared_ptr<MessageStorage> getPrivateObject(JSContextRef context,
-            JSValueRef value);
-
-    static void setPrivateObject(JSObjectRef object,
-            std::shared_ptr<MessageStorage> data);
-
-    static JSObjectRef makeJSObject(JSContextRef context,
-            std::shared_ptr<MessageStorage> ptr);
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context, JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    static JSValueRef addDraftMessage(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef findMessages(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef findConversations(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef removeConversations(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef findFolders(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-     static JSValueRef removeMessages(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-     static JSValueRef updateMessages(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef addMessagesChangeListener(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef addConversationsChangeListener(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef addFoldersChangeListener(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    static JSValueRef removeChangeListener(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSStaticFunction m_function[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-    static JSObjectRef getFunctionFromCallbackObj(JSContextRef context,
-            JSObjectRef obj,
-            const char* name);
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGE_STORAGE_H__
-
diff --git a/messaging/old/JSMessagingManager.cpp b/messaging/old/JSMessagingManager.cpp
deleted file mode 100755 (executable)
index 70c00d8..0000000
+++ /dev/null
@@ -1,182 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <string.h>
-
-#include <JSWebAPIErrorFactory.h>
-
-#include <GlobalContextManager.h>
-#include <ArgumentValidator.h>
-#include <Export.h>
-#include <Logger.h>
-#include <TimeTracer.h>
-#include <system_info.h>
-
-#include "JSMessagingManager.h"
-#include "MessagingManager.h"
-#include "MessagingUtil.h"
-
-#include "plugin_config_impl.h"
-
-using namespace std;
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const char* MESSAGING = "Messaging";
-}
-
-JSClassRef JSMessagingManager::m_jsClassRef = NULL;
-
-JSClassDefinition JSMessagingManager::m_classInfo = {
-    0,
-    kJSClassAttributeNone,
-    MESSAGING,
-    NULL,
-    NULL,
-    JSMessagingManager::m_function,
-    JSMessagingManager::initialize,
-    JSMessagingManager::finalize,
-    NULL, //hasProperty,
-    NULL, //getProperty,
-    NULL, //setProperty,
-    NULL, //deleteProperty,
-    NULL, //getPropertyNames,
-    NULL,
-    NULL,
-    NULL, //hasInstance,
-    NULL
-};
-
-JSStaticFunction JSMessagingManager::m_function[] = {
-        { MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
-                JSMessagingManager::getMessageServices, kJSPropertyAttributeNone },
-        { 0, 0, 0 }
-};
-
-const JSClassDefinition* JSMessagingManager::getClassInfo() {
-    LOGD("Entered");
-    return &(m_classInfo);
-}
-
-const JSClassRef DLL_EXPORT JSMessagingManager::getClassRef() {
-    LOGD("Entered");
-    if (!m_jsClassRef) {
-        m_jsClassRef = JSClassCreate(&m_classInfo);
-    }
-    return m_jsClassRef;
-}
-
-void JSMessagingManager::initialize(JSContextRef context,
-        JSObjectRef object)
-{
-    LOGD("Entered");
-    JSObjectSetPrivate(object, static_cast<void*>(&(MessagingManager::getInstance())));
-}
-
-void JSMessagingManager::finalize(JSObjectRef object)
-{
-    LOGD("Entered");
-    JSObjectSetPrivate(object, NULL);
-}
-
-JSValueRef JSMessagingManager::getMessageServices(JSContextRef context,
-        JSObjectRef object,
-        JSObjectRef thisObject,
-        size_t argumentCount,
-        const JSValueRef arguments[],
-        JSValueRef* exception)
-{
-    SET_TIME_TRACER_ITEM(0);
-    LOGD("Entered");
-
-    MessageServiceCallbackData *callback = NULL;
-    bool isSupported = false;
-
-    try {
-        ArgumentValidator validator(context, argumentCount, arguments);
-        MessageType msgTag = MessagingUtil::stringToMessageType(validator.toString(0));
-        LOGD("Messaging Service Type: %d", msgTag);
-
-        JSContextRef g_ctx =
-                GlobalContextManager::getInstance()->getGlobalContext(context);
-        callback = new(std::nothrow) MessageServiceCallbackData(g_ctx);
-        if (!callback) {
-            LOGE("Callback data creation failed");
-            throw Common::UnknownException("Callback data creation failed");
-        }
-        callback->setSuccessCallback(validator.toFunction(1));
-        callback->setErrorCallback(validator.toFunction(2, true));
-        callback->setMessageType(msgTag);
-
-        MessageType msgType = callback->getMessageType();
-        switch (msgType) {
-            case MessageType::SMS:
-                if (system_info_get_platform_bool("tizen.org/feature/network.telephony", &isSupported) != SYSTEM_INFO_ERROR_NONE) {
-                    LoggerE("Can't know whether SMS is supported or not");
-                    //TODO: need to throw unknown error
-                }
-                LoggerD("isSMSSupported " << isSupported);
-
-                if (isSupported == false) {
-                    LoggerE("SMS is not supported");
-                    throw DeviceAPI::Common::NotSupportedException("Unsupported message type (SMS)");
-                }
-                break;
-            case MessageType::MMS:
-                if (system_info_get_platform_bool("tizen.org/feature/network.telephony.mms", &isSupported) != SYSTEM_INFO_ERROR_NONE) {
-                    LoggerE("Can't know whether mms is supported or not");
-                    //TODO: need to throw unknown error
-                }
-                LoggerD("isSupported " << isSupported);
-
-                if (isSupported == false) {
-                    LoggerE("mms is not supported");
-                    throw DeviceAPI::Common::NotSupportedException("Unsupported message type (MMS)");
-                }
-                break;
-            case MessageType::EMAIL:
-                LoggerD("Email type");
-                break;
-            default:
-                LoggerE("This type is not supported");
-                throw DeviceAPI::Common::TypeMismatchException("Unsupported message type");
-        }
-        MessagingManager::getInstance().getMessageServices(callback);
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-    catch (...) {
-        Common::UnknownException err("Unknown error, cannot get message services");
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete callback;
-        callback = NULL;
-        return JSWebAPIErrorFactory::postException(context, exception, err);
-    }
-
-    return JSValueMakeUndefined(context);
-}
-
-} // Messaging
-} // DeviceAPI
-
diff --git a/messaging/old/JSMessagingManager.h b/messaging/old/JSMessagingManager.h
deleted file mode 100755 (executable)
index ad6850b..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_JS_MESSAGING_MANAGER_H__
-#define __TIZEN_JS_MESSAGING_MANAGER_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class JSMessagingManager
-{
-public:
-// @struct JSClassDefinition
-// @abstract This structure contains properties and callbacks that define a type of object.
-//           All fields other than the version field are optional. Any pointer may be NULL.
-    static const JSClassDefinition* getClassInfo();
-    static const JSClassRef getClassRef();
-
-private:
-    /**
-     * The callback invoked when an object is first created.
-     */
-    static void initialize(JSContextRef context, JSObjectRef object);
-
-    /**
-     * The callback invoked when an object is finalized.
-     */
-    static void finalize(JSObjectRef object);
-
-    /**
-    * The callback invoked when determining whether an object has a property.
-    */
-    static bool hasProperty(JSContextRef context,
-            JSObjectRef object,
-            JSStringRef propertyName);
-
-    static JSValueRef getMessageServices(JSContextRef context,
-            JSObjectRef object,
-            JSObjectRef thisObject,
-            size_t argumentCount,
-            const JSValueRef arguments[],
-            JSValueRef* exception);
-
-    /**
-     * This structure contains properties and callbacks that define a type of object.
-     */
-    static JSClassDefinition m_classInfo;
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSStaticFunction m_function[];
-
-    /**
-     * This structure describes a statically declared function property.
-     */
-    static JSClassRef m_jsClassRef;
-
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif //__TIZEN_JS_MESSAGING_MANAGER_H__
-
diff --git a/messaging/old/Message.cpp b/messaging/old/Message.cpp
deleted file mode 100644 (file)
index 388c5f6..0000000
+++ /dev/null
@@ -1,1628 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        Message.cpp
- */
-
-#include "Message.h"
-#include "MessageSMS.h"
-#include "MessageMMS.h"
-#include "MessageEmail.h"
-#include "MessagingUtil.h"
-#include "FilesystemExternalUtils.h"
-#include "FilesystemUtils.h"
-#include "Ecore_File.h"
-#include "JSMessage.h"
-
-#include <PlatformException.h>
-#include <Logger.h>
-#include <time.h>
-#include <sys/stat.h>
-#include <sstream>
-
-namespace DeviceAPI {
-
-using namespace Tizen;
-
-namespace Messaging {
-
-// *** constructor
-Message::Message():
-    m_id(-1), m_id_set(false), m_conversation_id(-1),
-    m_conversation_id_set(false), m_folder_id(-1), m_folder_id_set(false),
-    m_type(UNDEFINED), m_timestamp_set(false), m_from_set(false),
-    m_body(new(std::nothrow) MessageBody()),
-    m_service_id(0), m_is_read(false), m_has_attachment(false),
-    m_high_priority(false), m_in_response(-1), m_in_response_set(false),
-    m_service_id_set(false), m_status(STATUS_UNDEFINED),
-    m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN)
-{
-    LOGD("Message constructor (%p)", this);
-}
-
-Message::~Message()
-{
-    LOGD("Message destructor (%p)", this);
-}
-
-// *** attribute getters
-int Message::getId() const
-{
-    return m_id;
-}
-
-int Message::getConversationId() const
-{
-    return m_conversation_id;
-}
-
-int Message::getFolderId() const
-{
-    // TODO: folderId is supported different way in SMS/MMS and email
-    return m_folder_id;
-}
-
-MessageType Message::getType() const
-{
-    return m_type;
-}
-
-time_t Message::getTimestamp() const
-{
-    return m_timestamp;
-}
-
-std::string Message::getFrom() const
-{
-    return m_from;
-}
-
-std::vector<std::string> Message::getTO() const
-{
-    return m_to;
-}
-
-JSObjectRef Message::getJSTO(JSContextRef global_ctx)
-{
-    return m_to.getJSArray(global_ctx);
-}
-
-std::vector<std::string> Message::getCC() const
-{
-    return m_cc;
-}
-
-JSObjectRef Message::getJSCC(JSContextRef global_ctx)
-{
-    return m_cc.getJSArray(global_ctx);
-}
-
-std::vector<std::string> Message::getBCC() const
-{
-    return m_bcc;
-}
-
-JSObjectRef Message::getJSBCC(JSContextRef global_ctx)
-{
-    return m_bcc.getJSArray(global_ctx);
-}
-
-std::shared_ptr<MessageBody> Message::getBody() const
-{
-    return m_body;
-}
-
-bool Message::getIsRead() const
-{
-    return m_is_read;
-}
-
-bool Message::getHasAttachment() const
-{
-    // This function should be reimplemented for MMS and email
-    return m_has_attachment;
-}
-
-bool Message::getIsHighPriority() const
-{
-    return m_high_priority;
-}
-
-std::string Message::getSubject() const
-{
-    return m_subject;
-}
-
-int Message::getInResponseTo() const
-{
-    return m_in_response;
-}
-
-MessageStatus Message::getMessageStatus() const
-{
-    return m_status;
-}
-
-AttachmentPtrVector Message::getMessageAttachments() const
-{
-    return m_attachments;
-}
-
-JSObjectRef Message::getJSMessageAttachments(JSContextRef global_ctx)
-{
-    return m_attachments.getJSArray(global_ctx);
-}
-
-int Message::getServiceId() const
-{
-    return m_service_id;
-}
-
-TelNetworkDefaultDataSubs_t Message::getSimIndex() const
-{
-    return m_sim_index;
-}
-
-// *** attributes setters
-void Message::setId(int id)
-{
-    m_id = id;
-    m_id_set = true;
-    m_body->setMessageId(m_id);
-}
-
-void Message::setConversationId(int id)
-{
-    m_conversation_id = id;
-    m_conversation_id_set = true;
-}
-
-void Message::setFolderId(int id)
-{
-    m_folder_id = id;
-    m_folder_id_set = true;
-}
-
-// type setting not allowed - no setter for type
-
-void Message::setTimeStamp(time_t timestamp)
-{
-    m_timestamp = timestamp;
-    m_timestamp_set = true;
-}
-
-void Message::setFrom(std::string from)
-{
-    m_from = from;
-    m_from_set = true;
-}
-
-void Message::setTO(std::vector<std::string> &to)
-{
-    // Recipient's format validation should be done by Core API service
-    m_to = to;
-
-    if(m_to.empty()) {
-        LOGD("Recipient's list cleared");
-        return;
-    }
-}
-
-void Message::setCC(std::vector<std::string> &cc)
-{
-    // implementation (address/number format checking) is message specific
-}
-
-void Message::setBCC(std::vector<std::string> &bcc)
-{
-    // implementation (address/number format checking) is message specific
-}
-
-void Message::setBody(std::shared_ptr<MessageBody>& body)
-{
-    // while replacing message body old body should have some invalid id mark
-    m_body->setMessageId(-1);
-    m_body = body;
-    if(m_id_set) {
-        m_body->setMessageId(m_id);
-    }
-}
-
-void Message::setIsRead(bool read)
-{
-    m_is_read = read;
-}
-
-// has attachment can't be set explicity -> no setter for this flag
-
-void Message::setIsHighPriority(bool highpriority)
-{
-    // High priority field is used only in MessageEmail
-    m_high_priority = highpriority;
-}
-
-void Message::setSubject(std::string subject)
-{
-    // Subject is used only in MessageEmail and MessageMMS
-}
-
-void Message::setInResponseTo(int inresp)
-{
-    m_in_response = inresp;
-    m_in_response_set = true;
-}
-
-void Message::setMessageStatus(MessageStatus status)
-{
-    m_status = status;
-}
-
-void Message::setMessageAttachments(AttachmentPtrVector &attachments)
-{
-    // implementation provided only for MMS and email
-}
-
-
-void Message::setServiceId(int service_id)
-{
-    m_service_id = service_id;
-    m_service_id_set = true;
-}
-
-void Message::setSimIndex(TelNetworkDefaultDataSubs_t sim_index)
-{
-    m_sim_index = sim_index;
-}
-
-// ***  support for optional, nullable (at JS layer) attibutes
-bool Message::is_id_set() const
-{
-    return m_id_set;
-}
-
-bool Message::is_conversation_id_set() const
-{
-    return m_conversation_id_set;
-}
-
-bool Message::is_folder_id_set() const
-{
-    return m_folder_id_set;
-}
-
-bool Message::is_timestamp_set() const
-{
-    return m_timestamp_set;
-}
-
-bool Message::is_from_set() const
-{
-    return m_from_set;
-}
-
-bool Message::is_in_response_set() const
-{
-    return m_in_response_set;
-}
-
-bool Message::is_service_is_set() const
-{
-    return m_service_id_set;
-}
-
-std::string Message::convertEmailRecipients(const std::vector<std::string> &recipients)
-{
-    std::string address = "";
-    unsigned size = recipients.size();
-    for (unsigned i=0; i<size; ++i)
-    {
-        address += "<"+recipients[i]+">; ";
-    }
-
-    return address;
-}
-
-std::string saveToTempFile(const std::string &data)
-{
-    char buf[] = "XXXXXX";
-    int res = 0;
-
-    mode_t mask = umask(S_IWGRP | S_IWOTH);
-    res = mkstemp(buf);   //Just generate unique name
-
-    std::string fileName = std::string("/tmp/") + buf;
-
-    mode_t old_mask = umask(mask);
-    FILE *file = fopen(fileName.c_str(), "w");
-    umask(old_mask);
-
-    if (NULL == file) {
-        LOGE("Failed to create file");
-        throw Common::UnknownException("Failed to create file");
-    }
-    if (fprintf(file, "%s", data.c_str()) < 0) {
-        LOGE("Failed to write data into file");
-        throw Common::UnknownException("Failed to write data into file");
-    }
-    fflush(file);
-    fclose(file);
-    return fileName;
-}
-
-std::string copyFileToTemp(const std::string& sourcePath)
-{
-    LOGD("Entered");
-    char buf[] = "XXXXXX";
-    std::string dirPath, fileName, attPath, tmpPath;
-
-    mode_t mask = umask(S_IWGRP | S_IWOTH);
-    int err = mkstemp(buf);
-    if (-1 == err) {
-        LOGW("Failed to create unique filename");
-    }
-
-    umask(mask);
-    dirPath = "/tmp/" + std::string(buf);
-
-    if ( sourcePath[0] != '/' ) {
-        attPath = Filesystem::External::fromVirtualPath(sourcePath);
-    } else { // Assuming that the path is a real path
-        attPath = sourcePath;
-    }
-
-    // Looking for the last occurrence of slash in source path
-    std::size_t slashPos;
-    if ((slashPos = attPath.find_last_of('/')) == std::string::npos) {
-        throw Common::UnknownException(
-                "Error while copying file to temp: the source path is invalid.");
-    }
-
-    fileName = attPath.substr(slashPos + 1);
-    tmpPath = dirPath + "/" + fileName;
-
-    LOGD("attPath: %s, tmpPath: %s", attPath.c_str(), tmpPath.c_str());
-    if(EINA_TRUE != ecore_file_mkdir(dirPath.c_str())) {
-        throw Common::UnknownException("Unknown error while creating temp directory.");
-    }
-
-    if(EINA_TRUE != ecore_file_cp(attPath.c_str(), tmpPath.c_str())) {
-        throw Common::UnknownException("Unknown error while copying file to temp.");
-    }
-
-    return dirPath;
-}
-
-void removeDirFromTemp(const std::string& dirPath)
-{
-    if(EINA_TRUE != ecore_file_rmdir(dirPath.c_str())) {
-        throw Common::UnknownException("Unknown error while deleting temp directory.");
-    }
-}
-
-email_mail_data_t* Message::convertPlatformEmail(std::shared_ptr<Message> message)
-{
-    if(EMAIL != message->getType()) {
-        LOGE("Invalid type");
-        throw Common::InvalidValuesException("Invalid type.");
-    }
-
-    email_mail_data_t *mail_data = NULL;
-
-    if(message->is_id_set()) {
-        email_get_mail_data(message->getId(), &mail_data);
-    } else {
-        mail_data = (email_mail_data_t*)malloc(
-                sizeof(email_mail_data_t));
-        memset(mail_data, 0x00, sizeof(email_mail_data_t));
-    }
-
-    if(!message->getFrom().empty()) {
-        std::string from = "<"+message->getFrom()+">";
-        mail_data->full_address_from = strdup(from.c_str());
-    }
-
-    if(!message->getTO().empty()) {
-        std::string to = Message::convertEmailRecipients(message->getTO());
-        mail_data->full_address_to = strdup(to.c_str());
-    }
-
-    if(!message->getCC().empty()) {
-        std::string cc = Message::convertEmailRecipients(message->getCC());
-        mail_data->full_address_cc = strdup(cc.c_str());
-    }
-
-    if(!message->getBCC().empty()) {
-        std::string bcc = Message::convertEmailRecipients(message->getBCC());
-        mail_data->full_address_bcc = strdup(bcc.c_str());
-    }
-
-    if(!message->getSubject().empty()) {
-        std::string subject = message->getSubject();
-        mail_data->subject = strdup(subject.c_str());
-    }
-
-    if(message->getBody()) {
-        std::shared_ptr<MessageBody> body;
-        body = message->getBody();
-        if(!body->getPlainBody().empty()) {
-            std::string body_file_path = saveToTempFile(body->getPlainBody());
-            mail_data->file_path_plain = strdup(body_file_path.c_str());
-            if(!mail_data->file_path_plain)
-            {
-                LOGE("Plain Body file is NULL.");
-                free(mail_data);
-                mail_data = NULL;
-                throw Common::UnknownException("Plain Body file is NULL.");
-            }
-        }
-
-        if(!body->getHtmlBody().empty()) {
-            std::string html_file_path = saveToTempFile(body->getHtmlBody());
-            mail_data->file_path_html = strdup(html_file_path.c_str());
-            if(!mail_data->file_path_html)
-            {
-                LOGE("Html Body file is NULL.");
-                free(mail_data);
-                mail_data = NULL;
-                throw Common::UnknownException("Html Body file is NULL.");
-            }
-        } else if(!body->getPlainBody().empty()) {
-            // check html data is exist if not exist copy plain body to html body
-            std::string html_file_path = saveToTempFile(body->getPlainBody());
-            mail_data->file_path_html = strdup(html_file_path.c_str());
-            if(!mail_data->file_path_html)
-            {
-                LOGE("Plain Body file is NULL.");
-                free(mail_data);
-                mail_data = NULL;
-                throw Common::UnknownException("Plain Body file is NULL.");
-            }
-        }
-    }
-
-    mail_data->flags_seen_field = message->getIsRead()?1:0;
-
-    if(message->getIsHighPriority()) {
-        mail_data->priority = EMAIL_MAIL_PRIORITY_HIGH;
-    } else {
-        mail_data->priority = EMAIL_MAIL_PRIORITY_NORMAL;
-    }
-
-    return mail_data;
-}
-
-void addSingleEmailAttachment(std::shared_ptr<Message> message,
-        std::shared_ptr<MessageAttachment> att, AttachmentType attType)
-{
-    std::string dirPath = copyFileToTemp(att->getFilePath());
-
-    email_attachment_data_t* tmp = new email_attachment_data_t();
-    tmp->attachment_name = strdup(att->getShortFileName().c_str());
-    tmp->attachment_path  = strdup(std::string(dirPath + "/"
-            + att->getShortFileName()).c_str());
-    tmp->save_status = 1;
-    tmp->inline_content_status = attType;
-
-    int id = message->getId();
-    int err = email_add_attachment(id, tmp);
-    if(EMAIL_ERROR_NONE != err) {
-        LOGE("Error while adding attachment %d", err);
-        err = email_free_attachment_data(&tmp, 1);
-        if (EMAIL_ERROR_NONE != err) {
-            LOGW("Failed to free attachment data");
-        }
-        throw Common::UnknownException("Unknown error while adding attachment");
-    }
-
-    att->setId(tmp->attachment_id);
-    att->setMessageId(id);
-    err = email_free_attachment_data(&tmp, 1);
-    if (EMAIL_ERROR_NONE != err) {
-        LOGW("Failed to free attachment data");
-    }
-
-    removeDirFromTemp(dirPath);
-}
-
-void Message::addEmailAttachments(std::shared_ptr<Message> message)
-{
-    LOGD("Entered");
-
-    int attachment_data_count = 0, error;
-    email_mail_data_t *mail = NULL;
-    email_attachment_data_t *attachment_data_list = NULL;
-    email_meeting_request_t *meeting_req = NULL;
-
-
-    AttachmentPtrVector attachments = message->getMessageAttachments();
-    AttachmentPtrVector inlineAttachments = message->getBody()->getInlineAttachments();
-    LOGD("Attachments size: %d", attachments.size());
-    LOGD("Inline attachments size: %d", inlineAttachments.size());
-    LOGD("Adding attachments for mail id = [%d]\n", message->getId());
-    for (auto it = attachments.begin(); it != attachments.end(); ++it) {
-        addSingleEmailAttachment(message, *it, AttachmentType::EXTERNAL);
-    }
-    for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) {
-        addSingleEmailAttachment(message, *it, AttachmentType::INLINE);
-    }
-
-    //Update of mail on server using function email_update_mail() is not possible.
-    //Attachment is updated only locally, so there is need to use workaround:
-    //1. add new mail with null attachments list
-    //2. add attachments to mail (locally)
-    //3. create new email with attachments and add it to server
-    //4. delete mail without attachments
-
-    //getting mail and attachments data
-    mail = Message::convertPlatformEmail(message);
-    error = email_get_attachment_data_list(mail->mail_id, &attachment_data_list, &attachment_data_count);
-    if (EMAIL_ERROR_NONE != error) {
-        email_free_mail_data(&mail, 1);
-        email_free_attachment_data(&attachment_data_list,attachment_data_count);
-        LOGE("Error while adding attachments. Failed to get attachment list.");
-        throw Common::UnknownException("Error while adding attachments. Failed to get attachment list.");
-    }
-
-    //save mail without attachments id
-    int tmp_id = mail->mail_id;
-
-    //adding new mail with attachments
-    error = email_add_mail(mail, attachment_data_list, attachment_data_count, meeting_req, 0);
-    if (EMAIL_ERROR_NONE != error) {
-        email_free_mail_data(&mail, 1);
-        email_free_attachment_data(&attachment_data_list,attachment_data_count);
-        LOGE("Error while re-adding mail: %d", error);
-        throw Common::UnknownException("Error while re-adding mail");
-    }
-    LOGD("mail added - new id = [%d]\n", mail->mail_id);
-
-    //refresh message object
-    message->setId(mail->mail_id);
-    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
-    for (auto it = attachments.begin(); it != attachments.end(); ++it) {
-        (*it)->setMessageId(mail->mail_id);
-    }
-    for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) {
-        (*it)->setMessageId(mail->mail_id);
-    }
-    email_free_attachment_data(&attachment_data_list,attachment_data_count);
-
-    //deleting mail without attachments
-    error = email_delete_mail(mail->mailbox_id,&tmp_id,1,1);
-    if (EMAIL_ERROR_NONE != error) {
-        email_free_mail_data(&mail, 1);
-        LOGE("Error while deleting mail from server: %d", error);
-        throw Common::UnknownException("Error while deleting mail from server");
-    }
-    email_free_mail_data(&mail, 1);
-}
-
-void Message::addSMSRecipientsToStruct(const std::vector<std::string> &recipients,
-        msg_struct_t &msg)
-{
-    const unsigned size = recipients.size();
-    for (unsigned int i = 0; i < size; ++i) {
-        char *address = const_cast<char *>(recipients.at(i).c_str());
-
-        LOGD("[%d] address:[%s]", i, address);
-        msg_struct_t tmpAddr = NULL;
-        if (MSG_SUCCESS
-                == msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr)) {
-            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT,
-                    MSG_ADDRESS_TYPE_PLMN);
-            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
-                    MSG_RECIPIENTS_TYPE_TO);
-            msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
-                    address, strlen(address));
-        }
-        else {
-            LOGE("failed to add address[%d] %s", i, address);
-            throw Common::UnknownException("failed to add address");
-        }
-    }
-}
-
-void Message::addMMSRecipientsToStruct(const std::vector<std::string> &recipients,
-        msg_struct_t &msg, int type)
-{
-    const unsigned size = recipients.size();
-    for (unsigned int i = 0; i < size; ++i) {
-
-        msg_struct_t tmpAddr = NULL;
-        int address_type = MSG_ADDRESS_TYPE_PLMN;
-        const std::size_t found = recipients[i].find("@");
-        if (std::string::npos != found) {
-            address_type = MSG_ADDRESS_TYPE_EMAIL;
-        }
-
-        char *address = const_cast<char *>(recipients.at(i).c_str());
-        LOGD("[%d] address:[%s] address_type:%d type:%d", i, address, address_type, type);
-
-        int error = msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr);
-        if (MSG_SUCCESS == error) {
-            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT,
-                    address_type);
-            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
-                    type);
-            msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
-                    address, strlen(address));
-        }
-        else {
-            LOGE("[%d] failed to add address: [%s], error: %d", i, address, error);
-            throw Common::UnknownException("failed to add address");
-        }
-    }
-}
-
-void Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector attach,
-        msg_struct_t &mms_struct, Message* message)
-{
-    LOGD("Entered with %d attachments", attach.size());
-
-    int size = attach.size();
-    for (int i = 0; i < size; i++) {
-
-        msg_struct_t tmpAtt = NULL;
-        int error = msg_list_add_item(mms_struct, MSG_STRUCT_MMS_ATTACH, &tmpAtt);
-        if (MSG_SUCCESS == error) {
-
-            //Ensure we have right id set
-            attach[i]->setId(i+1);
-            attach[i]->setMessageId(message->getId());
-
-            //-------------------------------------------------------------------------
-            // set file path, file name, file size
-            if (attach.at(i)->isFilePathSet()) {
-                std::string filepath = attach.at(i)->getFilePath();
-                LOGD("att[%d]: org filepath: %s", i, filepath.c_str());
-                if(Filesystem::External::isVirtualPath(filepath)) {
-                    // TODO
-                    // When introducing below line fromVirtualPath() function
-                    // needed context, but never used it - allowing for null
-                    // context pointer. If it appears to need a real context
-                    // it will need a fix here.
-                    filepath = Filesystem::External::fromVirtualPath(filepath);
-                    LOGD("att[%d]: org virtual filepath: %s", i, filepath.c_str());
-                }
-                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILEPATH_STR,
-                        const_cast<char*>(filepath.c_str()), filepath.size());
-                const size_t last_slash_idx = filepath.find_last_of("\\/");
-                if (std::string::npos != last_slash_idx) {
-                    filepath.erase(0, last_slash_idx + 1);
-                }
-
-                LOGD("att[%d] filename: %s", i, filepath.c_str());
-                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILENAME_STR,
-                        const_cast<char*>(filepath.c_str()), filepath.size());
-                struct stat st;
-                if (stat(const_cast<char*>(filepath.c_str()), &st)) {
-                    LOGE("Stat error");
-                }
-                const int fsize = st.st_size;
-                msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_FILESIZE_INT, fsize);
-                LOGD("att[%d]: filesize: %d", i,fsize);
-            }
-
-            //-------------------------------------------------------------------------
-            //set mime type
-            if (attach.at(i)->isMimeTypeSet()) {
-                unsigned int type = MessageAttachment::MIMETypeStringToEnum(
-                        attach.at(i)->getMimeType());
-                msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_MIME_TYPE_INT, type);
-                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_CONTENT_TYPE_STR,
-                                    const_cast<char*>(attach.at(i)->getMimeType().c_str()),
-                                    MSG_MSG_ID_LEN);
-
-
-                LOGD("att[%d]: setting mime type:0x%x (orignal:%s)", i, type,
-                    attach.at(i)->getMimeType().c_str());
-            }
-        } else {
-            LOGE("att[%d]: failed to add attachment");
-            throw Common::UnknownException("failed to add attachment");
-        }
-    }
-}
-
-msg_struct_t Message::convertPlatformShortMessageToStruct(Message* message,
-        msg_handle_t handle)
-{
-    LOGD("Entered");
-
-    if (message->getType() != SMS && message->getType() != MMS) {
-        LOGD("Invalid type");
-        throw Common::InvalidValuesException("Invalid type");
-    }
-
-    msg_error_t err = MSG_SUCCESS;
-    msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
-    msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-
-    if (message->is_id_set()) { // id is set - the message exists in database
-        msg_message_id_t id = (msg_message_id_t) message->getId();
-        err = msg_get_message(handle, id, msg, sendOpt);
-        if (err != MSG_SUCCESS) {
-            msg_release_struct(&sendOpt);
-            msg_release_struct(&msg);
-            LOGD("msg_get_message() Fail [%d]", err);
-            throw Common::UnknownException("msg_get_message() Fail");
-        }
-        LOGD("Using existing msg for id: %d", id);
-    } else { // id is not set - the message does not exist in database
-        MessageType msgType = message->getType();
-        if (msgType == MessageType::SMS) {
-            // Set message type to SMS
-            if (MSG_SUCCESS
-                    != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_SMS)) {
-                msg_release_struct(&sendOpt);
-                msg_release_struct(&msg);
-                LOGE("Set SMS type error");
-                throw Common::UnknownException("Set SMS type error");
-            }
-        } else {
-            // Set message type to MMS
-            if (MSG_SUCCESS
-                    != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS)) {
-                msg_release_struct(&sendOpt);
-                msg_release_struct(&msg);
-                LOGE("Set MMS type error");
-                throw Common::UnknownException("Set MMS type error");
-            }
-        }
-    }
-    msg_release_struct(&sendOpt);
-
-    int type;
-    msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &type);
-    LOGD("Message(%p): MSG_MESSAGE_TYPE = %d", message, type);
-
-    if (type == MSG_TYPE_SMS) {
-        // Set SMS message body text
-        std::shared_ptr<MessageBody> body;
-        body = message->getBody();
-        if (!body->getPlainBody().empty()) {
-            msg_set_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, const_cast<char*>
-                    (body->getPlainBody().c_str()), body->getPlainBody().size());
-        }
-
-        // Reset SMS recipients
-        int error = msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND);
-        if( MSG_SUCCESS != error) {
-            LOGE("Failed to clear address list, error: %d", error);
-            throw Common::UnknownException("Failed to clear address list");
-        }
-
-        // Set SMS recipients
-        std::vector<std::string> recp_list = message->getTO();
-        if (!recp_list.empty()) {
-            message->addSMSRecipientsToStruct(recp_list, msg);
-        }
-
-    } else if (type == MSG_TYPE_MMS) {
-        // Set message type to MMS
-        if (MSG_SUCCESS
-                != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS)) {
-            LOGE("Message(%p): Set MMS type error", message);
-            throw Common::UnknownException("Set MMS type error");
-        }
-        // Create MMS data
-        msg_struct_t mms_data = msg_create_struct(MSG_STRUCT_MMS);
-        if (mms_data == NULL) {
-            LOGE("Message(%p): Set MMS data error", message);
-            throw Common::UnknownException("Set MMS data error");
-        }
-        // Set MMS message subject
-        std::string subject = message->getSubject();
-        if (subject != "") {
-            int r = msg_set_str_value(msg, MSG_MESSAGE_SUBJECT_STR,
-                    const_cast<char*>(subject.c_str()), subject.size());
-            if (r != MSG_SUCCESS) {
-                LOGE("Message(%p): Set MMS subject error: %d", message, r);
-                throw Common::UnknownException("Set MMS subject error");
-            }
-        }
-        // Set MMS message text
-        std::shared_ptr<MessageBody> body;
-        body = message->getBody();
-        if (!body->getPlainBody().empty()) {
-            LOGD("Message(%p): PlainBody is NOT empty", message);
-
-            static const int ROOT_LAYOUT_WIDTH = 100;
-            static const int ROOT_LAYOUT_HEIGHT = 100;
-            static const int WHITE_COLOR = 0xffffff;
-            static const int BLACK_COLOR = 0x000000;
-
-            //----------------------------------------------------------------------------
-            //Region
-            msg_struct_t region;
-            msg_list_add_item(mms_data, MSG_STRUCT_MMS_REGION, &region);
-            msg_set_str_value(region, MSG_MMS_REGION_ID_STR, const_cast<char*>("Text"), 4);
-
-            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_LEFT_INT, 0);
-            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_TOP_INT, 0);
-            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_WIDTH_INT,
-                    ROOT_LAYOUT_WIDTH);
-            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_INT,
-                    ROOT_LAYOUT_HEIGHT);
-            msg_set_int_value(region, MSG_MMS_REGION_BGCOLOR_INT, WHITE_COLOR);
-
-            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL, true);
-            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL, true);
-            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL, true);
-            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL, true);
-
-            //----------------------------------------------------------------------------
-            //Page
-            msg_struct_t page;
-            msg_list_add_item(mms_data, MSG_STRUCT_MMS_PAGE, &page);
-            msg_set_int_value(page, MSG_MMS_PAGE_PAGE_DURATION_INT, 0);
-
-            //----------------------------------------------------------------------------
-            //Media
-            msg_struct_t media;
-            msg_list_add_item(page, MSG_STRUCT_MMS_MEDIA, &media);
-            msg_set_int_value(media, MSG_MMS_MEDIA_TYPE_INT, MMS_SMIL_MEDIA_TEXT);
-            msg_set_str_value(media, MSG_MMS_MEDIA_REGION_ID_STR,
-                    const_cast<char*>("Text"), 4);
-
-            std::string body_file_path = saveToTempFile(body->getPlainBody());
-            int error = msg_set_str_value(media,
-                    MSG_MMS_MEDIA_FILEPATH_STR,
-                    const_cast<char*>(body_file_path.c_str()),
-                    body_file_path.size());
-            if (error != MSG_SUCCESS) {
-                LOGE("Message(%p): Failed to set mms body filepath", message);
-                throw Common::UnknownException("Failed to set mms body filepath");
-            }
-            msg_set_str_value(media, MSG_MMS_MEDIA_CONTENT_TYPE_STR,
-                "text/plain", 10);
-
-            //----------------------------------------------------------------------------
-            //Smile text
-            msg_struct_t smil_text;
-            msg_get_struct_handle(media, MSG_MMS_MEDIA_SMIL_TEXT_HND, &smil_text);
-            msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_COLOR_INT, BLACK_COLOR);
-            msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_SIZE_INT,
-                    MMS_SMIL_FONT_SIZE_NORMAL);
-            msg_set_bool_value(smil_text, MSG_MMS_SMIL_TEXT_BOLD_BOOL, true);
-        } else {
-            LOGD("Message(%p): PlainBody is EMPTY", message);
-        }
-        // Set MMS attachments
-        AttachmentPtrVector attach_list = message->getMessageAttachments();
-        LOGD("Message(%p): id:%d subject:[%s] plainBody:[%s] contains %d attachments",
-                message, message->getId(), message->getSubject().c_str(),
-                message->getBody()->getPlainBody().c_str(), attach_list.size());
-
-        msg_set_int_value(mms_data, MSG_MESSAGE_ATTACH_COUNT_INT,
-                attach_list.size());
-        if (!attach_list.empty()) {
-            addMMSBodyAndAttachmentsToStruct(attach_list, mms_data, message);
-        }
-        // Set MMS body
-        int r = msg_set_mms_struct(msg, mms_data);
-        if (r != MSG_SUCCESS) {
-            LOGE("Message(%p): Set MMS body error: %d", message, r);
-            throw Common::UnknownException("Set MMS body error");
-        }
-        msg_release_struct(&mms_data);
-
-        // Reset MMS recipients
-        msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND);
-
-        std::vector<std::string> recp_list = message->getTO();
-        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_TO);
-
-        recp_list = message->getCC();
-        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_CC);
-
-        recp_list = message->getBCC();
-        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_BCC);
-    }
-    else {
-        msg_release_struct(&msg);
-        LOGE("Message(%p): Invalid message type", message);
-        throw Common::InvalidValuesException("Invalid message type");
-    }
-
-    // set common attributes for SMS and MMS
-    // Set message conversation id
-    if (message->is_conversation_id_set()) {
-        msg_set_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, message->getConversationId());
-    }
-    // Set message folder id
-    if (message->is_folder_id_set()) {
-        msg_set_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, message->getFolderId());
-    }
-    // Set message timestamp
-    if (message->is_timestamp_set()) {
-        msg_set_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, message->getTimestamp());
-    }
-    // Set message from
-    if (message->is_from_set()) {
-        msg_set_str_value(msg, MSG_MESSAGE_REPLY_ADDR_STR, const_cast<char*>
-                (message->getFrom().c_str()), message->getFrom().size());
-    }
-    // Set message if is response
-    if (message->is_in_response_set()) {
-        msg_set_int_value(msg, MSG_MESSAGE_DIRECTION_INT, message->getInResponseTo());
-    }
-
-    // Set SIM index
-    // -1 means unknown - so do not set simindex in that case.
-    int sim_index = static_cast<int>(message->getSimIndex());
-    if (sim_index != -1) {
-        int error =
-            msg_set_int_value(msg, MSG_MESSAGE_SIM_INDEX_INT, sim_index+1);
-        if ( MSG_SUCCESS != error) {
-            LOGE("Failed to set sim index, error: %d", error);
-            throw Common::UnknownException("Failed to set sim index");
-        }
-    }
-
-    // Set message if is read
-    msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, message->getIsRead());
-
-    LOGD("End");
-    return msg;
-}
-
-std::string Message::getShortMsgSenderFromStruct(msg_struct_t &msg)
-{
-    msg_list_handle_t addr_list = NULL;
-    msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list);
-
-    char str_phone_number[MAX_ADDRESS_VAL_LEN];
-    const int count = msg_list_length(addr_list);
-    LOGD("Number of addresses: %d", count);
-
-    for (int i = 0; i < count; ++i)
-    {
-        int tempInt = 0;
-        msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &tempInt);
-        const int type = tempInt;
-
-        if (MSG_DIRECTION_TYPE_MT == type)
-        {
-            msg_struct_t cur_addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
-            msg_get_str_value(cur_addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
-                    str_phone_number, MAX_ADDRESS_VAL_LEN);
-
-            LOGD("[%d/%d] is TYPE_MT, phone number is: %s", i, count, str_phone_number);
-
-            if(0 != str_phone_number[0]) {
-                return std::string(str_phone_number);
-            }
-        } else {
-            LOGD("[%d/%d] is NOT of TYPE_MT skipping, is:%d", i, count, type);
-        }
-    }
-
-    return std::string();
-}
-
-std::vector<std::string> Message::getSMSRecipientsFromStruct(msg_struct_t &msg)
-{
-    std::vector<std::string> address;
-    msg_list_handle_t addr_list = NULL;
-    if (MSG_SUCCESS
-            == msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND,
-                    (void **) &addr_list)) {
-        unsigned size = msg_list_length(addr_list);
-        for (unsigned int i = 0; i < size; i++) {
-            msg_struct_t addr_info = NULL;
-            char infoStr[MAX_ADDRESS_VAL_LEN];
-            //get address
-            addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
-            msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
-                    infoStr, MAX_ADDRESS_VAL_LEN);
-            address.push_back(std::string(infoStr));
-        }
-    } else {
-        LOGE("failed to get recipients");
-        throw Common::UnknownException("failed to add recipients");
-    }
-    return address;
-}
-
-std::vector<std::string> Message::getMMSRecipientsFromStruct(msg_struct_t &msg,
-        int type)
-{
-    std::vector<std::string> address;
-    msg_list_handle_t addr_list = NULL;
-    if (MSG_SUCCESS
-            == msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND,
-                    (void **) &addr_list)) {
-        unsigned size = msg_list_length(addr_list);
-        for (unsigned int i = 0; i < size; i++) {
-            msg_struct_t addr_info = NULL;
-            char infoStr[MAX_ADDRESS_VAL_LEN];
-            int tempInt;
-            //get address
-            addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
-            msg_get_int_value(addr_info, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
-                    &tempInt);
-            if (tempInt == type) {
-                msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
-                        infoStr, MAX_ADDRESS_VAL_LEN);
-                address.push_back(std::string(infoStr));
-            }
-        }
-    } else {
-        LOGE("failed to get recipients");
-        throw Common::UnknownException("failed to add recipients");
-    }
-    return address;
-}
-
-void Message::setMMSBodyAndAttachmentsFromStruct(Message* message,
-        msg_struct_t &msg)
-{
-    LOGD("Entered message(%p)", message);
-    int tempInt = 0;
-    char infoStr[MSG_FILEPATH_LEN_MAX + 1];
-
-    msg_struct_t mms_struct = msg_create_struct(MSG_STRUCT_MMS);
-    int error = msg_get_mms_struct(msg, mms_struct);
-    if (MSG_SUCCESS != error) {
-        LOGE("Cannot get mms struct, error:%d", error);
-        msg_release_struct(&mms_struct);
-        throw Common::UnknownException("cannot get mms struct");
-    }
-
-    bool body_has_been_set = false;
-    // if there are some pages in msg_struct_t
-    msg_list_handle_t page_list = NULL;
-    error = msg_get_list_handle(mms_struct, MSG_MMS_PAGE_LIST_HND, (void **) &page_list);
-    if (MSG_SUCCESS == error) {
-        int pageLen = msg_list_length(page_list);
-        LOGD("MSG_MMS_PAGE_LIST length:%d", pageLen);
-
-        for (int p = 0; p < pageLen; ++p) {
-            msg_struct_t page = (msg_struct_t) msg_list_nth_data(page_list, p);
-            if (!page) {
-                LOGE("returned page is null, continue");
-                continue;
-            }
-
-            msg_list_handle_t media_list = NULL;
-            error = msg_get_list_handle(page, MSG_MMS_PAGE_MEDIA_LIST_HND,
-                    (void **) &media_list);
-            if (MSG_SUCCESS == error) {
-                int mediaLen = msg_list_length(media_list);
-                LOGD("[p:%d] MSG_MMS_PAGE_MEDIA_LIST length:%d", p, mediaLen);
-
-                for (int m = 0; m < mediaLen; ++m) {
-                    msg_struct_t media = (msg_struct_t) msg_list_nth_data(media_list, m);
-                    if (NULL == media) {
-                        LOGE("returned media is null, continue");
-                        continue;
-                    }
-                    // add media from pages to attachments vector
-                    //set file path
-                    memset(infoStr, 0, MSG_FILEPATH_LEN_MAX + 1);
-                    msg_get_str_value(media, MSG_MMS_MEDIA_FILEPATH_STR, infoStr,
-                            MSG_FILEPATH_LEN_MAX);
-                    LOGD("[p:%d, m:%d] attachment file path:%s", p, m, infoStr);
-
-                    msg_get_int_value(media, MSG_MMS_MEDIA_TYPE_INT, &tempInt);
-                    const int msg_media_type = tempInt;
-                    std::string msg_media_type_str =
-                            MessageAttachment::MIMETypeEnumToString(msg_media_type);
-
-                    LOGD("[p:%d, m:%d] MSG_MMS_MEDIA_TYPE: %d (%s)", p, m, msg_media_type,
-                            msg_media_type_str.c_str());
-
-                    //According to old implementation
-                    // "text value on first page goes to body attribute"
-                    if ((0 == p) && (MMS_SMIL_MEDIA_TEXT == msg_media_type)) {
-                        LOGD("Loading body from file: %s ", infoStr);
-
-                        try {
-                            message->getBody()->setPlainBody(
-                                    MessagingUtil::loadFileContentToString(infoStr));
-                            body_has_been_set = true;
-
-                            LOGD("Loaded body: %s",
-                                    message->getBody()->getPlainBody().c_str());
-
-                        } catch(const Common::BasePlatformException& exception) {
-                            LOGE("Unhandled exception: %s (%s)!",
-                                 (exception.getName()).c_str(),
-                                 (exception.getMessage()).c_str());
-                            LOGD("[p:%d, m:%d] body is not set", p, m);
-                        }
-                        catch (...) {
-                            LOGE("Unknown exception occured during plain body loading");
-                            LOGD("[p:%d, m:%d] body is not set", p, m);
-                        }
-
-                    } else {
-                        std::shared_ptr<MessageAttachment> ma (new MessageAttachment());
-                        ma->setFilePath(infoStr);
-
-                        //set message id
-                        msg_get_int_value(msg, MSG_MESSAGE_STORAGE_ID_INT, &tempInt);
-                        ma->setMessageId(tempInt);
-
-                        //set id
-                        ma->setId(message->m_attachments.size() + 1);
-                        message->m_attachments.push_back(ma);
-                        message->m_has_attachment = true;
-
-                        //set mime type
-                        ma->setMimeType(msg_media_type_str);
-
-                        MessageAttachment* att = ma.get();
-                        LOGD("[p:%d, m:%d] added attachment: %p "
-                                "(mime:0x%x mime:%s messageId:%d)", p, m, att,
-                                msg_media_type, msg_media_type_str.c_str(),
-                                ma->getMessageId());
-                    }
-
-                    msg_release_struct(&media);
-                }
-            } else {
-                msg_release_struct(&mms_struct);
-                LOGE("failed to get attachment");
-                throw Common::UnknownException("failed to get attachment");
-            }
-            msg_release_struct(&page);
-        }
-    } else {
-        msg_release_struct(&mms_struct);
-        LOGE("failed to get attachment");
-        throw Common::UnknownException("failed to get attachment");
-    }
-
-    if(false == body_has_been_set) {
-        LOGW("Warning: body has not been set!");
-    }
-
-    LOGD("after MSG_MMS_PAGE_LIST attachments count is:%d",
-            message->m_attachments.size());
-
-    // if there are some other attachments add it to attachments vector
-    msg_list_handle_t attach_list = NULL;
-    error = msg_get_list_handle(mms_struct, MSG_MMS_ATTACH_LIST_HND, (void **)
-            &attach_list);
-    if (MSG_SUCCESS == error) {
-
-        unsigned size = msg_list_length(attach_list);
-        LOGD("MSG_MMS_ATTACH_LIST length:%d", size);
-
-        for (unsigned int i = 0; i < size; i++) {
-            msg_struct_t attach_info = NULL;
-            attach_info = (msg_struct_t) msg_list_nth_data(attach_list, i);
-            if(!attach_info) {
-                LOGW("[att:%d] attach_info is NULL!", i);
-                continue;
-            }
-
-            std::shared_ptr<MessageAttachment> ma (new MessageAttachment());
-
-            //set message id
-            msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &tempInt);
-            ma->setMessageId(tempInt);
-
-            //set file path
-            msg_get_str_value(attach_info, MSG_MMS_ATTACH_FILEPATH_STR, infoStr,
-                    MSG_FILEPATH_LEN_MAX);
-            ma->setFilePath(infoStr);
-
-            //set attachment id
-            ma->setId(message->m_attachments.size() + 1);
-
-            //set mime type
-            msg_get_int_value(attach_info, MSG_MMS_ATTACH_MIME_TYPE_INT, &tempInt);
-            std::string type = MessageAttachment::MIMETypeEnumToString(tempInt);
-            ma->setMimeType(type);
-
-            MessageAttachment* att = ma.get();
-            LOGD("[att:%d] added attachement: %p (mime:0x%x mime:%s path:%s id:%d)",
-                i, att, tempInt, type.c_str(), infoStr, ma->getId());
-
-            message->m_attachments.push_back(ma);
-            message->m_has_attachment = true;
-
-            msg_release_struct(&attach_info);
-        }
-    } else {
-        msg_release_struct(&mms_struct);
-        LOGE("failed to get attachment");
-        throw Common::UnknownException("failed to add attachment");
-    }
-
-    LOGD("after MSG_MMS_ATTACH_LIST attachments count is:%d",
-            message->m_attachments.size());
-    msg_release_struct(&mms_struct);
-}
-
-Message* Message::convertPlatformShortMessageToObject(msg_struct_t msg){
-    Message *message = NULL;
-    int infoInt;
-    bool infoBool;
-    char infoStr[MAX_ADDRESS_VAL_LEN + 1];
-    //get type
-    msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &infoInt);
-    if (infoInt == MSG_TYPE_SMS) {
-        message = new MessageSMS();
-        // get SMS body
-        std::shared_ptr<MessageBody> body(new MessageBody());
-        char msgInfoStr[MAX_MSG_TEXT_LEN + 1];
-        msg_get_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, msgInfoStr, MAX_MSG_TEXT_LEN);
-        body->setPlainBody(std::string(msgInfoStr));
-        message->setBody(body);
-        // get recipients
-        std::vector<std::string> recp_list = message->getSMSRecipientsFromStruct(msg);
-        message->setTO(recp_list);
-    } else if (infoInt == MSG_TYPE_MMS) {
-        message = new MessageMMS();
-
-        // get MMS body
-        msg_get_int_value(msg, MSG_MESSAGE_DATA_SIZE_INT, &infoInt);
-        const int mms_body_length = infoInt;
-
-        if(mms_body_length > 0) {
-            std::unique_ptr<char[]> mms_body_str(new char[mms_body_length + 1]);
-            memset(mms_body_str.get(), 0, (mms_body_length + 1) * sizeof(char));
-
-            int error = msg_get_str_value(msg, MSG_MESSAGE_MMS_TEXT_STR,
-                    mms_body_str.get(), mms_body_length);
-            if(MSG_SUCCESS != error) {
-                LOGE("Error:%d occured during: "
-                        "msg_get_str_value(...,MSG_MESSAGE_MMS_TEXT_STR,...)", error);
-            } else {
-                //Check if fetched string is not empty
-                if((mms_body_str.get())[0] != 0) {
-                    LOGD("Fetched plain body (with MSG_MESSAGE_MMS_TEXT_STR):"
-                            "[%s] length:%d", mms_body_str.get(), mms_body_length);
-
-                    std::shared_ptr<MessageBody> body (new MessageBody());
-                    std::string infoString;
-                    infoString.assign(mms_body_str.get());
-                    body->setPlainBody(infoString);
-                    message->setBody(body);
-                } else {
-                    LOGW("Warning: fetched plain body is empty "
-                            "despite reported length is:%d!", mms_body_length);
-                }
-
-                LOGD("Set plain body: [%s]", message->getBody()->getPlainBody().c_str());
-            }
-        } else {
-            LOGW("Warning: mms plain body length is 0!");
-        }
-
-        // get recipients
-        std::vector<std::string> recp_list = getMMSRecipientsFromStruct(msg,
-                MSG_RECIPIENTS_TYPE_TO);
-        message->setTO(recp_list);
-        recp_list = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_CC);
-        message->setCC(recp_list);
-        recp_list = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_BCC);
-        message->setBCC(recp_list);
-        // get subject
-        memset(infoStr, 0, MAX_ADDRESS_VAL_LEN + 1);
-        msg_get_str_value(msg, MSG_MESSAGE_SUBJECT_STR, infoStr, MAX_SUBJECT_LEN);
-        message->setSubject(infoStr);
-        //set attachments
-        setMMSBodyAndAttachmentsFromStruct(message, msg);
-    } else {
-        LOGE("Invalid Message type: %d", infoInt);
-        throw Common::InvalidValuesException("Invalid Message type");
-    }
-
-    // get id
-    msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &infoInt);
-    message->setId(infoInt);
-    // get conversation id
-    msg_get_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, &infoInt);
-    message->setConversationId(infoInt);
-    // get folder id
-    msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt);
-    message->setFolderId(infoInt);
-    // get timestamp
-    msg_get_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, &infoInt);
-    message->setTimeStamp(infoInt);
-    // get from
-    const std::string& from = Message::getShortMsgSenderFromStruct(msg);
-    message->setFrom(from);
-    LOGD("Message(%p) from is: %s", message, message->getFrom().c_str());
-    // get if is in response
-    msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &infoInt);
-    LOGD("Message(%p) direction is: %d", message, infoInt);
-    message->setInResponseTo(infoInt);
-    // get is read
-    msg_get_bool_value(msg, MSG_MESSAGE_READ_BOOL, &infoBool);
-    message->setIsRead(infoBool);
-
-    // get status
-
-    // This "strange" fix has been taken from old implementation:
-    // void Mms::readMessageStatus(msg_struct_t& messageData)
-    //
-    int error = msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt);
-    if(MSG_SUCCESS == error) {
-        MessageStatus msg_status;
-        switch (infoInt) {
-            case MSG_INBOX_ID: msg_status = MessageStatus::STATUS_LOADED; break;
-            case MSG_OUTBOX_ID: msg_status = MessageStatus::STATUS_SENDING; break;
-            case MSG_SENTBOX_ID: msg_status = MessageStatus::STATUS_SENT; break;
-            case MSG_DRAFT_ID: msg_status = MessageStatus::STATUS_DRAFT; break;
-            default: msg_status = MessageStatus::STATUS_LOADED; break;
-        }
-        message->setMessageStatus(msg_status);
-
-        LOGD("MSG_MESSAGE_FOLDER_ID:%d -> messageStatus:%s", infoInt,
-                MessagingUtil::messageStatusToString(msg_status).c_str());
-    }
-    else
-    {
-        LOGE("Couldn't get MSG_MESSAGE_FOLDER_ID_INT, error:%d", error);
-        error = msg_get_int_value(msg, MSG_SENT_STATUS_NETWORK_STATUS_INT, &infoInt);
-
-        if(MSG_SUCCESS == error) {
-            MessageStatus msg_status;
-            if (infoInt == MSG_NETWORK_SEND_SUCCESS) {
-                msg_status = MessageStatus::STATUS_SENT;
-            } else if (infoInt == MSG_NETWORK_SENDING) {
-                msg_status = MessageStatus::STATUS_SENDING;
-            } else if (infoInt == MSG_NETWORK_SEND_FAIL) {
-                msg_status = MessageStatus::STATUS_FAILED;
-            } else if (infoInt == MSG_NETWORK_NOT_SEND) {
-                msg_status = MessageStatus::STATUS_DRAFT;
-            } else {
-                LOGW("warning undefined messageStatus: %d!", infoInt);
-                msg_status = MessageStatus::STATUS_UNDEFINED;
-            }
-            message->setMessageStatus(msg_status);
-
-            LOGD("MSG_SENT_STATUS_NETWORK_STATUS:%d MessageStatus:%s", infoInt,
-                MessagingUtil::messageStatusToString(msg_status).c_str());
-        } else {
-            LOGE("Couldn't get MSG_SENT_STATUS_NETWORK_STATUS_INT, error:%d", error);
-
-            if(0 == message->getId()) {
-                LOGW("Both MSG_SENT_STATUS_NETWORK_STATUS_INT and "
-                        "MSG_MESSAGE_FOLDER_ID_INT failed, messageId == 0 ASSUMING that"
-                        "this message is in DRAFT");
-                message->setMessageStatus(MessageStatus::STATUS_DRAFT);
-            }
-        }
-    }
-
-    LOGD("End");
-    return message;
-}
-
-std::vector<std::string> Message::split(const std::string& input,
-        char delimiter)
-{
-    std::vector<std::string> ret;
-    std::stringstream stream(input);
-    std::string item;
-    while (getline(stream, item, delimiter)) {
-        ret.push_back(item);
-    }
-    return ret;
-}
-
-std::vector<std::string> Message::getEmailRecipientsFromStruct(const char *recipients)
-{
-    std::vector<std::string> tmp = Message::split(recipients, ';');
-    for (std::vector<std::string>::iterator it = tmp.begin(); it != tmp.end(); ++it) {
-        *it = MessagingUtil::ltrim(*it);
-    }
-
-    if (tmp.begin() != tmp.end()) {
-        if (*(tmp.begin()) == "") {
-            tmp.erase(tmp.begin());
-        }
-
-        if (*(tmp.end() - 1) == "") {
-            tmp.erase(tmp.end() - 1);
-        }
-    }
-
-    // remove '<' and '>'
-    tmp = MessagingUtil::extractEmailAddresses(tmp);
-    return tmp;
-}
-
-std::shared_ptr<MessageBody> Message::convertEmailToMessageBody(
-        email_mail_data_t& mail)
-{
-    LOGD("Enter");
-    std::shared_ptr<MessageBody> body (new MessageBody());
-    body->updateBody(mail);
-    return body;
-}
-
-AttachmentPtrVector Message::convertEmailToMessageAttachment(email_mail_data_t& mail)
-{
-    LOGD("Enter");
-    email_attachment_data_t* attachment = NULL;
-    int attachmentCount = 0;
-
-    AttachmentPtrVector att;
-
-    if (EMAIL_ERROR_NONE != email_get_attachment_data_list(mail.mail_id,
-            &attachment, &attachmentCount)) {
-        throw Common::UnknownException("Couldn't get attachment.");
-    }
-    if ( attachment && attachmentCount > 0) {
-        for (int i = 0; i < attachmentCount; i++) {
-            std::shared_ptr<MessageAttachment> tmp_att (new MessageAttachment());
-            tmp_att->updateWithAttachmentData(attachment[i]);
-            att.push_back(tmp_att);
-        }
-    }
-
-    email_free_attachment_data(&attachment, attachmentCount);
-    return att;
-}
-
-std::shared_ptr<Message> Message::convertPlatformEmailToObject(
-        email_mail_data_t& mail)
-{
-    LOGD("Enter");
-    std::shared_ptr<Message> message(new MessageEmail());
-    message->updateEmailMessage(mail);
-    return message;
-}
-
-void Message::updateEmailMessage(email_mail_data_t& mail)
-{
-    LOGW("This should be called on MessageEmail instance");
-}
-
-/**
- *  Attribute      | Attribute filter| Attribute range filter
- *                 | supported       | supported
- * ----------------+-----------------+------------------------
- *  id             | Yes             | No
- *  serviceId      | Yes             | No
- *  conversationId | No              | No
- *  folderId       | Yes             | No
- *  type           | Yes             | No
- *  timestamp      | No              | Yes
- *  from           | Yes             | No
- *  to             | Yes             | No
- *  cc             | Yes             | No
- *  bcc            | Yes             | No
- *  body.plainBody | Yes             | No
- *  isRead         | Yes             | No
- *  hasAttachment  | Yes             | No
- *  isHighPriority | Yes             | No
- *  subject        | Yes             | No
- *  isResponseTo   | No              | No
- *  messageStatus  | No              | No
- *  attachments    | No              | No
- **/
-namespace MESSAGE_FILTER_ATTRIBUTE {
-
-const std::string ID = JSMessageKeys::MESSAGE_ATTRIBUTE_ID;
-const std::string SERVICE_ID = "serviceId";
-const std::string CONVERSATION_ID = JSMessageKeys::MESSAGE_ATTRIBUTE_CONVERSATION_ID;
-const std::string FOLDER_ID = JSMessageKeys::MESSAGE_ATTRIBUTE_FOLDER_ID;
-const std::string TYPE = JSMessageKeys::MESSAGE_ATTRIBUTE_TYPE;
-const std::string TIMESTAMP = JSMessageKeys::MESSAGE_ATTRIBUTE_TIMESTAMP;
-const std::string FROM = JSMessageKeys::MESSAGE_ATTRIBUTE_FROM;
-const std::string TO = JSMessageKeys::MESSAGE_ATTRIBUTE_TO;
-const std::string CC = JSMessageKeys::MESSAGE_ATTRIBUTE_CC;
-const std::string BCC = JSMessageKeys::MESSAGE_ATTRIBUTE_BCC;
-const std::string BODY_PLAIN_BODY = "body.plainBody";
-const std::string IS_READ = JSMessageKeys::MESSAGE_ATTRIBUTE_IS_READ;
-const std::string HAS_ATTACHMENT = JSMessageKeys::MESSAGE_ATTRIBUTE_HAS_ATTACHMENT;
-const std::string IS_HIGH_PRIORITY = JSMessageKeys::MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY;
-const std::string SUBJECT = JSMessageKeys::MESSAGE_ATTRIBUTE_SUBJECT;
-
-} //namespace MESSAGE_FILTER_ATTRIBUTE
-
-bool Message::isMatchingAttribute(const std::string& attribute_name,
-            const FilterMatchFlag match_flag,
-            AnyPtr match_value) const
-{
-    LOGD("Entered");
-    auto key = match_value->toString();
-    LOGD("attribute_name:%s match_flag:%d matchValue:%s", attribute_name.c_str(),
-            match_flag, key.c_str());
-
-    using namespace MESSAGE_FILTER_ATTRIBUTE;
-
-    if (ID == attribute_name) {
-        return FilterUtils::isStringMatching(key, std::to_string(getId()),
-                match_flag);
-    }
-    else if (SERVICE_ID == attribute_name) {
-        if(is_service_is_set()) {
-            return FilterUtils::isStringMatching(key, std::to_string(getServiceId()),
-                    match_flag);
-        }
-    }
-    else if (FOLDER_ID == attribute_name) {
-        return FilterUtils::isStringMatching(key, std::to_string(getFolderId()),
-                match_flag);
-    }
-    else if (TYPE == attribute_name) {
-        const std::string msgTypeStr = MessagingUtil::messageTypeToString(getType());
-        return FilterUtils::isStringMatching(key, msgTypeStr, match_flag);
-    }
-    else if (FROM == attribute_name) {
-        return FilterUtils::isStringMatching(key, getFrom() , match_flag);
-    }
-    else if (TO == attribute_name) {
-        return FilterUtils::isAnyStringMatching(key, getTO(), match_flag);
-    }
-    else if (CC == attribute_name) {
-        return FilterUtils::isAnyStringMatching(key, getCC(), match_flag);
-    }
-    else if (BCC == attribute_name) {
-        return FilterUtils::isAnyStringMatching(key, getBCC(), match_flag);
-    }
-    else if (BODY_PLAIN_BODY == attribute_name) {
-        if(getBody()) {
-            return FilterUtils::isStringMatching(key, getBody()->getPlainBody(),
-                    match_flag);
-        }
-    }
-    else if (IS_READ == attribute_name) {
-        return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getIsRead()),
-                match_flag);
-    }
-    else if (HAS_ATTACHMENT == attribute_name) {
-        return FilterUtils::isStringMatching(key,
-                FilterUtils::boolToString(getHasAttachment()),
-                match_flag);
-    }
-    else if (IS_HIGH_PRIORITY == attribute_name) {
-        return FilterUtils::isStringMatching(key,
-                FilterUtils::boolToString(getIsHighPriority()),
-                match_flag);
-    }
-    else if (SUBJECT == attribute_name) {
-        return FilterUtils::isStringMatching(key, getSubject(), match_flag);
-    }
-    else {
-        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
-    }
-
-    return false;
-}
-
-bool Message::isMatchingAttributeRange(const std::string& attribute_name,
-            AnyPtr initial_value,
-            AnyPtr end_value) const
-{
-    LOGD("Entered attribute_name: %s", attribute_name.c_str());
-
-    using namespace MESSAGE_FILTER_ATTRIBUTE;
-    if(TIMESTAMP == attribute_name) {
-        return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value,
-                end_value);
-    }
-    else {
-        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
-    }
-
-    return false;
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/Message.h b/messaging/old/Message.h
deleted file mode 100644 (file)
index eefd089..0000000
+++ /dev/null
@@ -1,230 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        Message.h
- */
-
-#ifndef __TIZEN_MESSAGE_H__
-#define __TIZEN_MESSAGE_H__
-
-#include <time.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string>
-#include <vector>
-#include <memory>
-#include <msg_product.h>
-#include <msg_storage.h>
-#include "MessagingUtil.h"
-#include "MessageAttachment.h"
-#include "MessageBody.h"
-#include "JSVector.h"
-#include <email-api.h>
-#include <AbstractFilter.h>
-#include <TelNetwork.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-
-struct MessageHolder {
-    std::shared_ptr<Message> ptr;
-};
-
-typedef std::shared_ptr<Message> MessagePtr;
-typedef std::vector<MessagePtr> MessagePtrVector;
-
-enum AttachmentType {
-    EXTERNAL = 0,
-    INLINE = 1
-};
-
-class Message : public Tizen::FilterableObject {
-public:
-// constructor
-    Message();
-    virtual ~Message();
-
-// attributes getters
-    int getId() const;
-    int getConversationId() const;
-    int getFolderId() const;
-    MessageType getType() const;
-    time_t getTimestamp() const;
-    std::string getFrom() const;
-    std::vector<std::string> getTO() const;
-    JSObjectRef getJSTO(JSContextRef global_ctx);
-    std::vector<std::string> getCC() const;
-    JSObjectRef getJSCC(JSContextRef global_ctx);
-    std::vector<std::string> getBCC() const;
-    JSObjectRef getJSBCC(JSContextRef global_ctx);
-    std::shared_ptr<MessageBody> getBody() const;
-    bool getIsRead() const;
-     // getHasAttachment() is virtual to support MMS and email differently
-    virtual bool getHasAttachment() const;
-    bool getIsHighPriority() const;
-    std::string getSubject() const;
-    int getInResponseTo() const;
-    MessageStatus getMessageStatus() const;
-    AttachmentPtrVector getMessageAttachments() const;
-    JSObjectRef getJSMessageAttachments(JSContextRef global_ctx);
-    int getServiceId() const;
-    TelNetworkDefaultDataSubs_t getSimIndex() const;
-
-// attributes setters (virtual because some of them can be overriden in sub classes)
-    virtual void setId(int id);
-    virtual void setConversationId(int id);
-    virtual void setFolderId(int id);
-    // type setting not allowed so no setter provided
-    virtual void setTimeStamp(time_t timestamp);
-    virtual void setFrom(std::string from);
-    virtual void setTO(std::vector<std::string> &to);
-    virtual void setCC(std::vector<std::string> &cc);
-    virtual void setBCC(std::vector<std::string> &bcc);
-    virtual void setBody(std::shared_ptr<MessageBody>& body);
-    virtual void setIsRead(bool read);
-    // has attachment can't be set explicity -> no setter for this flag
-    virtual void setIsHighPriority(bool highpriority);
-    virtual void setSubject(std::string subject);
-    virtual void setInResponseTo(int inresp);
-    virtual void setMessageStatus(MessageStatus status);
-    virtual void setMessageAttachments(AttachmentPtrVector &attachments);
-    virtual void setServiceId(int service_id);
-    virtual void setSimIndex(TelNetworkDefaultDataSubs_t sim_index);
-
-// support for optional, nullable (at JS layer) attibutes
-    // message id
-    bool is_id_set() const;
-    // conversation id
-    bool is_conversation_id_set() const;
-    // folder id
-    bool is_folder_id_set() const;
-    // timestamp
-    bool is_timestamp_set() const;
-    // message sender
-    bool is_from_set() const;
-    // related message ("parent" message)
-    bool is_in_response_set() const;
-    // service id
-    bool is_service_is_set() const;
-    // gets recipients list for SMS message
-    void addSMSRecipientsToStruct(const std::vector<std::string> &recipients,
-            msg_struct_t &msg);
-    // gets recipients list for SMS message
-    void addMMSRecipientsToStruct(const std::vector<std::string> &recipients,
-            msg_struct_t &msg, int type);
-    /**
-     * Updates message with data from email_mail_data_t structure.
-     * @param mail
-     */
-    virtual void updateEmailMessage(email_mail_data_t& mail);
-
-    // gets from(sender) address from short msg struct
-    static std::string getShortMsgSenderFromStruct(msg_struct_t &msg);
-    // function for filling msg_struct_t fields
-    static msg_struct_t convertPlatformShortMessageToStruct(Message* message,
-            msg_handle_t handle);
-    // gets recipients list for SMS message
-    std::vector<std::string> getSMSRecipientsFromStruct(msg_struct_t &msg);
-    // gets recipients list for MMS message
-    static std::vector<std::string> getMMSRecipientsFromStruct(msg_struct_t &msg, int type);
-    // function for filling Message attributes
-    static Message* convertPlatformShortMessageToObject(msg_struct_t msg);
-    static void addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector attach,
-            msg_struct_t &mms_struct, Message* message);
-    static void setMMSBodyAndAttachmentsFromStruct(Message *message, msg_struct_t &msg);
-
-    static email_mail_data_t* convertPlatformEmail(std::shared_ptr<Message> message);
-    static void addEmailAttachments(std::shared_ptr<Message> message);
-    static std::string convertEmailRecipients(const std::vector<std::string> &recipients);
-    static std::vector<std::string> getEmailRecipientsFromStruct(const char *recipients);
-    static std::shared_ptr<Message> convertPlatformEmailToObject(email_mail_data_t& mail);
-    static std::shared_ptr<MessageBody> convertEmailToMessageBody(email_mail_data_t& mail);
-    static AttachmentPtrVector convertEmailToMessageAttachment(email_mail_data_t& mail);
-
-    // Tizen::FilterableObject
-    virtual bool isMatchingAttribute(const std::string& attribute_name,
-            const Tizen::FilterMatchFlag match_flag,
-            Tizen::AnyPtr match_value) const;
-
-    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
-            Tizen::AnyPtr initial_value,
-            Tizen::AnyPtr end_value) const;
-protected:
-    //! Message id
-    int m_id;
-    //! Flag for checking if id is set (false means: not set)
-    bool m_id_set;
-    //! Conversation id
-    int m_conversation_id;
-    //! Flag for checking if conversation id is set (false means: not set)
-    bool m_conversation_id_set;
-    //! Folder id
-    int m_folder_id;
-    //! Flag for checking if folder id is set (false means: not set)
-    bool m_folder_id_set;
-    //! Message type (messaging.sms, messaging.mms, messaging.email)
-    MessageType m_type;
-    //! Timestamp - time when message has been sent/received
-    time_t m_timestamp;
-    //! Flag for checking if timestamp is set (false means: not set)
-    bool m_timestamp_set;
-    //! Message sender address (email) or number (SMS, MMS)
-    std::string m_from;
-    //! Flag for checking if sender is set (false means: not set)
-    bool m_from_set;
-    //! Message recipients
-    Common::JSStringVector m_to;
-    //! Message CarbonCopy recipients (used only for email)
-    Common::JSStringVector m_cc;
-    //! Message BlindCarbonCopy recipients (used only for email)
-    Common::JSStringVector m_bcc;
-    //! MessageBody (object containg plainBody and htmlBody for emails)
-    std::shared_ptr<MessageBody> m_body;
-    //! Service id
-    int m_service_id;
-    //! Message isRead flag
-    bool m_is_read;
-    //! Message hasAttachment flag
-    bool m_has_attachment;
-    //! Message isHighPriority flag
-    bool m_high_priority;
-    //! Message subject (used in MMS and email)
-    std::string m_subject;
-    //! Id of original message when message is a reply or forward
-    int m_in_response;
-    //! Flag for checking if id of related message is set (false means: not set)
-    bool m_in_response_set;
-    //! Flag for checking if service id is set
-    bool m_service_id_set;
-    //! Outgoing Message status (SENT, SENDING, DRAFT etc)
-    MessageStatus m_status;
-    //! Attachments attached to this message
-    JSAttachmentsVector m_attachments;
-    //! SIM index which indicate a sim to send message.
-    TelNetworkDefaultDataSubs_t m_sim_index;
-private:
-    static std::vector<std::string> split(const std::string& input,
-            char delimiter);
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_H__
diff --git a/messaging/old/MessageAttachment.cpp b/messaging/old/MessageAttachment.cpp
deleted file mode 100755 (executable)
index 68d6844..0000000
+++ /dev/null
@@ -1,590 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageAttachment.cpp
- */
-
-#include "MessageAttachment.h"
-#include <email-api.h>
-#include <PlatformException.h>
-#include <Logger.h>
-namespace DeviceAPI {
-namespace Messaging {
-
-std::map<std::string,unsigned int>& MessageAttachment::MIMETypeStringToEnumMap = initializeMIMETypeStringToEnumMap();
-std::map<unsigned int, std::string>& MessageAttachment::MIMETypeEnumToStringMap = initializeMIMETypeEnumToStringMap();
-
-
-
-MessageAttachment::MessageAttachment()
-{
-    LOGD("MessageAttachment constructor (%p)", this);
-    m_id = -1;
-    m_isIdSet = false;
-    m_messageId = -1;
-    m_isMessageIdSet = false;
-    m_mimeType = "";
-    m_isMimeTypeSet = false;
-    m_filePath = "";
-    m_isFilePathSet = false;
-    m_isSaved = true;
-}
-
-MessageAttachment::~MessageAttachment()
-{
-    LOGD("MessageAttachment destructor (%p)", this);
-}
-
-// id
-
-int MessageAttachment::getId()
-{
-    return m_id;
-}
-
-void MessageAttachment::setId(int value)
-{
-    m_id = value;
-    m_isIdSet = true;
-}
-
-bool MessageAttachment::isIdSet()
-{
-    return m_isIdSet;
-}
-
-void MessageAttachment::unsetId()
-{
-    m_isIdSet = false;
-}
-
-// messageId
-
-int MessageAttachment::getMessageId()
-{
-    return m_messageId;
-}
-
-void MessageAttachment::setMessageId(int value)
-{
-    m_messageId = value;
-    m_isMessageIdSet = true;
-}
-
-bool MessageAttachment::isMessageIdSet()
-{
-    return m_isMessageIdSet;
-}
-
-void MessageAttachment::unsetMessageId()
-{
-    m_isMessageIdSet = false;
-}
-
-// mimeType
-
-std::string MessageAttachment::getMimeType()
-{
-    return m_mimeType;
-}
-
-void MessageAttachment::setMimeType(const std::string &value)
-{
-    m_mimeType = value;
-    m_isMimeTypeSet = true;
-}
-
-bool MessageAttachment::isMimeTypeSet()
-{
-    return m_isMimeTypeSet;
-}
-
-void MessageAttachment::unsetMimeType()
-{
-    m_isMimeTypeSet = false;
-}
-
-// filePath
-
-std::string MessageAttachment::getFilePath()
-{
-    return m_filePath;
-}
-
-std::string MessageAttachment::getShortFileName() const
-{
-    if (!m_isFilePathSet) {
-        return "";
-    }
-    size_t pos;
-    // find position of last occurence of / sign (get only file name from all path
-    pos = m_filePath.find_last_of("/");
-
-    if ((pos + 1) >= m_filePath.size() || pos == std::string::npos) {
-        return m_filePath;
-    }
-    return m_filePath.substr(pos + 1);
-}
-
-void MessageAttachment::setFilePath(const std::string &value)
-{
-    m_filePath = value;
-    m_isFilePathSet = true;
-}
-
-bool MessageAttachment::isFilePathSet()
-{
-    return m_isFilePathSet;
-}
-
-void MessageAttachment::unsetFilePath()
-{
-    m_isFilePathSet = false;
-}
-
-void MessageAttachment::setIsSaved(bool isSaved)
-{
-    m_isSaved = isSaved;
-}
-
-bool MessageAttachment::isSaved() const
-{
-    return m_isSaved;
-}
-
-std::map<unsigned int, std::string>& MessageAttachment::initializeMIMETypeEnumToStringMap(){
-    static std::map<unsigned int, std::string> enumToString;
-    //0
-    enumToString[MIME_ASTERISK] = "*/*";
-    //1
-    enumToString[MIME_APPLICATION_XML] = "application/xml";
-    enumToString[MIME_APPLICATION_WML_XML] = "application/wml+xml";
-    enumToString[MIME_APPLICATION_XHTML_XML] = "application/xhtml+xml";
-    enumToString[MIME_APPLICATION_JAVA_VM] = "application/java-vm";
-    enumToString[MIME_APPLICATION_SMIL] = "application/smil";
-    enumToString[MIME_APPLICATION_JAVA_ARCHIVE] = "application/java-archive";
-    enumToString[MIME_APPLICATION_JAVA] = "application/java";
-    enumToString[MIME_APPLICATION_OCTET_STREAM] = "application/octet-stream";
-    enumToString[MIME_APPLICATION_STUDIOM] = "application/studiom";
-    enumToString[MIME_APPLICATION_FUNMEDIA] = "application/funMedia";
-    enumToString[MIME_APPLICATION_MSWORD] = "application/msword";
-    enumToString[MIME_APPLICATION_PDF] = "application/pdf";
-    enumToString[MIME_APPLICATION_SDP] = "application/sdp";
-    enumToString[MIME_APPLICATION_RAM] = "application/ram";
-    enumToString[MIME_APPLICATION_ASTERIC] = "application/*";
-    //16
-    enumToString[MIME_APPLICATION_VND_WAP_XHTMLXML] = "application/vnd.wap.xhtml+xml";
-    enumToString[MIME_APPLICATION_VND_WAP_WMLC] = "application/vnd.wap.wmlc";
-    enumToString[MIME_APPLICATION_VND_WAP_WMLSCRIPTC] = "application/vnd.wap.wmlscriptc";
-    enumToString[MIME_APPLICATION_VND_WAP_WTA_EVENTC] = "application/vnd.wap.wta-eventc";
-    enumToString[MIME_APPLICATION_VND_WAP_UAPROF] = "application/vnd.wap.uaprof";
-    enumToString[MIME_APPLICATION_VND_WAP_SIC] = "application/vnd.wap.sic";
-    enumToString[MIME_APPLICATION_VND_WAP_SLC] = "application/vnd.wap.slc";
-    enumToString[MIME_APPLICATION_VND_WAP_COC] = "application/vnd.wap.coc";
-    enumToString[MIME_APPLICATION_VND_WAP_SIA] = "application/vnd.wap.sia";
-    enumToString[MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML] = "application/vnd.wap.connectivity-wbxml";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA] = "application/vnd.wap.multipart.form-data";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES] = "application/vnd.wap.multipart.byteranges";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_MIXED] = "application/vnd.wap.multipart.mixed";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_RELATED] = "application/vnd.wap.multipart.related";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE] = "application/vnd.wap.multipart.alternative";
-    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC] = "application/vnd.wap.multipart.*";
-    enumToString[MIME_APPLICATION_VND_WAP_WBXML] = "application/vnd.wap.wbxml";
-    enumToString[MIME_APPLICATION_VND_OMA_DD_XML] = "application/vnd.oma.dd+xml";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_MESSAGE] = "application/vnd.oma.drm.message";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_CONTENT] = "application/vnd.oma.drm.content";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML] = "application/vnd.oma.drm.rights+xml";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML] = "application/vnd.oma.drm.rights+wbxml";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_RO_XML] = "application/vnd.oma.drm.ro+xml";
-    enumToString[MIME_APPLICATION_VND_OMA_DRM_DCF] = "application/vnd.oma.drm.dcf";
-    enumToString[MIME_APPLICATION_VND_OMA_ROAPPDU_XML] = "application/vnd.oma.drm.roap-pdu+xml";
-    enumToString[MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML] = "application/vnd.oma.drm.roap-trigger+xml";
-    enumToString[MIME_APPLICATION_VND_SMAF] = "application/vnd.smaf";
-    enumToString[MIME_APPLICATION_VND_RN_REALMEDIA] = "application/vnd.rn-realmedia";
-    enumToString[MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE] = "application/vnd.sun.j2me.java-archive";
-    enumToString[MIME_APPLICATION_VND_SAMSUNG_THEME] = "application/vnd.samsung.theme";
-    enumToString[MIME_APPLICATION_VND_EXCEL] = "application/vnd.ms-excel";
-    enumToString[MIME_APPLICATION_VND_POWERPOINT] = "application/vnd.ms-powerpoint";
-    enumToString[MIME_APPLICATION_VND_MSWORD] = "applcation/vnd.ms-word";
-    //49
-    enumToString[MIME_APPLICATION_X_HDMLC] = "application/x-hdmlc";
-    enumToString[MIME_APPLICATION_X_X968_USERCERT] = "application/x-x968-user-cert";
-    enumToString[MIME_APPLICATION_X_WWW_FORM_URLENCODED] = "application/x-www-form-urlencoded";
-    enumToString[MIME_APPLICATION_X_SMAF] = "application/x-smaf";
-    enumToString[MIME_APPLICATION_X_FLASH] = "application/x-shockwave-flash";
-    enumToString[MIME_APPLICATION_X_EXCEL] = "application/x-msexcel";
-    enumToString[MIME_APPLICATION_X_POWERPOINT] = "application/x-mspowerpoint";
-    //56
-    enumToString[MIME_AUDIO_BASIC] = "audio/basic";
-    enumToString[MIME_AUDIO_MPEG] = "audio/mpeg";
-    enumToString[MIME_AUDIO_MP3] = "audio/mp3";
-    enumToString[MIME_AUDIO_MPG3] = "audio/mpg3";
-    enumToString[MIME_AUDIO_MPEG3] = "audio/mpeg3";
-    enumToString[MIME_AUDIO_MPG] = "audio/mpg";
-    enumToString[MIME_AUDIO_AAC] = "audio/aac";
-    enumToString[MIME_AUDIO_G72] = "audio/g72";
-    enumToString[MIME_AUDIO_AMR] = "audio/amr";
-    enumToString[MIME_AUDIO_AMR_WB] = "audio/amr-wb";
-    enumToString[MIME_AUDIO_MMF] = "audio/mmf";
-    enumToString[MIME_AUDIO_SMAF] = "audio/smaf";
-    enumToString[MIME_AUDIO_IMELODY] = "audio/iMelody";
-    enumToString[MIME_AUDIO_IMELODY2] = "audio/imelody";
-    enumToString[MIME_AUDIO_MELODY] = "audio/melody";
-    enumToString[MIME_AUDIO_MID] = "audio/mid";
-    enumToString[MIME_AUDIO_MIDI] = "audio/midi";
-    enumToString[MIME_AUDIO_SP_MIDI] = "audio/sp-midi";
-    enumToString[MIME_AUDIO_WAVE] = "audio/wave";
-    enumToString[MIME_AUDIO_WAV] = "audio/wav";
-    enumToString[MIME_AUDIO_3GPP] = "audio/3gpp";
-    enumToString[MIME_AUDIO_MP4] = "audio/mp4";
-    enumToString[MIME_AUDIO_MP4A_LATM] = "audio/MP4A-LATM";
-    enumToString[MIME_AUDIO_M4A] = "audio/m4a";
-    enumToString[MIME_AUDIO_MPEG4] = "audio/mpeg4";
-    enumToString[MIME_AUDIO_WMA] = "audio/wma";
-    enumToString[MIME_AUDIO_XMF] = "audio/xmf";
-    enumToString[MIME_AUDIO_IMY] = "audio/imy";
-    enumToString[MIME_AUDIO_MOBILE_XMF] = "audio/mobile-xmf";
-    //85
-    enumToString[MIME_AUDIO_VND_RN_REALAUDIO] = "audio/vnd.rn-realaudio";
-    //86
-    enumToString[MIME_AUDIO_X_MPEG] = "audio/x-mpeg";
-    enumToString[MIME_AUDIO_X_MP3] = "audio/x-mp3";
-    enumToString[MIME_AUDIO_X_MPEG3] = "audio/x-mpeg3";
-    enumToString[MIME_AUDIO_X_MPG] = "audio/x-mpg";
-    enumToString[MIME_AUDIO_X_AMR] = "audio/x-amr";
-    enumToString[MIME_AUDIO_X_MMF] = "audio/x-mmf";
-    enumToString[MIME_AUDIO_X_SMAF] = "audio/x-smaf";
-    enumToString[MIME_AUDIO_X_IMELODY] = "audio/x-iMelody";
-    enumToString[MIME_AUDIO_X_MIDI] = "audio/x-midi";
-    enumToString[MIME_AUDIO_X_MPEGAUDIO] = "audio/x-mpegaudio";
-    enumToString[MIME_AUDIO_X_PN_REALAUDIO] = "audio/x-pn-realaudio";
-    enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO] = "audio/x-pn-multirate-realaudio";
-    enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE] = "audio/x-pn-multirate-realaudio-live";
-    enumToString[MIME_AUDIO_X_WAVE] = "audio/x-wave";
-    enumToString[MIME_AUDIO_X_WAV] = "audio/x-wav";
-    enumToString[MIME_AUDIO_X_MS_WMA] = "audio/x-ms-wma";
-    enumToString[MIME_AUDIO_X_MID] = "audio/x-mid";
-    enumToString[MIME_AUDIO_X_MS_ASF] = "audio/x-ms-asf";
-    enumToString[MIME_AUDIO_X_XMF] = "audio/x-xmf";
-    //105
-    enumToString[MIME_IMAGE_GIF] = "image/gif";
-    enumToString[MIME_IMAGE_JPEG] = "image/jpeg";
-    enumToString[MIME_IMAGE_JPG] = "image/jpg";
-    enumToString[MIME_IMAGE_TIFF] = "image/tiff";
-    enumToString[MIME_IMAGE_TIF] = "image/tif";
-    enumToString[MIME_IMAGE_PNG] = "image/png";
-    enumToString[MIME_IMAGE_WBMP] = "image/wbmp";
-    enumToString[MIME_IMAGE_PJPEG] = "image/pjpeg";
-    enumToString[MIME_IMAGE_BMP] = "image/bmp";
-    enumToString[MIME_IMAGE_SVG] = "image/svg+xml";
-    enumToString[MIME_IMAGE_SVG1] = "image/svg-xml";
-    //116
-    enumToString[MIME_IMAGE_VND_WAP_WBMP] = "image/vnd.wap.wbmp";
-    enumToString[MIME_IMAGE_VND_TMO_GIF] = "image/vnd.tmo.my5-gif";
-    enumToString[MIME_IMAGE_VND_TMO_JPG] = "image/vnd.tmo.my5-jpg";
-    //119
-    enumToString[MIME_IMAGE_X_BMP] = "image/x-bmp";
-    //120
-    enumToString[MIME_MESSAGE_RFC822] = "message/rfc822";
-    //121
-    enumToString[MIME_MULTIPART_MIXED] = "multipart/mixed";
-    enumToString[MIME_MULTIPART_RELATED] = "multipart/related";
-    enumToString[MIME_MULTIPART_ALTERNATIVE] = "multipart/alternative";
-    enumToString[MIME_MULTIPART_FORM_DATA] = "multipart/form-data";
-    enumToString[MIME_MULTIPART_BYTERANGE] = "multipart/byterange";
-    enumToString[MIME_MULTIPART_REPORT] = "multipart/report";
-    enumToString[MIME_MULTIPART_VOICE_MESSAGE] = "multipart/voice-message";
-    //128
-    enumToString[MIME_TEXT_TXT] = "text/txt";
-    enumToString[MIME_TEXT_HTML] = "text/html";
-    enumToString[MIME_TEXT_PLAIN] = "text/plain";
-    enumToString[MIME_TEXT_CSS] = "text/css";
-    enumToString[MIME_TEXT_XML] = "text/xml";
-    enumToString[MIME_TEXT_IMELODY] = "text/iMelody";
-    //134
-    enumToString[MIME_TEXT_VND_WAP_WMLSCRIPT] = "text/vnd.wap.wmlscript";
-    enumToString[MIME_TEXT_VND_WAP_WML] = "text/vnd.wap.wml";
-    enumToString[MIME_TEXT_VND_WAP_WTA_EVENT] = "text/vnd.wap.wta-event";
-    enumToString[MIME_TEXT_VND_WAP_CONNECTIVITY_XML] = "text/vnd.wap.connectivity-xml";
-    enumToString[MIME_TEXT_VND_WAP_SI] = "text/vnd.wap.si";
-    enumToString[MIME_TEXT_VND_WAP_SL] = "text/vnd.wap.sl";
-    enumToString[MIME_TEXT_VND_WAP_CO] = "text/vnd.wap.co";
-    enumToString[MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR] = "text/vnd.sun.j2me.app-descriptor";
-    //142
-    enumToString[MIME_TEXT_X_HDML] = "text/x-hdml";
-    enumToString[MIME_TEXT_X_VCALENDAR] = "text/x-vCalendar";
-    enumToString[MIME_TEXT_X_VCARD] = "text/x-vCard";
-    enumToString[MIME_TEXT_X_IMELODY] = "text/x-iMelody";
-    enumToString[MIME_TEXT_X_IMELODY2] = "text/x-imelody";
-    enumToString[MIME_TEXT_X_VNOTE] = "text/x-vnote";
-    //148
-    enumToString[MIME_VIDEO_MPEG4] = "video/mpeg4";
-    enumToString[MIME_VIDEO_MP4] = "video/mp4";
-    enumToString[MIME_VIDEO_H263] = "video/h263";
-    enumToString[MIME_VIDEO_3GPP] = "video/3gpp";
-    enumToString[MIME_VIDEO_3GP] = "video/3gp";
-    enumToString[MIME_VIDEO_AVI] = "video/avi";
-    enumToString[MIME_VIDEO_SDP] = "video/sdp";
-    enumToString[MIME_VIDEO_MP4_ES] = "video/mp4v-es";
-    enumToString[MIME_VIDEO_MPEG] = "video/mpeg";
-    //157
-    enumToString[MIME_VIDEO_VND_RN_REALVIDEO] = "video/vnd.rn-realvideo";
-    enumToString[MIME_VIDEO_VND_RN_REALMEDIA] = "video/vnd.rn-realmedia";
-    //159
-    enumToString[MIME_VIDEO_X_MP4] = "video/x-mp4";
-    enumToString[MIME_VIDEO_X_PV_MP4] = "video/x-pv-mp4";
-    enumToString[MIME_VIDEO_X_PN_REALVIDEO] = "video/x-pn-realvideo";
-    enumToString[MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO] = "video/x-pn-multirate-realvideo";
-    enumToString[MIME_VIDEO_X_MS_WMV] = "video/x-ms-wmv";
-    enumToString[MIME_VIDEO_X_MS_ASF] = "video/x-ms-asf";
-    enumToString[MIME_VIDEO_X_PV_PVX] = "video/x-pv-pvx";
-
-    return enumToString;
-}
-
-std::map<std::string,unsigned int>& MessageAttachment::initializeMIMETypeStringToEnumMap(){
-    static std::map<std::string,unsigned int> stringToEnum;
-    //0
-    stringToEnum["*/*"] = MIME_ASTERISK;
-    //1
-    stringToEnum["application/xml"] = MIME_APPLICATION_XML;
-    stringToEnum["application/wml+xml"] = MIME_APPLICATION_WML_XML;
-    stringToEnum["application/xhtml+xml"] = MIME_APPLICATION_XHTML_XML;
-    stringToEnum["application/java-vm"] = MIME_APPLICATION_JAVA_VM;
-    stringToEnum["application/smil"] = MIME_APPLICATION_SMIL;
-    stringToEnum["application/java-archive"] = MIME_APPLICATION_JAVA_ARCHIVE;
-    stringToEnum["application"] = MIME_APPLICATION_JAVA;
-    stringToEnum["application/octet-stream"] = MIME_APPLICATION_OCTET_STREAM;
-    stringToEnum["application/studiom"] = MIME_APPLICATION_STUDIOM;
-    stringToEnum["application/funMedia"] = MIME_APPLICATION_FUNMEDIA;
-    stringToEnum["application/msword"] = MIME_APPLICATION_MSWORD;
-    stringToEnum["application/pdf"] = MIME_APPLICATION_PDF;
-    stringToEnum["application/sdp"] = MIME_APPLICATION_SDP;
-    stringToEnum["application/ram"] = MIME_APPLICATION_RAM;
-    stringToEnum["application/*"] = MIME_APPLICATION_ASTERIC;
-    //16
-    stringToEnum["application/vnd.wap.xhtml+xml"] = MIME_APPLICATION_VND_WAP_XHTMLXML;
-    stringToEnum["application/vnd.wap.wmlc"] = MIME_APPLICATION_VND_WAP_WMLC;
-    stringToEnum["application/vnd.wap.wmlscriptc"] = MIME_APPLICATION_VND_WAP_WMLSCRIPTC;
-    stringToEnum["application/vnd.wap.wta-eventc"] = MIME_APPLICATION_VND_WAP_WTA_EVENTC;
-    stringToEnum["application/vnd.wap.uaprof"] = MIME_APPLICATION_VND_WAP_UAPROF;
-    stringToEnum["application/vnd.wap.sic"] = MIME_APPLICATION_VND_WAP_SIC;
-    stringToEnum["application/vnd.wap.slc"] = MIME_APPLICATION_VND_WAP_SLC;
-    stringToEnum["application/vnd.wap.coc"] = MIME_APPLICATION_VND_WAP_COC;
-    stringToEnum["application/vnd.wap.sia"] = MIME_APPLICATION_VND_WAP_SIA;
-    stringToEnum["application/vnd.wap.connectivity-wbxml"] = MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML;
-    stringToEnum["application/vnd.wap.multipart.form-data"] = MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA;
-    stringToEnum["application/vnd.wap.multipart.byteranges"] = MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES;
-    stringToEnum["application/vnd.wap.multipart.mixed"] = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
-    stringToEnum["application/vnd.wap.multipart.related"] = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
-    stringToEnum["application/vnd.wap.multipart.alternative"] = MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE;
-    stringToEnum["application/vnd.wap.multipart.*"] = MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC;
-    stringToEnum["application/vnd.wap.wbxml"] = MIME_APPLICATION_VND_WAP_WBXML;
-    stringToEnum["application/vnd.oma.dd+xml"] = MIME_APPLICATION_VND_OMA_DD_XML;
-    stringToEnum["application/vnd.oma.drm.message"] = MIME_APPLICATION_VND_OMA_DRM_MESSAGE;
-    stringToEnum["application/vnd.oma.drm.content"] = MIME_APPLICATION_VND_OMA_DRM_CONTENT;
-    stringToEnum["application/vnd.oma.drm.rights+xml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML;
-    stringToEnum["application/vnd.oma.drm.rights+wbxml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML;
-    stringToEnum["application/vnd.oma.drm.ro+xml"] = MIME_APPLICATION_VND_OMA_DRM_RO_XML;
-    stringToEnum["application/vnd.oma.drm.dcf"] = MIME_APPLICATION_VND_OMA_DRM_DCF;
-    stringToEnum["application/vnd.oma.drm.roap-pdu+xml"] = MIME_APPLICATION_VND_OMA_ROAPPDU_XML;
-    stringToEnum["application/vnd.oma.drm.roap-trigger+xml"] = MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML;
-    stringToEnum["application/vnd.smaf"] = MIME_APPLICATION_VND_SMAF;
-    stringToEnum["application/vnd.rn-realmedia"] = MIME_APPLICATION_VND_RN_REALMEDIA;
-    stringToEnum["application/vnd.sun.j2me.java-archive"] = MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE;
-    stringToEnum["application/vnd.samsung.theme"] = MIME_APPLICATION_VND_SAMSUNG_THEME;
-    stringToEnum["application/vnd.ms-excel"] = MIME_APPLICATION_VND_EXCEL;
-    stringToEnum["application/vnd.ms-powerpoint"] = MIME_APPLICATION_VND_POWERPOINT;
-    stringToEnum["applcation/vnd.ms-word"] = MIME_APPLICATION_VND_MSWORD;
-    //49
-    stringToEnum["application/x-hdmlc"] = MIME_APPLICATION_X_HDMLC;
-    stringToEnum["application/x-x968-user-cert"] = MIME_APPLICATION_X_X968_USERCERT;
-    stringToEnum["application/x-www-form-urlencoded"] = MIME_APPLICATION_X_WWW_FORM_URLENCODED;
-    stringToEnum["application/x-smaf"] = MIME_APPLICATION_X_SMAF;
-    stringToEnum["application/x-shockwave-flash"] = MIME_APPLICATION_X_FLASH;
-    stringToEnum["application/x-msexcel"] = MIME_APPLICATION_X_EXCEL;
-    stringToEnum["application/x-mspowerpoint"] = MIME_APPLICATION_X_POWERPOINT;
-    //56
-    stringToEnum["audio/basic"] = MIME_AUDIO_BASIC;
-    stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG;
-    stringToEnum["audio/mp3"] = MIME_AUDIO_MP3;
-    stringToEnum["audio/mpg3"] = MIME_AUDIO_MPG3;
-    stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG3;
-    stringToEnum["audio/mpg"] = MIME_AUDIO_MPG;
-    stringToEnum["audio/aac"] = MIME_AUDIO_AAC;
-    stringToEnum["audio/g72"] = MIME_AUDIO_G72;
-    stringToEnum["audio/amr"] = MIME_AUDIO_AMR;
-    stringToEnum["audio/amr-wb"] = MIME_AUDIO_AMR_WB;
-    stringToEnum["audio/mmf"] = MIME_AUDIO_MMF;
-    stringToEnum["audio/smaf"] = MIME_AUDIO_SMAF;
-    stringToEnum["audio/iMelody"] = MIME_AUDIO_IMELODY;
-    stringToEnum["audio/imelody"] = MIME_AUDIO_IMELODY2;
-    stringToEnum["audio/melody"] = MIME_AUDIO_MELODY;
-    stringToEnum["audio/mid"] = MIME_AUDIO_MID;
-    stringToEnum["audio/midi"] = MIME_AUDIO_MIDI;
-    stringToEnum["audio/sp-midi"] = MIME_AUDIO_SP_MIDI;
-    stringToEnum["audio/wave"] = MIME_AUDIO_WAVE;
-    stringToEnum["audio/wav"] = MIME_AUDIO_WAV;
-    stringToEnum["audio/3gpp"] = MIME_AUDIO_3GPP;
-    stringToEnum["audio/mp4"] = MIME_AUDIO_MP4;
-    stringToEnum["audio/MP4A-LATM"] = MIME_AUDIO_MP4A_LATM;
-    stringToEnum["audio/m4a"] = MIME_AUDIO_M4A;
-    stringToEnum["audio/mpeg4"] = MIME_AUDIO_MPEG4;
-    stringToEnum["audio/wma"] = MIME_AUDIO_WMA;
-    stringToEnum["audio/xmf"] = MIME_AUDIO_XMF;
-    stringToEnum["audio/imy"] = MIME_AUDIO_IMY;
-    stringToEnum["audio/mobile-xmf"] = MIME_AUDIO_MOBILE_XMF;
-    //85
-    stringToEnum["audio/vnd.rn-realaudio"] = MIME_AUDIO_VND_RN_REALAUDIO;
-    //86
-    stringToEnum["audio/x-mpeg"] = MIME_AUDIO_X_MPEG;
-    stringToEnum["audio/x-mp3"] = MIME_AUDIO_X_MP3;
-    stringToEnum["audio/x-mpeg3"] = MIME_AUDIO_X_MPEG3;
-    stringToEnum["audio/x-mpg"] = MIME_AUDIO_X_MPG;
-    stringToEnum["audio/x-amr"] = MIME_AUDIO_X_AMR;
-    stringToEnum["audio/x-mmf"] = MIME_AUDIO_X_MMF;
-    stringToEnum["audio/x-smaf"] = MIME_AUDIO_X_SMAF;
-    stringToEnum["audio/x-iMelody"] = MIME_AUDIO_X_IMELODY;
-    stringToEnum["audio/x-midi"] = MIME_AUDIO_X_MIDI;
-    stringToEnum["audio/x-mpegaudio"] = MIME_AUDIO_X_MPEGAUDIO;
-    stringToEnum["audio/x-pn-realaudio"] = MIME_AUDIO_X_PN_REALAUDIO;
-    stringToEnum["audio/x-pn-multirate-realaudio"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO;
-    stringToEnum["audio/x-pn-multirate-realaudio-live"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE;
-    stringToEnum["audio/x-wave"] = MIME_AUDIO_X_WAVE;
-    stringToEnum["audio/x-wav"] = MIME_AUDIO_X_WAV;
-    stringToEnum["audio/x-ms-wma"] = MIME_AUDIO_X_MS_WMA;
-    stringToEnum["audio/x-mid"] = MIME_AUDIO_X_MID;
-    stringToEnum["audio/x-ms-asf"] = MIME_AUDIO_X_MS_ASF;
-    stringToEnum["audio/x-xmf"] = MIME_AUDIO_X_XMF;
-    //105
-    stringToEnum["image/gif"] = MIME_IMAGE_GIF;
-    stringToEnum["image/jpeg"] = MIME_IMAGE_JPEG;
-    stringToEnum["image/jpga"] = MIME_IMAGE_JPG;
-    stringToEnum["image/tiff"] = MIME_IMAGE_TIFF;
-    stringToEnum["image/tif"] = MIME_IMAGE_TIF;
-    stringToEnum["image/png"] = MIME_IMAGE_PNG;
-    stringToEnum["image/wbmp"] = MIME_IMAGE_WBMP;
-    stringToEnum["image/pjpeg"] = MIME_IMAGE_PJPEG;
-    stringToEnum["image/bmp"] = MIME_IMAGE_BMP;
-    stringToEnum["image/svg+xml"] = MIME_IMAGE_SVG;
-    stringToEnum["image/svg-xml"] = MIME_IMAGE_SVG1;
-    //116
-    stringToEnum["image/vnd.wap.wbmp"] = MIME_IMAGE_VND_WAP_WBMP;
-    stringToEnum["image/vnd.tmo.my5-gif"] = MIME_IMAGE_VND_TMO_GIF;
-    stringToEnum["image/vnd.tmo.my5-jpg"] = MIME_IMAGE_VND_TMO_JPG;
-    //119
-    stringToEnum["image/x-bmp"] = MIME_IMAGE_X_BMP;
-    //120
-    stringToEnum["message/rfc822"] = MIME_MESSAGE_RFC822;
-    //121
-    stringToEnum["multipart/mixed"] = MIME_MULTIPART_MIXED;
-    stringToEnum["multipart/related"] = MIME_MULTIPART_RELATED;
-    stringToEnum["multipart/alternative"] = MIME_MULTIPART_ALTERNATIVE;
-    stringToEnum["multipart/form-data"] = MIME_MULTIPART_FORM_DATA;
-    stringToEnum["multipart/byterange"] = MIME_MULTIPART_BYTERANGE;
-    stringToEnum["multipart/report"] = MIME_MULTIPART_REPORT;
-    stringToEnum["multipart/voice-message"] = MIME_MULTIPART_VOICE_MESSAGE;
-    //128
-    stringToEnum["text/txt"] = MIME_TEXT_TXT;
-    stringToEnum["text/html"] = MIME_TEXT_HTML;
-    stringToEnum["text/plain"] = MIME_TEXT_PLAIN;
-    stringToEnum["text/css"] = MIME_TEXT_CSS;
-    stringToEnum["text/xml"] = MIME_TEXT_XML;
-    stringToEnum["text/iMelody"] = MIME_TEXT_IMELODY;
-    //134
-    stringToEnum["text/vnd.wap.wmlscript"] = MIME_TEXT_VND_WAP_WMLSCRIPT;
-    stringToEnum["text/vnd.wap.wml"] = MIME_TEXT_VND_WAP_WML;
-    stringToEnum["text/vnd.wap.wta-event"] = MIME_TEXT_VND_WAP_WTA_EVENT;
-    stringToEnum["text/vnd.wap.connectivity-xml"] = MIME_TEXT_VND_WAP_CONNECTIVITY_XML;
-    stringToEnum["text/vnd.wap.si"] = MIME_TEXT_VND_WAP_SI;
-    stringToEnum["text/vnd.wap.sl"] = MIME_TEXT_VND_WAP_SL;
-    stringToEnum["text/vnd.wap.co"] = MIME_TEXT_VND_WAP_CO;
-    stringToEnum["text/vnd.sun.j2me.app-descriptor"] = MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR;
-    //142
-    stringToEnum["text/x-hdml"] = MIME_TEXT_X_HDML;
-    stringToEnum["text/x-vCalendar"] = MIME_TEXT_X_VCALENDAR;
-    stringToEnum["text/x-vCard"] = MIME_TEXT_X_VCARD;
-    stringToEnum["text/x-iMelody"] = MIME_TEXT_X_IMELODY;
-    stringToEnum["text/x-imelody"] = MIME_TEXT_X_IMELODY2;
-    stringToEnum["text/x-vnote"] = MIME_TEXT_X_VNOTE;
-    //148
-    stringToEnum["video/mpeg4"] = MIME_VIDEO_MPEG4;
-    stringToEnum["video/mp4"] = MIME_VIDEO_MP4;
-    stringToEnum["video/h263"] = MIME_VIDEO_H263;
-    stringToEnum["video/3gpp"] = MIME_VIDEO_3GPP;
-    stringToEnum["video/3gp"] = MIME_VIDEO_3GP;
-    stringToEnum["video/avi"] = MIME_VIDEO_AVI;
-    stringToEnum["video/sdp"] = MIME_VIDEO_SDP;
-    stringToEnum["video/mp4v-es"] = MIME_VIDEO_MP4_ES;
-    stringToEnum["video/mpeg"] = MIME_VIDEO_MPEG;
-    //157
-    stringToEnum["video/vnd.rn-realvideo"] = MIME_VIDEO_VND_RN_REALVIDEO;
-    stringToEnum["video/vnd.rn-realmedia"] = MIME_VIDEO_VND_RN_REALMEDIA;
-    //159
-    stringToEnum["video/x-mp4"] = MIME_VIDEO_X_MP4;
-    stringToEnum["video/x-pv-mp4"] = MIME_VIDEO_X_PV_MP4;
-    stringToEnum["video/x-pn-realvideo"] = MIME_VIDEO_X_PN_REALVIDEO;
-    stringToEnum["video/x-pn-multirate-realvideo"] = MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO;
-    stringToEnum["video/x-ms-wmv"] = MIME_VIDEO_X_MS_WMV;
-    stringToEnum["video/x-ms-asf"] = MIME_VIDEO_X_MS_ASF;
-    stringToEnum["video/x-pv-pvx"] = MIME_VIDEO_X_PV_PVX;
-    stringToEnum[""] = MIME_UNKNOWN;
-
-    return stringToEnum;
-}
-
-
-unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str){
-    std::map<std::string,unsigned int>::iterator it = MIMETypeStringToEnumMap.find(str);
-    if(it != MIMETypeStringToEnumMap.end()){
-        return it->second;
-    }
-    return MIME_UNKNOWN;
-}
-
-std::string MessageAttachment::MIMETypeEnumToString(unsigned int num){
-    std::map<unsigned int, std::string>::iterator it = MIMETypeEnumToStringMap.find(num);
-    if(it != MIMETypeEnumToStringMap.end()){
-        return it->second;
-    }
-    return std::string();
-}
-
-void MessageAttachment::updateWithAttachmentData(
-        const email_attachment_data_t& attachment_data)
-{
-    setId(attachment_data.attachment_id);
-    setMessageId(attachment_data.mail_id);
-    if(attachment_data.attachment_mime_type) {
-        setMimeType(attachment_data.attachment_mime_type);
-    }
-
-    bool isSaved = false;
-    if (attachment_data.attachment_path) {
-        setFilePath(attachment_data.attachment_path);
-
-        LOGD("save status: %d", attachment_data.save_status);
-        LOGD("attachment_size : %d", attachment_data.attachment_size);
-        isSaved = attachment_data.save_status;
-    }
-
-    setIsSaved(isSaved);
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessageAttachment.h b/messaging/old/MessageAttachment.h
deleted file mode 100755 (executable)
index 9ed4cfe..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageAttachment.h
- */
-
-#ifndef __TIZEN_MESSAGE_ATTACHMENT_H__
-#define __TIZEN_MESSAGE_ATTACHMENT_H__
-
-#include <string>
-#include <memory>
-#include <vector>
-#include <map>
-#include <msg_types.h>
-#include <email-types.h>
-#include "JSVector.h"
-#include "JSMessageAttachment.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageAttachment;
-
-struct MessageAttachmentHolder {
-    std::shared_ptr<MessageAttachment> ptr;
-};
-
-typedef Common::JSObjectVector<std::shared_ptr<MessageAttachment>,
-    JSMessageAttachment> JSAttachmentsVector;
-
-typedef std::vector<std::shared_ptr<MessageAttachment>> AttachmentPtrVector;
-
-class MessageAttachment {
-private:
-    static std::map<std::string,unsigned int>& MIMETypeStringToEnumMap;
-    static std::map<unsigned int, std::string>& MIMETypeEnumToStringMap;
-    static std::map<std::string,unsigned int>& initializeMIMETypeStringToEnumMap();
-    static std::map<unsigned int, std::string>& initializeMIMETypeEnumToStringMap();
-    int m_id;
-    bool m_isIdSet;
-    int m_messageId;
-    bool m_isMessageIdSet;
-    std::string m_mimeType;
-    bool m_isMimeTypeSet;
-    std::string m_filePath;
-    bool m_isFilePathSet;
-    bool m_isSaved;
-public:
-    MessageAttachment();
-    ~MessageAttachment();
-
-    int getId();
-    void setId(int value);
-    bool isIdSet();
-    void unsetId();
-    int getMessageId();
-    void setMessageId(int value);
-    bool isMessageIdSet();
-    void unsetMessageId();
-    std::string getMimeType();
-    void setMimeType(const std::string &value);
-    bool isMimeTypeSet();
-    void unsetMimeType();
-    std::string getFilePath();
-    std::string getShortFileName() const;
-    void setFilePath(const std::string &value);
-    bool isFilePathSet();
-    void unsetFilePath();
-    void setIsSaved(const bool isSaved);
-    bool isSaved() const;
-    static unsigned int MIMETypeStringToEnum(std::string str);
-    static std::string MIMETypeEnumToString(unsigned int num);
-
-    /**
-     * This methods updates:
-     *      setId(attachment_data.attachment_id);
-     *      setMessageId(attachment_data.mail_id);
-     *      setMimeType(attachment_data.attachment_mime_type);
-     *      setFilePath(attachment_data.attachment_path);
-     */
-    void updateWithAttachmentData(const email_attachment_data_t& attachment_data);
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_ATTACHMENT_H__
diff --git a/messaging/old/MessageBody.cpp b/messaging/old/MessageBody.cpp
deleted file mode 100644 (file)
index d203ab7..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageBody.cpp
- */
-
-#include "MessageBody.h"
-#include "MessagingUtil.h"
-#include <Logger.h>
-#include <PlatformException.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageBody::MessageBody() : m_messageId(1),
-                             m_messageId_set(false),
-                             m_loaded(false),
-                             m_plainBody(""),
-                             m_htmlBody("")
-{
-}
-
-MessageBody::~MessageBody()
-{
-}
-
-// messageId
-
-int MessageBody::getMessageId() const
-{
-
-    return m_messageId;
-}
-
-void MessageBody::setMessageId(int value)
-{
-    m_messageId = value;
-    m_messageId_set = true;
-}
-
-// loaded
-
-bool MessageBody::getLoaded() const
-{
-    return m_loaded;
-}
-
-void MessageBody::setLoaded(bool value)
-{
-    m_loaded = value;
-}
-
-// plainBody
-
-std::string MessageBody::getPlainBody() const
-{
-    return m_plainBody;
-}
-
-void MessageBody::setPlainBody(const std::string &value)
-{
-    m_plainBody = value;
-}
-
-// htmlBody
-
-std::string MessageBody::getHtmlBody() const
-{
-    return m_htmlBody;
-}
-
-void MessageBody::setHtmlBody(const std::string &value)
-{
-    m_htmlBody = value;
-}
-
-// inlineAttachments
-
-AttachmentPtrVector MessageBody::getInlineAttachments() const
-{
-    return m_inlineAttachments;
-}
-
-JSObjectRef MessageBody::getJSInlineAttachments(JSContextRef global_ctx)
-{
-    return m_inlineAttachments.getJSArray(global_ctx);
-}
-
-void MessageBody::setInlineAttachments(const AttachmentPtrVector& attachments)
-{
-    m_inlineAttachments = attachments;
-}
-
-// ***  support for optional, nullable (at JS layer) attibutes
-bool MessageBody::is_message_id_set() const
-{
-    return m_messageId_set;
-}
-
-void MessageBody::updateBody(email_mail_data_t& mail)
-{
-    LOGD("Enter");
-    setMessageId(mail.mail_id);
-    setLoaded(mail.body_download_status);
-
-    if (mail.file_path_plain) {
-        try {
-            LOGD("Plain body");
-            setPlainBody(MessagingUtil::loadFileContentToString(mail.file_path_plain));
-        } catch (...) {
-            LOGE("Fail to open plain body.");
-            throw Common::UnknownException("Fail to open plain body.");
-        }
-    }
-
-    if (mail.file_path_html) {
-        try {
-            LOGD("Html body");
-            setHtmlBody(MessagingUtil::loadFileContentToString(mail.file_path_html));
-        } catch (...) {
-            LOGE("Fail to open html body.");
-            throw Common::UnknownException("Fail to open html body.");
-        }
-    }
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessageBody.h b/messaging/old/MessageBody.h
deleted file mode 100644 (file)
index 1fb297a..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageBody.h
- */
-
-#ifndef __TIZEN_MESSAGING_MESSAGE_BODY_H__
-#define __TIZEN_MESSAGING_MESSAGE_BODY_H__
-
-#include <vector>
-#include <string>
-#include "MessageAttachment.h"
-#include <email-types.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageBody;
-
-struct MessageBodyHolder {
-    std::shared_ptr<MessageBody> ptr;
-};
-
-class MessageBody {
-public:
-    explicit MessageBody();
-    ~MessageBody();
-    int getMessageId()  const;
-    void setMessageId(int value);
-    bool getLoaded()  const;
-    void setLoaded(bool value);
-    std::string getPlainBody()  const;
-    void setPlainBody(const std::string &value);
-    std::string getHtmlBody()  const;
-    void setHtmlBody(const std::string &value);
-    AttachmentPtrVector getInlineAttachments()  const;
-    JSObjectRef getJSInlineAttachments(JSContextRef global_ctx);
-    void setInlineAttachments(const AttachmentPtrVector& attachments);
-
-    // support for optional, nullable (at JS layer) attibutes
-    bool is_message_id_set() const;
-    /**
-     * Updates body with data from email_mail_data_t structure.
-     * @param mail
-     */
-    void updateBody(email_mail_data_t& mail);
-
-private:
-    int m_messageId;
-    bool m_messageId_set;
-    bool m_loaded;
-    std::string m_plainBody;
-    std::string m_htmlBody;
-    JSAttachmentsVector m_inlineAttachments;
-    JSContextRef m_context;
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGING_MESSAGE_BODY_H__
diff --git a/messaging/old/MessageCallbackUserData.cpp b/messaging/old/MessageCallbackUserData.cpp
deleted file mode 100644 (file)
index 97539b6..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "MessageCallbackUserData.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-
-MessageCallbackUserData::MessageCallbackUserData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_is_error(false)
-{
-}
-
-MessageCallbackUserData::~MessageCallbackUserData() {
-}
-
-void MessageCallbackUserData::setMessage(std::shared_ptr<Message> message) {
-    m_message = message;
-}
-
-std::shared_ptr<Message> MessageCallbackUserData::getMessage() const {
-    return m_message;
-}
-
-void MessageCallbackUserData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool MessageCallbackUserData::isError() const
-{
-    return m_is_error;
-}
-
-std::string MessageCallbackUserData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string MessageCallbackUserData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void MessageCallbackUserData::setAccountId(int account_id){
-    m_account_id = account_id;
-}
-
-int MessageCallbackUserData::getAccountId() const
-{
-    return m_account_id;
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/MessageCallbackUserData.h b/messaging/old/MessageCallbackUserData.h
deleted file mode 100644 (file)
index eb11724..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H
-#define __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H
-
-#include <CallbackUserData.h>
-#include <memory>
-#include <string>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-
-class MessageCallbackUserData: public Common::CallbackUserData {
-public:
-    MessageCallbackUserData(JSContextRef globalCtx);
-    virtual ~MessageCallbackUserData();
-
-    void setMessage(std::shared_ptr<Message> message);
-    std::shared_ptr<Message> getMessage() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void setAccountId(int account_id);
-    int getAccountId() const;
-private:
-    std::shared_ptr<Message> m_message;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    int m_account_id;
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H */
-
diff --git a/messaging/old/MessageConversation.cpp b/messaging/old/MessageConversation.cpp
deleted file mode 100644 (file)
index 2037bea..0000000
+++ /dev/null
@@ -1,522 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageConversation.cpp
- */
-
-#include <PlatformException.h>
-#include <Logger.h>
-#include "Message.h"
-#include "MessageConversation.h"
-#include "MessagingUtil.h"
-#include "JSMessageConversation.h"
-#include "MessagingUtil.h"
-
-#define MAX_THREAD_DATA_LEN 128
-
-namespace DeviceAPI {
-
-using namespace Tizen;
-
-namespace Messaging {
-
-// *** constructor
-MessageConversation::MessageConversation():
-    m_conversation_id(-1),
-    m_conversation_type(UNDEFINED),
-    m_count(0),
-    m_unread_messages(0),
-    m_is_read(false)
-{
-    LOGD("Message Conversation constructor.");
-}
-
-MessageConversation::~MessageConversation()
-{
-    LOGD("Message Conversation destructor.");
-}
-// *** attributes getters
-int MessageConversation::getConversationId() const
-{
-    return m_conversation_id;
-}
-
-MessageType MessageConversation::getType() const
-{
-    return m_conversation_type;
-}
-
-time_t MessageConversation::getTimestamp() const
-{
-    return m_timestamp;
-}
-
-unsigned long MessageConversation::getMessageCount() const
-{
-    return m_count;
-}
-
-unsigned long MessageConversation::getUnreadMessages() const
-{
-    return m_unread_messages;
-}
-
-std::string MessageConversation::getPreview() const
-{
-    return m_preview;
-}
-
-std::string MessageConversation::getSubject() const
-{
-    return m_conversation_subject;
-}
-
-bool MessageConversation::getIsRead() const
-{
-    return m_is_read;
-}
-
-std::string MessageConversation::getFrom() const
-{
-    return m_from;
-}
-
-std::vector<std::string> MessageConversation::getTo() const
-{
-    return m_to;
-}
-
-std::vector<std::string> MessageConversation::getCC() const
-{
-    return m_cc;
-}
-
-std::vector<std::string> MessageConversation::getBCC() const
-{
-    return m_bcc;
-}
-
-int MessageConversation::getLastMessageId() const
-{
-    return m_last_message_id;
-}
-
-std::shared_ptr<MessageConversation> MessageConversation::convertMsgConversationToObject(
-        unsigned int threadId, msg_handle_t handle)
-{
-    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
-
-    msg_struct_t msgInfo = NULL;
-    msg_struct_t sendOpt = NULL;
-
-    msg_struct_t msg_thread = NULL;
-
-    msg_struct_list_s convViewList;
-    msg_list_handle_t addr_list = NULL;
-    msg_struct_t addr_info = NULL;
-
-    msg_error_t err = MSG_SUCCESS;
-
-    int tempInt;
-    bool tempBool;
-    int nToCnt;
-    unsigned int lastMsgIndex = 0;
-    char msgData[MAX_THREAD_DATA_LEN] = {0,};
-
-    try {
-        msgInfo = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-        sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
-
-        conversation->m_conversation_id = threadId;
-
-        msg_thread = msg_create_struct(MSG_STRUCT_THREAD_INFO);
-        err = msg_get_thread(handle, conversation->m_conversation_id, msg_thread);
-        if (err != MSG_SUCCESS)
-        {
-            LOGE("Failed to retrieve thread.");
-            throw Common::UnknownException("Failed to retrieve thread.");
-        }
-        msg_get_int_value(msg_thread, MSG_THREAD_MSG_TYPE_INT, &tempInt);
-        switch(tempInt)
-        {
-            case MSG_TYPE_SMS:
-            case MSG_TYPE_SMS_CB:
-            case MSG_TYPE_SMS_JAVACB:
-            case MSG_TYPE_SMS_WAPPUSH:
-            case MSG_TYPE_SMS_MWI:
-            case MSG_TYPE_SMS_SYNCML:
-            case MSG_TYPE_SMS_REJECT:
-                conversation->m_conversation_type = SMS;
-                break;
-            case MSG_TYPE_MMS:
-            case MSG_TYPE_MMS_JAVA:
-            case MSG_TYPE_MMS_NOTI:
-                conversation->m_conversation_type = MMS;
-                break;
-        }
-
-        msg_get_int_value(msg_thread, MSG_THREAD_MSG_TIME_INT, &tempInt);
-        conversation->m_timestamp = tempInt;
-
-        msg_get_int_value(msg_thread, MSG_THREAD_UNREAD_COUNT_INT, &tempInt);
-        conversation->m_unread_messages = tempInt;
-
-        msg_get_str_value(msg_thread, MSG_THREAD_MSG_DATA_STR, msgData, MAX_THREAD_DATA_LEN);
-
-        conversation->m_preview = msgData;
-
-        err = msg_get_conversation_view_list(handle, conversation->m_conversation_id,
-            &convViewList);
-        if (err != MSG_SUCCESS)
-        {
-            LOGE("Get conversation(msg) view list fail.");
-            throw Common::UnknownException("Get conversation(msg) view list fail.");
-        }
-
-        lastMsgIndex = convViewList.nCount - 1;
-        conversation->m_count = convViewList.nCount;
-
-        msg_get_bool_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_READ_BOOL, &tempBool);
-        conversation->m_is_read = tempBool;
-
-        msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_ID_INT, &tempInt);
-        conversation->m_last_message_id = tempInt;
-
-        if (msg_get_message(handle, conversation->m_last_message_id, msgInfo,
-            sendOpt) != MSG_SUCCESS)
-        {
-            LOGE("Get message fail.");
-            throw Common::UnknownException("get message fail.");
-        }
-
-        msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_DIRECTION_INT, &tempInt);
-
-        msg_get_list_handle(msgInfo, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list);
-        nToCnt = msg_list_length(addr_list);
-
-        if (MSG_DIRECTION_TYPE_MT == tempInt)
-        {
-            if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT )
-            {
-                char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
-                addr_info = (msg_struct_t)msg_list_nth_data(addr_list, nToCnt-1);
-                msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
-
-                if (strNumber[0] != '\0')
-                {
-                    conversation->m_from = strNumber;
-                }
-                else
-                {
-                    LOGD("address is null ");
-                }
-            }
-            else
-            {
-                LOGD("address count index fail");
-            }
-        }
-        else
-        {
-            if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT )
-            {
-                for (int index = 0; index < nToCnt; index++)
-                {
-                    addr_info = (msg_struct_t)msg_list_nth_data(addr_list, index);
-                    char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
-                    msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
-
-                    conversation->m_to.push_back(strNumber);
-                }
-            }
-            else
-            {
-                LOGD("address fetch fail");
-            }
-        }
-
-        char strTemp[MAX_SUBJECT_LEN] = {0};
-        msg_get_str_value(msgInfo, MSG_MESSAGE_SUBJECT_STR, strTemp, MAX_SUBJECT_LEN);
-
-        conversation->m_conversation_subject = strTemp;
-        msg_release_list_struct(&convViewList);
-        msg_release_struct(&msgInfo);
-        msg_release_struct(&sendOpt);
-        msg_release_struct(&msg_thread);
-    } catch (const Common::BasePlatformException& ex) {
-        msg_release_list_struct(&convViewList);
-        msg_release_struct(&msgInfo);
-        msg_release_struct(&sendOpt);
-        msg_release_struct(&msg_thread);
-        LOGE("%s (%s)", (ex.getName()).c_str(), (ex.getMessage()).c_str());
-        throw Common::UnknownException("Unable to convert short message conversation.");
-    } catch (...) {
-        msg_release_list_struct(&convViewList);
-        msg_release_struct(&msgInfo);
-        msg_release_struct(&sendOpt);
-        msg_release_struct(&msg_thread);
-        throw Common::UnknownException("Unable to convert short message conversation.");
-    }
-
-    return conversation;
-}
-
-std::shared_ptr<MessageConversation> MessageConversation::convertEmailConversationToObject(
-        unsigned int threadId)
-{
-    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
-
-    email_mail_list_item_t *resultMail = NULL;
-
-    if(email_get_thread_information_ex(threadId, &resultMail) != EMAIL_ERROR_NONE)
-    {
-        LOGE("Couldn't get conversation");
-        throw Common::UnknownException("Couldn't get conversation.");
-    } else {
-        if (!resultMail)
-        {
-            LOGE("Data is null");
-            throw Common::UnknownException("Get email data fail.");
-        }
-
-        email_mail_data_t* mailData = NULL;
-
-        if (email_get_mail_data(resultMail->mail_id,
-                &mailData) != EMAIL_ERROR_NONE)
-        {
-            free(resultMail);
-            throw Common::UnknownException("Get email data fail.");
-        }
-
-        if (!mailData) {
-            free(resultMail);
-            throw Common::UnknownException("Get email data fail.");
-        }
-
-        int index = 0;
-        int count = 0;
-        conversation->m_unread_messages = 0;
-        email_mail_list_item_t *mailList = NULL;
-
-        if (email_get_mail_list(mailData->account_id, 0, threadId, 0,
-            resultMail->thread_item_count, EMAIL_SORT_DATETIME_HIGH, &mailList,
-            &count) != EMAIL_ERROR_NONE)
-        {
-            email_free_mail_data(&mailData , 1);
-            free(resultMail);
-            throw Common::UnknownException("Get email data list fail.");
-        }
-
-        for (index = 0; index < count; index++)
-        {
-            if (mailList[index].flags_seen_field)
-            {
-                conversation->m_unread_messages++;
-            }
-        }
-        conversation->m_count = resultMail->thread_item_count;
-
-        conversation->m_conversation_id = threadId;
-
-        conversation->m_conversation_type = EMAIL;
-
-        conversation->m_timestamp = resultMail->date_time;
-
-        if (resultMail->preview_text[0] != '\0')
-        {
-            conversation->m_preview = resultMail->preview_text;
-        }
-
-        if (resultMail->subject[0] != '\0')
-        {
-            conversation->m_conversation_subject = resultMail->subject;
-        }
-
-        conversation->m_is_read = (bool)resultMail->flags_seen_field;
-
-        if (resultMail->full_address_from[0] != '\0')
-        {
-            conversation->m_from = MessagingUtil::extractSingleEmailAddress(
-                    resultMail->full_address_from);
-        }
-
-        if (mailData->full_address_to != NULL)
-        {
-            conversation->m_to = Message::getEmailRecipientsFromStruct(
-                mailData->full_address_to);
-        }
-
-        if (mailData->full_address_cc != NULL)
-        {
-            conversation->m_cc = Message::getEmailRecipientsFromStruct(
-                mailData->full_address_cc);
-        }
-
-        if (mailData->full_address_bcc != NULL)
-        {
-            conversation->m_bcc = Message::getEmailRecipientsFromStruct(
-                mailData->full_address_bcc);
-        }
-
-        conversation->m_last_message_id = resultMail->mail_id;
-
-        if (mailData != NULL)
-        {
-            email_free_mail_data(&mailData , 1);
-        }
-    }
-
-    if (resultMail != NULL)
-    {
-        free(resultMail);
-    }
-
-    return conversation;
-}
-
-std::shared_ptr<MessageConversation> MessageConversation::convertConversationStructToObject(
-        unsigned int threadId, MessageType msgType, msg_handle_t handle)
-{
-    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
-
-    if (EMAIL == msgType) {
-        conversation = convertEmailConversationToObject(threadId);
-    } else {
-        if(handle != NULL) {
-            conversation = convertMsgConversationToObject(threadId, handle);
-        } else {
-            LOGE("Handle has not been sent.");
-            throw Common::UnknownException("Handle has not been sent.");
-        }
-    }
-
-    return conversation;
-}
-
-void MessageConversation::setConversationId(int id)
-{
-    m_conversation_id = id;
-}
-void MessageConversation::setMessageCount(int count)
-{
-    m_count = count;
-}
-
-void MessageConversation::setUnreadMessages(int count)
-{
-    m_unread_messages = count;
-}
-
-/**
- *
- *  Attribute      | Attribute filter| Attribute range filter
- *                 | supported       | supported
- * ----------------+-----------------+------------------------
- * id              | Yes             | No
- * type            | Yes             | No
- * timestamp       | No              | Yes
- * messageCount    | Yes             | No
- * unreadMessages  | Yes             | No
- * preview         | Yes             | No
- * subject         | No              | No
- * isRead          | No              | No
- * from            | Yes             | No
- * to              | Yes             | No
- * cc              | No              | No
- * bcc             | No              | No
- * lastMessageId   | No              | No
- */
-
-namespace CONVERSATION_FILTER_ATTRIBUTE {
-const std::string ID = JSMessageConversationKeys::MESSAGE_CONVERSATION_ID;
-const std::string TYPE = JSMessageConversationKeys::MESSAGE_CONVERSATION_TYPE;
-const std::string TIMESTAMP = JSMessageConversationKeys::MESSAGE_CONVERSATION_TIMESTAMP;
-const std::string MESSAGE_COUNT =
-        JSMessageConversationKeys::MESSAGE_CONVERSATION_MSG_COUNT;
-
-const std::string UNREAD_MESSAGES =
-        JSMessageConversationKeys::MESSAGE_CONVERSATION_UNREAD_MSG;
-
-const std::string PREVIEW = JSMessageConversationKeys::MESSAGE_CONVERSATION_PREVIEW;
-const std::string FROM = JSMessageConversationKeys::MESSAGE_CONVERSATION_FROM;
-const std::string TO = JSMessageConversationKeys::MESSAGE_CONVERSATION_TO;
-} //namespace CONVERSATION_FILTER_ATTRIBUTE
-
-bool MessageConversation::isMatchingAttribute(const std::string& attribute_name,
-            const FilterMatchFlag match_flag,
-            AnyPtr match_value) const
-{
-    LOGD("Entered");
-    auto key = match_value->toString();
-    LOGD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(),
-            match_flag, key.c_str());
-
-    using namespace CONVERSATION_FILTER_ATTRIBUTE;
-
-    if(ID == attribute_name) {
-        return FilterUtils::isStringMatching(key, std::to_string(getConversationId()),
-                match_flag);
-    }
-    else if(TYPE == attribute_name) {
-        const MessageType msg_type = getType();
-        const std::string msg_type_str = MessagingUtil::messageTypeToString(msg_type);
-        return FilterUtils::isStringMatching(key, msg_type_str, match_flag);
-    }
-    else if(MESSAGE_COUNT == attribute_name) {
-        return FilterUtils::isStringMatching(key, std::to_string(getMessageCount()),
-                match_flag);
-    }
-    else if(UNREAD_MESSAGES == attribute_name) {
-        return FilterUtils::isStringMatching(key, std::to_string(getUnreadMessages()),
-                match_flag);
-    }
-    else if(PREVIEW == attribute_name) {
-        return FilterUtils::isStringMatching(key, getPreview(), match_flag);
-    }
-    else if(FROM == attribute_name) {
-        return FilterUtils::isStringMatching(key, getFrom(), match_flag);
-    }
-    else if(TO == attribute_name) {
-        return FilterUtils::isAnyStringMatching(key, getTo(), match_flag);
-    }
-    else {
-        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
-    }
-
-    return false;
-}
-
-bool MessageConversation::isMatchingAttributeRange(const std::string& attribute_name,
-            AnyPtr initial_value,
-            AnyPtr end_value) const
-{
-    LOGD("Entered attribute_name: %s", attribute_name.c_str());
-
-    using namespace CONVERSATION_FILTER_ATTRIBUTE;
-
-    if(TIMESTAMP == attribute_name) {
-        return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, end_value);
-    }
-    else {
-        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
-    }
-    return false;
-}
-
-} //Messaging
-} //DeviceAPI
diff --git a/messaging/old/MessageConversation.h b/messaging/old/MessageConversation.h
deleted file mode 100644 (file)
index 568c32d..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageConversation.h
- */
-
-#ifndef __TIZEN_MESSAGE_CONVERSATION_H__
-#define __TIZEN_MESSAGE_CONVERSATION_H__
-
-#include <memory>
-#include <string>
-#include <time.h>
-#include <vector>
-#include <email-api.h>
-#include <msg.h>
-#include <msg_storage.h>
-#include "MessagingUtil.h"
-#include <AbstractFilter.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageConversation;
-
-struct MessageConversationHolder {
-    std::shared_ptr<MessageConversation>ptr;
-};
-
-typedef std::shared_ptr<MessageConversation> ConversationPtr;
-
-typedef std::vector<ConversationPtr> ConversationPtrVector;
-
-class MessageConversation : public Tizen::FilterableObject {
-public:
-    MessageConversation();
-    ~MessageConversation();
-
-    // attributes getters
-    int getConversationId() const;
-    MessageType getType() const;
-    time_t getTimestamp() const;
-    unsigned long getMessageCount() const;
-    unsigned long getUnreadMessages() const;
-    std::string getPreview() const;
-    std::string getSubject() const;
-    bool getIsRead() const;
-    std::string getFrom() const;
-    std::vector<std::string> getTo() const;
-    std::vector<std::string> getCC() const;
-    std::vector<std::string> getBCC() const;
-    int getLastMessageId() const;
-
-    static std::shared_ptr<MessageConversation> convertConversationStructToObject(
-        unsigned int threadId, MessageType msgType, msg_handle_t handle = NULL);
-    static std::shared_ptr<MessageConversation> convertEmailConversationToObject(
-        unsigned int threadId);
-    /**
-     *
-     * @param threadId Id of Message (not Conversation)
-     * @param handle
-     * @return
-     */
-    static std::shared_ptr<MessageConversation> convertMsgConversationToObject(
-        unsigned int threadId, msg_handle_t handle);
-
-    virtual void setConversationId(int id);
-    virtual void setMessageCount(int count);
-    virtual void setUnreadMessages(int count);
-
-    // Tizen::FilterableObject
-    virtual bool isMatchingAttribute(const std::string& attribute_name,
-            const Tizen::FilterMatchFlag match_flag,
-            Tizen::AnyPtr match_value) const;
-
-    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
-            Tizen::AnyPtr initial_value,
-            Tizen::AnyPtr end_value) const;
-
-private:
-    int m_conversation_id;
-    MessageType m_conversation_type;
-    time_t m_timestamp;
-    unsigned long m_count;
-    unsigned long m_unread_messages;
-    std::string m_preview;
-    std::string m_conversation_subject;
-    bool m_is_read;
-    std::string m_from;
-    std::vector<std::string> m_to;
-    std::vector<std::string> m_cc;
-    std::vector<std::string> m_bcc;
-    int m_last_message_id;
-};
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_CONVERSATION_H__
diff --git a/messaging/old/MessageEmail.cpp b/messaging/old/MessageEmail.cpp
deleted file mode 100644 (file)
index fd6699f..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageEmail.cpp
- */
-
-#include <PlatformException.h>
-#include <Logger.h>
-#include "MessageEmail.h"
-#include <GlobalContextManager.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageEmail::MessageEmail():
-    Message()
-{
-    LOGD("MessageEmail constructor.");
-    this->m_type = MessageType(EMAIL);
-}
-
-MessageEmail::~MessageEmail()
-{
-    LOGD("MessageEmail destructor.");
-}
-
-// *** overrided methods
-void MessageEmail::setCC(std::vector<std::string> &cc)
-{
-    // CC recipient's format validation should be done by email service
-    m_cc = cc;
-
-    if(m_cc.empty()) {
-        LOGD("Recipient's list cleared");
-        return;
-    }
-}
-
-void MessageEmail::setBCC(std::vector<std::string> &bcc)
-{
-    // BCC recipient's format validation should be done by email service
-    m_bcc = bcc;
-
-    if(m_bcc.empty()) {
-        LOGD("Recipient's list cleared");
-        return;
-    }
-}
-
-void MessageEmail::setSubject(std::string subject)
-{
-    m_subject = subject;
-}
-
-void MessageEmail::setIsHighPriority(bool highpriority)
-{
-    m_high_priority = highpriority;
-}
-
-void MessageEmail::setMessageAttachments(AttachmentPtrVector &attachments)
-{
-    m_attachments = attachments;
-
-    m_has_attachment = true;
-    if(m_attachments.empty()) {
-        LOGD("Recipient's list cleared");
-        m_has_attachment = false;
-    }
-}
-
-bool MessageEmail::getHasAttachment() const
-{
-    LOGD("MessageEmail::getHasAttachment()");
-    return m_has_attachment || !m_body->getInlineAttachments().empty();
-}
-
-void MessageEmail::updateEmailMessage(email_mail_data_t& mail)
-{
-    LOGD("Enter");
-    std::vector<std::string> recp_list;
-
-    setId(mail.mail_id);
-
-    setFolderId(mail.mailbox_id);
-
-    setConversationId(mail.thread_id);
-
-    if(mail.full_address_from) {
-        setFrom(MessagingUtil::extractSingleEmailAddress(mail.full_address_from));
-    }
-
-    if(mail.full_address_to) {
-        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_to);
-        setTO(recp_list);
-    }
-
-    if(mail.full_address_cc) {
-        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_cc);
-        setCC(recp_list);
-    }
-
-    if(mail.full_address_bcc) {
-        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_bcc);
-        setBCC(recp_list);
-    }
-
-    setTimeStamp(mail.date_time);
-
-    setIsRead(mail.flags_seen_field);
-
-    setIsHighPriority((EMAIL_MAIL_PRIORITY_HIGH == mail.priority) ? true : false);
-
-    if (mail.subject == NULL) {
-        LOGW("Subject is null");
-    } else {
-        LOGD("Subject: %s", mail.subject);
-        setSubject(mail.subject);
-    }
-
-    getBody()->updateBody(mail);
-
-    if (mail.mail_id != mail.thread_id) {
-        setInResponseTo(mail.thread_id);
-    }
-
-    switch(mail.save_status)
-    {
-        case EMAIL_MAIL_STATUS_SENT:
-            setMessageStatus(MessageStatus::STATUS_SENT);
-        break;
-        case EMAIL_MAIL_STATUS_SENDING:
-            setMessageStatus(MessageStatus::STATUS_SENDING);
-        break;
-        case EMAIL_MAIL_STATUS_SAVED:
-            setMessageStatus(MessageStatus::STATUS_DRAFT);
-        break;
-        case EMAIL_MAIL_STATUS_SEND_FAILURE:
-            setMessageStatus(MessageStatus::STATUS_FAILED);
-        break;
-        default:
-            setMessageStatus(MessageStatus::STATUS_UNDEFINED);
-        break;
-    }
-
-    AttachmentPtrVector att = convertEmailToMessageAttachment(mail);
-
-    setMessageAttachments(att);
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessageEmail.h b/messaging/old/MessageEmail.h
deleted file mode 100644 (file)
index aacf1b0..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageEmail.h
- */
-
-
-#ifndef __TIZEN_MESSAGE_EMAIL_H__
-#define __TIZEN_MESSAGE_EMAIL_H__
-
-#include "Message.h"
-#include "MessageAttachment.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageEmail: public Message {
-public:
-// constructor
-    MessageEmail();
-    ~MessageEmail();
-
-//overrided base class functions
-    void setCC(std::vector<std::string> &cc);
-    void setBCC(std::vector<std::string> &bcc);
-    void setSubject(std::string subject);
-    void setIsHighPriority(bool highpriority);
-    void setMessageAttachments(AttachmentPtrVector &attachments);
-
-    bool getHasAttachment() const;
-    /**
-     * Updates message with data from email_mail_data_t structure.
-     * @param mail
-     */
-    virtual void updateEmailMessage(email_mail_data_t& mail);
-
-private:
-    // function that verifies recipient's list validity
-    bool isValidRecpientsVector(std::vector<std::string> &recipients);
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_EMAIL_H__
diff --git a/messaging/old/MessageFolder.cpp b/messaging/old/MessageFolder.cpp
deleted file mode 100644 (file)
index 420006f..0000000
+++ /dev/null
@@ -1,200 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageFolder.cpp
- */
-
-#include "MessageFolder.h"
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-
-using namespace Tizen;
-
-namespace Messaging {
-
-MessageFolder::MessageFolder(
-        std::string id,
-        std::string parent_id,
-        std::string service_id,
-        std::string content_type,
-        std::string name,
-        std::string path,
-        MessageFolderType type,
-        bool synchronizable):
-    m_id(id),
-    m_parent_id(parent_id),
-    m_parent_id_set(true),
-    m_service_id(service_id),
-    m_content_type(content_type),
-    m_name(name),
-    m_path(path),
-    m_type(type),
-    m_synchronizable(synchronizable)
-{
-}
-
-MessageFolder::MessageFolder(email_mailbox_t mailbox)
-{
-    m_id = std::to_string(mailbox.mailbox_id);
-    m_parent_id_set = false;
-    m_service_id = std::to_string(mailbox.account_id);
-    m_content_type = MessagingUtil::messageTypeToString(EMAIL);
-    m_name = mailbox.alias;
-    m_path = mailbox.mailbox_name;
-    m_type = convertPlatformFolderType(mailbox.mailbox_type);
-    if (0 == mailbox.local) {
-        m_synchronizable = true;
-    }
-    else {
-        m_synchronizable = false;
-    }
-}
-
-std::string MessageFolder::getId() const
-{
-    return m_id;
-}
-
-std::string MessageFolder::getParentId() const
-{
-    return m_parent_id;
-}
-
-bool MessageFolder::isParentIdSet() const
-{
-    return m_parent_id_set;
-}
-
-void MessageFolder::setParentId(const std::string& parentId)
-{
-    m_parent_id = parentId;
-    m_parent_id_set = true;
-}
-
-std::string MessageFolder::getServiceId() const
-{
-    return m_service_id;
-}
-
-std::string MessageFolder::getContentType() const
-{
-    return m_content_type;
-}
-
-std::string MessageFolder::getName() const
-{
-    return m_name;
-}
-
-std::string MessageFolder::getPath() const
-{
-    return m_path;
-}
-
-MessageFolderType MessageFolder::getType() const
-{
-    return m_type;
-}
-
-bool MessageFolder::getSynchronizable() const
-{
-    return m_synchronizable;
-}
-
-void MessageFolder::setName(const std::string &value)
-{
-    m_name = value;
-}
-
-void MessageFolder::setSynchronizable(const bool &value)
-{
-    m_synchronizable = value;
-}
-
-MessageFolderType MessageFolder::convertPlatformFolderType(
-        email_mailbox_type_e folderType)
-{
-    switch (folderType) {
-        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_INBOX:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX;
-        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_SENTBOX:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX;
-        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_DRAFT:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS;
-        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_OUTBOX:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX;
-        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_ALL_EMAILS:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD;
-        default:
-            return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD;
-    }
-}
-
-/**
- *
- *  Attribute      | Attribute filter| Attribute range filter
- *                 | supported       | supported
- * ----------------+-----------------+------------------------
- *  id             | No              | No
- *  parentId       | No              | No
- *  serviceId      | Yes             | No
- *  contentType    | No              | No
- *  name           | No              | No
- *  path           | No              | No
- *  type           | No              | No
- *  synchronizable | No              | No
- */
-
-namespace FOLDER_FILTER_ATTRIBUTE {
-const std::string SERVICE_ID = "serviceId";
-} //namespace FOLDER_FILTER_ATTRIBUTE
-
-bool MessageFolder::isMatchingAttribute(const std::string& attribute_name,
-            const FilterMatchFlag match_flag,
-            AnyPtr match_value) const
-{
-    LOGD("Entered");
-    auto key = match_value->toString();
-    LOGD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(),
-            match_flag, key.c_str());
-
-    using namespace FOLDER_FILTER_ATTRIBUTE;
-
-    if (SERVICE_ID == attribute_name) {
-        return FilterUtils::isStringMatching(key, getServiceId() , match_flag);
-    }
-    else {
-        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
-    }
-
-    return false;
-}
-
-
-bool MessageFolder::isMatchingAttributeRange(const std::string& attribute_name,
-            AnyPtr initial_value,
-            AnyPtr end_value) const
-{
-    LOGD("Entered");
-    LOGD("attribute_name: %s NOT SUPPORTED", attribute_name.c_str());
-    return false;
-}
-
-} //Messaging
-} //DeviceAPI
diff --git a/messaging/old/MessageFolder.h b/messaging/old/MessageFolder.h
deleted file mode 100644 (file)
index dfb02f7..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageFolder.h
- */
-
-#ifndef __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
-#define __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
-
-#include <string>
-#include <memory>
-#include <vector>
-
-#include <email-types.h>
-#include <AbstractFilter.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-enum MessageFolderType {
-    MESSAGE_FOLDER_TYPE_INBOX,
-    MESSAGE_FOLDER_TYPE_OUTBOX,
-    MESSAGE_FOLDER_TYPE_DRAFTS,
-    MESSAGE_FOLDER_TYPE_SENTBOX,
-    MESSAGE_FOLDER_TYPE_NOTSTANDARD
-};
-
-class MessageFolder;
-
-struct MessageFolderHolder {
-    std::shared_ptr<MessageFolder> ptr;
-};
-
-typedef std::shared_ptr<MessageFolder> FolderPtr;
-
-typedef std::vector<FolderPtr> FolderPtrVector;
-
-class MessageFolder : public Tizen::FilterableObject{
-
-public:
-    MessageFolder(
-            std::string id,
-            std::string parent_id,
-            std::string service_id,
-            std::string content_type,
-            std::string name,
-            std::string path,
-            MessageFolderType type,
-            bool synchronizable);
-    MessageFolder(email_mailbox_t mailbox);
-
-    std::string getId() const;
-    std::string getParentId() const;
-    bool isParentIdSet() const;
-    void setParentId(const std::string& parentId);
-    std::string getServiceId() const;
-    std::string getContentType() const;
-    std::string getName() const;
-    void setName(const std::string &value);
-    std::string getPath() const;
-    MessageFolderType getType() const;
-    bool getSynchronizable() const;
-    void setSynchronizable(const bool &value);
-
-    // Tizen::FilterableObject
-    virtual bool isMatchingAttribute(const std::string& attribute_name,
-            const Tizen::FilterMatchFlag match_flag,
-            Tizen::AnyPtr match_value) const;
-
-    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
-            Tizen::AnyPtr initial_value,
-            Tizen::AnyPtr end_value) const;
-private:
-    MessageFolderType convertPlatformFolderType(
-            email_mailbox_type_e folderType);
-
-    std::string m_id;
-    std::string m_parent_id;
-    bool m_parent_id_set;
-    std::string m_service_id;
-    std::string m_content_type;
-    std::string m_name;
-    std::string m_path;
-    MessageFolderType m_type;
-    bool m_synchronizable;
-};
-
-} //Messaging
-} //DeviceAPI
-
-#endif // __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
diff --git a/messaging/old/MessageMMS.cpp b/messaging/old/MessageMMS.cpp
deleted file mode 100644 (file)
index c6dfa13..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageMMS.cpp
- */
-
-#include <PlatformException.h>
-#include <Logger.h>
-#include "MessageMMS.h"
-#include <GlobalContextManager.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageMMS::MessageMMS():
-    Message()
-{
-    LOGD("MessageMMS constructor.");
-    this->m_type = MessageType(MessageType(MMS));
-}
-
-MessageMMS::~MessageMMS()
-{
-    LOGD("MessageMMS destructor.");
-}
-
-// *** overrided methods
-void MessageMMS::setCC(std::vector<std::string> &cc)
-{
-    // CC recipient's format validation should be done by email service
-    m_cc = cc;
-
-    if(m_cc.empty()) {
-        LOGD("Recipient's list cleared");
-        return;
-    }
-}
-
-void MessageMMS::setBCC(std::vector<std::string> &bcc)
-{
-    // BCC recipient's format validation should be done by email service
-    m_bcc = bcc;
-
-    if(m_bcc.empty()) {
-        LOGD("Recipient's list cleared");
-        return;
-    }
-}
-
-void MessageMMS::setSubject(std::string subject)
-{
-    m_subject = subject;
-}
-
-void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments)
-{
-    m_attachments = attachments;
-
-    m_has_attachment = true;
-    if(m_attachments.empty()) {
-        LOGD("Recipient's list cleared");
-        m_has_attachment = false;
-    }
-}
-
-bool MessageMMS::getHasAttachment() const
-{
-    LOGD("MessageMMS::getHasAttachment()");
-    // TODO: Analyze relation between hasAttachment flag and inlineAttachments
-    return m_has_attachment;
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessageMMS.h b/messaging/old/MessageMMS.h
deleted file mode 100644 (file)
index 799f309..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageMMS.h
- */
-
-#ifndef __TIZEN_MESSAGE_MMS_H__
-#define __TIZEN_MESSAGE_MMS_H__
-
-// Header with core msg-service declarations
-#include <msg.h>
-
-#include "Message.h"
-#include "MessageAttachment.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageMMS: public Message {
-public:
-// constructor
-    MessageMMS();
-    ~MessageMMS();
-
-//overrided base class functions
-    void setCC(std::vector<std::string> &cc);
-    void setBCC(std::vector<std::string> &bcc);
-    void setSubject(std::string subject);
-    void setMessageAttachments(AttachmentPtrVector &attachments);
-
-    bool getHasAttachment() const;
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_MMS_H__
diff --git a/messaging/old/MessageSMS.cpp b/messaging/old/MessageSMS.cpp
deleted file mode 100644 (file)
index 4204035..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageSMS.cpp
- */
-
-#include <iterator>
-#include <PlatformException.h>
-#include <Logger.h>
-#include "MessageSMS.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageSMS::MessageSMS():
-    Message()
-{
-    LOGD("MessageSMS constructor.");
-    this->m_type = MessageType(MessageType(SMS));
-}
-
-MessageSMS::~MessageSMS()
-{
-    LOGD("MessageSMS destructor.");
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessageSMS.h b/messaging/old/MessageSMS.h
deleted file mode 100644 (file)
index e2afcc0..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessageSMS.h
- */
-
-#ifndef __TIZEN_MESSAGE_SMS_H__
-#define __TIZEN_MESSAGE_SMS_H__
-
-// Header with core msg-service declarations
-#include <msg.h>
-
-#include "Message.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageSMS: public Message {
-public:
-// constructor
-    MessageSMS();
-    ~MessageSMS();
-
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MESSAGE_SMS_H__
diff --git a/messaging/old/MessageService.cpp b/messaging/old/MessageService.cpp
deleted file mode 100644 (file)
index 00c5460..0000000
+++ /dev/null
@@ -1,442 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-
-#include "MessageService.h"
-#include "MessageStorageShortMsg.h"
-#include "MessageStorageEmail.h"
-
-using namespace std;
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-//#################### MessageRecipientsCallbackData ####################
-
-MessageRecipientsCallbackData::MessageRecipientsCallbackData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_is_error(false),
-        m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN),
-        m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN)
-{
-    LOGD("Entered");
-}
-
-MessageRecipientsCallbackData::~MessageRecipientsCallbackData()
-{
-    LOGD("Entered");
-}
-
-void MessageRecipientsCallbackData::setMessage(std::shared_ptr<Message> message)
-{
-    m_message = message;
-}
-
-std::shared_ptr<Message> MessageRecipientsCallbackData::getMessage() const
-{
-    return m_message;
-}
-
-void MessageRecipientsCallbackData::setMessageRecipients(
-        const std::vector<std::string>& msgRecipients)
-{
-    m_msg_recipients = msgRecipients;
-}
-
-const std::vector<std::string>& MessageRecipientsCallbackData::getMessageRecipients() const
-{
-    return m_msg_recipients;
-}
-
-void MessageRecipientsCallbackData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-        if (m_message) {
-            m_err_message += " for: ";
-            // platform issue: we cannot get error per recipient
-            // so all recipients are added to error message
-            std::vector<std::string> recp_list = m_message->getTO();
-            unsigned int count = recp_list.size();
-            for (unsigned int i = 0; i < count; ++i) {
-                m_err_message += recp_list.at(i) + ", ";
-            }
-            recp_list = m_message->getCC();
-            count = recp_list.size();
-            for (unsigned int i = 0; i < count; ++i) {
-                m_err_message += recp_list.at(i) + ", ";
-            }
-            recp_list = m_message->getBCC();
-            count = recp_list.size();
-            for (unsigned int i = 0; i < count; ++i) {
-                m_err_message += recp_list.at(i) + ", ";
-            }
-
-        }
-    }
-}
-
-bool MessageRecipientsCallbackData::isError() const
-{
-    return m_is_error;
-}
-
-std::string MessageRecipientsCallbackData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string MessageRecipientsCallbackData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void MessageRecipientsCallbackData::setAccountId(int account_id){
-    m_account_id = account_id;
-}
-
-int MessageRecipientsCallbackData::getAccountId() const
-{
-    return m_account_id;
-}
-
-void MessageRecipientsCallbackData::setSimIndex(
-    TelNetworkDefaultDataSubs_t sim_index)
-{
-    m_sim_index = sim_index;
-}
-
-TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getSimIndex() const
-{
-    return m_sim_index;
-}
-
-bool MessageRecipientsCallbackData::isSetSimIndex() const
-{
-    return m_sim_index != TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN;
-}
-
-void MessageRecipientsCallbackData::setDefaultSimIndex(
-    TelNetworkDefaultDataSubs_t sim_index)
-{
-    m_default_sim_index = sim_index;
-}
-
-TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() const
-{
-    return m_default_sim_index;
-}
-
-//#################### BaseMessageServiceCallbackData ####################
-
-BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_is_error(false),
-        m_op_handle(-1)
-{
-    LOGD("Entered");
-}
-
-BaseMessageServiceCallbackData::~BaseMessageServiceCallbackData()
-{
-    LOGD("Entered");
-}
-
-void BaseMessageServiceCallbackData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool BaseMessageServiceCallbackData::isError() const
-{
-    return m_is_error;
-}
-
-std::string BaseMessageServiceCallbackData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string BaseMessageServiceCallbackData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void BaseMessageServiceCallbackData::setOperationHandle(const int op_handle)
-{
-    m_op_handle = op_handle;
-}
-
-int BaseMessageServiceCallbackData::getOperationHandle() const
-{
-    return m_op_handle;
-}
-
-//#################### MessageBodyCallbackData ####################
-
-MessageBodyCallbackData::MessageBodyCallbackData(JSContextRef globalCtx):
-        BaseMessageServiceCallbackData(globalCtx)
-{
-    LOGD("Entered");
-}
-
-MessageBodyCallbackData::~MessageBodyCallbackData()
-{
-    LOGD("Entered");
-}
-
-void MessageBodyCallbackData::setMessage(std::shared_ptr<Message> message)
-{
-    m_message = message;
-}
-
-std::shared_ptr<Message> MessageBodyCallbackData::getMessage() const
-{
-    return m_message;
-}
-
-//#################### MessageAttachmentCallbackData ####################
-
-MessageAttachmentCallbackData::MessageAttachmentCallbackData(JSContextRef globalCtx):
-        BaseMessageServiceCallbackData(globalCtx),
-        m_nth(0)
-{
-    LOGD("Entered");
-}
-
-
-MessageAttachmentCallbackData::~MessageAttachmentCallbackData()
-{
-    LOGD("Entered");
-}
-
-void MessageAttachmentCallbackData::setMessageAttachment(
-        std::shared_ptr<MessageAttachment> messageAttachment)
-{
-    m_message_attachment = messageAttachment;
-}
-
-std::shared_ptr<MessageAttachment> MessageAttachmentCallbackData::
-    getMessageAttachment() const
-{
-    return m_message_attachment;
-}
-
-void MessageAttachmentCallbackData::setNth(const int nth)
-{
-    m_nth = nth;
-}
-
-int MessageAttachmentCallbackData::getNth() const
-{
-    return m_nth;
-}
-
-//#################### SyncCallbackData ####################
-
-SyncCallbackData::SyncCallbackData(JSContextRef globalCtx):
-        BaseMessageServiceCallbackData(globalCtx),
-        m_is_limit(false),
-        m_limit(0),
-        m_account_id(-1)
-{
-    LOGD("Entered");
-}
-
-SyncCallbackData::~SyncCallbackData()
-{
-    LOGD("Entered");
-}
-
-void SyncCallbackData::setLimit(const unsigned long limit)
-{
-    m_is_limit = true;
-    m_limit = limit;
-}
-
-bool SyncCallbackData::isLimit() const
-{
-    return m_is_limit;
-}
-
-unsigned long SyncCallbackData::getLimit() const
-{
-    return m_limit;
-}
-
-void SyncCallbackData::setOpId(long op_id)
-{
-    m_op_id = op_id;
-}
-
-long SyncCallbackData::getOpId()
-{
-    return m_op_id;
-}
-
-void SyncCallbackData::setAccountId(int account_id)
-{
-    m_account_id = account_id;
-}
-
-int SyncCallbackData::getAccountId() const
-{
-    return m_account_id;
-}
-
-//#################### SyncFolderCallbackData ####################
-
-SyncFolderCallbackData::SyncFolderCallbackData(JSContextRef globalCtx):
-        SyncCallbackData(globalCtx)
-{
-    LOGD("Entered");
-}
-
-SyncFolderCallbackData::~SyncFolderCallbackData()
-{
-    LOGD("Entered");
-}
-
-void SyncFolderCallbackData::setMessageFolder(
-        std::shared_ptr<MessageFolder> message_folder)
-{
-    m_message_folder = message_folder;
-}
-
-std::shared_ptr<MessageFolder> SyncFolderCallbackData::getMessageFolder() const
-{
-    return m_message_folder;
-}
-
-//#################### MessageService ####################
-
-MessageService::MessageService(int id,
-                    MessageType msgType,
-                    string name):
-        SecurityAccessor(),
-        m_id(id),
-        m_msg_type(msgType),
-        m_name(name)
-{
-    LOGD("Entered");
-    switch (msgType) {
-        case MessageType::SMS:
-        case MessageType::MMS:
-            m_storage.reset(new MessageStorageShortMsg(id, msgType));
-            break;
-        case MessageType::EMAIL:
-            m_storage.reset(new MessageStorageEmail(id));
-            break;
-        default:
-            LOGE("Undefined message type");
-            throw InvalidValuesException("Undefined message type");
-    }
-}
-
-MessageService::~MessageService()
-{
-    LOGD("Entered");
-}
-
-int MessageService::getMsgServiceId() const
-{
-    return m_id;
-}
-
-string MessageService::getMsgServiceIdStr() const
-{
-    return to_string(m_id);
-}
-
-MessageType MessageService::getMsgServiceType() const
-{
-    return m_msg_type;
-}
-
-std::string MessageService::getMsgServiceName() const
-{
-    return m_name;
-}
-
-std::shared_ptr<MessageStorage> MessageService::getMsgStorage() const
-{
-    return m_storage;
-}
-
-void MessageService::sendMessage(MessageRecipientsCallbackData *callback)
-{
-    // this method should be overwritten be specific services
-    LOGE("Cannot send message");
-    throw NotSupportedException("Cannot send message");
-}
-
-void MessageService::loadMessageBody(MessageBodyCallbackData *callback)
-{
-    // this method should be overwritten by specific services
-    LOGE("Cannot load message body");
-    throw NotSupportedException("Cannot load message body");
-}
-
-void MessageService::loadMessageAttachment(MessageAttachmentCallbackData *callback)
-{
-    // this method should be overwritten by email service
-    // for MMS and SMS this function is not supported
-    LOGE("Cannot load message attachment");
-    throw NotSupportedException("Cannot load message attachment");
-}
-
-long MessageService::sync(SyncCallbackData *callback)
-{
-    // this method should be overwritten by email service
-    // for MMS and SMS this function is not supported
-    LOGE("Cannot sync with external server");
-    throw NotSupportedException("Cannot sync with external server");
-}
-
-long MessageService::syncFolder(SyncFolderCallbackData *callback)
-{
-    // this method should be overwritten by email service
-    // for MMS and SMS this function is not supported
-    LOGE("Cannot sync folder with external server");
-    throw NotSupportedException("Cannot sync folder with external server");
-}
-
-void MessageService::stopSync(long op_id)
-{
-    // this method should be overwritten by email service
-    // for MMS and SMS this function is not supported
-    LOGE("Cannot stop sync with external server");
-    throw NotSupportedException("Cannot stop sync with external server");
-}
-
-} // Messaging
-} // DeviceAPI
-
diff --git a/messaging/old/MessageService.h b/messaging/old/MessageService.h
deleted file mode 100755 (executable)
index e710792..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_SERVICE_H__
-#define __TIZEN_MESSAGE_SERVICE_H__
-
-#include <msg.h>
-#include <msg_transport.h>
-#include <msg_storage.h>
-#include <memory>
-#include <ITapiNetwork.h>
-
-#include <CallbackUserData.h>
-#include <PlatformException.h>
-#include <Security.h>
-
-#include "MessagingUtil.h"
-#include "Message.h"
-#include "MessageStorage.h"
-#include "MessageFolder.h"
-
-#include "DBus/Connection.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-enum MessageServiceAccountId
-{
-    UNKNOWN_ACCOUNT_ID = 0,
-    SMS_ACCOUNT_ID = 101,
-    MMS_ACCOUNT_ID = 102
-};
-
-class MessageRecipientsCallbackData : public Common::CallbackUserData {
-public:
-    MessageRecipientsCallbackData(JSContextRef globalCtx);
-    virtual ~MessageRecipientsCallbackData();
-
-    void setMessage(std::shared_ptr<Message> message);
-    std::shared_ptr<Message> getMessage() const;
-
-    void setMessageRecipients(const std::vector<std::string>& msgRecipients);
-    const std::vector<std::string>& getMessageRecipients() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void setAccountId(int account_id);
-    int getAccountId() const;
-
-    void setSimIndex(TelNetworkDefaultDataSubs_t sim_index);
-    TelNetworkDefaultDataSubs_t getSimIndex() const;
-    void setDefaultSimIndex(TelNetworkDefaultDataSubs_t sim_index);
-    TelNetworkDefaultDataSubs_t getDefaultSimIndex() const;
-    bool isSetSimIndex() const;
-
-private:
-    std::shared_ptr<Message> m_message;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    std::vector<std::string> m_msg_recipients;
-    int m_account_id;
-    TelNetworkDefaultDataSubs_t m_sim_index;
-    TelNetworkDefaultDataSubs_t m_default_sim_index;
-};
-
-
-class BaseMessageServiceCallbackData : public Common::CallbackUserData {
-public:
-    BaseMessageServiceCallbackData(JSContextRef globalCtx);
-    virtual ~BaseMessageServiceCallbackData();
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    /**
-     * This handle is returned from various native API functions:
-     *   int email_sync_header(..., int *handle);
-     *   int email_download_body(..., int *handle);
-     *   int email_download_attachment(..., int *handle);
-     *
-     * It is used to stop and identify request.
-     */
-    void setOperationHandle(const int op_handle);
-    int getOperationHandle() const;
-
-protected:
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-
-    int m_op_handle;
-};
-
-class MessageBodyCallbackData : public BaseMessageServiceCallbackData {
-public:
-    MessageBodyCallbackData(JSContextRef globalCtx);
-    virtual ~MessageBodyCallbackData();
-
-    void setMessage(std::shared_ptr<Message> message);
-    std::shared_ptr<Message> getMessage() const;
-
-private:
-    std::shared_ptr<Message> m_message;
-};
-
-class MessageAttachmentCallbackData : public BaseMessageServiceCallbackData {
-public:
-    MessageAttachmentCallbackData(JSContextRef globalCtx);
-    virtual ~MessageAttachmentCallbackData();
-
-    void setMessageAttachment(std::shared_ptr<MessageAttachment> messageAttachment);
-    std::shared_ptr<MessageAttachment> getMessageAttachment() const;
-
-    /**
-     * nth is used in native api call:
-     * int email_download_attachment(int mail_id, int nth, int *handle);
-     *
-     * nth is equal to attachment index+1 (starts from 1 not 0) see
-     * email-api-network.h for details.
-     * */
-    void setNth(const int nth);
-    int getNth() const;
-
-private:
-    std::shared_ptr<MessageAttachment> m_message_attachment;
-    int m_nth;
-};
-
-class SyncCallbackData : public BaseMessageServiceCallbackData {
-public:
-    SyncCallbackData(JSContextRef globalCtx);
-    virtual ~SyncCallbackData();
-
-    void setLimit(const unsigned long limit);
-    bool isLimit() const;
-    unsigned long getLimit() const;
-
-    void setOpId(long op_id);
-    long getOpId();
-    void setAccountId(int account_id);
-    int getAccountId() const;
-
-protected:
-    bool m_is_limit;
-    unsigned long m_limit;
-
-    long m_op_id;
-    int m_account_id;
-};
-
-class SyncFolderCallbackData : public SyncCallbackData {
-public:
-    SyncFolderCallbackData(JSContextRef globalCtx);
-    virtual ~SyncFolderCallbackData();
-
-    void setMessageFolder(std::shared_ptr<MessageFolder> message_folder);
-    std::shared_ptr<MessageFolder> getMessageFolder() const;
-
-private:
-    std::shared_ptr<MessageFolder> m_message_folder;
-};
-
-
-class MessageService : public Common::SecurityAccessor
-{
-public:
-    virtual ~MessageService();
-
-    virtual int getMsgServiceId() const;
-    virtual std::string getMsgServiceIdStr() const;
-    virtual MessageType getMsgServiceType() const;
-    virtual std::string getMsgServiceName() const;
-    virtual std::shared_ptr<MessageStorage> getMsgStorage() const;
-
-    virtual void sendMessage(MessageRecipientsCallbackData *callback);
-    virtual void loadMessageBody(MessageBodyCallbackData *callback);
-    virtual void loadMessageAttachment(MessageAttachmentCallbackData *callback);
-    virtual long sync(SyncCallbackData *callback);
-
-    /**
-     * @param callback - owned by this method unless exception is thrown
-     * @return opId - "long Identifier which can be used to stop this service operation"
-     *                (form JS documentation)
-     *
-     */
-    virtual long syncFolder(SyncFolderCallbackData *callback);
-
-    virtual void stopSync(long op_id);
-
-protected:
-    /**
-     * We have child classes MessageServiceEmail and MessageServiceShortMsg which
-     * should provide specialized implementation.
-     */
-    MessageService(int id,
-            MessageType msgType,
-            std::string name);
-
-    int m_id;
-    MessageType m_msg_type;
-    std::string m_name;
-    std::shared_ptr<MessageStorage> m_storage;
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_MESSAGE_SERVICE_H__
diff --git a/messaging/old/MessageServiceEmail.cpp b/messaging/old/MessageServiceEmail.cpp
deleted file mode 100644 (file)
index ca45652..0000000
+++ /dev/null
@@ -1,288 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-#include <PlatformException.h>
-
-#include "MessageServiceEmail.h"
-#include "EmailManager.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageServiceEmail::MessageServiceEmail(int id, std::string name)
-        : MessageService(id,
-                MessageType::EMAIL,
-                name)
-{
-    LOGD("Entered");
-}
-
-MessageServiceEmail::~MessageServiceEmail()
-{
-    LOGD("Entered");
-}
-
-static gboolean sendMessageTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        EmailManager::getInstance().sendMessage(
-                static_cast<MessageRecipientsCallbackData*>(data));
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    return FALSE;
-}
-
-void MessageServiceEmail::sendMessage(MessageRecipientsCallbackData *callback)
-{
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    if (m_msg_type != callback->getMessage()->getType()) {
-
-        LOGE("Incorrect message type");
-        throw Common::TypeMismatchException("Incorrect message type");
-    }
-
-    callback->setAccountId(m_id);
-
-    guint id = g_idle_add(sendMessageTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add fails");
-        delete callback;
-        throw Common::UnknownException("Could not add task");
-    }
-}
-
-static gboolean loadMessageBodyTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        EmailManager::getInstance().loadMessageBody(
-                static_cast<MessageBodyCallbackData*>(data));
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    return FALSE;
-}
-
-void MessageServiceEmail::loadMessageBody(MessageBodyCallbackData *callback)
-{
-    LOGD("Entered");
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    guint id = g_idle_add(loadMessageBodyTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        throw Common::UnknownException("Could not add task");
-    }
-}
-
-static gboolean loadMessageAttachmentTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        MessageAttachmentCallbackData *callback =
-                static_cast<MessageAttachmentCallbackData *>(data);
-        if (!callback) {
-            LOGE("Callback is null");
-            throw Common::UnknownException("Callback is null");
-        }
-
-        std::shared_ptr<MessageAttachment> att =  callback->getMessageAttachment();
-
-        // if the attachment is already saved, then it doesn't need to load again.
-        if (att->isFilePathSet() && att->isSaved()){
-            JSContextRef context = callback->getContext();
-            JSObjectRef jsMessageAtt = JSMessageAttachment::makeJSObject(context, att);
-            callback->callSuccessCallback(jsMessageAtt);
-
-            delete callback;
-            callback = NULL;
-            return FALSE;
-        }
-
-        EmailManager::getInstance().loadMessageAttachment(
-                static_cast<MessageAttachmentCallbackData*>(data));
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-                (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-    return FALSE;
-}
-
-void MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallbackData *callback)
-{
-    LOGD("Entered");
-    guint id = g_idle_add(loadMessageAttachmentTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        throw Common::UnknownException("Could not add task");
-    }
-}
-
-static gboolean syncTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        EmailManager::getInstance().sync(data);
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    return FALSE;
-}
-
-long MessageServiceEmail::sync(SyncCallbackData *callback)
-{
-    LOGD("Entered");
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    long op_id = EmailManager::getInstance().getUniqueOpId();
-    callback->setOpId(op_id);
-    callback->setAccountId(m_id);
-
-    guint id = g_idle_add(syncTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        throw Common::UnknownException("Could not add task");
-    }
-    return op_id;
-}
-
-static gboolean syncFolderTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        EmailManager::getInstance().syncFolder(
-                static_cast<SyncFolderCallbackData*>(data));
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    return FALSE;
-}
-
-long MessageServiceEmail::syncFolder(SyncFolderCallbackData *callback)
-{
-    LOGD("Entered");
-    if(!callback){
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    if(!callback->getMessageFolder()) {
-        LOGE("Message folder is null");
-        throw Common::TypeMismatchException("Message folder is null");
-    }
-
-    long op_id = EmailManager::getInstance().getUniqueOpId();
-    callback->setOpId(op_id);
-    callback->setAccountId(m_id);
-
-    guint id = g_idle_add(syncFolderTask, callback);
-    if (!id) {
-        LOGE("g_idle_add fails");
-        delete callback;
-    }
-
-    return op_id;
-}
-
-static gboolean stopSyncTask(void* data)
-{
-    LOGD("Entered");
-
-    try {
-        if (!data) {
-            LOGE("opId is null");
-            return FALSE;
-        }
-
-        const long op_id = *(static_cast<long*>(data));
-        delete static_cast<long*>(data);
-        data = NULL;
-        EmailManager::getInstance().stopSync(op_id);
-
-    } catch(const Common::BasePlatformException& exception) {
-        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
-             (exception.getMessage()).c_str());
-    } catch(...) {
-        LOGE("Unhandled exception!");
-    }
-
-    return FALSE;
-}
-
-void MessageServiceEmail::stopSync(long data)
-{
-    LOGD("Entered");
-    long* op_id = new long();
-    *op_id = data;
-    guint id = g_idle_add(stopSyncTask, static_cast<void*>(op_id));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete op_id;
-        op_id = NULL;
-        throw Common::UnknownException("Could not add task");
-    }
-}
-
-
-} // Messaging
-} // DeviceAPI
-
diff --git a/messaging/old/MessageServiceEmail.h b/messaging/old/MessageServiceEmail.h
deleted file mode 100755 (executable)
index f8dfd9b..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_SERVICE_EMAIL_H__
-#define __TIZEN_MESSAGE_SERVICE_EMAIL_H__
-
-#include "MessageService.h"
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageServiceEmail : public MessageService {
-public:
-    MessageServiceEmail(int id, std::string name);
-    virtual ~MessageServiceEmail();
-
-    virtual void sendMessage(MessageRecipientsCallbackData *callback);
-    virtual void loadMessageBody(MessageBodyCallbackData *callback);
-    virtual void loadMessageAttachment(MessageAttachmentCallbackData *callback);
-    virtual long sync(SyncCallbackData *callback);
-
-   /**
-     * @param callback - owned by this method unless exception is thrown
-     * @return opId - "long Identifier which can be used to stop this service operation"
-     *                (form JS documentation)
-     *
-     */
-    virtual long syncFolder(SyncFolderCallbackData *callback);
-
-    virtual void stopSync(long op_id);
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_MESSAGE_SERVICE_EMAIL_H__
diff --git a/messaging/old/MessageServiceShortMsg.cpp b/messaging/old/MessageServiceShortMsg.cpp
deleted file mode 100755 (executable)
index dcf3a00..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-#include <tapi_common.h>
-#include <ITapiSim.h>
-#include <ITapiNetwork.h>
-#include "MessageServiceShortMsg.h"
-#include "ShortMsgManager.h"
-#include "JSMessage.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType)
-        : MessageService(id,
-                msgType,
-                MessagingUtil::messageTypeToString(msgType))
-{
-    LOGD("Entered");
-}
-
-MessageServiceShortMsg::~MessageServiceShortMsg()
-{
-    LOGD("Entered");
-}
-
-static gboolean sendMessageThread(void* data)
-{
-    LOGD("Entered");
-
-    auto callback = static_cast<MessageRecipientsCallbackData *>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    ShortMsgManager::getInstance().sendMessage(callback);
-    return FALSE;
-}
-
-void MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData *callback)
-{
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    if (m_msg_type != callback->getMessage()->getType()) {
-        LOGE("Incorrect message type");
-        throw Common::TypeMismatchException("Incorrect message type");
-    }
-
-    /*
-     * Set sim index.
-     * If user has set sim index manually, check sim index is valid.
-     * Otherwise, use default sim which is already set.
-     */
-    TelNetworkDefaultDataSubs_t default_sim =
-        TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN;
-    TapiHandle *handle = tel_init(NULL);
-
-    int ret = tel_get_network_default_data_subscription(handle, &default_sim);
-    if (ret != TAPI_API_SUCCESS) {
-        LOGE("Failed to find default sim index %d", ret);
-    }
-
-    LOGD("Default sim index: %d", default_sim);
-    callback->setDefaultSimIndex(default_sim);
-    tel_deinit(handle);
-
-    // simIndex parameter is only available for sms message.
-    // In case of mms, the parameter is silently ignored.
-    if (callback->isSetSimIndex() &&
-        callback->getMessage()->getType() == MessageType::SMS) {
-        char **cp_list = tel_get_cp_name_list();
-        TelNetworkDefaultDataSubs_t sim_index = callback->getSimIndex();
-        int sim_count = 0;
-
-        if (cp_list) {
-            while (cp_list[sim_count]) {
-                sim_count++;
-            }
-            g_strfreev(cp_list);
-        } else {
-            LOGD("Empty cp name list");
-        }
-
-        if (sim_index >= sim_count) {
-            LOGE("Sim index out of count %d : %d", sim_index, sim_count);
-            throw InvalidValuesException("The index of sim is out of bound");
-        }
-
-        callback->getMessage()->setSimIndex(sim_index);
-    } else {
-        callback->getMessage()->setSimIndex(default_sim);
-    }
-
-    if(!g_idle_add(sendMessageThread, static_cast<void*>(callback))) {
-        LOGE("g_idle_add fails");
-        throw UnknownException("Could not add task");
-    }
-}
-
-static gboolean loadMessageBodyTask(void* data)
-{
-    LOGD("Entered");
-    MessageBodyCallbackData* callback = static_cast<MessageBodyCallbackData*>(data);
-    if(!callback) {
-        LOGE("callback is NULL");
-        return FALSE;
-    }
-
-    try {
-        JSContextRef context = callback->getContext();
-        JSObjectRef jsMessage = JSMessage::makeJSObject(context, callback->getMessage());
-        callback->callSuccessCallback(jsMessage);
-    } catch (...) {
-        LOGE("Couldn't create JSMessage object!");
-        callback->callErrorCallback();
-    }
-
-    return FALSE;
-}
-
-void MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData *callback)
-{
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    if (m_msg_type != callback->getMessage()->getType()) {
-        LOGE("Incorrect message type");
-        throw Common::TypeMismatchException("Incorrect message type");
-    }
-
-    guint id = g_idle_add(loadMessageBodyTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add fails");
-        throw Common::UnknownException("Could not add task");
-    }
-}
-
-} // Messaging
-} // DeviceAPI
-
diff --git a/messaging/old/MessageServiceShortMsg.h b/messaging/old/MessageServiceShortMsg.h
deleted file mode 100755 (executable)
index 54dd4e1..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
-#define __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
-
-#include "MessageService.h"
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageServiceShortMsg : public MessageService {
-public:
-    MessageServiceShortMsg(int id, MessageType msgType);
-    virtual ~MessageServiceShortMsg();
-
-    void sendMessage(MessageRecipientsCallbackData *callback);
-
-    virtual void loadMessageBody(MessageBodyCallbackData *callback);
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
diff --git a/messaging/old/MessageStorage.cpp b/messaging/old/MessageStorage.cpp
deleted file mode 100644 (file)
index 10eb8b8..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "MessageStorage.h"
-#include "ChangeListenerContainer.h"
-#include "MessagesChangeCallback.h"
-#include "ConversationsChangeCallback.h"
-#include "FoldersChangeCallback.h"
-#include <Logger.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageStorage::MessageStorage(int id, MessageType msgType):
-        SecurityAccessor(),
-        m_id(id),
-        m_msg_type(msgType)
-{
-    LOGD("Entered");
-}
-
-MessageStorage::~MessageStorage()
-{
-    LOGD("Entered");
-}
-
-int MessageStorage::getMsgServiceId() const {
-    return m_id;
-}
-
-MessageType MessageStorage::getMsgServiceType() const {
-    return m_msg_type;
-}
-
-long MessageStorage::addMessagesChangeListener(
-            std::shared_ptr<MessagesChangeCallback> callback)
-{
-    LOGD("Entered");
-    return ChangeListenerContainer::getInstance().addMessageChangeListener(callback);
-}
-
-long MessageStorage::addConversationsChangeListener(
-            std::shared_ptr<ConversationsChangeCallback> callback)
-{
-    LOGD("Entered");
-    return ChangeListenerContainer::getInstance().addConversationChangeListener(callback);
-}
-
-long MessageStorage::addFoldersChangeListener(
-            std::shared_ptr<FoldersChangeCallback> callback)
-{
-    LOGD("Entered");
-    return ChangeListenerContainer::getInstance().addFolderChangeListener(callback);
-}
-
-void MessageStorage::removeChangeListener(JSContextRef context, long watchId)
-{
-    LOGD("Entered");
-    return ChangeListenerContainer::getInstance().removeChangeListener(context, watchId);
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/MessageStorage.h b/messaging/old/MessageStorage.h
deleted file mode 100644 (file)
index 82dbc19..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_STORAGE_H
-#define __TIZEN_MESSAGE_STORAGE_H
-
-#include "MessageCallbackUserData.h"
-#include "MessagesCallbackUserData.h"
-#include "FindMsgCallbackUserData.h"
-#include "ConversationCallbackData.h"
-#include "FoldersCallbackData.h"
-#include "MessagingUtil.h"
-#include <memory>
-// headers for ChangeListeners support
-#include "MessagesChangeCallback.h"
-#include "FoldersChangeCallback.h"
-#include "ConversationsChangeCallback.h"
-#include <Security.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessagesChangeCallback;
-
-class MessageStorage : public Common::SecurityAccessor
-{
-public:
-    MessageStorage(int id, MessageType msgType);
-    virtual ~MessageStorage();
-
-    virtual int getMsgServiceId() const;
-    virtual MessageType getMsgServiceType() const;
-
-    virtual void addDraftMessage(MessageCallbackUserData* callback) = 0;
-    virtual void removeMessages(MessagesCallbackUserData* callback) = 0;
-    virtual void updateMessages(MessagesCallbackUserData* callback) = 0;
-    virtual void findMessages(FindMsgCallbackUserData* callback) = 0;
-    virtual void findConversations(ConversationCallbackData* callback) = 0;
-    virtual void removeConversations(ConversationCallbackData* callback) = 0;
-    virtual void findFolders(FoldersCallbackData* callback) = 0;
-
-    // Listeners registration/removal is common for all types of storage
-    // and does not have to be overwritten in derived classes.
-    long addMessagesChangeListener(
-            std::shared_ptr<MessagesChangeCallback> callback);
-    long addConversationsChangeListener(
-            std::shared_ptr<ConversationsChangeCallback> callback);
-    long addFoldersChangeListener(
-            std::shared_ptr<FoldersChangeCallback> callback);
-    void removeChangeListener(JSContextRef context, long watchId);
-
-protected:
-    int m_id;
-    MessageType m_msg_type;
-};
-
-struct MessageStorageHolder {
-    std::shared_ptr<MessageStorage> ptr;
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_MESSAGE_STORAGE_H */
-
diff --git a/messaging/old/MessageStorageEmail.cpp b/messaging/old/MessageStorageEmail.cpp
deleted file mode 100644 (file)
index c906eb3..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "MessageStorageEmail.h"
-#include "EmailManager.h"
-#include "Message.h"
-
-#include <Logger.h>
-#include <PlatformException.h>
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageStorageEmail::MessageStorageEmail(int id):
-        MessageStorage(id, MessageType::EMAIL) {
-    LOGD("Entered");
-}
-
-MessageStorageEmail::~MessageStorageEmail() {
-    LOGD("Entered");
-}
-
-static gboolean callError(void* data)
-{
-    LOGD("Entered");
-    MessageCallbackUserData* callback =
-           static_cast<MessageCallbackUserData*>(data);
-    if (!callback) {
-       LOGE("Callback is null");
-       return FALSE;
-    }
-    JSContextRef context = callback->getContext();
-    JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-            callback->getErrorName(), callback->getErrorMessage());
-    callback->callErrorCallback(errobj);
-
-    return FALSE;
-}
-
-static gboolean addDraftMessageTask(void* data)
-{
-    LOGD("Entered");
-
-    MessageCallbackUserData *callback = static_cast<MessageCallbackUserData*>(data);
-    EmailManager::getInstance().addDraftMessage(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::addDraftMessage(MessageCallbackUserData* callback) {
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    if (m_msg_type != callback->getMessage()->getType()) {
-       LOGE("Incorrect message type");
-       callback->setError(JSWebAPIErrorFactory::INVALID_VALUES_ERROR,
-               "Incorrect message type");
-       guint id = g_idle_add(callError, static_cast<void*>(callback));
-       if (!id) {
-           LOGE("g_idle_add failed");
-           delete callback;
-           callback = NULL;
-       }
-       return;
-    }
-
-    callback->setAccountId(m_id);
-
-    guint id = g_idle_add(addDraftMessageTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-static gboolean removeMessagesTask(void* data)
-{
-    LOGD("Entered");
-
-    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
-    EmailManager::getInstance().removeMessages(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(removeMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-static gboolean updateMessagesTask(void* data)
-{
-    LOGD("Entered");
-
-    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
-    EmailManager::getInstance().updateMessages(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-    guint id = g_idle_add(updateMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-static gboolean findMessagesTask(void* data)
-{
-    LOGD("Entered");
-
-    FindMsgCallbackUserData *callback = static_cast<FindMsgCallbackUserData*>(data);
-    EmailManager::getInstance().findMessages(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    callback->setAccountId(m_id);
-    callback->setMessageServiceType(m_msg_type);
-    guint id = g_idle_add(findMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-static gboolean findConversationsTask(void* data)
-{
-    LOGD("Entered");
-
-    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
-    EmailManager::getInstance().findConversations(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::findConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    callback->setAccountId(m_id);
-    callback->setMessageServiceType(m_msg_type);
-    guint id = g_idle_add(findConversationsTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-static gboolean removeConversationsTask(void* data)
-{
-    LOGD("Entered");
-
-    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
-    EmailManager::getInstance().removeConversations(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::removeConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-    guint id = g_idle_add(removeConversationsTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-static gboolean findFoldersTask(void* data)
-{
-    LOGD("Entered");
-
-    FoldersCallbackData *callback = static_cast<FoldersCallbackData*>(data);
-    EmailManager::getInstance().findFolders(callback);
-
-    return FALSE;
-}
-
-void MessageStorageEmail::findFolders(FoldersCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw Common::UnknownException("Callback is null");
-    }
-
-    guint id = g_idle_add(findFoldersTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/MessageStorageEmail.h b/messaging/old/MessageStorageEmail.h
deleted file mode 100644 (file)
index 49f1aac..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_STORAGE_EMAIL_H
-#define __TIZEN_MESSAGE_STORAGE_EMAIL_H
-
-#include "MessageStorage.h"
-#include <JSWebAPIErrorFactory.h>
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageStorageEmail: public MessageStorage {
-public:
-    MessageStorageEmail(int id);
-    virtual ~MessageStorageEmail();
-
-    virtual void addDraftMessage(MessageCallbackUserData* callback);
-    virtual void removeMessages(MessagesCallbackUserData* callback);
-    virtual void updateMessages(MessagesCallbackUserData* callback);
-    virtual void findMessages(FindMsgCallbackUserData* callback);
-    virtual void findConversations(ConversationCallbackData* callback);
-    virtual void removeConversations(ConversationCallbackData* callback);
-    virtual void findFolders(FoldersCallbackData* callback);
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_MESSAGE_STORAGE_EMAIL_H */
-
diff --git a/messaging/old/MessageStorageShortMsg.cpp b/messaging/old/MessageStorageShortMsg.cpp
deleted file mode 100755 (executable)
index da28f16..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-#include "JSMessageFolder.h"
-#include <JSUtil.h>
-#include "MessageStorageShortMsg.h"
-#include "ShortMsgManager.h"
-#include <Logger.h>
-#include <PlatformException.h>
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageStorageShortMsg::MessageStorageShortMsg(int id, MessageType msgType):
-        MessageStorage(id, msgType) {
-    LOGD("Entered");
-}
-
-MessageStorageShortMsg::~MessageStorageShortMsg() {
-    LOGD("Entered");
-}
-
-static gboolean addDraftMessageTask(void* data) {
-    LOGD("Entered");
-
-    MessageCallbackUserData *callback = static_cast<MessageCallbackUserData*>(data);
-    ShortMsgManager::getInstance().addDraftMessage(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::addDraftMessage(MessageCallbackUserData* callback) {
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    if (m_msg_type != callback->getMessage()->getType()) {
-        LOGE("Incorrect message type");
-        throw TypeMismatchException("Incorrect message type");
-    }
-
-    guint id = g_idle_add(addDraftMessageTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean removeMessagesTask(void* data) {
-    LOGD("Entered");
-
-    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
-    ShortMsgManager::getInstance().removeMessages(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(removeMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean updateMessagesTask(void* data) {
-    LOGD("Entered");
-
-    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
-    ShortMsgManager::getInstance().updateMessages(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(updateMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean findMessagesTask(void* data) {
-    LOGD("Entered");
-
-    FindMsgCallbackUserData *callback = static_cast<FindMsgCallbackUserData*>(data);
-    ShortMsgManager::getInstance().findMessages(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(findMessagesTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean findConversationsTask(void* data) {
-    LOGD("Entered");
-
-    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
-    ShortMsgManager::getInstance().findConversations(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::findConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(findConversationsTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean removeConversationsTask(void* data) {
-    LOGD("Entered");
-
-    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
-    ShortMsgManager::getInstance().removeConversations(callback);
-
-    return false;
-}
-
-void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback) {
-        LOGE("Callback is null");
-        throw UnknownException("Callback is null");
-    }
-
-    callback->setMessageServiceType(m_msg_type);
-
-    guint id = g_idle_add(removeConversationsTask, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        throw UnknownException("g_idle_add failed");
-    }
-}
-
-static gboolean findFoldersCB(void* data)
-{
-    LOGD("Entered");
-
-    FoldersCallbackData *callback = static_cast<FoldersCallbackData*>(data);
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return FALSE;
-    }
-
-    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,
-                JSMessageFolder>(context, callback->getFolders());
-
-    callback->callSuccessCallback(js_obj);
-
-    delete callback;
-    callback = NULL;
-
-    return FALSE;
-}
-
-
-void MessageStorageShortMsg::findFolders(FoldersCallbackData* callback)
-{
-    LOGD("Entered");
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    std::string content_type = MessagingUtil::messageTypeToString(m_msg_type);
-    std::string empty = "";
-    std::shared_ptr<MessageFolder> folder;
-
-    /* For SMS and MMS, folderId can be one of these values:
-     *
-     *  INBOX = 1,
-     *  OUTBOX = 2,
-     *  DRAFTS = 3,
-     *  SENTBOX = 4
-     */
-
-    for(int i = 1;i < 5;i++)
-    {
-        folder = std::make_shared<MessageFolder>(
-                std::to_string(i),
-                empty,
-                std::to_string(m_id),
-                content_type,
-                MessagingUtil::messageFolderTypeToString((MessageFolderType)i),
-                empty,
-                (MessageFolderType)i,
-                false);
-
-        callback->addFolder(folder);
-    }
-
-    guint id = g_idle_add(findFoldersCB, static_cast<void*>(callback));
-    if (!id) {
-        LOGE("g_idle_add failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/MessageStorageShortMsg.h b/messaging/old/MessageStorageShortMsg.h
deleted file mode 100644 (file)
index ac1d77f..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGE_STORAGE_SMS_H
-#define __TIZEN_MESSAGE_STORAGE_SMS_H
-
-#include "MessageStorage.h"
-
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageStorageShortMsg: public MessageStorage {
-public:
-    MessageStorageShortMsg(int id, MessageType msgType);
-    virtual ~MessageStorageShortMsg();
-
-    virtual void addDraftMessage(MessageCallbackUserData* callback);
-    virtual void removeMessages(MessagesCallbackUserData* callback);
-    virtual void updateMessages(MessagesCallbackUserData* callback);
-    virtual void findMessages(FindMsgCallbackUserData* callback);
-    virtual void findConversations(ConversationCallbackData* callback);
-    virtual void removeConversations(ConversationCallbackData* callback);
-    virtual void findFolders(FoldersCallbackData* callback);
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_MESSAGE_STORAGE_SMS_H */
-
diff --git a/messaging/old/MessagesCallbackUserData.cpp b/messaging/old/MessagesCallbackUserData.cpp
deleted file mode 100644 (file)
index 1e436de..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include "MessagesCallbackUserData.h"
-#include "JSMessage.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-
-MessagesCallbackUserData::MessagesCallbackUserData(JSContextRef globalCtx):
-        CallbackUserData(globalCtx),
-        m_is_error(false),
-        m_service_type(MessageType::UNDEFINED)
-{
-}
-
-MessagesCallbackUserData::~MessagesCallbackUserData() {
-}
-
-void MessagesCallbackUserData::addMessage(std::shared_ptr<Message> msg)
-{
-    m_messages.push_back(msg);
-}
-
-std::vector<std::shared_ptr<Message>> MessagesCallbackUserData::getMessages() const
-{
-    return m_messages;
-}
-
-void MessagesCallbackUserData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool MessagesCallbackUserData::isError() const
-{
-    return m_is_error;
-}
-
-std::string MessagesCallbackUserData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string MessagesCallbackUserData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void MessagesCallbackUserData::setMessageServiceType(MessageType m_msg_type)
-{
-    m_service_type = m_msg_type;
-}
-
-MessageType MessagesCallbackUserData::getMessageServiceType() const
-{
-    return m_service_type;
-}
-
-void MessagesCallbackUserData::addMessages(JSContextRef context,
-            const std::vector<JSValueRef>& jsobject_messages)
-{
-    const size_t new_messages_count = jsobject_messages.size();
-    if(0 == new_messages_count) {
-        return;
-    }
-
-    m_messages.reserve(m_messages.size() + new_messages_count);
-    for (auto it = jsobject_messages.begin() ; it != jsobject_messages.end(); ++it) {
-        m_messages.push_back(JSMessage::getPrivateObject(context, *it));
-    }
-}
-
-}//Messaging
-}//DeviceAPI
diff --git a/messaging/old/MessagesCallbackUserData.h b/messaging/old/MessagesCallbackUserData.h
deleted file mode 100644 (file)
index 39b7797..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGES_CALLBACK_USER_DATA_H
-#define __TIZEN_MESSAGES_CALLBACK_USER_DATA_H
-
-#include <CallbackUserData.h>
-#include <memory>
-#include <vector>
-#include <string>
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-
-class MessagesCallbackUserData: public Common::CallbackUserData {
-public:
-    MessagesCallbackUserData(JSContextRef globalCtx);
-    virtual ~MessagesCallbackUserData();
-
-    void addMessages(JSContextRef context,
-            const std::vector<JSValueRef>& jsobject_messages);
-
-    void addMessage(std::shared_ptr<Message> msg);
-    std::vector<std::shared_ptr<Message>> getMessages() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void setMessageServiceType(MessageType m_msg_type);
-    MessageType getMessageServiceType() const;
-
-private:
-    std::vector<std::shared_ptr<Message>> m_messages;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    MessageType m_service_type;
-};
-
-}//Messaging
-}//DeviceAPI
-
-#endif /* __TIZEN_MESSAGES_CALLBACK_USER_DATA_H */
diff --git a/messaging/old/MessagesChangeCallback.cpp b/messaging/old/MessagesChangeCallback.cpp
deleted file mode 100644 (file)
index b10c6bf..0000000
+++ /dev/null
@@ -1,234 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <PlatformException.h>
-#include <JSUtil.h>
-#include <Logger.h>
-
-#include "MessagesChangeCallback.h"
-#include "JSMessage.h"
-#include "AbstractFilter.h"
-#include "MessagingUtil.h"
-
-using namespace DeviceAPI::Common;
-using namespace DeviceAPI::Tizen;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-
-std::string limitedString(const std::string& src,
-                          const size_t max_len = 40)
-{
-    if(src.length() > max_len) {
-        return src.substr(0,max_len);
-    } else {
-        return src;
-    }
-}
-
-} //Anonymous namespace
-
-const char* MESSAGESADDED = "messagesadded";
-const char* MESSAGESUPDATED = "messagesupdated";
-const char* MESSAGESREMOVED = "messagesremoved";
-
-MessagesChangeCallback::MessagesChangeCallback(JSContextRef global_ctx,
-        JSObjectRef on_added_obj,
-        JSObjectRef on_updated_obj,
-        JSObjectRef on_removed_obj,
-        int service_id,
-        MessageType service_type) :
-        m_callback_data(global_ctx),
-        m_service_id(service_id),
-        m_msg_type(service_type),
-        m_is_act(true)
-{
-    LOGD("Entered");
-
-    m_callback_data.setCallback(MESSAGESADDED, on_added_obj);
-    m_callback_data.setCallback(MESSAGESUPDATED, on_updated_obj);
-    m_callback_data.setCallback(MESSAGESREMOVED, on_removed_obj);
-}
-
-MessagesChangeCallback::~MessagesChangeCallback()
-{
-    LOGD("Entered");
-}
-
-MessagePtrVector MessagesChangeCallback::filterMessages(
-        AbstractFilterPtr filter,
-        const MessagePtrVector& source_messages,
-        const int service_id)
-{
-    LOGD("Entered sourceMessages.size():%d filter:%s", source_messages.size(),
-            (filter ? "PRESENT" : "NULL"));
-
-    if (filter) {
-        MessagePtrVector filtered_messages;
-        MessagePtrVector::const_iterator it = source_messages.begin();
-        MessagePtrVector::const_iterator end_it = source_messages.end();
-
-        for(int i = 0; it != end_it ; ++i, ++it) {
-            const MessagePtr& message = *it;
-            message->setServiceId(service_id);
-
-            const bool matched = filter->isMatching(message.get());
-            if(matched) {
-                filtered_messages.push_back(message);
-            }
-
-            LOGD("[%d] is Message(%p) {", i, message.get());
-            LOGD("[%d] messageId: %d", i, message->getId());
-            LOGD("[%d] message subject: %s", i, message->getSubject().c_str());
-            LOGD("[%d] from: %s", i, message->getFrom().c_str());
-
-            if(message->getBody()) {
-                const std::string& pBody = message->getBody()->getPlainBody();
-                LOGD("[%d] message plainBody: %s", i, limitedString(pBody).c_str());
-            }
-
-            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
-            LOGD("[%d] }");
-        }
-
-        LOGD("returning matching %d of %d messages", filtered_messages.size(),
-                source_messages.size());
-        return filtered_messages;
-    }
-    else {
-        return source_messages;
-    }
-}
-
-void MessagesChangeCallback::added(const MessagePtrVector& msgs)
-{
-    LOGD("Entered num messages: %d", msgs.size());
-    if (!m_is_act) {
-        return;
-    }
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
-    //cancel callback only if filter did remove all messages
-    //if callback was called with empty msgs list, call it
-    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
-        LOGD("All messages were filtered out, not calling callback");
-        return;
-    }
-    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
-            ctx, filtered_msgs);
-
-    LOGD("Calling:%s with:%d added messages", MESSAGESADDED,
-        filtered_msgs.size());
-    m_callback_data.invokeCallback(MESSAGESADDED, js_obj);
-}
-
-void MessagesChangeCallback::updated(const MessagePtrVector& msgs)
-{
-    LOGD("Entered num messages: %d", msgs.size());
-    if (!m_is_act) {
-        return;
-    }
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
-    //cancel callback only if filter did remove all messages
-    //if callback was called with empty msgs list, call it
-    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
-        LOGD("All messages were filtered out, not calling callback");
-        return;
-    }
-    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
-            ctx, filtered_msgs);
-
-    LOGD("Calling:%s with:%d updated messages", MESSAGESUPDATED,
-        filtered_msgs.size());
-    m_callback_data.invokeCallback(MESSAGESUPDATED, js_obj);
-}
-
-void MessagesChangeCallback::removed(const MessagePtrVector& msgs)
-{
-    LOGD("Enter event: msgs.size() = %d", msgs.size());
-    if (!m_is_act) {
-        return;
-    }
-
-    JSContextRef ctx = m_callback_data.getContext();
-    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
-    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
-    //cancel callback only if filter did remove all messages
-    //if callback was called with empty msgs list, call it
-    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
-        LOGD("All messages were filtered out, not calling callback");
-        return;
-    }
-    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
-            ctx, filtered_msgs);
-
-    LOGD("Calling:%s with:%d removed messages", MESSAGESREMOVED,
-        filtered_msgs.size());
-    m_callback_data.invokeCallback(MESSAGESREMOVED, js_obj);
-}
-
-void MessagesChangeCallback::setFilter(AbstractFilterPtr filter)
-{
-    m_filter = filter;
-}
-
-AbstractFilterPtr MessagesChangeCallback::getFilter() const
-{
-    return m_filter;
-}
-
-int MessagesChangeCallback::getServiceId() const
-{
-    return m_service_id;
-}
-
-MessageType MessagesChangeCallback::getServiceType() const
-{
-    return m_msg_type;
-}
-
-void MessagesChangeCallback::setActive(bool act) {
-    m_is_act = act;
-}
-
-bool MessagesChangeCallback::isActive() {
-    return m_is_act;
-}
-
-void MessagesChangeCallback::setItems(MessagePtrVector& items)
-{
-    m_items = items;
-}
-MessagePtrVector MessagesChangeCallback::getItems()
-{
-    return m_items;
-}
-
-JSContextRef MessagesChangeCallback::getContext() const
-{
-    return m_callback_data.getContext();
-}
-
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessagesChangeCallback.h b/messaging/old/MessagesChangeCallback.h
deleted file mode 100644 (file)
index 6f5c571..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
-#define __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
-
-#include <JavaScriptCore/JavaScript.h>
-
-#include <MultiCallbackUserData.h>
-
-#include <AbstractFilter.h>
-
-#include "Message.h"
-#include "MessagingUtil.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-extern const char* MESSAGESADDED;
-extern const char* MESSAGESUPDATED;
-extern const char* MESSAGESREMOVED;
-
-class MessagesChangeCallback {
-public:
-    MessagesChangeCallback(JSContextRef globalCtx,
-            JSObjectRef on_added_obj,
-            JSObjectRef on_updated_obj,
-            JSObjectRef on_removed_obj,
-            int service_id,
-            MessageType service_type);
-    virtual ~MessagesChangeCallback();
-
-    void added(const MessagePtrVector& messages);
-    void updated(const MessagePtrVector& messages);
-    void removed(const MessagePtrVector& messages);
-
-    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
-    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
-
-    int getServiceId() const;
-    MessageType getServiceType() const;
-    static MessagePtrVector filterMessages(
-            DeviceAPI::Tizen::AbstractFilterPtr a_filter,
-            const MessagePtrVector& a_sourceMessages,
-            const int service_id);
-
-    void setActive(bool act);
-    bool isActive();
-
-    void setItems(MessagePtrVector& items);
-    MessagePtrVector getItems();
-    JSContextRef getContext() const;
-private:
-    Common::MultiCallbackUserData m_callback_data;
-    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
-    int m_service_id;
-    MessageType m_msg_type;
-    bool m_is_act;
-    MessagePtrVector m_items;
-};
-
-} // Messaging
-} // DeviceAPI
-
-
-#endif // __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
diff --git a/messaging/old/MessagingDatabaseManager.cpp b/messaging/old/MessagingDatabaseManager.cpp
deleted file mode 100755 (executable)
index 17c1cb1..0000000
+++ /dev/null
@@ -1,872 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessagingDatabaseManager.cpp
- */
-
-#include <sstream>
-#include <stdio.h>
-#include <stddef.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <time.h>
-
-#include <msg_storage.h>
-#include <email-api.h>
-
-#include <Logger.h>
-
-#include "MessagingDatabaseManager.h"
-#include "MessagingManager.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-using namespace DeviceAPI::Common;
-using namespace DeviceAPI::Tizen;
-
-AttributeInfo::AttributeInfo() :
-        sql_name(),
-        sql_type(UNDEFINED_TYPE),
-        any_type(PrimitiveType_NoType)
-{
-}
-
-AttributeInfo::AttributeInfo(const std::string& in_sql_name,
-        const SQLAttributeType in_sql_type,
-        const Tizen::PrimitiveType in_any_type) :
-        sql_name(in_sql_name),
-        sql_type(in_sql_type),
-        any_type(in_any_type)
-{
-}
-
-AttributeInfo::AttributeInfo(const AttributeInfo& other) :
-        sql_name(other.sql_name),
-        sql_type(other.sql_type),
-        any_type(other.any_type)
-{
-}
-
-AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other)
-{
-    sql_name = other.any_type;
-    sql_type = other.sql_type;
-    any_type = other.any_type;
-    return *this;
-}
-
-MessagingDatabaseManager::MessagingDatabaseManager()
-{
-// Attributes map for short messages ==========================================
-    m_msg_attr_map.insert(std::make_pair("id",
-            AttributeInfo("A.MSG_ID", INTEGER, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("serviceId",
-            AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("folderId",
-            AttributeInfo("A.FOLDER_ID", INTEGER, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("type",
-            AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("timestamp",
-            AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time)));
-    m_msg_attr_map.insert(std::make_pair("from",
-            AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("to",
-            AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("body.plainBody",
-            AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("isRead",
-            AttributeInfo("A.READ_STATUS", INTEGER, PrimitiveType_Boolean)));
-    m_msg_attr_map.insert(std::make_pair("hasAttachment",
-            AttributeInfo("A.ATTACHMENT_COUNT", INTEGER, PrimitiveType_Boolean)));
-    m_msg_attr_map.insert(std::make_pair("isHighPriority",
-            AttributeInfo("A.PRIORITY", INTEGER, PrimitiveType_Boolean)));
-    m_msg_attr_map.insert(std::make_pair("subject",
-            AttributeInfo("A.SUBJECT", TEXT, PrimitiveType_String)));
-    m_msg_attr_map.insert(std::make_pair("direction",
-            AttributeInfo("A.MSG_DIRECTION", INTEGER, PrimitiveType_String)));
-
-// Attributes map for emails ==================================================
-    m_email_attr_map.insert(std::make_pair("id",
-            AttributeInfo("mail_id", INTEGER, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("serviceId",
-            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("folderId",
-            AttributeInfo("mailbox_id", INTEGER, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("type",
-            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("timestamp",
-            AttributeInfo("date_time", DATETIME, PrimitiveType_Time)));
-    m_email_attr_map.insert(std::make_pair("from",
-            AttributeInfo("full_address_from", TEXT, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("to",
-            AttributeInfo("full_address_to", TEXT, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("cc",
-            AttributeInfo("full_address_cc", TEXT, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("bcc",
-            AttributeInfo("full_address_bcc", TEXT, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("body.plainBody",
-            AttributeInfo("preview_text", TEXT, PrimitiveType_String)));
-    m_email_attr_map.insert(std::make_pair("isRead",
-            AttributeInfo("flags_seen_field", BOOLEAN, PrimitiveType_Boolean)));
-    m_email_attr_map.insert(std::make_pair("hasAttachment",
-            AttributeInfo("attachment_count", INTEGER, PrimitiveType_Boolean)));
-    m_email_attr_map.insert(std::make_pair("isHighPriority",
-            AttributeInfo("priority", INTEGER, PrimitiveType_Boolean)));
-    m_email_attr_map.insert(std::make_pair("subject",
-            AttributeInfo("subject", TEXT, PrimitiveType_String)));
-
-// Attributes map for short message conversations =============================
-    m_msg_conv_attr_map.insert(std::make_pair("id",
-            AttributeInfo("A.CONV_ID", INTEGER, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("type",
-            AttributeInfo("B.MAIN_TYPE", INTEGER, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("timestamp",
-            AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time)));
-    m_msg_conv_attr_map.insert(std::make_pair("messageCount",
-            AttributeInfo("(A.SMS_CNT + A.MMS_CNT)", INTEGER, PrimitiveType_ULong)));
-    m_msg_conv_attr_map.insert(std::make_pair("unreadMessages",
-            AttributeInfo("A.UNREAD_CNT", INTEGER, PrimitiveType_ULong)));
-    m_msg_conv_attr_map.insert(std::make_pair("preview",
-            AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("from",
-            AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("to",
-            AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("msgId",
-            AttributeInfo("B.MSG_ID", INTEGER, PrimitiveType_String)));
-    m_msg_conv_attr_map.insert(std::make_pair("direction",
-            AttributeInfo("B.MSG_DIRECTION", INTEGER, PrimitiveType_String)));
-
-// Attributes map for email conversations =====================================
-    m_email_conv_attr_map.insert(std::make_pair("id",
-            AttributeInfo("thread_id", INTEGER, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("serviceId",
-            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("type",
-            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("timestamp",
-            AttributeInfo("date_time", DATETIME, PrimitiveType_Time)));
-    m_email_conv_attr_map.insert(std::make_pair("messageCount",
-            AttributeInfo("thread_item_count", INTEGER, PrimitiveType_ULong)));
-    m_email_conv_attr_map.insert(std::make_pair("unreadMessages",
-            AttributeInfo(std::string("thread_id IN (SELECT thread_id ")
-                    + std::string("FROM mail_tbl WHERE flags_seen_field = 0 ")
-                    + std::string("GROUP BY thread_id HAVING COUNT(thread_id)"),
-                    INTEGER,
-                    PrimitiveType_ULong)));
-    m_email_conv_attr_map.insert(std::make_pair("preview",
-            AttributeInfo("preview_text", TEXT, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("subject",
-            AttributeInfo("subject", TEXT, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("from",
-            AttributeInfo("full_address_from", TEXT, PrimitiveType_String)));
-    m_email_conv_attr_map.insert(std::make_pair("to",
-            AttributeInfo("full_address_to", TEXT, PrimitiveType_String)));
-}
-
-MessagingDatabaseManager::~MessagingDatabaseManager()
-{
-
-}
-
-MessagingDatabaseManager& MessagingDatabaseManager::getInstance()
-{
-    static MessagingDatabaseManager instance;
-    return instance;
-}
-
-__thread sqlite3* sqlHandle = NULL;
-__thread sqlite3_stmt* stmt = NULL;
-
-msg_error_t MessagingDatabaseManager::connect()
-{
-    LOGD("Entered");
-    int err = 0;
-    if (NULL == sqlHandle) {
-        char strDBName[64];
-
-        memset(strDBName, 0x00, sizeof(strDBName));
-        snprintf(strDBName, sizeof(strDBName), "%s", MSG_DB_NAME);
-
-        err = db_util_open(strDBName, &sqlHandle, DB_UTIL_REGISTER_HOOK_METHOD);
-
-        if (SQLITE_OK != err) {
-            LOGE("DB connecting fail [%d]", err);
-            return MSG_ERR_DB_CONNECT;
-        }
-
-        LOGD("DB connecting success: [%d]", sqlHandle);
-    } else {
-        LOGD("DB connection exists: [%d]", sqlHandle);
-    }
-
-    return MSG_SUCCESS;
-}
-
-msg_error_t MessagingDatabaseManager::disconnect()
-{
-    LOGD("Entered");
-    msg_error_t err = 0;
-    if (NULL != sqlHandle) {
-        err = db_util_close(sqlHandle);
-
-        if (SQLITE_OK != err) {
-            LOGE("DB disconnecting fail [%d]", err);
-            return MSG_ERR_DB_DISCONNECT;
-        }
-
-        sqlHandle = NULL;
-        LOGD("DB disconnecting success");
-    }
-
-    return MSG_SUCCESS;
-}
-
-msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery,
-        char*** results,
-        int* resultsCount)
-{
-    LOGD("Entered");
-    msg_error_t err = 0;
-    *resultsCount = 0;
-
-    freeTable(results);
-    connect();
-
-
-    char* error_msg = NULL;
-    err = sqlite3_get_table(sqlHandle, sqlQuery.c_str(), results,
-            resultsCount, 0, &error_msg);
-
-    if (SQLITE_OK != err) {
-        LOGE("Getting table fail [%d] error_msg:%s querry was:%s", err, error_msg,
-                sqlQuery.c_str());
-        freeTable(results);
-        return MSG_ERR_DB_GETTABLE;
-    }
-
-    LOGD("Getting table success");
-    if (0 == *resultsCount) {
-        LOGD("No results");
-    }
-
-    disconnect();
-    return MSG_SUCCESS;
-}
-
-void MessagingDatabaseManager::freeTable(char*** results)
-{
-    LOGD("Entered");
-    if (*results) {
-        sqlite3_free_table(*results);
-        *results = NULL;
-    }
-}
-
-int MessagingDatabaseManager::cellToInt(char** array, int cellId)
-{
-    LOGD("Entered");
-    if (NULL == array) {
-        LOGD("Array is NULL");
-        return 0;
-    }
-
-    char* tmp = *(array + cellId);
-    if (NULL == tmp) {
-        LOGD("Cell is NULL");
-        return 0;
-    }
-
-    return static_cast<int>(strtol(tmp, (char**) NULL, 10));
-}
-
-std::string MessagingDatabaseManager::getMatchString(Tizen::AnyPtr match_value,
-        const PrimitiveType type) const
-{
-    if(!match_value) {
-        LOGD("Warning: match value is NULL");
-        return std::string();
-    }
-
-    std::ostringstream converter;
-    switch(type) {
-        case PrimitiveType_NoType: {
-            LOGD("Warning: match value is no type");
-            return std::string();
-        }
-        case PrimitiveType_Null: {
-            LOGD("Warning: match value is null");
-            return std::string();
-        }
-        case PrimitiveType_Boolean: {
-            converter << match_value->toBool();
-            return converter.str();
-        }
-        case PrimitiveType_Long: {
-            converter << match_value->toLong();
-            return converter.str();
-        }
-        case PrimitiveType_ULong: {
-            converter << match_value->toULong();
-            return converter.str();
-        }
-        case PrimitiveType_LongLong: {
-            converter << match_value->toLongLong();
-            return converter.str();
-        }
-        case PrimitiveType_ULongLong: {
-            converter << match_value->toULongLong();
-            return converter.str();
-        }
-        case PrimitiveType_Double: {
-            converter << match_value->toDouble();
-            return converter.str();
-        }
-        case PrimitiveType_String: {
-            return match_value->toString();
-        }
-        case PrimitiveType_Time: {
-            converter << match_value->toTimeT();
-            return converter.str();
-        }
-        default: {
-            LOGD("Warning: match value is not specified");
-            return std::string();
-        }
-    }
-}
-
-std::string MessagingDatabaseManager::getAttributeFilterQuery(AbstractFilterPtr filter,
-        AttributeInfoMap& attribute_map, MessageType msgType)
-{
-    LOGD("Entered");
-
-    std::ostringstream sqlQuery;
-    AttributeFilterPtr attr_filter = castToAttributeFilter(filter);
-    if(!attr_filter) {
-        LOGE("passed filter is not valid AttributeFilter!");
-        throw UnknownException("Wrong filter type - not attribute filter");
-    }
-
-    const std::string attribute_name = attr_filter->getAttributeName();
-
-    AttributeInfoMap::iterator it = attribute_map.find(attribute_name);
-    if (it != attribute_map.end()) {
-        sqlQuery << "(" << attribute_map[attribute_name].sql_name << " ";
-    } else {
-        LOGE("The attribute: %s does not exist.", attribute_name.c_str());
-        throw InvalidValuesException("The attribute does not exist.");
-    }
-
-    AnyPtr match_value_any_ptr = attr_filter->getMatchValue();
-    const AttributeInfo& attr_info = it->second;
-    std::string match_value = getMatchString(match_value_any_ptr, attr_info.any_type);
-    const FilterMatchFlag match_flag = attr_filter->getMatchFlag();
-
-    LOGD("match_value_any_ptr:%p any_type:%d attr_name:%s match_value:%s",
-            match_value_any_ptr.get(), attr_info.any_type, attribute_name.c_str(),
-            match_value.c_str());
-
-    if ("serviceId" == attribute_name) {
-
-        int i_matchValue;
-        std::istringstream iss(match_value);
-        iss >> i_matchValue;
-
-        switch(i_matchValue) {
-        case MessageServiceAccountId::SMS_ACCOUNT_ID: {
-            sqlQuery << "= " << MessageType::SMS;
-            break;
-        }
-        case MessageServiceAccountId::MMS_ACCOUNT_ID: {
-            sqlQuery << "= " << MessageType::MMS;
-            break;
-        }
-        default:
-            sqlQuery << "= " << match_value;
-        }
-    }
-    else if ("type" == attribute_name) {
-        if ("messaging.sms" == match_value && MessageType::SMS == msgType) {
-            sqlQuery << "= " << msgType;
-        } else if ("messaging.mms" == match_value && MessageType::MMS == msgType) {
-            sqlQuery << "= " << msgType;
-        } else if ("messaging.email" == match_value && MessageType::EMAIL == msgType) {
-            sqlQuery << "= " << attr_info.sql_name;
-        } else {
-            LOGE("attribute \"type\" matchValue:%s "
-                    "does not match messaging.sms/mms/email\n"
-                    "msgType:%d does not match SMS(%d), MMS(%d) nor EMAIL(%d)!",
-                    match_value.c_str(), msgType, MessageType::SMS, MessageType::MMS,
-                    MessageType::EMAIL);
-            throw UnknownException("The value does not match service type.");
-        }
-    }
-    else if ("isRead" == attribute_name || "hasAttachment" == attribute_name) {
-        if (attr_filter->getMatchValue()->toBool()) {
-            sqlQuery << "> 0";
-        } else {
-            sqlQuery << "= 0";
-        }
-    }
-    else if ("isHighPriority" == attribute_name) {
-        if (attr_filter->getMatchValue()->toBool()) {
-            sqlQuery << "= ";
-        } else {
-            sqlQuery << "<> ";
-        }
-
-        if (MessageType::SMS == msgType || MessageType::MMS == msgType) {
-            sqlQuery << MSG_MESSAGE_PRIORITY_HIGH;
-        } else if (MessageType::EMAIL == msgType) {
-            sqlQuery << EMAIL_MAIL_PRIORITY_HIGH;
-        }
-    }
-    else {
-        // Addresses which are stored in database can have different form than in filters
-        if (MessageType::EMAIL == msgType && ("from" == attribute_name ||
-                "to" == attribute_name || "cc" == attribute_name ||
-                "bcc" == attribute_name)) {
-            std::size_t foundPos;
-            while ((foundPos = match_value.find('<')) != std::string::npos) {
-                match_value.erase(foundPos, 1);
-            }
-
-            while ((foundPos = match_value.find('>')) != std::string::npos) {
-                match_value.erase(foundPos, 1);
-            }
-
-            if (EXACTLY == match_flag) {
-                match_value = "%<" + match_value + ">%";
-            } else if (CONTAINS == match_flag) {
-                match_value = "%<%" + match_value + "%>%";
-            } else if (STARTSWITH == match_flag) {
-                match_value = "%<" + match_value + "%>%";
-            } else if (ENDSWITH == match_flag) {
-                match_value = "%<%" + match_value + ">%";
-            }
-        }
-
-        switch (match_flag) {
-            /*
-            case NONE: {
-                // Determines if the apostrophes have to be added over match value
-                if (TEXT == attribute_map[attribute_name].sql_type) {
-                    sqlQuery << "NOT LIKE '" << match_value << "'";
-                } else {
-                    sqlQuery << "<> " << match_value;
-                }
-                break;
-            }*/
-            case EXACTLY: {
-                // Determines if the apostrophes have to be added over match value
-                if (TEXT == attribute_map[attribute_name].sql_type) {
-                    sqlQuery << "LIKE '" << match_value << "'";
-                } else {
-                    sqlQuery << "= " << match_value;
-                }
-                break;
-            }
-            case CONTAINS: {
-                sqlQuery << "LIKE '%" << match_value << "%'";
-                break;
-            }
-            case STARTSWITH: {
-                sqlQuery << "LIKE '" << match_value << "%'";
-                break;
-            }
-            case ENDSWITH: {
-                sqlQuery << "LIKE '%" << match_value << "'";
-                break;
-            }
-            case EXISTS: {
-                if ("unreadMessages" != attribute_name) {
-                    sqlQuery << "IS NOT NULL";
-                } else {
-                    sqlQuery << "!= 0";
-                }
-                break;
-            }
-            default:
-                throw UnknownException("The match flag is incorrect.");
-        }
-
-        if (MessageType::SMS == msgType || MessageType::MMS == msgType) {
-            if ("from" == attribute_name) {
-                // "From" and "to" attributes require message direction value
-                sqlQuery << " AND " << attribute_map["direction"].sql_name << " = 1";
-            } else if ("to" == attribute_name) {
-                sqlQuery << " AND " << attribute_map["direction"].sql_name << " <> 1";
-            }
-        } else if (MessageType::EMAIL == msgType) {
-            if("unreadMessages" == attribute_name) {
-                sqlQuery << ")";
-            }
-        }
-    }
-    sqlQuery << ") ";
-    return sqlQuery.str();
-}
-
-std::string MessagingDatabaseManager::getAttributeRangeFilterQuery(AbstractFilterPtr filter,
-        AttributeInfoMap& attribute_map, MessageType msg_type)
-{
-    LOGD("Entered");
-
-    std::ostringstream sql_query, converter;
-    std::string initial_value, end_value;
-
-    AttributeRangeFilterPtr attr_range_filter = castToAttributeRangeFilter(filter);
-    if(!attr_range_filter) {
-        LOGE("passed filter is not valid AttributeRangeFilter!");
-        throw UnknownException("Wrong filter type - not attribute range filter");
-    }
-
-    converter << attr_range_filter->getInitialValue()->toTimeT();
-    initial_value = converter.str();
-    converter.str("");
-    converter << attr_range_filter->getEndValue()->toTimeT();
-    end_value = converter.str();
-
-    sql_query << "(" << attribute_map[attr_range_filter->getAttributeName()].sql_name << " ";
-    sql_query << "BETWEEN " << initial_value << " AND " << end_value << ") ";
-    return sql_query.str();
-}
-
-std::string MessagingDatabaseManager::getCompositeFilterQuery(AbstractFilterPtr filter,
-        AttributeInfoMap& attribute_map, MessageType msg_type)
-{
-    LOGD("Entered");
-    std::ostringstream sql_query;
-
-    CompositeFilterPtr comp_filter = castToCompositeFilter(filter);
-    if(!comp_filter) {
-        LOGE("passed filter is not valid CompositeFilter!");
-        throw UnknownException("Wrong filter type - not composite filter");
-    }
-
-    AbstractFilterPtrVector filters_arr = comp_filter->getFilters();
-
-    std::string logical_operator;
-    if (UNION == comp_filter->getType()) {
-        logical_operator = "OR ";
-    } else {
-        logical_operator = "AND ";
-    }
-
-    sql_query << "(";
-    const unsigned int size = filters_arr.size();
-    for (unsigned int i = 0; i < size; ++i) {
-
-        const FilterType filter_type = filters_arr[i]->getFilterType();
-        switch (filter_type) {
-            case ATTRIBUTE_FILTER: {
-                sql_query << getAttributeFilterQuery(filters_arr[i], attribute_map, msg_type);
-                break;
-            }
-            case ATTRIBUTE_RANGE_FILTER: {
-                sql_query << getAttributeRangeFilterQuery(filters_arr[i], attribute_map, msg_type);
-                break;
-            }
-            case COMPOSITE_FILTER: {
-                sql_query << getCompositeFilterQuery(filters_arr[i], attribute_map, msg_type);
-                break;
-            }
-            default:
-                LOGE("Error while querying message - unsupported filter type: %d",
-                        filter_type);
-                throw UnknownException("Error while querying message.");
-        }
-
-        if (i != (size - 1)) {
-            sql_query << logical_operator;
-        }
-    }
-    sql_query << ") ";
-
-    return sql_query.str();
-}
-
-std::string MessagingDatabaseManager::addFilters(AbstractFilterPtr filter,
-        SortModePtr sort_mode, long limit, long offset, AttributeInfoMap& attribute_map,
-        MessageType msg_type)
-{
-    LOGD("Entered");
-    std::ostringstream sql_query;
-
-    // Service type query
-    if (MessageType::SMS == msg_type || MessageType::MMS == msg_type) {
-        if (UNDEFINED != msg_type) {
-            sql_query << attribute_map["type"].sql_name << " = " << msg_type << " AND ";
-        } else {
-            LOGE("The service type is incorrect - msg_type is UNDEFINED");
-            throw UnknownException("The service type is incorrect.");
-        }
-    }
-
-    if(filter) {
-        // Filter query
-        switch (filter->getFilterType()) {
-            case ATTRIBUTE_FILTER: {
-                sql_query << getAttributeFilterQuery(filter, attribute_map, msg_type);
-            } break;
-
-            case ATTRIBUTE_RANGE_FILTER: {
-                sql_query << getAttributeRangeFilterQuery(filter, attribute_map, msg_type);
-            } break;
-
-            case COMPOSITE_FILTER : {
-                sql_query << getCompositeFilterQuery(filter, attribute_map, msg_type);
-            } break;
-
-            default:
-                LOGE("The filter type is incorrect: %d", filter->getFilterType());
-                throw UnknownException("The filter type is incorrect.");
-        }
-    }
-
-    // SortMode query
-    if (sort_mode) {
-        if (attribute_map.find(sort_mode->getAttributeName()) != attribute_map.end()) {
-            sql_query << "ORDER BY "
-                    << attribute_map[sort_mode->getAttributeName()].sql_name << " ";
-        } else {
-            LOGE("The attribute does not exist.");
-            throw UnknownException("The attribute does not exist.");
-        }
-
-        if (ASC == sort_mode->getOrder()) {
-            sql_query << "ASC ";
-        } else {
-            sql_query << "DESC ";
-        }
-    }
-
-    // Limit query
-    if (0 != limit) {
-        sql_query << "LIMIT " << limit << " ";
-    }
-
-    // Offset query
-    if (0 != offset) {
-        if( 0 == limit ) {
-            //Ugly fix proposed by mySQL team:
-            //http://dev.mysql.com/doc/refman/5.0/en/select.html
-            //To retrieve all rows from a certain offset up to the end of the result set,
-            //you can use some large number for the second parameter.
-            //
-            //Reason: to use OFFSET you need to have LIMIT statement
-            //18446744073709551615 is 2^64-1 - max value of big int
-            //However we will use -1 since it will work fine for various int sizes (this
-            //trick have been used in old implementation).
-
-            sql_query << "LIMIT -1 ";
-        }
-        sql_query << "OFFSET " << offset << " ";
-    }
-
-    return sql_query.str();
-}
-
-std::vector<int> MessagingDatabaseManager::findShortMessages(
-        FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-    std::ostringstream sqlQuery;
-    int attributesCount = 1; // It has to be set manually each time when the query is changed
-    int cellId = attributesCount;
-    char** results = NULL;
-    int resultsCount;
-    std::vector<int> messagesIds;
-
-    sqlQuery << "SELECT " << "DISTINCT(" << m_msg_attr_map["id"].sql_name << ") "
-            << "FROM " << MSG_MESSAGE_TABLE_NAME << " A "
-            << "JOIN " << MSG_ADDRESS_TABLE_NAME << " B "
-            << "ON A.CONV_ID = B.CONV_ID " << "WHERE B.ADDRESS_ID <> 0 AND ";
-
-    // Adding filters query
-    AbstractFilterPtr filter = callback->getFilter();
-    SortModePtr sortMode = callback->getSortMode();
-    long limit = callback->getLimit();
-    long offset = callback->getOffset();
-    MessageType msgType = callback->getMessageServiceType();
-
-    sqlQuery << addFilters(filter, sortMode, limit, offset, m_msg_attr_map, msgType);
-    LOGD("%s", sqlQuery.str().c_str());
-
-    // Getting results from database
-    msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount);
-    if (MSG_SUCCESS != err) {
-        freeTable(&results);
-        throw UnknownException("Error while getting data from database.");
-    }
-
-    for (int i = 0; i < resultsCount; ++i) {
-        messagesIds.push_back(cellToInt(results, cellId++));
-        LOGD("id: %d", messagesIds.at(messagesIds.size() - 1));
-    }
-
-    freeTable(&results);
-    return messagesIds;
-}
-
-std::pair<int, email_mail_data_t*> MessagingDatabaseManager::findEmails(
-        FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-    std::ostringstream sqlWhereClause;
-    int resultsCount;
-    email_mail_data_t* results;
-
-    // Adding filters query
-    AbstractFilterPtr filter = callback->getFilter();
-    SortModePtr sortMode = callback->getSortMode();
-    long limit = callback->getLimit();
-    long offset = callback->getOffset();
-    MessageType msgType = callback->getMessageServiceType();
-    int accountId = callback->getAccountId();
-
-    sqlWhereClause << "WHERE "
-            << m_email_attr_map["serviceId"].sql_name << " = " << accountId << " AND "
-            << addFilters(filter, sortMode, limit, offset, m_email_attr_map, msgType);
-    LOGD("%s", sqlWhereClause.str().c_str());
-
-    // Getting results from database
-    msg_error_t err = email_query_mails(const_cast<char*>(sqlWhereClause.str().c_str()),
-                &results, &resultsCount);
-    if (EMAIL_ERROR_NONE != err) {
-        LOGE("Getting mail list fail [%d]", err);
-
-        if (EMAIL_ERROR_MAIL_NOT_FOUND == err) {
-            resultsCount = 0;
-        } else {
-            throw UnknownException("Error while getting data from database.");
-        }
-    }
-
-    return std::make_pair(resultsCount, results);
-}
-
-std::vector<int> MessagingDatabaseManager::findShortMessageConversations(
-        ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-    std::ostringstream sqlQuery;
-    int attributesCount = 1; // It has to be set manually each time when the query is changed
-    int cellId = attributesCount;
-    char** results = NULL;
-    int resultsCount;
-    std::vector<int> conversationsIds;
-
-    sqlQuery << "SELECT " << "DISTINCT(" << m_msg_conv_attr_map["id"].sql_name << ") "
-            << "FROM " << MSG_CONVERSATION_TABLE_NAME << " A "
-            << "JOIN " << MSG_MESSAGE_TABLE_NAME << " B "
-            << "ON A.CONV_ID = B.CONV_ID "
-            << "JOIN " << MSG_ADDRESS_TABLE_NAME << " C "
-            << "ON A.CONV_ID = C.CONV_ID "
-            << "WHERE (A.SMS_CNT > 0 OR A.MMS_CNT > 0) AND ";
-
-    // Adding filters query
-    AbstractFilterPtr filter = callback->getFilter();
-    SortModePtr sortMode = callback->getSortMode();
-    long limit = callback->getLimit();
-    long offset = callback->getOffset();
-    MessageType msgType = callback->getMessageServiceType();
-
-    sqlQuery << addFilters(filter, sortMode, limit, offset, m_msg_conv_attr_map, msgType);
-    LOGD("%s", sqlQuery.str().c_str());
-
-    // Getting results from database
-    msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount);
-    if (MSG_SUCCESS != err) {
-        freeTable(&results);
-        throw UnknownException("Error while getting data from database.");
-    }
-
-    for (int i = 0; i < resultsCount; ++i) {
-        conversationsIds.push_back(cellToInt(results, cellId++));
-        LOGD("id: %d", conversationsIds.at(conversationsIds.size() - 1));
-    }
-
-    freeTable(&results);
-    return conversationsIds;
-}
-
-std::vector<EmailConversationInfo> MessagingDatabaseManager::findEmailConversations(
-        ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-    std::ostringstream sqlWhereClause;
-    int resultsCount;
-    email_mail_data_t* results;
-    std::map<int, int> conversationsBag;
-    std::vector<EmailConversationInfo> conversationsInfo;
-
-    // Adding filters query
-    AbstractFilterPtr filter = callback->getFilter();
-    SortModePtr sortMode = callback->getSortMode();
-    long limit = callback->getLimit();
-    long offset = callback->getOffset();
-    MessageType msgType = callback->getMessageServiceType();
-    int accountId = callback->getAccountId();
-
-    sqlWhereClause << "WHERE "
-            << m_email_conv_attr_map["serviceId"].sql_name << " = " << accountId << " AND "
-            << addFilters(filter, sortMode, limit, offset, m_email_conv_attr_map, msgType);
-    LOGD("%s", sqlWhereClause.str().c_str());
-
-    // Getting results from database
-    msg_error_t err = email_query_mails(const_cast<char*>(sqlWhereClause.str().c_str()),
-                &results, &resultsCount);
-    if (EMAIL_ERROR_NONE != err) {
-        LOGE("Getting mail list fail [%d]", err);
-
-        if (EMAIL_ERROR_MAIL_NOT_FOUND == err) {
-            resultsCount = 0;
-        } else {
-            throw UnknownException("Error while getting data from database.");
-        }
-    }
-
-    // Assigning found emails to conversation
-    for (int i = 0; i < resultsCount; ++i) {
-        if (conversationsBag.find(results[i].thread_id) == conversationsBag.end()) {
-            EmailConversationInfo info;
-            info.id = results[i].thread_id;
-            conversationsInfo.push_back(info);
-            conversationsBag.insert(std::make_pair(results[i].thread_id, 0));
-        }
-
-        if (!(static_cast<bool>(results[i].flags_seen_field))) {
-            ++conversationsBag[results[i].thread_id];
-        }
-    }
-
-    for (std::vector<EmailConversationInfo>::iterator it = conversationsInfo.begin();
-            it != conversationsInfo.end(); ++it) {
-        (*it).unreadMessages = conversationsBag[(*it).id];
-    }
-
-    email_free_mail_data(&results, resultsCount);
-    return conversationsInfo;
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessagingDatabaseManager.h b/messaging/old/MessagingDatabaseManager.h
deleted file mode 100755 (executable)
index 6c0286a..0000000
+++ /dev/null
@@ -1,121 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessagingDatabaseManager.h
- */
-
-#ifndef __TIZEN_MSG_DATABASE_MANAGER_H__
-#define __TIZEN_MSG_DATABASE_MANAGER_H__
-
-#include <iostream>
-#include <map>
-
-#include <msg.h>
-#include <db-util.h>
-#include <AbstractFilter.h>
-
-#include "FindMsgCallbackUserData.h"
-#include "ConversationCallbackData.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-// =================================================================
-#define MSG_DB_NAME                     "/opt/usr/dbspace/.msg_service.db"
-#define MSG_MESSAGE_TABLE_NAME          "MSG_MESSAGE_TABLE"
-#define MSG_FOLDER_TABLE_NAME           "MSG_FOLDER_TABLE"
-#define MSG_ADDRESS_TABLE_NAME          "MSG_ADDRESS_TABLE"
-#define MSG_CONVERSATION_TABLE_NAME     "MSG_CONVERSATION_TABLE"
-#define MSG_SIM_MSG_TABLE_NAME          "MSG_SIM_TABLE"
-#define MSG_FILTER_TABLE_NAME           "MSG_FILTER_TABLE"
-#define MSG_PUSH_MSG_TABLE_NAME         "MSG_PUSH_TABLE"
-#define MSG_CB_MSG_TABLE_NAME           "MSG_CBMSG_TABLE"
-#define MMS_PLUGIN_MESSAGE_TABLE_NAME   "MSG_MMS_MESSAGE_TABLE"
-#define MSG_SYNCML_MSG_TABLE_NAME       "MSG_SYNCML_TABLE"
-#define MSG_SCHEDULED_MSG_TABLE_NAME    "MSG_SCHEDULED_TABLE"
-#define MSG_SMS_SENDOPT_TABLE_NAME      "MSG_SMS_SENDOPT_TABLE"
-// =================================================================
-enum SQLAttributeType {
-    UNDEFINED_TYPE,
-    BOOLEAN,
-    INTEGER,
-    DATETIME,
-    TEXT,
-};
-
-struct AttributeInfo {
-    AttributeInfo();
-    AttributeInfo(const std::string& in_sql_name,
-            const SQLAttributeType in_sql_type,
-            const Tizen::PrimitiveType in_any_type);
-    AttributeInfo(const AttributeInfo& other);
-    AttributeInfo& operator=(const AttributeInfo& other);
-
-    std::string sql_name;
-    SQLAttributeType sql_type;
-    Tizen::PrimitiveType any_type;
-};
-
-typedef std::map<std::string, AttributeInfo> AttributeInfoMap;
-
-struct EmailConversationInfo {
-    int id, unreadMessages;
-};
-// =================================================================
-
-class MessagingDatabaseManager {
-public:
-    static MessagingDatabaseManager& getInstance();
-    std::vector<int> findShortMessages(FindMsgCallbackUserData* callback);
-    std::pair<int, email_mail_data_t*> findEmails(FindMsgCallbackUserData* callback);
-    std::vector<int> findShortMessageConversations(ConversationCallbackData* callback);
-    std::vector<EmailConversationInfo> findEmailConversations(ConversationCallbackData* callback);
-
-private:
-    MessagingDatabaseManager();
-    MessagingDatabaseManager(const MessagingDatabaseManager &);
-    void operator=(const MessagingDatabaseManager &);
-    virtual ~MessagingDatabaseManager();
-
-    msg_error_t connect();
-    msg_error_t disconnect();
-    msg_error_t getTable(std::string query, char*** results, int* resultsCount);
-    void freeTable(char*** array);
-    int cellToInt(char** array, int cellId);
-    std::string getMatchString(Tizen::AnyPtr matchValue,
-            const Tizen::PrimitiveType type) const;
-    std::string getAttributeFilterQuery(Tizen::AbstractFilterPtr filter,
-            AttributeInfoMap& attributeMap, MessageType msgType);
-    std::string getAttributeRangeFilterQuery(Tizen::AbstractFilterPtr filter,
-            AttributeInfoMap& attributeMap, MessageType msgType);
-    std::string getCompositeFilterQuery(Tizen::AbstractFilterPtr filter,
-            AttributeInfoMap& attributeMap, MessageType msgType);
-    std::string addFilters(Tizen::AbstractFilterPtr filter, Tizen::SortModePtr sortMode,
-            long limit, long offset, AttributeInfoMap& attributeMap, MessageType msgType);
-
-    AttributeInfoMap m_msg_attr_map;
-    AttributeInfoMap m_email_attr_map;
-
-    AttributeInfoMap m_msg_conv_attr_map;
-    AttributeInfoMap m_email_conv_attr_map;
-};
-
-} // Messaging
-} // DeviceAPI
-
-#endif // __TIZEN_MSG_DATABASE_MANAGER_H__
diff --git a/messaging/old/MessagingManager.cpp b/messaging/old/MessagingManager.cpp
deleted file mode 100755 (executable)
index 0367248..0000000
+++ /dev/null
@@ -1,343 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-#include <GlobalContextManager.h>
-
-#include <system_info.h>
-
-#include <email-types.h>
-#include <email-api.h>
-
-#include "MessagingManager.h"
-#include "MessagingUtil.h"
-#include "JSMessageService.h"
-#include "MessageService.h"
-#include "MessageServiceShortMsg.h"
-#include "MessageServiceEmail.h"
-#include "ShortMsgManager.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-MessageServiceCallbackData::MessageServiceCallbackData(JSContextRef globalCtx):
-    CallbackUserData(globalCtx),
-    m_msg_type(MessageType::UNDEFINED),
-    m_is_error(false)
-{
-    LOGD("Entered");
-}
-
-MessageServiceCallbackData::~MessageServiceCallbackData()
-{
-    LOGD("Entered");
-}
-
-void MessageServiceCallbackData::setMessageType(MessageType msgType)
-{
-    m_msg_type = msgType;
-}
-
-MessageType MessageServiceCallbackData::getMessageType() const
-{
-    return m_msg_type;
-}
-
-void MessageServiceCallbackData::setMessageServices(
-        const std::vector<MessageService*>& msgServices)
-{
-    m_msg_services = msgServices;
-}
-
-const std::vector<MessageService*>& MessageServiceCallbackData::getMessageServices() const
-{
-    return m_msg_services;
-}
-
-void MessageServiceCallbackData::setError(const std::string& err_name,
-        const std::string& err_message)
-{
-    // keep only first error in chain
-    if (!m_is_error) {
-        m_is_error = true;
-        m_err_name = err_name;
-        m_err_message = err_message;
-    }
-}
-
-bool MessageServiceCallbackData::isError() const
-{
-    return m_is_error;
-}
-
-std::string MessageServiceCallbackData::getErrorName() const
-{
-    return m_err_name;
-}
-
-std::string MessageServiceCallbackData::getErrorMessage() const
-{
-    return m_err_message;
-}
-
-void MessageServiceCallbackData::clearServices()
-{
-    unsigned int count = m_msg_services.size();
-    for (unsigned int i = 0; i < count; ++i) {
-        delete m_msg_services.at(i);
-    }
-    m_msg_services.clear();
-}
-
-
-static gboolean getMsgServicesCompleteCB(void* data)
-{
-    LOGD("Entered");
-
-    MessageServiceCallbackData* callback = static_cast<MessageServiceCallbackData*>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        return false;
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return false;
-    }
-
-    try {
-        if (callback->isError()) {
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        }
-        else {
-            std::vector<MessageService*> msgServices = callback->getMessageServices();
-            unsigned int count = msgServices.size();
-            JSValueRef result = NULL;
-
-            JSObjectRef jsMsgServicesObject[count];
-            for (unsigned int i = 0; i < count; ++i) {
-                jsMsgServicesObject[i] = JSMessageService::createJSObject(context,
-                        msgServices.at(i));
-                if (NULL == jsMsgServicesObject[i]) {
-                    LOGE("Message service object creation failed");
-                    throw Common::UnknownException(
-                            "Message service object creation failed");
-                }
-            }
-            result = JSObjectMakeArray(context, count,
-                    count > 0 ? jsMsgServicesObject : NULL, NULL);
-
-            if (!result) {
-                JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                        JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                        "Could not create JS array object");
-                callback->clearServices();
-                callback->callErrorCallback(errobj);
-            }
-            else {
-                callback->callSuccessCallback(result);
-            }
-        }
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, err);
-        callback->clearServices();
-        callback->callErrorCallback(errobj);
-    }
-    catch (...) {
-        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                "Cannot retrieve JS message services");
-        callback->clearServices();
-        callback->callErrorCallback(errobj);
-    }
-
-    delete callback;
-    callback = NULL;
-
-    return false;
-}
-
-static void* getMsgServicesThread(void* data)
-{
-    LOGD("Entered");
-
-    MessageServiceCallbackData* callback = static_cast<MessageServiceCallbackData*>(data);
-    if(!callback){
-        LOGE("Callback is null");
-        return NULL;
-    }
-
-    MessageType msgType = callback->getMessageType();
-    std::vector<MessageService*> msgServices;
-    MessageService* messageService = NULL;
-    email_account_t* email_accounts = NULL;
-    int count = 0;
-    bool isSupported = false;
-
-    try {
-        switch (msgType) {
-        case MessageType::SMS:
-            messageService = new(std::nothrow) MessageServiceShortMsg(
-                    MessageServiceAccountId::SMS_ACCOUNT_ID,
-                    MessageType::SMS);
-            if (!messageService) {
-                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                        "MessageService for SMS creation failed");
-            } else {
-                msgServices.push_back(messageService);
-            }
-            callback->setMessageServices(msgServices);
-            break;
-        case MessageType::MMS:
-            messageService = new(std::nothrow) MessageServiceShortMsg(
-                    MessageServiceAccountId::MMS_ACCOUNT_ID,
-                    MessageType::MMS);
-            if (!messageService) {
-                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                        "MessageService for MMS creation failed");
-            } else {
-                msgServices.push_back(messageService);
-            }
-            callback->setMessageServices(msgServices);
-            break;
-        case MessageType::EMAIL:
-            if (email_get_account_list(&email_accounts, &count) != EMAIL_ERROR_NONE) {
-                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                        "Cannot get email accounts");
-            } else {
-                std::stringstream stream_name;
-                for (int i = 0; i < count; ++i) {
-                    stream_name << "[" << email_accounts[i].account_name << "] "
-                            << email_accounts[i].incoming_server_user_name;
-                    SLOGD("Account[%d/%d] id: %d, name: %s", i, count,
-                            email_accounts[i].account_id, stream_name.str().c_str());
-
-                    messageService = new(std::nothrow) MessageServiceEmail(
-                            email_accounts[i].account_id, stream_name.str());
-                    if (!messageService) {
-                        LOGE("message service[%d] is NULL", i);
-                        unsigned int count_srvcs = msgServices.size();
-                        for (unsigned int j = 0; j < count_srvcs; ++j) {
-                            delete msgServices.at(j);
-                        }
-                        msgServices.clear();
-                        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                                "MessageService for email creation failed");
-                        break;
-                    }
-                    else {
-                        msgServices.push_back(messageService);
-                    }
-
-                    messageService = NULL;
-                    stream_name.str("");
-                }
-                callback->setMessageServices(msgServices);
-            }
-
-            if (email_accounts != NULL) {
-                email_free_account(&email_accounts, count);
-                email_accounts = NULL;
-            }
-            break;
-        default:
-            callback->clearServices();
-            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                    "Invalid message service tag");
-            break;
-        }
-    }
-    catch (...) {
-        unsigned int count_srvcs = msgServices.size();
-        for (unsigned int j = 0; j < count_srvcs; ++j) {
-            delete msgServices.at(j);
-        }
-        msgServices.clear();
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                "Cannot retrieve message services");
-    }
-
-    if (!g_idle_add(getMsgServicesCompleteCB, static_cast<void*>(callback))) {
-        LOGE("g_idle addition failed");
-        callback->clearServices();
-        delete callback;
-        callback = NULL;
-    }
-
-    return NULL;
-}
-
-MessagingManager& MessagingManager::getInstance()
-{
-    LOGD("Entered");
-
-    static MessagingManager instance;
-    return instance;
-}
-
-void MessagingManager::getMessageServices(MessageServiceCallbackData* callback)
-{
-    LOGD("Entered");
-
-    pthread_t thread;
-    if (pthread_create(&thread, NULL, getMsgServicesThread, static_cast<void*>(callback))) {
-        LOGE("Thread creation failed");
-        throw Common::UnknownException("Thread creation failed");
-    }
-    if (pthread_detach(thread)) {
-        LOGE("Thread detachment failed");
-    }
-}
-
-MessagingManager::MessagingManager():
-        SecurityAccessor()
-{
-    LOGD("Entered");
-
-    int ret = msg_open_msg_handle(&m_msg_handle);
-    if (ret != MSG_SUCCESS) {
-        LOGE("Cannot get message handle: %d", ret);
-    }
-    else {
-        ShortMsgManager::getInstance().registerStatusCallback(m_msg_handle);
-    }
-}
-
-MessagingManager::~MessagingManager()
-{
-    LOGD("Entered");
-    int ret = msg_close_msg_handle(&m_msg_handle);
-    if (ret != MSG_SUCCESS) {
-        LOGW("Cannot close message handle: %d", ret);
-    }
-}
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/MessagingManager.h b/messaging/old/MessagingManager.h
deleted file mode 100755 (executable)
index 8af9399..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_MESSAGING_MANAGER_H__
-#define __TIZEN_MESSAGING_MANAGER_H__
-
-#include <CallbackUserData.h>
-#include <PlatformException.h>
-#include <Security.h>
-
-#include "MessagingUtil.h"
-#include "MessageService.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class MessageServiceCallbackData : public Common::CallbackUserData {
-public:
-    MessageServiceCallbackData(JSContextRef globalCtx);
-    ~MessageServiceCallbackData();
-
-    void setMessageType(MessageType msgType);
-    MessageType getMessageType() const;
-
-    void setMessageServices(const std::vector<MessageService*>& msgServices);
-    const std::vector<MessageService*>& getMessageServices() const;
-
-    void setError(const std::string& err_name,
-            const std::string& err_message);
-    bool isError() const;
-    std::string getErrorName() const;
-    std::string getErrorMessage() const;
-
-    void clearServices();
-
-private:
-    MessageType m_msg_type;
-    bool m_is_error;
-    std::string m_err_name;
-    std::string m_err_message;
-    std::vector<MessageService*> m_msg_services;
-};
-
-class MessagingManager : public Common::SecurityAccessor
-{
-public:
-    static MessagingManager& getInstance();
-
-    void getMessageServices(MessageServiceCallbackData *callback);
-
-private:
-    MessagingManager();
-    MessagingManager(const MessagingManager &);
-    void operator=(const MessagingManager &);
-    virtual ~MessagingManager();
-
-    msg_handle_t m_msg_handle;
-
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_MESSAGING_MANAGER_H__
diff --git a/messaging/old/MessagingUtil.cpp b/messaging/old/MessagingUtil.cpp
deleted file mode 100644 (file)
index ec733bf..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessagingUtil.cpp
- */
-
-#include <PlatformException.h>
-#include <string>
-#include "MessagingUtil.h"
-#include <Logger.h>
-#include <fstream>
-#include <streambuf>
-
-using namespace std;
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-namespace {
-const string TYPE_SMS = "messaging.sms";
-const string TYPE_MMS = "messaging.mms";
-const string TYPE_EMAIL = "messaging.email";
-const string SENT = "SENT";
-const string SENDING = "SENDING";
-const string FAILED = "FAILED";
-const string DRAFT = "DRAFT";
-
-const string FOLDER_TYPE_INBOX = "INBOX";
-const string FOLDER_TYPE_OUTBOX = "OUTBOX";
-const string FOLDER_TYPE_DRAFTS = "DRAFTS";
-const string FOLDER_TYPE_SENTBOX = "SENTBOX";
-}
-
-string MessagingUtil::messageFolderTypeToString(MessageFolderType type)
-{
-    switch(type) {
-        case MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX:
-            return FOLDER_TYPE_INBOX;
-        case MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX:
-            return FOLDER_TYPE_OUTBOX;
-        case MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS:
-            return FOLDER_TYPE_DRAFTS;
-        case MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX:
-            return FOLDER_TYPE_SENTBOX;
-        default:
-            return "";
-    }
-}
-
-MessageType MessagingUtil::stringToMessageType(string type)
-{
-    if (TYPE_SMS == type) {
-        return MessageType(SMS);
-    }
-    if (TYPE_MMS == type) {
-        return MessageType(MMS);
-    }
-    if (TYPE_EMAIL == type) {
-        return MessageType(EMAIL);
-    }
-    std::string exceptionMsg = "Not supported type: ";
-    exceptionMsg += type;
-    throw TypeMismatchException(exceptionMsg.c_str());
-}
-
-string MessagingUtil::messageTypeToString(MessageType type)
-{
-    if (type == MessageType(SMS)) {
-        return TYPE_SMS;
-    }
-    if (type == MessageType(MMS)) {
-        return TYPE_MMS;
-    }
-    if (type == MessageType(EMAIL)) {
-        return TYPE_EMAIL;
-    }
-    throw TypeMismatchException("Invalid MessageType");
-}
-
-MessageStatus MessagingUtil::stringToMessageStatus(std::string status)
-{
-    LOGD("Converting string %s to MessageStatus.", status.c_str());
-    if(status == SENT) {
-        return STATUS_SENT;
-    }
-    if(status == SENDING) {
-        return STATUS_SENDING;
-    }
-    if(status == FAILED) {
-        return STATUS_FAILED;
-    }
-    if(status == DRAFT) {
-        return STATUS_DRAFT;
-    }
-    LOGE("Invalid MessageStatus");
-    throw TypeMismatchException("Invalid MessageStatus");
-}
-
-std::string MessagingUtil::messageStatusToString(MessageStatus status) {
-    LOGD("Converting MessageStatus %d to string.", (int)status);
-    switch(status) {
-        case STATUS_SENT:
-            return SENT;
-        case STATUS_SENDING:
-            return SENDING;
-        case STATUS_FAILED:
-            return FAILED;
-        case STATUS_DRAFT:
-            return DRAFT;
-        default:
-        // According to Web API documentation: If the status of the current
-        // message does not correspond to any item from the list, an empty
-        // value is returned.
-            LOGD("Unsupported or undefined MessageStatus");
-            return "";
-    }
-}
-
-std::string MessagingUtil::ltrim(const std::string& input)
-{
-    std::string str = input;
-    std::string::iterator i;
-    for (i = str.begin(); i != str.end(); i++) {
-        if (!isspace(*i)) {
-            break;
-        }
-    }
-    if (i == str.end()) {
-        str.clear();
-    } else {
-        str.erase(str.begin(), i);
-    }
-    return str;
-}
-
-std::string MessagingUtil::extractSingleEmailAddress(const std::string& address)
-{
-    std::size_t found_begin = address.rfind('<');
-    std::size_t found_end = address.rfind('>');
-    // if both '<' and '>' bracket found and '<' is before '>'
-    // then extract email address from the inside
-    if(found_begin != std::string::npos &&
-            found_end != std::string::npos &&
-            found_begin < found_end) {
-        return address.substr(found_begin+1, found_end-found_begin-1);
-    }
-    else {
-        // return unmodified source string
-        return address;
-    }
-}
-
-std::vector<std::string> MessagingUtil::extractEmailAddresses(
-        const std::vector<std::string>& addresses)
-{
-    std::vector<std::string> extractedAddresses;
-    for(auto it = addresses.begin(); it != addresses.end(); ++it) {
-        extractedAddresses.push_back(MessagingUtil::extractSingleEmailAddress(*it));
-    }
-
-    return extractedAddresses;
-}
-
-std::string MessagingUtil::loadFileContentToString(const std::string& file_path)
-{
-    std::ifstream input_file;
-    input_file.open(file_path, std::ios::in);
-
-    if (input_file.is_open()) {
-        std::string outString;
-        input_file.seekg(0, std::ios::end);
-        outString.reserve(input_file.tellg());
-        input_file.seekg(0, std::ios::beg);
-
-        outString.assign((std::istreambuf_iterator<char>(input_file)),
-                std::istreambuf_iterator<char>());
-        input_file.close();
-        return outString;
-    } else {
-        std::stringstream ss_error_msg;
-        ss_error_msg << "Failed to open file: " << file_path;
-        throw Common::IOException(ss_error_msg.str().c_str());
-    }
-}
-
-}
-}
diff --git a/messaging/old/MessagingUtil.h b/messaging/old/MessagingUtil.h
deleted file mode 100644 (file)
index aeae2c4..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        MessagingUtil.h
- */
-
-#ifndef __TIZEN_MESSAGING_UTIL_H__
-#define __TIZEN_MESSAGING_UTIL_H__
-#include <string>
-#include <Logger.h>
-#include <PlatformException.h>
-#include "MessageFolder.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-enum MessageType {
-    UNDEFINED = 0,
-    SMS,
-    MMS,
-    EMAIL
-};
-
-enum MessageStatus {
-    STATUS_UNDEFINED = 0,
-    STATUS_DRAFT,
-    STATUS_SENDING,
-    STATUS_SENT,
-    STATUS_LOADED,
-    STATUS_FAILED
-};
-
-class MessagingUtil {
-public:
-    static std::string messageFolderTypeToString(MessageFolderType);
-
-    static MessageType stringToMessageType(std::string);
-    static std::string messageTypeToString(MessageType);
-
-    static MessageStatus stringToMessageStatus(std::string status);
-    static std::string messageStatusToString(MessageStatus status);
-
-    static std::string ltrim(const std::string& input);
-    static std::string extractSingleEmailAddress(const std::string& address);
-    static std::vector<std::string> extractEmailAddresses(
-            const std::vector<std::string>& addresses);
-
-    /**
-    * Throws Common::IOException when file cannot be opened.
-    *
-    * To increase performance invoke this function this way:
-    * std::string result = loadFileContentToString(...);
-    * Reason: no copy constructor will be invoked on return.
-    */
-    static std::string loadFileContentToString(const std::string& file_path);
-
-    /**
-     * Function converts vector of shared_pointers into JSArray
-     */
-    template<class T, class U>
-    static JSObjectRef vectorToJSObjectArray(JSContextRef context,
-            const std::vector<T> & vec)
-    {
-        size_t count = vec.size();
-
-        JSObjectRef array[count];
-        for (size_t i = 0; i < count; ++i) {
-            array[i] = U::makeJSObject(context, vec[i]);
-        }
-        JSObjectRef result = JSObjectMakeArray(context, count,
-                count > 0 ? array : NULL, NULL);
-        if (!result) {
-            LOGW("Failed to create array");
-            throw Common::UnknownException("Failed to create array");
-        }
-        return result;
-    }
-
-};
-
-}
-}
-#endif // __TIZEN_MESSAGING_UTIL_H__
diff --git a/messaging/old/ShortMsgManager.cpp b/messaging/old/ShortMsgManager.cpp
deleted file mode 100644 (file)
index 3d7feb8..0000000
+++ /dev/null
@@ -1,1234 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <JSWebAPIErrorFactory.h>
-#include <JSWebAPIError.h>
-#include <JSUtil.h>
-#include <Logger.h>
-#include <msg.h>
-#include <msg_transport.h>
-#include <msg_storage.h>
-#include <unordered_set>
-#include <GlobalContextManager.h>
-
-#include "ShortMsgManager.h"
-#include "MessagingUtil.h"
-#include "MessageService.h"
-#include "MessageSMS.h"
-#include "MessageMMS.h"
-#include "JSMessage.h"
-#include "JSMessageConversation.h"
-#include "ChangeListenerContainer.h"
-#include "MessagingDatabaseManager.h"
-#include "Message.h"
-
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-ShortMsgManager& ShortMsgManager::getInstance()
-{
-    LOGD("Entered");
-
-    static ShortMsgManager instance;
-    return instance;
-}
-
-static gboolean sendMessageCompleteCB(void* data)
-{
-    LOGD("Entered callback:%p", data);
-
-    MessageRecipientsCallbackData* callback =
-            static_cast<MessageRecipientsCallbackData*>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        return false;
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return false;
-    }
-
-    try {
-        if (callback->isError()) {
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(),
-                    callback->getErrorMessage());
-
-            LOGD("Calling error callback with error:%s msg:%s",
-                    callback->getErrorName().c_str(),
-                    callback->getErrorMessage().c_str());
-
-            callback->callErrorCallback(errobj);
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
-        }
-        else {
-            std::shared_ptr<Message> message = callback->getMessage();
-
-            LOGD("Calling success callback with: %d recipients", message->getTO().size());
-            callback->callSuccessCallback(
-                    JSUtil::toJSValueRef(context, message->getTO()));
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT);
-        }
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("Error while calling sendMessage callback: %s (%s)",
-                (err.getName()).c_str(),(err.getMessage()).c_str());
-    }
-    catch (...) {
-        LOGE("Unknown error when calling sendMessage callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-
-    return false;
-}
-
-static gboolean addDraftMessageCompleteCB(void *data)
-{
-    LOGD("Enter");
-    auto callback = static_cast<MessageCallbackUserData *>(data);
-    if (!callback) {
-        LOGE("Callback is null");
-        return FALSE;
-    }
-
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return FALSE;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling addDraftMessage callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling addDraftMessage callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-
-    return FALSE;
-}
-
-
-void ShortMsgManager::addDraftMessagePlatform(std::shared_ptr<Message> message)
-{
-    LOGD("Add new message(%p)", message.get());
-
-    // Save platform msg to get ID
-    msg_struct_t platform_msg
-            = Message::convertPlatformShortMessageToStruct(message.get(), m_msg_handle);
-    if (NULL == platform_msg) {
-        LOGE("Failed to prepare platform message");
-        throw UnknownException("Cannot prepare platform message");
-    }
-
-    msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT);
-    msg_set_bool_value(send_opt, MSG_SEND_OPT_SETTING_BOOL, false);
-    const int msg_id = msg_add_message(m_msg_handle, platform_msg, send_opt);
-    if (msg_id < MSG_SUCCESS) {
-        LOGE("Message(%p): Failed to add draft, error: %d", message.get(), msg_id);
-        msg_release_struct(&send_opt);
-        msg_release_struct(&platform_msg);
-        throw UnknownException("Cannot add message to draft");
-    }
-
-    LOGD("Message(%p): New message ID: %d", message.get(), msg_id);
-    msg_set_int_value(platform_msg, MSG_MESSAGE_ID_INT, msg_id);
-    message->setId(msg_id);
-    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
-
-    msg_struct_t msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO);
-    msg_error_t err = msg_get_conversation(m_msg_handle, msg_id, msg_conv);
-    if (MSG_SUCCESS == err) {
-        int conversationId = 0;
-        msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, &conversationId);
-        message->setConversationId(conversationId);
-    } else {
-        LOGE("Message(%p): Failed to get conv", message.get());
-    }
-
-    Message* msgInfo = Message::convertPlatformShortMessageToObject(
-            platform_msg);
-
-    const int folderId = msgInfo->getFolderId();
-    message->setFolderId(folderId);
-
-    const time_t timestamp = msgInfo->getTimestamp();
-    message->setTimeStamp(timestamp);
-
-    const std::string from = msgInfo->getFrom();
-    LOGD("From: %s", from.c_str());
-    message->setFrom(from);
-
-    const bool isRead = msgInfo->getIsRead();
-    message->setIsRead(isRead);
-
-    const int inResponseTo = msgInfo->getInResponseTo();
-    message->setInResponseTo(inResponseTo);
-
-    if (msg_release_struct(&platform_msg) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    if (msg_release_struct(&msg_conv) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    if (msg_release_struct(&send_opt) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    delete msgInfo;
-}
-
-void ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int msg_id;
-    Message* msgInfo = NULL;
-    msg_struct_t platform_msg = NULL;
-    msg_struct_t send_opt = NULL;
-    msg_struct_t msg_conv = NULL;
-    msg_struct_t req = NULL;
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-
-        std::shared_ptr<Message> message = callback->getMessage();
-        MessageStatus msg_status = message->getMessageStatus();
-        int ret = MSG_ERR_UNKNOWN;
-
-        // if it is draft message just send it
-        // in other case create new platform message
-        // add it to draft and finally send it
-        if (!( message->is_id_set() && MessageStatus::STATUS_DRAFT == msg_status)) {
-            LOGD("Add message to draft");
-            addDraftMessagePlatform(message);
-        }
-
-        msg_id = message->getId();
-        LOGD("Message ID: %d", msg_id);
-
-        platform_msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-        send_opt = msg_create_struct(MSG_STRUCT_SENDOPT);
-        msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO);
-        ret = msg_get_message(m_msg_handle, msg_id, platform_msg, send_opt);
-        if (MSG_SUCCESS != ret) {
-            LOGE("Failed to get platform message structure: %d", ret);
-            throw UnknownException("Cannot get platform Message structure");
-        }
-
-        // Send message
-        message->setMessageStatus(MessageStatus::STATUS_SENDING);
-        req = msg_create_struct(MSG_STRUCT_REQUEST_INFO);
-        msg_set_struct_handle(req, MSG_REQUEST_MESSAGE_HND, platform_msg);
-
-        int req_id = -1;
-        ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id);
-        if (MSG_SUCCESS != ret) {
-            LOGE("Failed to get send request ID: %d", ret);
-            throw UnknownException("Failed to get send request ID");
-        }
-
-        if (MessageType::MMS == message->getType()) {
-            LOGD("Send MMS message");
-            ret = msg_mms_send_message(m_msg_handle, req);
-        }
-        else if (MessageType::SMS == message->getType()) {
-            LOGD("Send SMS message");
-            ret = msg_sms_send_message(m_msg_handle, req);
-        }
-        else {
-            LOGE("Invalid message type: %d", message->getType());
-            throw TypeMismatchException("Invalid message type");
-        }
-
-        if (ret != MSG_SUCCESS) {
-            LOGE("Failed to send message: %d", ret);
-            throw UnknownException("Failed to send message");
-        }
-
-        ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id);
-        if (ret != MSG_SUCCESS) {
-            LOGE("Failed to get message request ID: %d", ret);
-            throw UnknownException("Failed to get send request");
-        }
-        LOGD("req_id: %d", req_id);
-
-        msgInfo = Message::convertPlatformShortMessageToObject(platform_msg);
-
-        int conversationId;
-        ret = msg_get_conversation(m_msg_handle, msg_id, msg_conv);
-        if (MSG_SUCCESS != ret) {
-            LOGE("Failed to get conv");
-        }
-        msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT,
-                &conversationId);
-        message->setConversationId(conversationId);
-
-        int folderId = msgInfo->getFolderId();
-        message->setFolderId(folderId);
-
-        time_t timestamp = msgInfo->getTimestamp();
-        message->setTimeStamp(timestamp);
-
-        std::string from = msgInfo->getFrom();
-        LOGD("From:%s", from.c_str());
-        message->setFrom(from);
-
-        bool isRead = msgInfo->getIsRead();
-        message->setIsRead(isRead);
-
-        int inResponseTo = msgInfo->getInResponseTo();
-        message->setInResponseTo(inResponseTo);
-
-        m_sendRequests[req_id] = callback;
-        LOGD("Send MSG_SUCCESS");
-    }
-    catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
-            LOGE("g_idle addition failed");
-            delete callback;
-            callback = NULL;
-        }
-    }
-    catch (...) {
-        LOGE("Message send failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message send failed");
-        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
-            LOGE("g_idle addition failed");
-            delete callback;
-            callback = NULL;
-        }
-    }
-
-    if (msg_release_struct(&req) != MSG_SUCCESS) {
-        LOGW("Request structure is already destroyed");
-    }
-    if (msg_release_struct(&platform_msg) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    if (msg_release_struct(&send_opt) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    if (msg_release_struct(&msg_conv) != MSG_SUCCESS) {
-        LOGW("Platform message is already destroyed");
-    }
-    delete msgInfo;
-
-    return;
-}
-
-void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status)
-{
-    int reqId = 0;
-    int status = MSG_NETWORK_NOT_SEND;
-
-    msg_get_int_value(sent_status, MSG_SENT_STATUS_REQUESTID_INT, &reqId);
-    LOGD("Send msg %d", reqId);
-    msg_get_int_value(sent_status, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status);
-    LOGD("Send msg status: %d", status);
-
-    if(MSG_NETWORK_SEND_SUCCESS != status
-        && MSG_NETWORK_SEND_FAIL != status
-        && MSG_NETWORK_SEND_TIMEOUT != status)
-    {
-        LOGD("Not final status, return");
-        return;
-    }
-
-    std::lock_guard<std::mutex> lock(m_mutex);
-    SendReqMap::iterator it = m_sendRequests.find(reqId);
-    if (it != m_sendRequests.end()) {
-        LOGD("Matching request found");
-
-        MessageRecipientsCallbackData* callback = it->second;
-        m_sendRequests.erase(it);
-
-        if (MSG_NETWORK_SEND_FAIL == status
-                || MSG_NETWORK_SEND_TIMEOUT == status) {
-            LOGE("req_id:%d : Failed sending Message(%p) with msg_id:%d msg status is: %s",
-                reqId,
-                callback->getMessage().get(),
-                callback->getMessage()->getId(),
-                (MSG_NETWORK_SEND_FAIL == status ? "FAIL" : "TIMEOUT"));
-
-            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
-                    "Send message failed");
-        }
-
-        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
-            LOGE("g_idle addition failed");
-            delete callback;
-            callback = NULL;
-        }
-    }
-    else {
-        LOGE("No matching request found");
-    }
-
-    return;
-}
-
-static void sent_status_cb(msg_handle_t handle,
-        msg_struct_t sent_status,
-        void *data)
-{
-    LOGD("Entered");
-    ShortMsgManager::getInstance().sendStatusCallback(sent_status);
-
-    return;
-}
-
-void ShortMsgManager::callProperEventMessages(EventMessages* event,
-        msg_storage_change_type_t storageChangeType)
-{
-    LOGD("Entered event.items.size()=%d event.removed_conversations.size()=%d"
-            " sChangeType:%d", event->items.size(),
-            event->removed_conversations.size(), storageChangeType);
-
-    EventConversations* eventConv = new EventConversations();
-    eventConv->service_id = event->service_id;
-    eventConv->service_type = event->service_type;
-
-    if(MSG_STORAGE_CHANGE_DELETE == storageChangeType) {
-        eventConv->items = event->removed_conversations;
-    } else {
-        eventConv->items = ShortMsgManager::getConversationsForMessages(
-                event->items, storageChangeType);
-    }
-
-    switch (storageChangeType) {
-        case MSG_STORAGE_CHANGE_INSERT: {
-            ChangeListenerContainer::getInstance().callMessageAdded(event);
-            if (!eventConv->items.empty()) {
-
-                ConversationPtrVector added_conv;
-                ConversationPtrVector updated_conv;
-
-                for(ConversationPtrVector::iterator it = eventConv->items.begin();
-                        it != eventConv->items.end(); it++) {
-                    ConversationPtr cur_conv = *it;
-                    const bool new_conv = (cur_conv->getMessageCount() <= 1);
-                    if(new_conv) {
-                        added_conv.push_back(cur_conv);
-                    } else {
-                        updated_conv.push_back(cur_conv);
-                    }
-
-                    LOGD("%s conversation with id:%d last_msg_id:d",
-                            (new_conv ? "ADDED" : "UPDATED"),
-                            cur_conv->getConversationId(), cur_conv->getLastMessageId());
-                }
-
-                LOGD("num conversations:all=%d added=%d update=%d", eventConv->items.size(),
-                        added_conv.size(), updated_conv.size());
-
-                if(false == added_conv.empty()) {
-                    LOGD("%d new conversations, calling onConversationAdded",
-                            added_conv.size());
-                    eventConv->items = added_conv;
-                    ChangeListenerContainer::getInstance().callConversationAdded(
-                            eventConv);
-                }
-
-                if(false == updated_conv.empty()) {
-                    LOGD("%d updated conversation, calling onConversationUpdated",
-                            updated_conv.size());
-                    eventConv->items = updated_conv;
-                    ChangeListenerContainer::getInstance().callConversationUpdated(
-                            eventConv);
-                }
-
-            }
-        } break;
-        case MSG_STORAGE_CHANGE_DELETE: {
-            ChangeListenerContainer::getInstance().callMessageRemoved(event);
-
-            if(false == eventConv->items.empty()) {
-                LOGD("At least one conversation will be deleted, "
-                     "triggering also onConversationRemoved");
-                ChangeListenerContainer::getInstance().callConversationRemoved(eventConv);
-            }
-        } break;
-        case MSG_STORAGE_CHANGE_UPDATE: {
-            ChangeListenerContainer::getInstance().callMessageUpdated(event);
-            ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
-        } break;
-        default:
-            LOGW("Unknown storageChangeType: %d", storageChangeType);
-    }
-    delete event;
-    delete eventConv;
-}
-
-void ShortMsgManager::storage_change_cb(msg_handle_t handle,
-        msg_storage_change_type_t storageChangeType,
-        msg_id_list_s *pMsgIdList,
-        void* data)
-{
-    LOGD("Entered handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType,
-            pMsgIdList->nCount);
-
-    if (MSG_STORAGE_CHANGE_CONTACT == storageChangeType) {
-        LOGD("storageChangeType is MSG_STORAGE_CHANGE_CONTACT, ignoring");
-        return;
-    }
-
-    if (pMsgIdList->nCount < 1) {
-        LOGW("no messages in callback list");
-        return;
-    }
-
-    LOGD("Messages count %d", pMsgIdList->nCount);
-
-    /*
-     * There is possibility that in one callback from msg service will come
-     * SMS and MMS messages in the same list. ChangeListenerContainer requires
-     * that messages in event have common service_id and service_type. So we
-     * create here 2 events: one for SMS and one for MMS. If one of events
-     * has empty message list, we won't trigger it.
-     */
-    EventMessages* eventSMS = NULL;
-    EventMessages* eventMMS = NULL;
-    try {
-        // if allocation below fails than exception is thrown - no NULL check
-        eventSMS = new EventMessages();
-        eventSMS->service_type = MessageType::SMS;
-        eventSMS->service_id = SMS_ACCOUNT_ID;
-        eventMMS = new EventMessages();
-        eventMMS->service_type = MessageType::MMS;
-        eventMMS->service_id = MMS_ACCOUNT_ID;
-
-        if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) {
-
-            ShortMsgManager& msg_manager = ShortMsgManager::getInstance();
-            std::lock_guard<std::mutex> lock(msg_manager.m_mutex);
-
-            std::map<int, MessagePtr>* rem_msgs[2] = {  // Recently removed messages
-                    &msg_manager.m_sms_removed_messages,
-                    &msg_manager.m_mms_removed_messages };
-            std::map<int, int>* rem_convs[2] = { // Recently removed conversations
-                    &msg_manager.m_sms_removed_msg_id_conv_id_map,
-                    &msg_manager.m_mms_removed_msg_id_conv_id_map };
-            EventMessages* dest_event[2] = { // SMS/MMS EventMessage to be propagated
-                    eventSMS,
-                    eventMMS };
-            std::map<int, ConversationPtr>* conv_map[2] = { //Map conversationId - object
-                    &msg_manager.m_sms_removed_conv_id_object_map,
-                    &msg_manager.m_mms_removed_conv_id_object_map };
-
-            for(int event_i = 0; event_i < 2; ++event_i) {
-
-                std::map<int, MessagePtr>& cur_rem_msgs = *(rem_msgs[event_i]);
-                std::map<int, int>& cur_rem_convs = *(rem_convs[event_i]);
-                EventMessages* cur_dest_event = dest_event[event_i];
-                std::map<int, ConversationPtr>& cur_conv_map = *(conv_map[event_i]);
-                std::unordered_set<int> conv_rem_now;
-
-                for (int i = 0; i < pMsgIdList->nCount; ++i) {
-                    const msg_message_id_t& msg_id = pMsgIdList->msgIdList[i];
-                    LOGD("pMsgIdList[%d] = %d", i, msg_id);
-
-                    std::map<int, MessagePtr> ::iterator it = cur_rem_msgs.find(msg_id);
-                    if(it != cur_rem_msgs.end()) {
-                        LOGD("[%d] is %s, Pushing message with id:%d subject:%s", i,
-                                (0 == i) ? "SMS" : "MMS",
-                                it->second->getId(),
-                                it->second->getSubject().c_str());
-                        cur_dest_event->items.push_back(it->second);
-                        cur_rem_msgs.erase(it);
-                    }
-
-                    std::map<int, int>::iterator cit = cur_rem_convs.find(msg_id);
-                    if(cit != cur_rem_convs.end()) {
-                        conv_rem_now.insert(cit->second);
-                        cur_rem_convs.erase(cit);
-                    }
-                }
-
-                for (auto it = conv_rem_now.begin(); it != conv_rem_now.end(); it++) {
-                    const int cur_rem_conv_id = *it;
-
-                    //---------------------------------------------------------------------
-                    // Check if we have removed last message from conversation
-                    //
-                    bool found = false;
-                    for(auto it2 = cur_rem_convs.begin();
-                            it2 != cur_rem_convs.end();
-                            it2++) {
-                        if( cur_rem_conv_id == it2->second) {
-                            found = true;
-                            break;
-                        }
-                    }
-
-                    if(false == found) {
-                        //We have removed last message from conversation
-
-                        std::map<int, ConversationPtr>::iterator conv_it =
-                            cur_conv_map.find(cur_rem_conv_id);
-                        if(conv_it != cur_conv_map.end()) {
-                            LOGD("Pushing removed %s MessageConversation(%p) with id:%d",
-                                    (0 == event_i) ? "SMS" : "MMS",
-                                    conv_it->second.get(), cur_rem_conv_id);
-
-                            cur_dest_event->removed_conversations.push_back(
-                                conv_it->second);
-                            cur_conv_map.erase(conv_it);
-                        } else {
-                            LOGW("Couldn't find ConversationPtr object with id:%d",
-                                    cur_rem_conv_id);
-                        }
-                    }
-                }
-            }
-
-        } else {
-            for (int i = 0; i < pMsgIdList->nCount; ++i) {
-
-                msg_struct_t msg = ShortMsgManager::getInstance().getMessage(
-                        pMsgIdList->msgIdList[i]);
-                if (NULL == msg) {
-                    LOGE("Failed to load short message");
-                    delete eventSMS;
-                    eventSMS = NULL;
-                    delete eventMMS;
-                    eventMMS = NULL;
-                    throw Common::UnknownException("Failed to load short message");
-                }
-                std::shared_ptr<Message> message(
-                        Message::convertPlatformShortMessageToObject(msg));
-                msg_release_struct(&msg);
-                switch (message->getType()) {
-                    case MessageType::SMS:
-                        eventSMS->items.push_back(message);
-                        break;
-                    case MessageType::MMS:
-                        eventMMS->items.push_back(message);
-                        break;
-                    default:
-                        LOGE("Unsupported message type");
-                        delete eventSMS;
-                        eventSMS = NULL;
-                        delete eventMMS;
-                        eventMMS = NULL;
-                        throw Common::UnknownException("Unsupported message type");
-                }
-            }
-        }
-
-        if (!eventSMS->items.empty() || !eventSMS->removed_conversations.empty()) {
-            ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType);
-        } else {
-            LOGD("No SMS messages, not triggering eventSMS");
-            delete eventSMS;
-            eventSMS = NULL;
-        }
-        if (!eventMMS->items.empty() || !eventMMS->removed_conversations.empty()) {
-            ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType);
-        } else {
-            LOGD("No MMS messages, not triggering eventMMS");
-            delete eventMMS;
-            eventMMS = NULL;
-        }
-
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        delete eventSMS;
-        delete eventMMS;
-    } catch (...) {
-        LOGE("Failed to call callback");
-        delete eventSMS;
-        delete eventMMS;
-    }
-}
-
-void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle)
-{
-    m_msg_handle = msg_handle;
-    // set message sent status callback
-    if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle,
-            &sent_status_cb, NULL)) {
-        LOGE("sent status callback register error!!!");
-    }
-    if (MSG_SUCCESS != msg_reg_storage_change_callback(m_msg_handle,
-            &storage_change_cb, NULL)) {
-        LOGE("storage change callback register error!");
-    }
-}
-
-void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback)
-{
-    LOGD("Enter");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::shared_ptr<Message> message = callback->getMessage();
-
-        addDraftMessagePlatform(message);
-
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Message add draft failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
-    }
-
-    // Complete task
-    if (!g_idle_add(addDraftMessageCompleteCB, static_cast<void *>(callback))) {
-        LOGE("g_idle addition failed");
-        delete callback;
-        callback = NULL;
-    }
-}
-
-void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int error;
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
-        MessageType type = callback->getMessageServiceType();
-        for(auto it = messages.begin() ; it != messages.end(); ++it) {
-            if((*it)->getType() != type) {
-                LOGE("Invalid message type: %d", (*it)->getType());
-                throw TypeMismatchException("Error while deleting message");
-            }
-        }
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-
-            const int id = (*it)->getId();
-
-            //Store message object
-            LOGD("Storing removed message (id:%d) in m_removed_messages", id);
-            switch((*it)->getType()) {
-
-                case SMS:  m_sms_removed_messages[id] = (*it); break;
-                case MMS:  m_mms_removed_messages[id] = (*it); break;
-                default:
-                    LOGD("Unknown message type: %d", (*it)->getType());
-                    break;
-            }
-
-            error = msg_delete_message(m_msg_handle, id);
-            if (MSG_SUCCESS != error) {
-                LOGE("Error while deleting message");
-                throw UnknownException("Error while deleting message");
-            }
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages remove failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling removeShortMsg callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling removeShortMsg callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    LOGD("messages to update: %d", callback->getMessages().size());
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
-        MessageType type = callback->getMessageServiceType();
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-            if ((*it)->getType() != type) {
-                LOGE("Invalid message type");
-                throw TypeMismatchException("Error while updating message");
-            }
-        }
-        for (auto it = messages.begin() ; it != messages.end(); ++it) {
-
-            LOGD("updating Message(%p) msg_id:%d", (*it).get(), (*it)->getId());
-
-            msg_struct_t platform_msg
-                    = Message::convertPlatformShortMessageToStruct(it->get(), m_msg_handle);
-            if (NULL == platform_msg) {
-                LOGE("Failed to prepare platform message");
-                throw UnknownException("Cannot prepare platform message");
-            }
-            msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
-            int error = msg_update_message(m_msg_handle, platform_msg, sendOpt);
-            msg_release_struct(&platform_msg);
-            msg_release_struct(&sendOpt);
-            if (error != MSG_SUCCESS) {
-                LOGE("Failed to update message %d", (*it)->getId());
-                throw UnknownException("Error while updating message");
-            }
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages update failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages update failed");
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling updateShortMsg callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling updateShortMsg callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-msg_struct_t ShortMsgManager::getMessage(int msg_id)
-{
-    msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
-    msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-    int error = msg_get_message(m_msg_handle, msg_id, msg, sendOpt);
-    if (MSG_SUCCESS != error) {
-        LOGE("Couldn't retrieve message from service, msgId: %d, error:%d", msg_id, error);
-        throw Common::UnknownException("Couldn't retrieve message from service");
-    }
-    msg_release_struct(&sendOpt);
-    return msg;
-}
-
-ConversationPtrVector ShortMsgManager::getConversationsForMessages(
-        MessagePtrVector messages,
-        msg_storage_change_type_t storageChangeType)
-{
-    LOGD("Entered messages.size()=%d storageChangeType=%d", messages.size(),
-            storageChangeType);
-
-    std::unordered_set<int> unique_conv_ids;
-    ConversationPtrVector convs;
-    for (auto it = messages.begin(); it != messages.end(); ++it) {
-
-        MessagePtr msg = (*it);
-        const int conv_id = msg->getConversationId();
-        const int count = unique_conv_ids.count(conv_id);
-        LOGD("Message(%p) msg_id:%d conversationId: %d count:%d", msg.get(),
-                msg->getId(), conv_id, count);
-
-        if (0 == count) {
-            //conversation isn't loaded yet
-            unique_conv_ids.insert(conv_id);
-            ConversationPtr conv = MessageConversation::convertMsgConversationToObject(
-                    conv_id, ShortMsgManager::getInstance().m_msg_handle);
-
-            LOGD("Pushed conv=%p", conv.get());
-            convs.push_back(conv);
-        }
-    }
-    return convs;
-}
-
-void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback)
-{
-    LOGD("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<int> messagesIds =
-                MessagingDatabaseManager::getInstance().findShortMessages(callback);
-        int msgListCount = messagesIds.size();
-        LOGD("Found %d messages", msgListCount);
-
-        msg_struct_t msg;
-        msg_struct_t sendOpt;
-        msg_error_t err;
-        for (int i = 0; i < msgListCount; i++) {
-            msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
-            sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
-            err = msg_get_message(m_msg_handle, messagesIds.at(i), msg, sendOpt);
-
-            if (MSG_SUCCESS != err) {
-                LOGE("Failed to get platform message structure: %d", err);
-                throw UnknownException("Cannot get platform Message structure");
-            }
-
-            try {
-                std::shared_ptr<Message> message(
-                    Message::convertPlatformShortMessageToObject(msg));
-                callback->addMessage(message);
-
-                LOGD("Created message with id %d:", messagesIds[i]);
-            }
-            catch(const Common::InvalidValuesException& exception) {
-                //Ignore messages with not supported/unrecognized type
-            }
-
-            msg_release_struct(&sendOpt);
-            msg_release_struct(&msg);
-        }
-
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Message add draft failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback with %d messages:",
-                    callback->getMessages().size());
-            callback->callSuccessCallback(JSMessage::messageVectorToJSObjectArray(context,
-                    callback->getMessages()));
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling findMessages callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Failed to call findMessages callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-void ShortMsgManager::findConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if(!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        std::vector<int> conversationsIds =
-                MessagingDatabaseManager::getInstance().findShortMessageConversations(callback);
-        int convListCount = conversationsIds.size();
-        LOGD("Found %d conversations", convListCount);
-
-        for (int i = 0; i < convListCount; i++) {
-            std::shared_ptr<MessageConversation> conversation =
-                    MessageConversation::convertMsgConversationToObject(
-                            conversationsIds.at(i), m_msg_handle);
-
-            callback->addConversation(conversation);
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Message add draft failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback(MessagingUtil::vectorToJSObjectArray<
-                    ConversationPtr, JSMessageConversation>(context, callback->getConversations()));
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling findConversations callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Failed to call findConversations callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-void ShortMsgManager::removeConversations(ConversationCallbackData* callback)
-{
-    LOGD("Entered");
-
-    if (!callback){
-        LOGE("Callback is null");
-        return;
-    }
-
-    int error = MSG_SUCCESS;
-    msg_handle_t handle = NULL;
-
-    try {
-        std::lock_guard<std::mutex> lock(m_mutex);
-        ConversationPtrVector conversations = callback->getConversations();
-        const MessageType type = callback->getMessageServiceType();
-
-        error = msg_open_msg_handle(&handle);
-        if (MSG_SUCCESS != error) {
-            LOGE("Open message handle error: %d", error);
-            throw UnknownException("Error while creatng message handle");
-        }
-
-        for(auto it = conversations.begin() ; it != conversations.end(); ++it) {
-            if((*it)->getType() != type) {
-                LOGE("Invalid message type");
-                throw TypeMismatchException("Error while deleting message conversation");
-            }
-        }
-
-        std::map<int, int>* msg_id_conv_id_map = NULL;
-        std::map<int, ConversationPtr>* conv_id_object_map = NULL;
-        if(MessageType::SMS == type) {
-            msg_id_conv_id_map = &m_sms_removed_msg_id_conv_id_map;
-            conv_id_object_map = &m_sms_removed_conv_id_object_map;
-        } else if(MessageType::MMS == type) {
-            msg_id_conv_id_map = &m_mms_removed_msg_id_conv_id_map;
-            conv_id_object_map = &m_mms_removed_conv_id_object_map;
-        } else {
-            LOGE("Invalid message type:%d for ShortMsgManager!", type);
-            throw UnknownException("Invalid message type for ShortMsgManager!");
-        }
-
-        int conv_index = 0;
-        for (auto it = conversations.begin() ; it != conversations.end();
-                    ++it, ++conv_index) {
-
-            ConversationPtr conv = (*it);
-            msg_thread_id_t conv_id = conv->getConversationId();
-
-            LOGD("[%d] MessageConversation(%p) conv_id:%d", conv_index, conv.get(),
-                    conv_id);
-
-            msg_struct_list_s conv_view_list;
-            error = msg_get_conversation_view_list(handle, (msg_thread_id_t)conv_id,
-                    &conv_view_list);
-            if (MSG_SUCCESS == error) {
-                for(int msg_index = 0; msg_index < conv_view_list.nCount; ++msg_index)
-                {
-                    int cur_msg_id = 0;
-                    error = msg_get_int_value(conv_view_list.msg_struct_info[msg_index],
-                            MSG_CONV_MSG_ID_INT, &cur_msg_id);
-
-                    if(MSG_SUCCESS == error && cur_msg_id > 0) {
-                        (*msg_id_conv_id_map)[cur_msg_id] = conv_id;
-                        (*conv_id_object_map)[conv_id] = conv;
-
-                        LOGD("[%d] message[%d] msg_id:%d,"
-                                "saved MessageConversation(%p) with conv_id:%d",
-                                conv_index, msg_index, cur_msg_id, conv.get(), conv_id);
-                    } else {
-                        LOGE("[%d] Couldn't get msg_id, error: %d!", error);
-                    }
-                }
-            } else {
-                LOGE("[%d] Couldn' get conversation view list for conv_id:%d error: %d",
-                        conv_index, conv_id, error);
-            }
-
-            msg_release_list_struct(&conv_view_list);
-
-            error = msg_delete_thread_message_list(handle, (msg_thread_id_t) conv_id,
-                    FALSE);
-            if (MSG_SUCCESS != error) {
-                LOGE("Error while deleting message conversation");
-                throw UnknownException("Error while deleting message conversation");
-            }
-
-        }
-
-    } catch (const BasePlatformException& err) {
-        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
-        callback->setError(err.getName(), err.getMessage());
-    } catch (...) {
-        LOGE("Messages remove failed");
-        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
-    }
-
-    error = msg_close_msg_handle(&handle);
-    if (MSG_SUCCESS != error) {
-        LOGW("Cannot close message handle: %d", error);
-    }
-
-    //Complete task
-    JSContextRef context = callback->getContext();
-    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
-        LOGE("context was closed");
-        delete callback;
-        callback = NULL;
-        return;
-    }
-
-    try {
-        if (callback->isError()) {
-            LOGD("Calling error callback");
-            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
-                    callback->getErrorName(), callback->getErrorMessage());
-            callback->callErrorCallback(errobj);
-        } else {
-            LOGD("Calling success callback");
-            callback->callSuccessCallback();
-        }
-    } catch (const BasePlatformException& err) {
-        LOGE("Error while calling removeConversations callback: %s (%s)",
-                (err.getName()).c_str(), (err.getMessage()).c_str());
-    } catch (...) {
-        LOGE("Unknown error when calling removeConversations callback.");
-    }
-
-    delete callback;
-    callback = NULL;
-}
-
-ShortMsgManager::ShortMsgManager() : m_msg_handle(NULL)
-{
-    LOGD("Entered");
-}
-
-ShortMsgManager::~ShortMsgManager()
-{
-    LOGD("Entered");
-    LOGD("m_sms_removed_messages.size() = %d",
-            m_sms_removed_messages.size());
-    LOGD("m_mms_removed_messages.size() = %d",
-            m_mms_removed_messages.size());
-    LOGD("m_sms_removed_msg_id_conv_id_map.size() = %d",
-            m_sms_removed_msg_id_conv_id_map.size());
-    LOGD("m_sms_removed_conv_id_object_map.size() = %d",
-            m_sms_removed_conv_id_object_map.size());
-    LOGD("m_mms_removed_msg_id_conv_id_map.size() = %d",
-            m_mms_removed_msg_id_conv_id_map.size());
-    LOGD("m_mms_removed_conv_id_object_map.size() = %d",
-            m_mms_removed_conv_id_object_map.size());
-}
-
-
-} // Messaging
-} // DeviceAPI
diff --git a/messaging/old/ShortMsgManager.h b/messaging/old/ShortMsgManager.h
deleted file mode 100755 (executable)
index 6f17f06..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef __TIZEN_SEND_SHORT_MSG_MANAGER_H__
-#define __TIZEN_SEND_SHORT_MSG_MANAGER_H__
-
-#include <glib.h>
-#include <mutex>
-#include <map>
-
-#include <msg_storage_types.h>
-#include <CallbackUserData.h>
-#include <PlatformException.h>
-#include <msg_types.h>
-
-#include "ChangeListenerContainer.h"
-#include "MessagingUtil.h"
-#include "MessageService.h"
-#include "Message.h"
-#include "MessageConversation.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-class Message;
-class FindMsgCallbackUserData;
-
-class ShortMsgManager {
-public:
-    static ShortMsgManager& getInstance();
-
-    void sendMessage(MessageRecipientsCallbackData* callback);
-    void sendStatusCallback(msg_struct_t sent_status);
-
-    void addDraftMessage(MessageCallbackUserData* callback);
-    void findMessages(FindMsgCallbackUserData* callback);
-    void findConversations(ConversationCallbackData* callback);
-    void removeConversations(ConversationCallbackData* callback);
-
-    void registerStatusCallback(msg_handle_t msg_handle);
-
-    void removeMessages(MessagesCallbackUserData* callback);
-    void updateMessages(MessagesCallbackUserData* callback);
-    msg_struct_t getMessage(int msg_id);
-private:
-    ShortMsgManager();
-    ShortMsgManager(const ShortMsgManager &);
-    void operator=(const ShortMsgManager &);
-    virtual ~ShortMsgManager();
-
-    /**
-     * Listener for msg storage changes. Calls callbacks from ChangeListenerContainer.
-     * @param handle
-     * @param storageChangeType
-     * @param pMsgIdList
-     * @param data
-     */
-    static void storage_change_cb(msg_handle_t handle,
-        msg_storage_change_type_t storageChangeType,
-        msg_id_list_s *pMsgIdList,
-        void* data);
-
-    void addDraftMessagePlatform(std::shared_ptr<Message> message);
-    /**
-     * Returns unique list of conversations for given vector of messages.
-     * storageChangeType is needed to filter conversations returned:
-     * - for MSG_STORAGE_CHANGE_UPDATE all conversations are fetched
-     * - for MSG_STORAGE_CHANGE_INSERT only conversations with 1 message are returned
-     * - for MSG_STORAGE_CHANGE_DELETE  only conversations with 1 message are returned
-     * @param messages
-     * @param storageChangeType
-     * @return
-     */
-    static ConversationPtrVector getConversationsForMessages(
-            MessagePtrVector messages,
-            msg_storage_change_type_t storageChangeType);
-    static void callProperEventMessages(EventMessages* event,
-            msg_storage_change_type_t storageChangeType);
-    typedef std::map<msg_request_id_t, MessageRecipientsCallbackData*> SendReqMap;
-    SendReqMap m_sendRequests;
-    msg_handle_t m_msg_handle;
-
-    /**
-     * Map MessageId - Message object of recently removed SMS messages
-     */
-    std::map<int, MessagePtr> m_sms_removed_messages;
-
-    /**
-     * Map MessageId - Message object of recently removed MMS messages
-     */
-    std::map<int, MessagePtr> m_mms_removed_messages;
-
-
-
-    /**
-     * Map MessageId - ConversationId for SMS messages (only from removed conversation)
-     */
-    std::map<int, int> m_sms_removed_msg_id_conv_id_map;
-
-    /**
-     * Map ConversationId - ConversationPtr object (only removed) for SMS
-     */
-    std::map<int, ConversationPtr> m_sms_removed_conv_id_object_map;
-
-    /**
-     * Map MessageId - ConversationId for MMS messages (only from removed conversation)
-     */
-    std::map<int, int> m_mms_removed_msg_id_conv_id_map;
-
-    /**
-     * Map ConversationId - ConversationPtr object (only removed) for MMS
-     */
-    std::map<int, ConversationPtr> m_mms_removed_conv_id_object_map;
-
-    std::mutex m_mutex;
-};
-
-} // Messaging
-} // DeviceAPI
-#endif // __TIZEN_SEND_SHORT_MSG_MANAGER_H__
diff --git a/messaging/old/TestScripts/addConversationsChangeListener_01.js b/messaging/old/TestScripts/addConversationsChangeListener_01.js
deleted file mode 100644 (file)
index 285c8b7..0000000
+++ /dev/null
@@ -1,121 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        addConversationsChangeListener_01.js
- */
-
-//
-//
-//  Attribute      | Attribute filter| Attribute range filter
-//                 | supported       | supported
-// ----------------+-----------------+------------------------
-// id              | Yes             | No
-// type            | Yes             | No
-// timestamp       | No              | Yes
-// messageCount    | Yes             | No
-// unreadMessages  | Yes             | No
-// preview         | Yes             | No
-// subject         | No              | No
-// isRead          | No              | No
-// from            | Yes             | No
-// to              | Yes             | No
-// cc              | No              | No
-// bcc             | No              | No
-// lastMessageId   | No              | No
-
-
-var prefferedEmailService = "a.jacak.testmail";
-
-function containCaseInsensitive(string, searchString) {
-    var lcString = string.toLowerCase();
-    var lcSearchString = searchString.toLowerCase();
-    return lcString.indexOf(lcSearchString)>=0;
-}
-
-var currentService = null;
-
-function listConversations(prefix, conversations) {
-
-    for (var i=0; i<conversations.length; i++) {
-        var conversation = conversations[i];
-        console.log(prefix + " CONVERSATION[" + i + "] " +
-                " id: " + conversation.id +
-                " type: " + conversation.type +
-                " timestamp: " + conversation.timestamp +
-                " messageCount: " + conversation.messageCount +
-                " unreadMessages: " + conversation.unreadMessages +
-                " preview: " + conversation.preview +
-                " subject:" + conversation.subject +
-                " isRead: " + conversation.isRead +
-                " from: " + conversation.from +
-                " lastMessageId: " + conversation.lastMessageId);
-    }
-}
-
-var conversationChangeCB = {
-    conversationsupdated: function(conversations) {
-        console.log(conversations.length + " conversation(s) updated");
-        listConversations("conversationsupdated", conversations);
-    },
-    conversationsadded: function(conversations) {
-        console.log(conversations.length + " conversation(s) added");
-        listConversations("conversationsadded", conversations);
-    },
-    conversationsremoved: function(conversations) {
-        console.log(conversations.length + " conversation(s) removed");
-        listConversations("conversationsremoved", conversations);
-    }
-};
-
-function serviceSyncSuccessCB() {
-    console.log("Synced!");
-}
-
-function serviceSyncFailCB() {
-    console.log("Sync failed!");
-}
-
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-
-        var chosenServiceIndex = 0;
-        for(var i = 0; i < services.length; i++) {
-            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
-                chosenServiceIndex = i;
-                console.log("servicesListSuccessCB: " +
-                        "found service which name contains: " +
-                        prefferedEmailService);
-                break;
-            }
-        }
-        currentService = services[chosenServiceIndex];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-
-        var filter = new tizen.AttributeFilter("preview", "CONTAINS", "Home");
-        currentService.messageStorage.addConversationsChangeListener(
-                conversationChangeCB, filter);
-
-        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/messaging/old/TestScripts/addFoldersChangeListener_01.js b/messaging/old/TestScripts/addFoldersChangeListener_01.js
deleted file mode 100644 (file)
index f669a7e..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-// Please send two emails with subject containing "Alaska"
-//  1. subject "Alaska Good" and body containing "hack"
-//  2. subject "Alaska Bad" and body NOT containing "hack"
-//
-// Only 1. should printed in JS console.
-
-/**
- * @file        addFoldersChangeListener_01.js
- */
-
-/**
- *
- *  Attribute      | Attribute filter| Attribute range filter
- *                 | supported       | supported
- * ----------------+-----------------+------------------------
- *  id             | No              | No
- *  parentId       | No              | No
- *  serviceId      | Yes             | No
- *  contentType    | No              | No
- *  name           | No              | No
- *  path           | No              | No
- *  type           | No              | No
- *  synchronizable | No              | No
- */
-
-var prefferedEmailService = "a.jacak.testmail";
-
-function containCaseInsensitive(string, searchString) {
-    var lcString = string.toLowerCase();
-    var lcSearchString = searchString.toLowerCase();
-    return lcString.indexOf(lcSearchString)>=0;
-}
-
-var currentService = null;
-
-function listFolders(prefix, folders) {
-    for (var i=0; i<folders.length; i++) {
-        var folder = folders[i];
-        console.log(prefix + " FOLDER[" + i + "] id: "
-                + folder.id
-                + " name:" + folder.name
-                + " serviceid: " + folder.serviceId);
-    }
-}
-
-var folderChangeCB = {
-    foldersupdated: function(folders) {
-        console.log(folders.length + " folder(s) updated");
-        listFolders("foldersupdated",folders);
-    },
-    foldersadded: function(folders) {
-        console.log(folders.length + " folder(s) added");
-        listFolders("foldersadded",folders);
-    },
-    foldersremoved: function(folders) {
-        console.log(folders.length + " folder(s) removed");
-        listFolders("foldersremoved",folders);
-    }
- };
-
-function serviceSyncSuccessCB() {
-    console.log("Synced!");
-}
-
-function serviceSyncFailCB() {
-    console.log("Sync failed!");
-}
-
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-        var chosenServiceIndex = 0;
-        for(var i = 0; i < services.length; i++) {
-            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
-                chosenServiceIndex = i;
-                console.log("servicesListSuccessCB: " +
-                        "found service which name contains: " +
-                        prefferedEmailService);
-                break;
-            }
-        }
-        currentService = services[chosenServiceIndex];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-
-        var filter = new tizen.AttributeFilter("serviceId", "EXACTLY", currentService.id);
-
-        currentService.messageStorage.addFoldersChangeListener(folderChangeCB, filter);
-        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
\ No newline at end of file
diff --git a/messaging/old/TestScripts/addMessagesChangeListener_01.js b/messaging/old/TestScripts/addMessagesChangeListener_01.js
deleted file mode 100644 (file)
index 91455e9..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-// Please send two emails with subject containing "Alaska"
-//  1. subject "Alaska Good" and body containing "hack"
-//  2. subject "Alaska Bad" and body NOT containing "hack"
-//
-// Only 1. should printed in JS console.
-
-/**
- * @file        addMessagesChangeListener_01.js
- */
-
-//https://developer.tizen.org/help/index.jsp?topic=%2Forg.tizen.gettingstarted%2Fhtml%2Ftizen_overview%2Fapplication_filtering.htm
-
-var prefferedEmailService = "a.jacak.testmail";
-
-function containCaseInsensitive(string, searchString) {
-    var lcString = string.toLowerCase();
-    var lcSearchString = searchString.toLowerCase();
-    return lcString.indexOf(lcSearchString)>=0;
-}
-
-var currentService = null;
-
-function listMessages(prefix, messages) {
-    for (var i=0; i<messages.length; i++) {
-        var message = messages[i];
-        console.log(prefix + " MSG[" + i + "] status: "
-                    + message.messageStatus
-                    + " subject:" + message.subject);
-    }
-}
-
-var messageChangeCB = {
-    messagesupdated: function(messages) {
-        console.log(messages.length + " message(s) updated");
-        listMessages("messagesupdated",messages);
-    },
-    messagesadded: function(messages) {
-       console.log("messagesadded: " + messages.length + " message(s) added");
-       listMessages("messagesadded",messages);
-
-    },
-    messagesremoved: function(messages) {
-        console.log(messages.length + " message(s) removed");
-        listMessages("messagesremoved",messages);
-    }
-};
-
-function serviceSyncSuccessCB() {
-    console.log("Synced!");
-}
-
-function serviceSyncFailCB() {
-    console.log("Sync failed!");
-}
-
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-
-        var chosenServiceIndex = 0;
-        for(var i = 0; i < services.length; i++) {
-            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
-                chosenServiceIndex = i;
-                console.log("servicesListSuccessCB: " +
-                        "found service which name contains: " +
-                        prefferedEmailService);
-                break;
-            }
-        }
-        currentService = services[chosenServiceIndex];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-
-        var subjectFilter1 = new tizen.AttributeFilter("subject", "CONTAINS", "Alaska");
-        var subjectFilter2 = new tizen.AttributeFilter("subject", "CONTAINS", "Alabama");
-        var subsfilter = new tizen.CompositeFilter("UNION",
-                [subjectFilter1, subjectFilter2]);
-
-        var pbodyFilter = new tizen.AttributeFilter("body.plainBody", "CONTAINS", "hack");
-        var filter = new tizen.CompositeFilter("INTERSECTION", [subsfilter, pbodyFilter]);
-
-        currentService.messageStorage.addMessagesChangeListener(messageChangeCB, filter);
-        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/messaging/old/TestScripts/allChangeListeners_01.js b/messaging/old/TestScripts/allChangeListeners_01.js
deleted file mode 100644 (file)
index ff7512f..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/**
- * @file        allChangeListeners_01.js
- */
-
-var prefferedEmailService = "a.jacak.testmail";
-
-function containCaseInsensitive(string, searchString) {
-    var lcString = string.toLowerCase();
-    var lcSearchString = searchString.toLowerCase();
-    return lcString.indexOf(lcSearchString)>=0;
-}
-
-var currentService = null;
-
-//=============================================================================
-// FOLDERS
-//=============================================================================
-function listFolders(prefix, folders) {
-    for (var i=0; i<folders.length; i++) {
-        var folder = folders[i];
-        console.log(prefix + " FOLDER[" + i + "] id: "
-                + folder.id
-                + " name:" + folder.name
-                + " serviceid: " + folder.serviceId);
-    }
-}
-
-var folderChangeCB = {
-    foldersupdated: function(folders) {
-        console.log(folders.length + " folder(s) updated");
-        listFolders("foldersupdated",folders);
-    },
-    foldersadded: function(folders) {
-        console.log(folders.length + " folder(s) added");
-        listFolders("foldersadded",folders);
-    },
-    foldersremoved: function(folders) {
-        console.log(folders.length + " folder(s) removed");
-        listFolders("foldersremoved",folders);
-    }
- };
-
-
-
-//=============================================================================
-// CONVERSATIONS
-//=============================================================================
-function listConversations(prefix, conversations) {
-
-    for (var i=0; i<conversations.length; i++) {
-        var conversation = conversations[i];
-        console.log(prefix + " CONVERSATION[" + i + "] " +
-                " id: " + conversation.id +
-                " type: " + conversation.type +
-                " timestamp: " + conversation.timestamp +
-                " messageCount: " + conversation.messageCount +
-                " unreadMessages: " + conversation.unreadMessages +
-                " preview: " + conversation.preview +
-                " subject:" + conversation.subject +
-                " isRead: " + conversation.isRead +
-                " from: " + conversation.from +
-                " lastMessageId: " + conversation.lastMessageId);
-    }
-}
-
-var conversationChangeCB = {
-    conversationsupdated: function(conversations) {
-        console.log(conversations.length + " conversation(s) updated");
-        listConversations("conversationsupdated", conversations);
-    },
-    conversationsadded: function(conversations) {
-        console.log(conversations.length + " conversation(s) added");
-        listConversations("conversationsadded", conversations);
-    },
-    conversationsremoved: function(conversations) {
-        console.log(conversations.length + " conversation(s) removed");
-        listConversations("conversationsremoved", conversations);
-    }
-};
-
-//=============================================================================
-// MESSAGES
-//=============================================================================
-function listMessages(prefix, messages) {
-    for (var i=0; i<messages.length; i++) {
-        var message = messages[i];
-        console.log(prefix + " MSG[" + i + "] status: "
-                    + message.messageStatus
-                    + " subject:" + message.subject);
-    }
-}
-
-var messageChangeCB = {
-    messagesupdated: function(messages) {
-        console.log(messages.length + " message(s) updated");
-        listMessages("messagesupdated",messages);
-    },
-    messagesadded: function(messages) {
-       console.log("messagesadded: " + messages.length + " message(s) added");
-       listMessages("messagesadded",messages);
-
-    },
-    messagesremoved: function(messages) {
-        console.log(messages.length + " message(s) removed");
-        listMessages("messagesremoved",messages);
-    }
-};
-
-
-//=============================================================================
-// Sync
-//=============================================================================
-function serviceSyncSuccessCB() {
-    console.log("Synced!");
-}
-
-function serviceSyncFailCB() {
-    console.log("Sync failed!");
-}
-
-//=============================================================================
-// Main
-//=============================================================================
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-
-        var chosenServiceIndex = 0;
-        for(var i = 0; i < services.length; i++) {
-            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
-                chosenServiceIndex = i;
-                console.log("servicesListSuccessCB: " +
-                        "found service which name contains: " +
-                        prefferedEmailService);
-                break;
-            }
-        }
-        currentService = services[chosenServiceIndex];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-
-        var filter = null;
-
-        currentService.messageStorage.addMessagesChangeListener(messageChangeCB, filter);
-        currentService.messageStorage.addFoldersChangeListener(folderChangeCB, filter);
-        currentService.messageStorage.addConversationsChangeListener(
-                conversationChangeCB, filter);
-
-        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/messaging/old/TestScripts/loadMessageAttachment_01.js b/messaging/old/TestScripts/loadMessageAttachment_01.js
deleted file mode 100644 (file)
index ed6a18c..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-// For simplicity this script is using ONLY first found email message service.
-// If you want to change this please visit servicesListSuccessCB function.
-//
-// It is important to test mailservice which contains at least TWO mails containing
-// attachments.
-//
-
-/**
- * @file        testLoadMessageAttachment_01.js
- */
-
-var currentService = null;
-
-function loadMsgAttSuccessCB(attachment) {
-    console.log("loadMsgAttSuccessCB: received attachment:\n"
-            + "        attachmentId: " + attachment.id + "\n"
-            + "        filePath: " + attachment.filePath + "\n"
-            + "        messageId: " + attachment.messageId + "\n"
-            + "        mimeType: " + attachment.mimeType);
-}
-
-function loadMsgAttErrorCB(error) {
-    console.log("loadMsgAttErrorCB: Cannot load message attachment:" + error.message);
-}
-
-function findMessagesSuccessCB(messages) {
-    console.log("messagesFoundCB: found: " + messages.length + " messages");
-
-    for (var msgIndex = 0; msgIndex < messages.length; ++msgIndex) {
-        var message = messages[msgIndex];
-
-        for(var attIndex = 0; attIndex < message.attachments.length; ++attIndex) {
-            var attachment = message.attachments[attIndex];
-
-            console.log("messagesFoundCB: requesting loadMessageAttachment for:\n"
-                    + "        messageId: " + message.id + "\n"
-                    + "        message: " + message.subject + "\n"
-                    + "        attachmentId: " + attachment.id);
-
-            currentService.loadMessageAttachment(attachment, loadMsgAttSuccessCB,
-                         loadMsgAttErrorCB);
-        }
-    }
-}
-
-function findMessagesErrorCB(err) {
-    console.log("servicesListSuccessCB: error:" + err);
-}
-
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-        currentService = services[0];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-        console.log("servicesListSuccessCB: service id is:" + currentService.id);
-        var filter = new tizen.AttributeFilter("hasAttachment", "EXACTLY", true);
-        currentService.messageStorage.findMessages(filter, findMessagesSuccessCB,
-            findMessagesErrorCB);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/messaging/old/TestScripts/loadMessageBody_01.js b/messaging/old/TestScripts/loadMessageBody_01.js
deleted file mode 100644 (file)
index f15dd89..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//
-// This script registers messagesChangeListener and requests syncing first
-// email message service.
-//
-// If there are new messages it requests loadBody for each message without
-// downloaded body data.
-//
-// Please ensure that there is new email waiting to receive (send new mail before
-// running this test).
-
-/**
- * @file        testLoadMessageBody_01.js
- */
-
-var currentService = null;
-
-function loadMBodySuccessCB(message) {
-    console.log("loadMBodySuccessCB: success!");
-    console.log("loadMBodySuccessCB: message subject:" + message.subject);
-
-    if(message.body.plainBody) {
-        console.log("loadMBodySuccessCB: message plainBody:" + message.body.plainBody);
-    } else if(message.body.htmlBody) {
-        console.log("loadMBodySuccessCB: message htmlBody:" + message.body.htmlBody);
-    } else {
-        console.log("loadMBodySuccessCB:"
-            + "ERROR: message do not contain plain nor htmlBody!");
-    }
-}
-function loadMBodyErrorCB(error) {
-    console.log("loadMBodyErrorCB: failes with error:"+error+"!");
-}
-
-var messageChangeCB = {
-    messagesupdated: function(messages) {
-        console.log(messages.length + " message(s) updated");
-    },
-    messagesadded: function(messages) {
-       console.log("messagesadded: " + messages.length + " message(s) added");
-
-        for (var i=0; i<messages.length; i++) {
-            var message = messages[i];
-
-            console.log("messagesadded: MSG[" + i + "] status: "
-                     + message.messageStatus
-                     + " subject:" + message.subject);
-
-            if (message.body.loaded) {
-                console.log("messagesadded: body for message[" + i
-                         + "] is already loaded");
-            } else {
-                console.log("messagesadded: requesting loadMessageBody for message["
-                         + i + "]");
-
-                currentService.loadMessageBody(message, loadMBodySuccessCB,
-                         loadMBodyErrorCB);
-            }
-        }
-    },
-    messagesremoved: function(messages) {
-        console.log(messages.length + " message(s) removed");
-    }
- };
-
-function serviceSyncSuccessCB() {
-    console.log("Synced!");
-}
-
-function serviceSyncFailCB() {
-    console.log("Sync failed!");
-}
-
-function servicesListSuccessCB(services) {
-    console.log("servicesListSuccessCB: received:" + services.length + " services");
-
-    if(services.length > 0) {
-        currentService = services[0];
-        console.log("servicesListSuccessCB: testing service:" + currentService.name);
-
-        currentService.messageStorage.addMessagesChangeListener(messageChangeCB);
-        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
-    } else {
-        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
-    }
-}
-
-tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
-
diff --git a/messaging/old/config.xml b/messaging/old/config.xml
deleted file mode 100755 (executable)
index aea0e73..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" ?>
-<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd">
-<plugin-properties>
-    <library-name>libwrt-plugins-tizen-messaging.so</library-name>
-    <feature-install-uri>messaging.install.uri</feature-install-uri>
-
-    <api-feature>
-        <name>http://tizen.org/privilege/messaging.read</name>
-        <device-capability>messaging.read</device-capability>
-    </api-feature>
-
-    <api-feature>
-        <name>http://tizen.org/privilege/messaging.send</name>
-        <device-capability>messaging.send</device-capability>
-    </api-feature>
-
-     <api-feature>
-        <name>http://tizen.org/privilege/messaging.write</name>
-        <device-capability>messaging.write</device-capability>
-    </api-feature>
-
-</plugin-properties>
diff --git a/messaging/old/plugin_config.cpp b/messaging/old/plugin_config.cpp
deleted file mode 100755 (executable)
index ecc4fc9..0000000
+++ /dev/null
@@ -1,302 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <map>
-#include <utility>
-#include <Commons/FunctionDefinition.h>
-#include <Commons/FunctionDeclaration.h>
-#include <Commons/Exception.h>
-#include "plugin_config.h"
-
-#define MESSAGING_FEATURE_API_READ "http://tizen.org/privilege/messaging.read"
-#define MESSAGING_FEATURE_API_SEND "http://tizen.org/privilege/messaging.send"    // before sendMessage move to write privilege start
-#define MESSAGING_FEATURE_API_WRITE "http://tizen.org/privilege/messaging.write"
-
-#define MESSAGING_DEVICE_CAP_READ "messaging.read"
-#define MESSAGING_DEVICE_CAP_SEND "messaging.send"    // before sendMessage move to write privilege start
-#define MESSAGING_DEVICE_CAP_WRITE "messaging.write"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-using namespace WrtDeviceApis::Commons;
-
-static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions();
-static WrtDeviceApis::Commons::FunctionMapping MessagingFunctions = createMessagingFunctions();
-
-#pragma GCC visibility push(default)
-
-DEFINE_FUNCTION_GETTER(Messaging, MessagingFunctions);
-
-#pragma GCC visibility pop
-
-static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions()
-{
-     /**
-     * Device capabilities
-     */
-
-    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_READ, MESSAGING_DEVICE_CAP_READ);
-    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_SEND, MESSAGING_DEVICE_CAP_SEND);
-    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_WRITE, MESSAGING_DEVICE_CAP_WRITE);
-
-    ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST);
-
-    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_READ);
-    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_READ, DEVICE_CAP_MESSAGING_READ);
-
-    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_SEND);
-    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_SEND, DEVICE_CAP_MESSAGING_SEND);
-
-    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_WRITE);
-    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_WRITE, DEVICE_CAP_MESSAGING_WRITE);
-
-    /**
-    * API features
-    */
-    ACE_CREATE_FEATURE(FEATURE_MESSAGING_READ, MESSAGING_FEATURE_API_READ);
-    ACE_CREATE_FEATURE(FEATURE_MESSAGING_SEND, MESSAGING_FEATURE_API_SEND);
-    ACE_CREATE_FEATURE(FEATURE_MESSAGING_WRITE, MESSAGING_FEATURE_API_WRITE);
-
-    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE);
-
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_READ);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_SEND);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_WRITE);
-
-    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ, FEATURE_MESSAGING_READ);
-
-    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_SEND);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND, FEATURE_MESSAGING_SEND);
-
-    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_WRITE);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_WRITE, FEATURE_MESSAGING_WRITE);
-
-// before sendMessage move to write privilege start
-    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_SEND_WRITE);
-
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND_WRITE, FEATURE_MESSAGING_SEND);
-    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND_WRITE, FEATURE_MESSAGING_WRITE);
-// before sendMessage move to write privilege end
-
-    /**
-     * Functions
-     */
-
-     FunctionMapping MessagingMapping;
-
-    //get Message Service
-    AceFunction getMessagingServiceFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
-            MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert(std::make_pair(
-            MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
-            getMessagingServiceFunc));
-
-      /**  Read  **/
-    AceFunction stopSyncFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_STOP_SYNC,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_STOP_SYNC,
-            stopSyncFunc));
-
-    AceFunction findMessagesFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_FIND_MESSAGES,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_FIND_MESSAGES,
-            findMessagesFunc));
-
-    AceFunction findConversationsFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_FIND_CONVERSATIONS,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_FIND_CONVERSATIONS,
-            findConversationsFunc));
-
-    AceFunction findFoldersFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_FIND_FOLDERS,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_FIND_FOLDERS,
-            findFoldersFunc));
-
-    AceFunction addMessagesChangeListenerFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER,
-            addMessagesChangeListenerFunc));
-
-    AceFunction addConversationsChangeListenerFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER,
-            addConversationsChangeListenerFunc));
-
-    AceFunction addFoldersChangeListenerFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER,
-            addFoldersChangeListenerFunc));
-
-    AceFunction removeChangeListenerFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER,
-            MESSAGING_FEATURES_MESSAGING_READ,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER,
-            removeChangeListenerFunc));
-
-    /**  Send  **/
-
-    // before sendMessage move to write privilege start
-    AceFunction sendMessageFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_SEND_MESSAGE,
-            MESSAGING_FEATURES_MESSAGING_SEND_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_SEND_MESSAGE,
-            sendMessageFunc));
-// before sendMessage move to write privilege end
-      /**  Write  **/
-    AceFunction loadMessageBodyFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY,
-            loadMessageBodyFunc));
-
-    AceFunction loadMessageAttachmentFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
-            loadMessageAttachmentFunc));
-
-    AceFunction syncFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_SYNC,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_SYNC,
-            syncFunc));
-
-    AceFunction syncFolderFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_SYNC_FOLDER,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_SYNC_FOLDER,
-            syncFolderFunc));
-
-    AceFunction addDraftMessageFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE,
-            addDraftMessageFunc));
-
-    AceFunction removeMessagesFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_REMOVE_MESSAGES,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_REMOVE_MESSAGES,
-            removeMessagesFunc));
-
-    AceFunction removeConversationsFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS,
-            removeConversationsFunc));
-
-    AceFunction updateMessagesFunc = ACE_CREATE_FUNCTION(
-            FUNCTION_GET_MGR_SERVICE,
-            MESSAGING_FUNCTION_API_UPDATE_MESSAGES,
-            MESSAGING_FEATURES_MESSAGING_WRITE,
-            EMPTY_DEVICE_LIST);
-
-    MessagingMapping.insert( std::make_pair(
-            MESSAGING_FUNCTION_API_UPDATE_MESSAGES,
-            updateMessagesFunc));
-
-    return MessagingMapping;
-}
-
-}
-}
-
-#undef MESSAGING_FEATURE_API
-#undef MESSAGING_FEATURE_API_READ
-#undef MESSAGING_FEATURE_API_SEND // before sendMessage move to write privilege start
-#undef MESSAGING_FEATURE_API_WRITE
-#undef MESSAGING_DEVICE_CAP_READ
-#undef MESSAGING_DEVICE_CAP_SEND // before sendMessage move to write privilege start
-#undef MESSAGING_DEVICE_CAP_WRITE
-
diff --git a/messaging/old/plugin_config.h b/messaging/old/plugin_config.h
deleted file mode 100755 (executable)
index c00107a..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef _MESSAGING_PLUGIN_CONFIG_H_
-#define _MESSAGING_PLUGIN_CONFIG_H_
-
-#include <Commons/FunctionDeclaration.h>
-#include <Security.h>
-#include "plugin_config_impl.h"
-
-namespace DeviceAPI {
-namespace Messaging {
-
-DECLARE_FUNCTION_GETTER(Messaging);
-
-#define MESSAGING_CHECK_ACCESS(functionName)   \
-    aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >(        \
-    getMessagingFunctionData,                                              \
-    functionName)
-
-}
-}
-
-#endif //MESSAGING_PLUGIN_CONFIG_H_
-
diff --git a/messaging/old/plugin_config_impl.h b/messaging/old/plugin_config_impl.h
deleted file mode 100755 (executable)
index 9ade59b..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#ifndef _MESSAGING_PLUGIN_CONFIG_IMPL_H_
-#define _MESSAGING_PLUGIN_CONFIG_IMPL_H_
-
-#define TIZEN_MESSAGING_MESSAGING_MANAGER_CLASS "messaging"
-#define TIZEN_MESSAGING_MESSAGE_INTERFACE "Message"
-#define TIZEN_MESSAGING_MESSAGE_ATTACHMENT_INTERFACE "MessageAttachment"
-
-// functions
-#define MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE "getMessageServices"
-#define MESSAGING_FUNCTION_API_SEND_MESSAGE "sendMessage"
-#define MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY "loadMessageBody"
-#define MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT "loadMessageAttachment"
-#define MESSAGING_FUNCTION_API_SYNC "sync"
-#define MESSAGING_FUNCTION_API_SYNC_FOLDER "syncFolder"
-#define MESSAGING_FUNCTION_API_STOP_SYNC "stopSync"
-#define MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE "addDraftMessage"
-#define MESSAGING_FUNCTION_API_FIND_MESSAGES "findMessages"
-#define MESSAGING_FUNCTION_API_REMOVE_MESSAGES "removeMessages"
-#define MESSAGING_FUNCTION_API_UPDATE_MESSAGES "updateMessages"
-#define MESSAGING_FUNCTION_API_FIND_CONVERSATIONS "findConversations"
-#define MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS "removeConversations"
-#define MESSAGING_FUNCTION_API_FIND_FOLDERS "findFolders"
-#define MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER "addMessagesChangeListener"
-#define MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER "addConversationsChangeListener"
-#define MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER "addFoldersChangeListener"
-#define MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER "removeChangeListener"
-
-#endif //MESSAGING_PLUGIN_CONFIG_IMPL_H_
-
diff --git a/messaging/old/plugin_initializer.cpp b/messaging/old/plugin_initializer.cpp
deleted file mode 100644 (file)
index e613aa7..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-//
-// Tizen Web Device API
-// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the License);
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-#include <Commons/plugin_initializer_def.h>
-#include <Commons/WrtAccess/WrtAccess.h>
-
-#include <GlobalContextManager.h>
-#include <Logger.h>
-#include <Security.h>
-#include <TimeTracer.h>
-
-#include "JSMessageAttachment.h"
-#include "JSMessage.h"
-#include "JSMessagingManager.h"
-#include "MessagingManager.h"
-
-#include "plugin_config.h"
-
-using namespace WrtDeviceApis;
-using namespace WrtDeviceApis::Commons;
-using namespace DeviceAPI::Common;
-
-namespace DeviceAPI {
-namespace Messaging {
-
-AceSecurityStatus messagingAceCheckAccessFunction(const char* functionName)
-{
-    return MESSAGING_CHECK_ACCESS(functionName);
-}
-
-DEFINE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor);
-
-DEFINE_SECURITY_ACCESSOR_SETTER(AceCheckerMessagingSetter, MessagingManager, gSecurityAccessor);
-
-class_definition_options_t MessagingOptions =
-{
-    JS_CLASS,
-    CREATE_INSTANCE,
-    ALWAYS_NOTICE,
-    USE_OVERLAYED, //ignored
-    AceCheckerMessagingSetter,
-    NULL,
-    NULL
-};
-
-class_definition_options_t MessagingInterfaceOptions = {
-    JS_INTERFACE,
-    CREATE_INSTANCE,
-    NONE_NOTICE,
-    USE_OVERLAYED, //ignored
-    NULL, // JSWidget::acquireGlobalContext,
-    NULL,
-    NULL
-};
-
-void on_widget_start_callback(int widgetId) {
-    LOGD("[Tizen\\MessagingManager] on_widget_start_callback (%d)", widgetId);
-    TIME_TRACER_INIT();
-    try {
-        WrtAccessSingleton::Instance().initialize(widgetId);
-    } catch (...) {
-        LOGE("WrtAccess initialization failed");
-    }
-    INITAILIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor, messagingAceCheckAccessFunction);
-}
-
-void on_widget_stop_callback(int widgetId) {
-    LOGD("[Tizen\\MessagingManager] on_widget_stop_callback (%d)", widgetId);
-    std::string name = "MessagingManager";
-    TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE, const_cast<char*>(name.c_str()));
-    TIME_TRACER_RELEASE();
-    try {
-        WrtAccessSingleton::Instance().deinitialize(widgetId);
-    } catch (...) {
-        LOGE("WrtAccess deinitialization failed");
-    }
-    FINALIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor);
-}
-
-void on_frame_load_callback(const void * context)
-{
-    LOGD("[Tizen\\MessagingManager] on_frame_load_callback (%p)", context);
-    DeviceAPI::Common::GlobalContextManager::getInstance()->
-            addGlobalContext(static_cast<JSContextRef>(context));
-}
-
-void on_frame_unload_callback(const void * context)
-{
-    LOGD("[Tizen\\MessagingManager] on_frame_unload_callback (%p)", context);
-    DeviceAPI::Common::GlobalContextManager::getInstance()->
-            removeGlobalContext(static_cast<JSContextRef>(context));
-}
-
-
-PLUGIN_ON_WIDGET_START(on_widget_start_callback)
-PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback)
-
-PLUGIN_ON_FRAME_LOAD(on_frame_load_callback)
-PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback)
-
-PLUGIN_CLASS_MAP_BEGIN
-PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN,
-        TIZEN_MESSAGING_MESSAGING_MANAGER_CLASS,
-        (js_class_template_getter)DeviceAPI::Messaging::JSMessagingManager::getClassRef,
-        &MessagingOptions)
-PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN,
-        TIZEN_MESSAGING_MESSAGE_INTERFACE,
-        (js_class_template_getter)DeviceAPI::Messaging::JSMessage::getClassRef,
-        (js_class_constructor_cb_t)DeviceAPI::Messaging::JSMessage::constructor,
-        &MessagingInterfaceOptions)
-PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN,
-        TIZEN_MESSAGING_MESSAGE_ATTACHMENT_INTERFACE,
-        (js_class_template_getter)DeviceAPI::Messaging::JSMessageAttachment::getClassRef,
-        (js_class_constructor_cb_t)DeviceAPI::Messaging::JSMessageAttachment::constructor,
-        &MessagingInterfaceOptions)
-PLUGIN_CLASS_MAP_END
-
-} // Messaging
-} // DeviceAPI
diff --git a/src/messaging/messaging.gyp b/src/messaging/messaging.gyp
new file mode 100644 (file)
index 0000000..bb817aa
--- /dev/null
@@ -0,0 +1,30 @@
+
+{
+  'includes':[
+    '../common/common.gypi',
+  ],
+  'targets': [
+    {
+      'target_name': 'tizen_messaging',
+      'type': 'loadable_module',
+      'sources': [
+        'messaging_api.js',
+        'messaging_instance.cc',
+        'messaging_instance.h',
+        'messaging_extension.cc',
+        'messaging_extension.h'
+      ],
+      'includes': [
+        '../common/pkg-config.gypi',
+      ],
+      'conditions': [
+        ['tizen == 1', {
+          'variables': {
+            'packages': [
+            ]
+          },
+        }],
+      ],
+    },
+  ],
+}
diff --git a/src/messaging/messaging_api.js b/src/messaging/messaging_api.js
new file mode 100644 (file)
index 0000000..17f85be
--- /dev/null
@@ -0,0 +1,469 @@
+// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+var validator_ = xwalk.utils.validator;
+var types_ = validator_.Types;
+
+function throwException_(err) {
+    throw new tizen.WebAPIException(err.code, err.name, err.message);
+}
+
+var Property = {
+    W: 1 << 0,   // WRITABLE
+    E: 1 << 1,   // ENUMERABLE
+    C: 1 << 2    // CONFIGURABLE
+}
+
+/**
+ * Example usage:
+ * function Messaging () {
+ *     propertyFactory_(this, 'ids', [2,3,4], Property.W | Property.E | Property.C);
+ *     propertyFactory_(this, 'name', 'Name', Property.E);
+ *     propertyFactory_(this, 'age', 25, Property.W);
+ *     propertyFactory_(this, 'something', 1);
+ * }
+ * Will produce:
+ * var m = new Messaging();
+ * {
+ *     id: [2,3,4],
+ *     name: 'Name',
+ *     age: 25
+ * }
+ *
+ * m.name = 'A brand new name';
+ * console.log(m.name); // Name
+ */
+function propertyFactory_(that, name, value, flags) {
+    flags = flags || 0;
+    var options = {value: value, writable: false, enumerable: false, configurable: false};
+    if ((flags & Property.W) === Property.W) options.writable = true;
+    if ((flags & Property.E) === Property.E) options.enumerable = true;
+    if ((flags & Property.C) === Property.C) options.configurable = true;
+
+    Object.defineProperty(
+        that,
+        name,
+        options
+    );
+}
+
+/*
+ *bridge is a two way communication interface
+ *Example usage:
+ *    To send sync method:
+ *    var result = bridge.sync({
+ *        cmd: 'my_cpp_function_symbol',
+ *        data: {
+ *            name: 'My name',
+ *            age: 28
+ *        }
+ *    });
+ *    console.log(result);
+ *
+ *    To send async method and handle response:
+ *    bridge.async({
+ *        cmd: 'my_cpp_function_symbol',
+ *        data: {
+ *            name: 'My name'
+ *        }
+ *    }).then({
+ *        success: function (data) {
+ *            var age = data.age;
+ *            args.successCallback(age);
+ *        },
+ *        error: function (e) {...},
+ *        someCallback: function (data) {...}
+ *    });
+ *bridge.async will add special param to passed data called cid
+ *that param need to be kept and returned with respons
+ *To determine which callback should be invoked, response should
+ *contain "action" param. Value of "action" param indicates name of
+ *triggered callback.
+ *Callbask are removed from listenr by defoult to prevent that behaviour
+ *param "keep" should be assigned to value true
+ *Example of c++ async response:
+ *    Simple succes with data:
+ *    {
+ *        cid: 23,
+ *        action: 'success',
+ *        data: {
+ *            age: 23
+ *        }
+ *    }
+ *    More complicated example:
+ *    {
+ *        cid: 23,
+ *        action: 'progress',
+ *        keep: true,
+ *        data: {
+ *            age: 23
+ *        }
+ *    }
+ */
+var bridge = (function (extension) {
+    var Callbacks = (function () {
+        var _collection = {};
+        var _cid = 0;
+        var _next = function () {
+            return (_cid += 1);
+        };
+
+        var CallbackManager = function () {};
+
+        CallbackManager.prototype = {
+            add: function (/*callbacks, cid?*/) {
+                console.log('bridge', 'CallbackManager', 'add');
+                var args = Array.prototype.slice.call(arguments);
+                console.dir('bridge', 'CallbackManager', 'add', args);
+                var c = args.shift();
+                var cid = args.pop();
+                if (cid) {
+                    if (c !== null && typeof c === 'object') {
+                        for (var key in c) {
+                            if (c.hasOwnProperty(key)) _collection[cid][key] = c[key];
+                        }
+                    }
+                } else {
+                    cid = _next();
+                    _collection[cid] = c;
+                }
+                return cid;
+            },
+            remove: function (cid) {
+                console.log('bridge', 'CallbackManager', 'remove');
+                if (_collection[cid]) delete _collection[cid];
+            },
+            call: function (cid, key, args, keep) {
+                console.log('bridge', 'CallbackManager', 'call');
+                var callbacks = _collection[cid];
+                keep = !!keep;
+                if (callbacks) {
+                    var fn = callbacks[key];
+                    if (fn) {
+                        fn.apply(null, args);
+                        if (!keep) this.remove(cid)
+                    }
+                }
+            }
+        };
+
+        return {
+            getInstance: function () {
+                return this.instance || (this.instance = new CallbackManager);
+            }
+        };
+    })();
+
+
+    var Listeners = (function () {
+        var _listeners = {};
+        var _id = 0;
+        var _next = function () {
+            return (_id += 1);
+        };
+
+        var ListenerManager = function () {};
+
+        ListenerManager.prototype = {
+            add: function (l) {
+                console.log('bridge', 'ListenerManager', 'add');
+                var id = _next();
+                _listeners[id] = l;
+                return id;
+            },
+            resolve: function (id, action, data, keep) {
+                console.log('bridge', 'ListenerManager', 'resolve');
+                keep = !!keep;
+                var l = _listeners[id];
+                if (l) {
+                    var cm = Callbacks.getInstance();
+                    cm.call(l.cid, action, [data], keep);
+                }
+                return l;
+            },
+            remove: function (id) {
+                console.log('bridge', 'ListenerManager', 'remove');
+                var l = _listeners[id];
+                if (l) {
+                    var cm = Callbacks.getInstance();
+                    if (l.cid) cm.remove(l.cid);
+                    delete _listeners[id];
+                }
+            }
+        }
+
+        return {
+            getInstance: function () {
+                return this.instance || (this.instance = new ListenerManager);
+            }
+        };
+    })();
+
+    var Listener = function () {
+        console.log('bridge', 'Listener constructor');
+        this.cid = null;
+    };
+    Listener.prototype = {
+        then: function (c) {
+            console.log('bridge', 'Listener', 'then');
+            var cm = Callbacks.getInstance();
+            this.cid = cm.add(c, this.cid);
+            return this;
+        }
+    };
+
+    var Bridge = function () {};
+    Bridge.prototype = {
+        sync: function (data) {
+            console.log('bridge', 'sync');
+            var result = extension.internal.sendSyncMessage(JSON.stringify(data));
+            var obj = JSON.parse(result);
+            if (obj.error)
+                throw new tizen.WebAPIException(obj.code, obj.name, obj.message);
+            return obj.result;
+        },
+        async: function (data) {
+            console.log('bridge', 'async');
+            var l = new Listener();
+            data.cid = Listeners.getInstance().add(l);
+            setTimeout(function () {
+                extension.postMessage(JSON.stringify(data));
+            });
+            return l;
+        }
+    };
+
+    extension.setMessageListener(function (json) {
+        /*
+         *Expected response:
+         *{
+         *    cid: 23,                        // callback id
+         *    action: 'success',              // expected callback action
+         *    keep: false                     // optional param
+         *    data: {...}                     // data pased to callback
+         *}
+         */
+
+        console.log('bridge', 'setMessageListener', json);
+        var data = JSON.parse(json);
+        if (data.cid && data.action) {
+            Listeners.getInstance().resolve(data.cid, data.action, data.data, data.keep);
+        }
+    });
+
+    return new Bridge;
+})(extension);
+
+/**
+ * Specifies the Messaging service tags.
+ */
+var MessageServiceTag = ['messaging.sms', 'messaging.mms', 'messaging.email'];
+
+function Messaging() {};
+
+/**
+ * Gets the messaging service of a given type for a given account.
+ * @param {!MessageServiceTag} messageServiceType Type of the services to be retrieved.
+ * @param {!MessageServiceArraySuccessCallback} successCallback Callback function that is called
+ *     when the services are successfully retrieved.
+ * @param {ErrorCallback} errorCallback Callback function that is called when an error occurs.
+ */
+Messaging.prototype.getMessageServices = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'messageServiceType', type: types_.ENUM, values: MessageServiceTag},
+        {name: 'successCallback', type: types_.FUNCTION},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+    ]);
+
+    bridge.async({
+        cmd: 'Messaging_getMessageServices',
+        data: {
+            messageServiceType: args.messageServiceType
+        }
+    }).then({
+        success: function (data) {
+            args.successCallback.call(null, new MessageService(data));
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+}
+
+function MessageService(data) {
+    propertyFactory_(this, 'id', data.id, Property.E);
+    propertyFactory_(this, 'type', data.type, Property.E);
+    propertyFactory_(this, 'name', data.name, Property.E);
+    propertyFactory_(this, 'messageStorage', new MessageStorage(data.messageStorage), Property.E);
+};
+
+MessageService.prototype.sendMessage = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message},
+        {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'simIndex', type: types_.LONG, optional: true, nullable: true}
+    ]);
+
+    bridge.async({
+        cmd: 'MessageService_sendMessage',
+        data: {
+            message: args.message,
+            simIndex: args.simIndex
+        }
+    }).then({
+        success: function (data) {
+            if (args.successCallback) {
+                args.successCallback.call(null, data.recipients);
+            }
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+};
+
+MessageService.prototype.loadMessageBody = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message},
+        {name: 'successCallback', type: types_.FUNCTION},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+    ]);
+
+    bridge.async({
+        cmd: 'MessageService_loadMessageBodu',
+        data: {
+            message: args.message
+        }
+    }).then({
+        success: function (data) {
+            args.successCallback.call(
+                null,
+                new tizen.Message(data.type, new MessageInit_(data.messageInit))
+            );
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+};
+MessageService.prototype.loadMessageAttachment = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'attachment', type: types_.PLATFORM_OBJECT, values: tizen.MessageAttachment},
+        {name: 'successCallback', type: types_.FUNCTION},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+    ]);
+
+    bridge.async({
+        cmd: 'MessageService_loadMessageAttachment',
+        data: {
+            attachment: args.attachment
+        }
+    }).then({
+        success: function (data) {
+            if (args.successCallback) {
+                // TODO problem with MessageAttachment Constructor need to be investigated
+                args.successCallback.call(
+                    null,
+                    new MessageAttachment(data.filePath, data.mimeType)
+                );
+            }
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+};
+MessageService.prototype.sync = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+    ]);
+
+    bridge({
+        cmd: 'MessageService_sync',
+        data: {
+            limit: args.limit
+        }
+    }).then({
+        success: function () {
+            if (args.successCallback) {
+                args.successCallback.call(null);
+            }
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+};
+MessageService.prototype.syncFolder = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'folder', type: types_.PLATFORM_OBJECT, values: MessageFolder},
+        {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
+        {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+    ]);
+
+    bridge.async({
+        cmd: 'MessageService_syncFolder',
+        data: {
+            folder: args.folder,
+            limit: args.limit
+        }
+    }).then({
+        success: function () {
+            if (args.successCallback) {
+                args.successCallback.call(null);
+            }
+        },
+        error: function (e) {
+            if (args.errorCallback) {
+                args.errorCallback.call(
+                    null,
+                    new tizen.WebAPIException(e.code, e.name, e.message)
+                )
+            }
+        }
+    });
+};
+MessageService.prototype.stopSync = function () {
+    var args = validator_.validateArgs(arguments, [
+        {name: 'opId', type: types_.LONG}
+    ]);
+
+    bridge.sync({
+        cmd: 'MessageService_stopSync',
+        data: {
+            opId: args.opId
+        }
+    });
+};
+
+exports = new Messaging();
diff --git a/src/messaging/messaging_extension.cc b/src/messaging/messaging_extension.cc
new file mode 100644 (file)
index 0000000..3b42c82
--- /dev/null
@@ -0,0 +1,25 @@
+// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "messaging_extension.h"
+
+#include "messaging_instance.h"
+
+// This will be generated from time_api.js.
+extern const char kSource_messaging_api[];
+
+common::Extension* CreateExtension() {
+  return new MessagingExtension;
+}
+
+MessagingExtension::MessagingExtension() {
+  SetExtensionName("tizen.messaging");
+  SetJavaScriptAPI(kSource_messaging_api);
+}
+
+MessagingExtension::~MessagingExtension() {}
+
+common::Instance* MessagingExtension::CreateInstance() {
+  return new extension::messaging::MessagingInstance;
+}
diff --git a/src/messaging/messaging_extension.h b/src/messaging/messaging_extension.h
new file mode 100644 (file)
index 0000000..ebf1691
--- /dev/null
@@ -0,0 +1,20 @@
+// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef MESSAGING_MESSAGING_EXTENSION_H_
+#define MESSAGING_MESSAGING_EXTENSION_H_
+
+#include "common/extension.h"
+
+class MessagingExtension : public common::Extension {
+ public:
+  MessagingExtension();
+  virtual ~MessagingExtension();
+
+ private:
+  virtual common::Instance* CreateInstance();
+};
+
+#endif // MESSAGING_MESSAGING_EXTENSION_H_
+
diff --git a/src/messaging/messaging_instance.cc b/src/messaging/messaging_instance.cc
new file mode 100644 (file)
index 0000000..275f5e9
--- /dev/null
@@ -0,0 +1,17 @@
+
+// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "messaging_instance.h"
+
+namespace extension {
+namespace messaging {
+
+MessagingInstance::MessagingInstance() {}
+
+MessagingInstance::~MessagingInstance() {}
+
+} // namespace messaging
+} // namespace extension
+
diff --git a/src/messaging/messaging_instance.h b/src/messaging/messaging_instance.h
new file mode 100644 (file)
index 0000000..0b41021
--- /dev/null
@@ -0,0 +1,22 @@
+// Copyright 2014 Samsung Electronics Co, Ltd. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef MESSAGING_MESSAGING_INSTANCE_H_
+#define MESSAGING_MESSAGING_INSTANCE_H_
+
+#include "common/extension.h"
+
+namespace extension {
+namespace messaging {
+
+class MessagingInstance : public common::ParsedInstance {
+    public:
+        MessagingInstance();
+        virtual ~MessagingInstance();
+};
+
+} // namespace messaging
+} // namespace extension
+
+#endif // MESSAGING_MESSAGING_INSTANCE_H_
diff --git a/src/messaging/old/BaseFilterVisitor.cpp b/src/messaging/old/BaseFilterVisitor.cpp
new file mode 100644 (file)
index 0000000..47ab777
--- /dev/null
@@ -0,0 +1,236 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        BaseFilterVisitor.cpp
+ */
+
+#include "BaseFilterVisitor.h"
+#include <Logger.h>
+#include <cstring>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+inline std::string convertToLowerCase(const std::string& input_string)
+{
+    std::string outputString=input_string;
+    outputString.reserve(input_string.length());
+    std::transform(outputString.begin(), outputString.end(), outputString.begin(),
+            ::tolower);
+    return outputString;
+}
+
+BaseFilterVisitor::BaseFilterVisitor()
+{
+}
+
+BaseFilterVisitor::~BaseFilterVisitor()
+{
+}
+
+void BaseFilterVisitor::visitPreComposite(Tizen::FilterType& type, int depth)
+{
+    LOGD("Entered");
+    m_operand_list.push_back(FCO_START);
+}
+
+void BaseFilterVisitor::visitInComposite(Tizen::FilterType& type, int depth)
+{
+    LOGD("Entered");
+    if(Tizen::UNION_FILTER == type) {
+        m_operand_list.push_back(FCO_OR);
+        LOGD("operand OR");
+    }else if(Tizen::INTERSECTION_FILTER == type) {
+        LOGD("operand AND");
+        m_operand_list.push_back(FCO_AND);
+    } else {
+        LOGE("Invalid filter type:%d", type);
+    }
+}
+
+void BaseFilterVisitor::visitPostComposite(Tizen::FilterType& type, int depth)
+{
+    LOGD("Entered");
+    LOGD("Start: numResults:%d numOperands:%d", m_result_list.size(),
+            m_operand_list.size());
+
+    while(m_operand_list.back() != FCO_START) {
+
+        const bool left =  m_result_list.back();
+        m_result_list.pop_back();
+        const bool right =  m_result_list.back();
+        m_result_list.pop_back();
+        const FilterCompositeOperand& operand = m_operand_list.back();
+        m_operand_list.pop_back();
+
+        bool result = false;
+        if(FCO_AND == operand) {
+            result = left && right;
+        } else if(FCO_OR == operand) {
+            result = left || right;
+        }
+        m_result_list.push_back(result);
+    }
+
+    m_operand_list.pop_back(); //remove FCO_START
+    LOGD("End: numResults:%d numOperands:%d", m_result_list.size(),
+            m_operand_list.size());
+}
+
+void BaseFilterVisitor::testStringMatch(const std::string& key,
+        const std::string& value,
+        Tizen::MatchFlag flag)
+{
+    m_result_list.push_back(matchString(key, value, flag));
+}
+
+void BaseFilterVisitor::testAnyStringMatch(const std::string& key,
+        const std::vector<std::string>& values,
+        Tizen::MatchFlag flag)
+{
+    m_result_list.push_back(matchStringVector(key, values, flag));
+}
+
+void BaseFilterVisitor::testTimeStampIsInRange(const time_t& timeStamp,
+            Tizen::AnyPtr& initialValue, Tizen::AnyPtr& endValue)
+{
+    m_result_list.push_back(matchTimeStampRange(timeStamp, initialValue, endValue));
+}
+
+bool BaseFilterVisitor::matchString(const std::string& key,
+        const std::string& value,
+        Tizen::MatchFlag flag)
+{
+    bool res = false;
+
+    switch(flag)
+    {
+        case Tizen::MATCH_ENDSWITH: {
+            if (key.empty()) return false;
+            if (key.size() > value.size()) return false;
+            std::string lvalue = convertToLowerCase(value);
+            std::string lkey = convertToLowerCase(key);
+            res = lvalue.substr(lvalue.size() - lkey.size(), lkey.size()) == lkey;
+        } break;
+
+        case Tizen::MATCH_EXACTLY: {
+            res = key == value;
+        } break;
+
+        case Tizen::MATCH_STARTSWITH: {
+            if (key.empty()) return false;
+            if (key.size() > value.size()) return false;
+            std::string lvalue = convertToLowerCase(value);
+            std::string lkey = convertToLowerCase(key);
+            res = lvalue.substr(0, lkey.size()) == lkey;
+        } break;
+
+        case Tizen::MATCH_CONTAINS: {
+            if (key.empty()) return false;
+            if (key.size() > value.size()) return false;
+            std::string lvalue = convertToLowerCase(value);
+            std::string lkey = convertToLowerCase(key);
+            res = lvalue.find(lkey) != std::string::npos;
+        } break;
+
+        default: {
+            LOGE("Unknown match flag");
+            res =  false;
+        } break;
+    }
+
+    LOGD("key:%s value:%s matchFlag:%d RESULT:%d", key.c_str(), value.c_str(), flag, res);
+    return res;
+}
+
+bool BaseFilterVisitor::matchStringVector(const std::string& key,
+        const std::vector<std::string>& values,
+        Tizen::MatchFlag flag)
+{
+    for(auto it = values.begin(); it != values.end(); ++it) {
+        if(matchString(key,*it,flag)) {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool BaseFilterVisitor:: matchTimeStampRange(const time_t& timeStamp,
+        Tizen::AnyPtr& initialValue, Tizen::AnyPtr& endValue)
+{
+    time_t from_time;
+    time_t to_time;
+
+    if (initialValue && !initialValue->isNullOrUndefined() &&
+            initialValue->isType(DeviceAPI::Tizen::PrimitiveType_Time)) {
+        struct tm ftime = *initialValue->getDateTm();
+        from_time = mktime(&ftime);
+    } else {
+        LOGE("initialValue is not Time!");
+        throw Common::InvalidValuesException("initialValue is not Time!");
+    }
+
+    if (endValue && !endValue->isNullOrUndefined() &&
+            endValue->isType(DeviceAPI::Tizen::PrimitiveType_Time) ) {
+        struct tm ttime = *endValue->getDateTm();
+        to_time = mktime(&ttime);
+    } else {
+        LOGE("endValue is not Time!");
+        throw Common::InvalidValuesException("endValue is not Time!");
+    }
+
+    bool isInRange = isBetweenTimeRange(timeStamp, from_time, to_time);
+
+    LOGD("%d is%s in time range <%d, %d>", timeStamp, (isInRange ? "" : " NOT"),
+            from_time, to_time);
+
+    return isInRange;
+}
+
+bool BaseFilterVisitor::isMatched()
+{
+    if(m_result_list.empty()) {
+        LOGW("m_result_list is empty!");
+        return false;
+    }
+    return m_result_list.back();
+}
+
+std::string BaseFilterVisitor::formatResultListChangeLog(const size_t old_res_count)
+{
+    const size_t new_res_count = m_result_list.size();
+    const int delta = new_res_count - old_res_count;
+    std::ostringstream oss;
+
+    if(delta > 0) {
+        oss << "m_result_list added: "<< delta << " {" << std::endl;
+        std::vector<bool>::reverse_iterator rit = m_result_list.rbegin();
+        for(size_t i = 0; i < delta; ++i, ++rit) {
+            const bool result = *rit;
+            oss << "    [LAST -" << (delta - (i+1)) <<"] added: "<< result;
+        }
+        oss << "}" << std::endl;
+    } else if(delta < 0) {
+        oss <<"m_result_list removed: "<< delta;
+    }
+
+    return oss.str();
+}
+
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/CMakeLists.txt b/src/messaging/old/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..e9c8ec3
--- /dev/null
@@ -0,0 +1,106 @@
+SET(TARGET_NAME ${messaging_target})
+SET(DESTINATION_NAME ${messaging_dest})
+SET(TARGET_IMPL_NAME ${messaging_impl})
+
+PKG_CHECK_MODULES(platform_pkgs_messaging REQUIRED msg-service email-service
+                  dbus-1 capi-system-info dbus-glib-1 tapi)
+
+ADD_DEFINITIONS("-fvisibility=hidden")
+
+SET(INCLUDE_DIRS
+    ${filesystem_include}
+    ${messaging_include}
+    ${tizen_include}
+    ${platform_pkgs_messaging_INCLUDE_DIRS}
+)
+
+INCLUDE_DIRECTORIES(${INCLUDE_COMMON} ${INCLUDE_DIRS})
+MESSAGE(STATUS "${TARGET_NAME} module includes: INCLUDE_COMMON ${INCLUDE_DIRS}")
+
+SET(CMAKE_INSTALL_RPATH
+    ${CMAKE_INSTALL_RPATH}
+    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${filesystem_dest}
+    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest}
+    ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}
+)
+
+SET(SRCS_IMPL
+    ChangeListenerContainer.cpp
+    JSMessagingManager.cpp
+    MessagingManager.cpp
+    JSMessage.cpp
+    JSMessageAttachment.cpp
+    JSMessageBody.cpp
+    JSMessageConversation.cpp
+    JSMessageFolder.cpp
+    JSMessageService.cpp
+    MessageService.cpp
+    MessageServiceShortMsg.cpp
+    MessageServiceEmail.cpp
+    ShortMsgManager.cpp
+    EmailManager.cpp
+    MessageCallbackUserData.cpp
+    MessagesCallbackUserData.cpp
+    ConversationCallbackData.cpp
+    FoldersCallbackData.cpp
+    JSMessageStorage.cpp
+    MessageStorage.cpp
+    MessageStorageEmail.cpp
+    MessageStorageShortMsg.cpp
+    MessagingUtil.cpp
+    JSMessageAttachment.cpp
+    MessageAttachment.cpp
+    Message.cpp
+    MessageEmail.cpp
+    MessageMMS.cpp
+    MessageSMS.cpp
+    MessageConversation.cpp
+    MessageBody.cpp
+    MessageFolder.cpp
+    JSMessageFolder.cpp
+    MessagesChangeCallback.cpp
+    ConversationsChangeCallback.cpp
+    FoldersChangeCallback.cpp
+    FindMsgCallbackUserData.cpp
+    DBus/Connection.cpp
+    DBus/Proxy.cpp
+    DBus/SyncProxy.cpp
+    DBus/LoadBodyProxy.cpp
+    DBus/LoadAttachmentProxy.cpp
+    DBus/EmailSignalProxy.cpp
+    DBus/MessageProxy.cpp
+    DBus/SendProxy.cpp
+    MessagingDatabaseManager.cpp
+)
+
+ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL})
+
+SET(LINK_LIBS
+    ${LIBS_WIDGETDB}
+    ${filesystem_config}
+    ${filesystem_impl}
+    ${tizen_impl}
+    ${platform_pkgs_messaging_LIBRARIES}
+)
+
+TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} ${LIBS_COMMON} ${LINK_LIBS})
+MESSAGE(STATUS "${TARGET_NAME} module links: LIBS_COMMON ${LINK_LIBS}")
+
+SET(SRCS
+    plugin_config.cpp
+    plugin_initializer.cpp
+)
+
+ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS})
+
+TARGET_LINK_LIBRARIES(${TARGET_NAME}
+    ${TARGET_IMPL_NAME}
+    "-Wl,--no-as-needed" ${filesystem_config}
+)
+
+INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME})
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME})
+INSTALL(
+    DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/messaging
+    FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE
+)
diff --git a/src/messaging/old/ChangeListenerContainer.cpp b/src/messaging/old/ChangeListenerContainer.cpp
new file mode 100644 (file)
index 0000000..ef32e51
--- /dev/null
@@ -0,0 +1,456 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "ChangeListenerContainer.h"
+
+#include <Logger.h>
+#include "EmailManager.h"
+#include "ShortMsgManager.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+ChangeListenerContainer& ChangeListenerContainer::getInstance()
+{
+    EmailManager::getInstance(); //make sure that callbacks are registered in email-service
+    ShortMsgManager::getInstance(); //make sure that callbacks are registered in msg-service
+    static ChangeListenerContainer clc;
+    return clc;
+}
+
+ChangeListenerContainer::ChangeListenerContainer():
+        m_current_id(0)
+{
+    LOGD("Entered");
+    // call getNextId() function to properly initialize static mutex inside
+    getNextId();
+}
+
+// --- Listeners registration functions ---
+long ChangeListenerContainer::addMessageChangeListener(
+        std::shared_ptr<MessagesChangeCallback> callback)
+{
+    LOGD("Entered");
+    // Check type of service for which listener should be registered
+    // and lock appropriate mutex
+    MessageType mtype = callback->getServiceType();
+    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
+    {
+        std::lock_guard<std::mutex> lock(m_short_lock);
+        int new_id = getNextId();
+        m_short_message_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
+        return new_id;
+    }
+    else if (MessageType(EMAIL) == mtype) {
+        std::lock_guard<std::mutex> lock(m_email_lock);
+        int new_id = getNextId();
+        m_email_message_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for Email, watchId: %d", new_id);
+        return new_id;
+    }
+    LOGE("Listener with invalid MessageService type - failed to register");
+    return -1;
+}
+
+long ChangeListenerContainer::addConversationChangeListener(
+        std::shared_ptr<ConversationsChangeCallback> callback)
+{
+    LOGD("Entered");
+    // Check type of service for which listener should be registered
+    // and lock appropriate mutex
+    MessageType mtype = callback->getServiceType();
+    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
+    {
+        std::lock_guard<std::mutex> lock(m_short_lock);
+        int new_id = getNextId();
+        m_short_conversation_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
+        return new_id;
+    }
+    else if (MessageType(EMAIL) == mtype) {
+        std::lock_guard<std::mutex> lock(m_email_lock);
+        int new_id = getNextId();
+        m_email_conversation_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for Email, watchId: %d", new_id);
+        return new_id;
+    }
+    LOGE("Listener with invalid MessageService type - failed to register");
+    return -1;
+}
+
+long ChangeListenerContainer::addFolderChangeListener(
+        std::shared_ptr<FoldersChangeCallback> callback)
+{
+    LOGD("Entered");
+    // Check type of service for which listener should be registered
+    // and lock appropriate mutex
+    MessageType mtype = callback->getServiceType();
+    if (MessageType(SMS) == mtype || MessageType(MMS) == mtype)
+    {
+        std::lock_guard<std::mutex> lock(m_short_lock);
+        int new_id = getNextId();
+        m_short_folder_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for ShortMessage, watchId: %d", new_id);
+        return new_id;
+    }
+    else if (MessageType(EMAIL) == mtype) {
+        std::lock_guard<std::mutex> lock(m_email_lock);
+        int new_id = getNextId();
+        m_email_folder_callbacks.insert(std::make_pair(new_id, callback));
+        LOGD("Added callback for Email, watchId: %d", new_id);
+        return new_id;
+    }
+    LOGE("Listener with invalid MessageService type - failed to register");
+    return -1;
+}
+
+// --- listeners removal ---
+void ChangeListenerContainer::removeChangeListener(JSContextRef context, long id)
+{
+    LOGD("Entered");
+    // Lock both types of collections - id does not indicate service type
+    // TODO: consider additional map<listener_id, service_type> or
+    //       map<lister_id, map<>&> to provide faster and less complicated removal
+    std::lock_guard<std::mutex> shortlock(m_short_lock);
+    std::lock_guard<std::mutex> maillock(m_email_lock);
+    LOGD("Locks done");
+    if(id<0 || id > m_current_id) {
+        LOGE("Invalid id %d given.", id);
+        return;
+    }
+    if (removeCallbackIfExists<MessagesChangeCallback>(
+            context, m_short_message_callbacks,id)) {
+        LOGD("ShortMessage message listener with id: %d removed", id);
+    }
+    else if (removeCallbackIfExists<ConversationsChangeCallback>(
+            context, m_short_conversation_callbacks, id)) {
+        LOGD("ShortMessage conversation listener with id: %d removed", id);
+    }
+    else if (removeCallbackIfExists<FoldersChangeCallback>(
+            context, m_short_folder_callbacks, id)) {
+        LOGD("ShortMessage folder listener with id: %d removed", id);
+    }
+    else if (removeCallbackIfExists<MessagesChangeCallback>(
+            context, m_email_message_callbacks, id)) {
+        LOGD("Email message listener with id: %d removed", id);
+    }
+    else if (removeCallbackIfExists<ConversationsChangeCallback>(
+            context, m_email_conversation_callbacks, id)) {
+        LOGD("Email conversation listener with id: %d removed", id);
+    }
+    else if (removeCallbackIfExists<FoldersChangeCallback>(
+            context, m_email_folder_callbacks,id)) {
+        LOGD("Email folder listener with id: %d removed", id);
+    }
+    else {
+        LOGW("WatchId %d not found", id);
+    }
+}
+
+// --- Callback invoking functions ---
+// -- for message --
+void ChangeListenerContainer::callMessageAdded(EventMessages* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling messageadded for ShortMessage");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_message_callbacks;
+        }
+        callAdded<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling messageadded for Email");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_message_callbacks;
+        }
+        callAdded<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+void ChangeListenerContainer::callMessageUpdated(EventMessages* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling messageupdated for ShortMessage");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_message_callbacks;
+        }
+        callUpdated<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling messageupdated for Email");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_message_callbacks;
+        }
+        callUpdated<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+void ChangeListenerContainer::callMessageRemoved(EventMessages* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling messageremoved for ShortMessage");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_message_callbacks;
+        }
+        callRemoved<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling messageremoved for Email");
+        MCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_message_callbacks;
+        }
+        callRemoved<MessagesChangeCallback, EventMessages>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+// -- for conversation --
+void ChangeListenerContainer::callConversationAdded(EventConversations* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling converationadded for ShortMessage");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_conversation_callbacks;
+        }
+        callAdded<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling conversationadded for Email");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_conversation_callbacks;
+        }
+        callAdded<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+void ChangeListenerContainer::callConversationUpdated(EventConversations* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling conversationupdated for ShortConversation");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_conversation_callbacks;
+        }
+        callUpdated<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling conversationupdated for Email");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_conversation_callbacks;
+        }
+        callUpdated<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+void ChangeListenerContainer::callConversationRemoved(EventConversations* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling conversationremoved for ShortConversation");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            LOGD("m_short_conversation_callbacks.size() = %d",
+                    m_short_conversation_callbacks.size());
+
+            callbacksCopy = m_short_conversation_callbacks;
+        }
+        callRemoved<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling conversationremoved for Email");
+        CCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            LOGD("m_email_conversation_callbacks.size() = %d",
+                m_email_conversation_callbacks.size());
+
+            callbacksCopy = m_email_conversation_callbacks;
+        }
+        callRemoved<ConversationsChangeCallback, EventConversations>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+// -- for folder --
+void ChangeListenerContainer::callFolderAdded(EventFolders* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling folderadded for ShortMessage");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_folder_callbacks;
+        }
+        callAdded<FoldersChangeCallback, EventFolders>(
+                m_short_folder_callbacks, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling folderadded for Email");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_folder_callbacks;
+        }
+        callAdded<FoldersChangeCallback, EventFolders>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+
+void ChangeListenerContainer::callFolderUpdated(EventFolders* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling folderupdated for ShortFolder");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_folder_callbacks;
+        }
+        callUpdated<FoldersChangeCallback, EventFolders>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling folderupdated for Email");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_folder_callbacks;
+        }
+        callUpdated<FoldersChangeCallback, EventFolders>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+void ChangeListenerContainer::callFolderRemoved(EventFolders* event)
+{
+    LOGD("Entered");
+
+    if(MessageType(SMS) == event->service_type ||
+            MessageType(MMS) == event->service_type) {
+        LOGD("Calling folderremoved for ShortFolder");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> shortlock(m_short_lock);
+            callbacksCopy = m_short_folder_callbacks;
+        }
+        callRemoved<FoldersChangeCallback, EventFolders>(
+                callbacksCopy, event);
+    }
+    else if(MessageType(EMAIL) == event->service_type) {
+        LOGD("Calling folderremoved for Email");
+        FCLmap callbacksCopy;
+        {
+            std::lock_guard<std::mutex> maillock(m_email_lock);
+            callbacksCopy = m_email_folder_callbacks;
+        }
+        callRemoved<FoldersChangeCallback, EventFolders>(
+                callbacksCopy, event);
+    }
+    else {
+        LOGW("Invalid event type (%d) - no callback called.", event->service_type);
+    }
+}
+
+int ChangeListenerContainer::getNextId() {
+    // mutex is created only on first call (first call added to constructor
+    // to initialize mutex correctly
+    static std::mutex id_mutex;
+    std::lock_guard<std::mutex> idlock(id_mutex);
+
+    return m_current_id++;
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/ChangeListenerContainer.h b/src/messaging/old/ChangeListenerContainer.h
new file mode 100755 (executable)
index 0000000..3fd7831
--- /dev/null
@@ -0,0 +1,251 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_CHANGE_LISTENER_CONTAINER_H__
+#define __TIZEN_CHANGE_LISTENER_CONTAINER_H__
+
+#include <memory>
+#include <mutex>
+#include <vector>
+#include <map>
+#include <Logger.h>
+#include <GlobalContextManager.h>
+
+#include "Message.h"
+#include "MessageConversation.h"
+#include "MessageFolder.h"
+#include "MessagingUtil.h"
+#include "MessagesChangeCallback.h"
+#include "ConversationsChangeCallback.h"
+#include "FoldersChangeCallback.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+//! Data related to MessageChange event passed to add/update/remove callbacks
+struct EventMessages {
+    int service_id;
+    MessageType service_type;
+    MessagePtrVector items;
+    ConversationPtrVector removed_conversations;
+    // TODO: Filtering support
+};
+
+//! Data related to ConversationChange event passed to add/update/remove callbacks
+struct EventConversations {
+    int service_id;
+    MessageType service_type;
+    ConversationPtrVector items;
+    // TODO: Filtering support
+};
+
+//! Data related to FolderChange event passed to add/update/remove callbacks
+struct EventFolders {
+    int service_id;
+    MessageType service_type;
+    FolderPtrVector items;
+    // TODO: Filtering support
+};
+
+template <class T > struct CallbackDataHolder {
+    std::shared_ptr<T> ptr;
+    int operation_type;
+};
+
+//! Map that stores MessageChangeListeners
+typedef std::map<long, std::shared_ptr<MessagesChangeCallback>> MCLmap;
+//! Map that stores ConversationsChangeListeners
+typedef std::map<long, std::shared_ptr<ConversationsChangeCallback>> CCLmap;
+//! Map that stores FoldersChangeListeners
+typedef std::map<long, std::shared_ptr<FoldersChangeCallback>> FCLmap;
+
+
+/**
+ * Singleton class for managing (storing and calling) ChangeListeners for
+ * short message (SMS/MMS) service and email service.
+ *
+ * Two mutexes used to lock separately addition and searching of Short and
+ * Email message related listeners. Listeneres removal functions locks access
+ * to both types of listeners (havind listener id only it is not possible
+ * to determine message (service) type.
+ */
+class ChangeListenerContainer {
+    public:
+        static ChangeListenerContainer& getInstance();
+
+
+        // Interface for listener's manipulation (registration and removal).
+        long addMessageChangeListener(std::shared_ptr<MessagesChangeCallback> callback);
+        long addConversationChangeListener(std::shared_ptr<ConversationsChangeCallback> callback);
+        long addFolderChangeListener(std::shared_ptr<FoldersChangeCallback> callback);
+        void removeChangeListener(JSContextRef context, long id);
+
+        // Methods used to invoke registered listeners
+        void callMessageAdded(EventMessages* event);
+        void callMessageUpdated(EventMessages* event);
+        void callMessageRemoved(EventMessages* event);
+        void callConversationAdded(EventConversations* event);
+        void callConversationUpdated(EventConversations* event);
+        void callConversationRemoved(EventConversations* event);
+        void callFolderAdded(EventFolders* event);
+        void callFolderUpdated(EventFolders* event);
+        void callFolderRemoved(EventFolders* event);
+
+    private:
+        //! Highest used id (in most cases id of last registered listener)
+        long m_current_id;
+        //! Mutex for preventing race conditions on SMS/MMS callbacks collection
+        std::mutex m_short_lock;
+        //! Mutex for preventing race conditions on email callbacks collection
+        std::mutex m_email_lock;
+
+        //! Functions for listener id incrementation with thread safe mutex locking
+        int getNextId();
+
+        /* Callbacks for emails and short messages should be stored in separate
+         * collections to simplyfy adding ang searching on call */
+
+        // Callbacks for short messages service
+        MCLmap m_short_message_callbacks;
+        CCLmap m_short_conversation_callbacks;
+        FCLmap m_short_folder_callbacks;
+
+        // Callbacks for email service
+        MCLmap m_email_message_callbacks;
+        CCLmap m_email_conversation_callbacks;
+        FCLmap m_email_folder_callbacks;
+
+        ChangeListenerContainer();
+
+        template<class T> static bool removeCallbackIfExists(
+                JSContextRef context, std::map<long,std::shared_ptr<T>>& collection, long id ) {
+            LOGD("Entered");
+
+            JSContextRef g_ctx = Common::GlobalContextManager::getInstance()->
+                    getGlobalContext(context);
+            auto itr = collection.find(id);
+            if ( itr != collection.end()) {
+                if(itr->second->getContext() == g_ctx){
+                    itr->second->setActive(false);
+                    collection.erase(id);
+                    return true;
+                } else {
+                    LOGE("Removing callback which does not belong to the current context is not allowed.");
+                    throw Common::NotFoundException(
+                            "Removing callback which does not belong to the current context is not allowed.");
+                }
+            }
+            return false;
+        }
+
+        /* Templates below written for code reusage (each template is used
+         * 2 times in each callXxxx[Added | Removed | Updated] function. */
+
+        /**
+         * Template function for calling "added" callback for all listeners
+         * from given collection with given event.
+         * */
+        template<class T, class U> void callAdded(
+                std::map<long,std::shared_ptr<T>>& collection,
+                U* event) {
+            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
+            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
+            try {
+                for (; itstart != itend; ++itstart) {
+                    auto callback = (*itstart).second;
+                    if (callback->getServiceType() == event->service_type
+                            && callback->getServiceId() == event->service_id) {
+                        LOGD("Found callback for given service id (%d) and type (%d)",
+                                event->service_id, event->service_type);
+                        //@todo filter msgs
+                        callback->added(event->items);
+                    }
+                }
+            }catch (const Common::BasePlatformException &err) {
+                LOGE("callAdded failed, %s: %s", err.getName().c_str(),
+                        err.getMessage().c_str());
+            }
+            catch (...) {
+                LOGE("callAdded failed");
+            }
+        }
+
+        /**
+         * Template function for calling "updated" callback for all listeners
+         * from given collection with given event.
+         * */
+        template<class T, class U> void callUpdated(
+                std::map<long,std::shared_ptr<T>>& collection,
+                U* event) {
+            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
+            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
+            try {
+                for (; itstart != itend; ++itstart) {
+                    auto callback = (*itstart).second;
+                    if (callback->getServiceType() == event->service_type
+                            && callback->getServiceId() == event->service_id) {
+                        LOGD("Found callback for given service id (%d) and type (%d)",
+                                event->service_id, event->service_type);
+                        //@todo filter msgs
+                        callback->updated(event->items);
+                    }
+                }
+            }catch (const Common::BasePlatformException &err) {
+                LOGE("callUpdated failed, %s: %s", err.getName().c_str(),
+                        err.getMessage().c_str());
+            }
+            catch (...) {
+                LOGE("callUpdated failed");
+            }
+        }
+
+        /**
+         * Template function for calling "removed" callback for all listeners
+         * from given collection with given event.
+         * */
+
+        template<class T, class U> void callRemoved(
+                std::map<long,std::shared_ptr<T>>& collection,
+                U* event) {
+            typename std::map<long,std::shared_ptr<T>>::iterator itstart = collection.begin();
+            typename std::map<long,std::shared_ptr<T>>::iterator itend = collection.end();
+            try {
+                for (; itstart != itend; ++itstart) {
+                    auto callback = (*itstart).second;
+                    if (callback->getServiceType() == event->service_type
+                            && callback->getServiceId() == event->service_id) {
+                        LOGD("Found callback for given service id (%d) and type (%d)",
+                                event->service_id, event->service_type);
+                        //@todo filter msgs
+                        callback->removed(event->items);
+                    }
+                }
+            }catch (const Common::BasePlatformException &err) {
+                LOGE("callRemoved failed, %s: %s", err.getName().c_str(),
+                        err.getMessage().c_str());
+            }
+            catch (...) {
+                LOGE("callRemoved failed");
+            }
+        }
+};
+
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_CHANGE_LISTENER_CONTAINER_H__
diff --git a/src/messaging/old/ConversationCallbackData.cpp b/src/messaging/old/ConversationCallbackData.cpp
new file mode 100644 (file)
index 0000000..51d309e
--- /dev/null
@@ -0,0 +1,151 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "ConversationCallbackData.h"
+#include "JSMessageConversation.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+ConversationCallbackData::ConversationCallbackData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_filter(),
+        m_sort(),
+        m_limit(0),
+        m_offset(0),
+        m_is_error(false),
+        m_account_id(0),
+        m_service_type(UNDEFINED)
+{
+}
+
+ConversationCallbackData::~ConversationCallbackData()
+{
+}
+
+void ConversationCallbackData::setFilter(Tizen::AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+void ConversationCallbackData::setSortMode(Tizen::SortModePtr sortMode)
+{
+    m_sort = sortMode;
+}
+
+void ConversationCallbackData::setLimit(long limit)
+{
+    m_limit = limit;
+}
+
+void ConversationCallbackData::setOffset(long offset)
+{
+    m_offset = offset;
+}
+
+void ConversationCallbackData::addConversation(std::shared_ptr<MessageConversation> msg)
+{
+    m_conversations.push_back(msg);
+}
+
+void ConversationCallbackData::addConversations(JSContextRef context,
+        const std::vector<JSValueRef>& jsobject_conservations)
+{
+    const size_t new_conversations_count = jsobject_conservations.size();
+    if(0 == new_conversations_count) {
+        return;
+    }
+
+    m_conversations.reserve(m_conversations.size() + new_conversations_count);
+    for (auto it = jsobject_conservations.begin();
+            it != jsobject_conservations.end();
+            ++it) {
+        m_conversations.push_back(JSMessageConversation::getPrivateObject(context, *it));
+    }
+}
+
+std::vector<std::shared_ptr<MessageConversation>> ConversationCallbackData::getConversations() const
+{
+    return m_conversations;
+}
+
+void ConversationCallbackData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool ConversationCallbackData::isError() const
+{
+    return m_is_error;
+}
+
+std::string ConversationCallbackData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string ConversationCallbackData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void ConversationCallbackData::setAccountId(int account_id){
+    m_account_id = account_id;
+}
+
+int ConversationCallbackData::getAccountId() const
+{
+    return m_account_id;
+}
+
+void ConversationCallbackData::setMessageServiceType(MessageType m_msg_type)
+{
+    m_service_type = m_msg_type;
+}
+
+MessageType ConversationCallbackData::getMessageServiceType() const
+{
+    return m_service_type;
+}
+
+Tizen::AbstractFilterPtr ConversationCallbackData::getFilter() const
+{
+    return m_filter;
+}
+
+Tizen::SortModePtr ConversationCallbackData::getSortMode() const
+{
+    return m_sort;
+}
+
+long ConversationCallbackData::getLimit() const
+{
+    return m_limit;
+}
+
+long ConversationCallbackData::getOffset() const
+{
+    return m_offset;
+}
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/ConversationCallbackData.h b/src/messaging/old/ConversationCallbackData.h
new file mode 100644 (file)
index 0000000..4bc3a38
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_CONVERSATION_CALLBACK_DATA_H__
+#define __TIZEN_CONVERSATION_CALLBACK_DATA_H__
+
+#include <CallbackUserData.h>
+#include <memory>
+#include <string>
+#include <vector>
+#include <AttributeFilter.h>
+#include <SortMode.h>
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+class MessageConversation;
+
+class ConversationCallbackData: public Common::CallbackUserData {
+public:
+    ConversationCallbackData(JSContextRef globalCtx);
+    virtual ~ConversationCallbackData();
+
+    void setFilter(Tizen::AbstractFilterPtr filter);
+    void setSortMode(Tizen::SortModePtr sortMode);
+    void setLimit(long limit);
+    void setOffset(long offset);
+    void addConversation(std::shared_ptr<MessageConversation> msg);
+    void addConversations(JSContextRef context,
+            const std::vector<JSValueRef>& jsobject_conservations);
+
+    std::vector<std::shared_ptr<MessageConversation>> getConversations() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void setAccountId(int account_id);
+    int getAccountId() const;
+
+    void setMessageServiceType(MessageType m_msg_type);
+    MessageType getMessageServiceType() const;
+    Tizen::AbstractFilterPtr getFilter() const;
+    Tizen::SortModePtr getSortMode() const;
+    long getLimit() const;
+    long getOffset() const;
+
+private:
+    Tizen::AbstractFilterPtr m_filter;
+    Tizen::SortModePtr m_sort;
+    long m_limit;
+    long m_offset;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    std::vector<std::shared_ptr<MessageConversation>> m_conversations;
+    int m_account_id;
+    MessageType m_service_type;
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif // __TIZEN_CONVERSATION_CALLBACK_DATA_H__
diff --git a/src/messaging/old/ConversationsChangeCallback.cpp b/src/messaging/old/ConversationsChangeCallback.cpp
new file mode 100644 (file)
index 0000000..678513c
--- /dev/null
@@ -0,0 +1,198 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <PlatformException.h>
+#include <JSUtil.h>
+#include <GlobalContextManager.h>
+
+#include "MessagingUtil.h"
+#include "ConversationsChangeCallback.h"
+#include "JSMessageConversation.h"
+#include "MessagingUtil.h"
+#include <Logger.h>
+
+using namespace DeviceAPI::Common;
+using namespace DeviceAPI::Tizen;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+const char* CONVERSATIONSADDED = "conversationsadded";
+const char* CONVERSATIONSUPDATED = "conversationsupdated";
+const char* CONVERSATIONSREMOVED = "conversationsremoved";
+
+ConversationsChangeCallback::ConversationsChangeCallback(
+        JSContextRef global_ctx,
+        JSObjectRef on_added_obj,
+        JSObjectRef on_updated_obj,
+        JSObjectRef on_removed_obj,
+        int service_id,
+        MessageType service_type) :
+        m_callback_data(global_ctx),
+        m_id(service_id),
+        m_msg_type(service_type),
+        m_is_act(true)
+{
+    LOGD("Entered");
+
+    m_callback_data.setCallback(CONVERSATIONSADDED, on_added_obj);
+    m_callback_data.setCallback(CONVERSATIONSUPDATED, on_updated_obj);
+    m_callback_data.setCallback(CONVERSATIONSREMOVED, on_removed_obj);
+}
+
+ConversationsChangeCallback::~ConversationsChangeCallback()
+{
+    LOGD("Entered");
+}
+
+ConversationPtrVector ConversationsChangeCallback::filterConversations(
+        AbstractFilterPtr filter,
+        const ConversationPtrVector& source_conversations)
+{
+    if (filter) {
+        ConversationPtrVector filtered_conversations;
+        ConversationPtrVector::const_iterator it = source_conversations.begin();
+        ConversationPtrVector::const_iterator end_it = source_conversations.end();
+
+        for(int i = 0; it != end_it; ++i, ++it) {
+            const ConversationPtr& conversation = *it;
+            const bool matched = filter->isMatching(conversation.get());
+            if(matched) {
+                filtered_conversations.push_back(conversation);
+            }
+
+            LOGD("[%d] conversation id:%d", i, conversation->getConversationId());
+            LOGD("[%d] conversation subject :%s", i, conversation->getSubject().c_str());
+            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
+        }
+
+        LOGD("returning matching %d of %d conversations", filtered_conversations.size(),
+                source_conversations.size());
+
+        return filtered_conversations;
+    }
+    else {
+        return source_conversations;
+    }
+}
+
+void ConversationsChangeCallback::added(
+        const ConversationPtrVector& conversations)
+{
+    LOGD("Entered conversations.size()=%d", conversations.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
+            JSMessageConversation>(ctx, filtered);
+
+    LOGD("Calling:%s with:%d added conversations", CONVERSATIONSADDED,
+        filtered.size());
+
+    m_callback_data.invokeCallback(CONVERSATIONSADDED, js_obj);
+}
+
+void ConversationsChangeCallback::updated(
+        const ConversationPtrVector& conversations)
+{
+    LOGD("Entered conversations.size()=%d", conversations.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
+            JSMessageConversation>(ctx, filtered);
+
+    LOGD("Calling:%s with:%d updated conversations", CONVERSATIONSUPDATED,
+            filtered.size());
+
+    m_callback_data.invokeCallback(CONVERSATIONSUPDATED, js_obj);
+}
+
+void ConversationsChangeCallback::removed(
+        const ConversationPtrVector& conversations)
+{
+    LOGD("Entered conversations.size()=%d", conversations.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    ConversationPtrVector filtered = filterConversations(m_filter, conversations);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<ConversationPtr,
+            JSMessageConversation>(ctx, filtered);
+
+    LOGD("Calling:%s with:%d removed conversations", CONVERSATIONSREMOVED,
+            filtered.size());
+
+    m_callback_data.invokeCallback(CONVERSATIONSREMOVED, js_obj);
+}
+
+void ConversationsChangeCallback::setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+DeviceAPI::Tizen::AbstractFilterPtr ConversationsChangeCallback::getFilter() const
+{
+    return m_filter;
+}
+
+int ConversationsChangeCallback::getServiceId() const
+{
+    return m_id;
+}
+
+MessageType ConversationsChangeCallback::getServiceType() const
+{
+    return m_msg_type;
+}
+
+void ConversationsChangeCallback::setActive(bool act) {
+    m_is_act = act;
+}
+
+bool ConversationsChangeCallback::isActive() {
+    return m_is_act;
+}
+
+void ConversationsChangeCallback::setItems(ConversationPtrVector& items)
+{
+    m_items = items;
+}
+ConversationPtrVector ConversationsChangeCallback::getItems()
+{
+    return m_items;
+}
+
+JSContextRef ConversationsChangeCallback::getContext() const
+{
+    return m_callback_data.getContext();
+}
+
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/ConversationsChangeCallback.h b/src/messaging/old/ConversationsChangeCallback.h
new file mode 100644 (file)
index 0000000..612db76
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
+#define __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+#include <MultiCallbackUserData.h>
+
+#include <AbstractFilter.h>
+
+#include "MessageConversation.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+extern const char* CONVERSATIONSADDED;
+extern const char* CONVERSATIONSUPDATED;
+extern const char* CONVERSATIONSREMOVED;
+
+class ConversationsChangeCallback {
+public:
+    ConversationsChangeCallback(JSContextRef globalCtx,
+            JSObjectRef on_added_obj,
+            JSObjectRef on_updated_obj,
+            JSObjectRef on_removed_obj,
+            int service_id,
+            MessageType service_type);
+    virtual ~ConversationsChangeCallback();
+
+    void added(const ConversationPtrVector& conversations);
+    void updated(const ConversationPtrVector& conversations);
+    void removed(const ConversationPtrVector& conversations);
+
+    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
+    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
+
+    int getServiceId() const;
+    MessageType getServiceType() const;
+
+    void setActive(bool act);
+    bool isActive();
+
+    void setItems(ConversationPtrVector& items);
+    ConversationPtrVector getItems();
+    JSContextRef getContext() const;
+private:
+    static ConversationPtrVector filterConversations(
+            DeviceAPI::Tizen::AbstractFilterPtr a_filter,
+            const ConversationPtrVector& a_sourceConversations);
+
+    Common::MultiCallbackUserData m_callback_data;
+    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
+    int m_id;
+    MessageType m_msg_type;
+    bool m_is_act;
+    ConversationPtrVector m_items;
+
+};
+
+} // Messaging
+} // DeviceAPI
+
+
+
+
+#endif // __TIZEN_CONVERSATIONS_CHANGE_CALLBACK_H__
diff --git a/src/messaging/old/DBus/Connection.cpp b/src/messaging/old/DBus/Connection.cpp
new file mode 100644 (file)
index 0000000..67c243c
--- /dev/null
@@ -0,0 +1,60 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "Connection.h"
+#include <Logger.h>
+#include <PlatformException.h>
+#include <cstring>
+#include <email-types.h>
+#include "MessageService.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+Connection& Connection::getInstance()
+{
+    LOGD("Entered");
+    static Connection instance;
+    return instance;
+}
+
+GDBusConnection* Connection::getDBus()
+{
+    return m_dbus;
+}
+
+Connection::Connection()
+{
+    dbus_g_thread_init();
+    g_type_init();
+
+    m_dbus = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &m_error);
+    if (!m_dbus || m_error) {
+        LOGE("Could not get connection");
+    }
+    LOGD("Connection set");
+}
+
+Connection::~Connection()
+{
+    g_object_unref(m_dbus);
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/Connection.h b/src/messaging/old/DBus/Connection.h
new file mode 100644 (file)
index 0000000..16afddc
--- /dev/null
@@ -0,0 +1,49 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_DBUS_CONNECTION_H__
+#define __TIZEN_DBUS_CONNECTION_H__
+
+#include <dbus/dbus.h>
+#include <dbus/dbus-glib.h>
+#include <gio/gio.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+class Connection {
+public:
+    static Connection& getInstance();
+
+    GDBusConnection* getDBus();
+
+private:
+    Connection();
+    Connection(const Connection&);
+    void operator=(const Connection&);
+    virtual ~Connection();
+
+    GDBusConnection* m_dbus;
+    GError* m_error;
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif
diff --git a/src/messaging/old/DBus/EmailSignalProxy.cpp b/src/messaging/old/DBus/EmailSignalProxy.cpp
new file mode 100644 (file)
index 0000000..a3a9702
--- /dev/null
@@ -0,0 +1,85 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        EmailSignalProxy.cpp
+ */
+
+#include "EmailSignalProxy.h"
+#include <Logger.h>
+#include <cstring>
+#include <PlatformException.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+EmailSignalProxy::EmailSignalProxy(const std::string& proxy_path,
+        const std::string& proxy_iface) :
+        Proxy (proxy_path,
+                      proxy_iface,
+                      Proxy::DBUS_NAME_SIGNAL_EMAIL,   //specify email signal details
+                      DBUS_PATH_NETWORK_STATUS,
+                      DBUS_IFACE_NETWORK_STATUS)
+{
+}
+
+EmailSignalProxy::~EmailSignalProxy()
+{
+
+}
+
+void EmailSignalProxy::signalCallback(GDBusConnection* connection,
+        const gchar* sender_name,
+        const gchar* object_path,
+        const gchar* interface_name,
+        const gchar* signal_name,
+        GVariant* parameters)
+{
+    int status, mail_id, op_handle, error_code;
+    char* source = NULL;
+
+    try {
+        g_variant_get(parameters, "(iisii)",
+                &status,
+                &mail_id,
+                &source,
+                &op_handle,
+                &error_code);
+
+        //It is better to log this only when subclass is responsible of handling
+        //passed signal (usually determined by status value).
+        //
+        //LOGD("email:\n  status: %d\n  mail_id: %d\n  "
+        //        "source: %s\n  op_handle: %d\n  error_code: %d",
+        //        status, mail_id, source, op_handle, error_code);
+
+        handleEmailSignal(status, mail_id, source, op_handle, error_code);
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    g_free(source);
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/EmailSignalProxy.h b/src/messaging/old/DBus/EmailSignalProxy.h
new file mode 100644 (file)
index 0000000..378076a
--- /dev/null
@@ -0,0 +1,64 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        EmailSignalProxy.h
+ */
+
+#ifndef __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
+#define __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
+
+#include "Proxy.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+class EmailSignalProxy;
+typedef std::shared_ptr<EmailSignalProxy> EmailSignalProxyPtr;
+
+class EmailSignalProxy : public Proxy {
+public:
+    EmailSignalProxy(const std::string& proxy_path,
+            const std::string& proxy_iface);
+    virtual ~EmailSignalProxy();
+
+protected:
+    /**
+     * Override this method in subclass to handle email signal
+     */
+    virtual void handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code) = 0;
+
+    virtual void signalCallback(GDBusConnection *connection,
+            const gchar *sender_name,
+            const gchar *object_path,
+            const gchar *interface_name,
+            const gchar *signal_name,
+            GVariant *parameters);
+
+private:
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif // __TIZEN_DBUS_EMAIL_SIGNAL_PROXY_H__
diff --git a/src/messaging/old/DBus/LoadAttachmentProxy.cpp b/src/messaging/old/DBus/LoadAttachmentProxy.cpp
new file mode 100644 (file)
index 0000000..55eac0b
--- /dev/null
@@ -0,0 +1,231 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        LoadAttachmentProxy.cpp
+ */
+
+#include "LoadAttachmentProxy.h"
+#include <Logger.h>
+#include <PlatformException.h>
+#include <cstring>
+#include <email-types.h>
+#include "MessageService.h"
+#include "Message.h"
+#include "MessageBody.h"
+#include "EmailManager.h"
+#include "JSMessageAttachment.h"
+#include <email-api.h>
+#include <JSWebAPIErrorFactory.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+/**
+  * This method perform very specified task (see warning comment) so it should not be
+  * visible outside LoadAttachmentProxy class.
+  */
+void updateAttachmentDataWithEmailGetAttachmentData(
+        std::shared_ptr<MessageAttachment> attachment)
+{
+    struct ScopedEmailAttachmentData {
+        ScopedEmailAttachmentData() : data(NULL) { }
+        ~ScopedEmailAttachmentData() {
+            if(data) {
+                email_free_attachment_data(&data, 1);
+            }
+        }
+        email_attachment_data_t* operator->() { return data; }
+        email_attachment_data_t* data;
+    } attachment_data_holder;
+
+    LOGD("attachmentId = %d", attachment->getId());
+
+    /*
+     * WARNING: email_get_attachment_data seems to be getting NOT COMPLETE
+     *          email_attachment_data_t object, observed that:
+     *              mail_id is 0
+     *              account_id is 0
+     *              mailbox_id is 0
+     *          Thus currently only attachment_path and attachment_mime_type is used!
+     *
+     *          To get COMPLETE data please use: Message::convertEmailToMessageAttachment
+     *          mtehod which fetches all attachments from specified email.
+     */
+    int err = email_get_attachment_data(attachment->getId(), &attachment_data_holder.data);
+    if (EMAIL_ERROR_NONE != err ||
+        NULL == attachment_data_holder.data) {
+        LOGE("Couldn't get attachment data for attachmentId:%d", attachment->getId());
+        throw Common::UnknownException("Couldn't get attachment.");
+    }
+
+    LOGD("attachment name : %s", attachment_data_holder->attachment_name);
+
+    if(attachment_data_holder->attachment_mime_type) {
+        attachment->setMimeType(attachment_data_holder->attachment_mime_type);
+    }
+
+    bool isSaved = false;
+    if (attachment_data_holder->attachment_path) {
+        LOGD("set attachment path: %s", attachment_data_holder->attachment_path);
+        attachment->setFilePath(attachment_data_holder->attachment_path);
+
+        LOGD("save_status: %d", attachment_data_holder->save_status);
+        LOGD("attachment_size : %d", attachment_data_holder->attachment_size);
+    }
+    isSaved = attachment_data_holder->save_status;
+    attachment->setIsSaved(isSaved);
+}
+
+LoadAttachmentProxy::LoadAttachmentProxy(const std::string& path,
+        const std::string& iface) :
+        EmailSignalProxy(path, iface)
+{
+}
+
+LoadAttachmentProxy::~LoadAttachmentProxy()
+{
+}
+
+void LoadAttachmentProxy::addCallback(MessageAttachmentCallbackData* callbackOwned)
+{
+    if(callbackOwned->getMessageAttachment()) {
+        LOGD("Registered callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d",
+            callbackOwned->getMessageAttachment()->getId(),
+            callbackOwned->getMessageAttachment()->getMessageId(),
+            callbackOwned->getOperationHandle(),
+            callbackOwned->getNth());
+    }
+
+    m_callback_set.insert(callbackOwned);
+}
+
+void LoadAttachmentProxy::removeCallback(MessageAttachmentCallbackData* callback)
+{
+    if(callback->getMessageAttachment()) {
+        LOGD("Removed callback for attachment_id: %d mail_id:%d op_handle:%d nth:%d",
+            callback->getMessageAttachment()->getId(),
+            callback->getMessageAttachment()->getMessageId(),
+            callback->getOperationHandle(),
+            callback->getNth());
+    }
+
+    m_callback_set.erase(callback);
+}
+
+MessageAttachmentCallbackData* LoadAttachmentProxy::findCallback(const int nth,
+        const int mail_id)
+{
+    CallbackSet::iterator it = m_callback_set.begin();
+    for (; it != m_callback_set.end(); ++it) {
+        MessageAttachmentCallbackData* callback = *it;
+        if (nth == callback->getNth() &&
+            mail_id == callback->getMessageAttachment()->getMessageId()) {
+            return callback;
+        }
+    }
+
+    LOGW("Could not find callback with nth: %d and mail_id: %d", nth, mail_id);
+    return NULL;
+}
+
+void LoadAttachmentProxy::handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code)
+{
+    if(NOTI_DOWNLOAD_ATTACH_FINISH != status &&
+            NOTI_DOWNLOAD_ATTACH_FAIL != status) {
+        return;
+    }
+
+    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
+            "source: %s\n  op_handle(nth): %d\n  error_code: %d",
+            status, mail_id, source.c_str(), op_handle, error_code);
+
+    MessageAttachmentCallbackData* callback = NULL;
+
+    //It seems that D-Bus signal op_handle is equal to nth in:
+    // int email_download_attachment(int mail_id, int nth, int *handle)
+    // and not handle returned from above call!!
+    const int nth = op_handle;
+
+    try {
+        // From old implementation it looks that op_handle(nth) is is equal to
+        // index (1 based) of attachment inside email thus it is not globally unique!
+        // Therfore we need to test if mail_id match.
+        // For details see old implementation MailSync.cp line 461
+
+        callback = findCallback(nth, mail_id);
+        if(!callback) {
+            //We should not log not found pair since it could be requested by
+            //different application.
+            return;
+        }
+
+        LOGD("Found callback for pair mailId:%d nth:%d", mail_id, nth);
+
+        if(NOTI_DOWNLOAD_ATTACH_FINISH == status) {
+            LOGD("Message attachment downloaded!");
+
+            std::shared_ptr<MessageAttachment> att = callback->getMessageAttachment();
+            updateAttachmentDataWithEmailGetAttachmentData(att);
+            LOGD("Updated Message attachment object");
+
+            try {
+                JSContextRef context = callback->getContext();
+                JSObjectRef jsMessageAtt = JSMessageAttachment::makeJSObject(context, att);
+                callback->callSuccessCallback(jsMessageAtt);
+            } catch (...) {
+                LOGW("Couldn't create JSMessageAttachment object!");
+                throw Common::UnknownException(
+                        "Couldn't create JSMessageAttachment object!");
+            }
+
+        } else if(NOTI_DOWNLOAD_ATTACH_FAIL) {
+            LOGD("Load message attachment failed!");
+            JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                    callback->getContext(),
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        }
+    } catch (const Common::BasePlatformException& e) {
+        LOGE("Exception in signal callback");
+        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                callback->getContext(), e);
+        callback->callErrorCallback(errobj);
+    } catch (...) {
+        LOGE("Exception in signal callback");
+        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                callback->getContext(),
+                Common::JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                "Handling signal callback failed");
+        callback->callErrorCallback(errobj);
+    }
+
+    if(callback) {
+        removeCallback(callback);
+        delete callback;
+    }
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/LoadAttachmentProxy.h b/src/messaging/old/DBus/LoadAttachmentProxy.h
new file mode 100644 (file)
index 0000000..06db27d
--- /dev/null
@@ -0,0 +1,69 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        LoadAttachmentProxy.h
+ */
+
+#ifndef __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
+#define __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
+
+#include "EmailSignalProxy.h"
+#include <set>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageAttachmentCallbackData;
+
+namespace DBus {
+
+class LoadAttachmentProxy;
+typedef std::shared_ptr<LoadAttachmentProxy> LoadAttachmentProxyPtr;
+
+class LoadAttachmentProxy : public EmailSignalProxy {
+public:
+
+    // Callback is owned by this set
+    typedef std::set<MessageAttachmentCallbackData*> CallbackSet;
+
+    LoadAttachmentProxy(const std::string& path,
+            const std::string& iface);
+    virtual ~LoadAttachmentProxy();
+
+    //Passed callback will be owned by this proxy
+    void addCallback(MessageAttachmentCallbackData* callbackOwned);
+    void removeCallback(MessageAttachmentCallbackData* callback);
+
+protected:
+    virtual void handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code);
+
+private:
+    MessageAttachmentCallbackData* findCallback(const int nth, const int mail_id);
+
+    CallbackSet m_callback_set;
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif // __TIZEN_DBUS_LOAD_ATTACHMENT_PROXY_H__
diff --git a/src/messaging/old/DBus/LoadBodyProxy.cpp b/src/messaging/old/DBus/LoadBodyProxy.cpp
new file mode 100644 (file)
index 0000000..990d04f
--- /dev/null
@@ -0,0 +1,206 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        LoadBodyProxy.cpp
+ */
+
+#include "LoadBodyProxy.h"
+#include <Logger.h>
+#include <PlatformException.h>
+#include <cstring>
+#include <email-types.h>
+#include "MessageService.h"
+#include "Message.h"
+#include "MessageBody.h"
+#include "EmailManager.h"
+#include "JSMessage.h"
+#include <JSWebAPIErrorFactory.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+LoadBodyProxy::LoadBodyProxy(const std::string& path,
+        const std::string& iface) :
+        EmailSignalProxy(path, iface)
+{
+
+}
+
+LoadBodyProxy::~LoadBodyProxy()
+{
+
+}
+
+void LoadBodyProxy::addCallback(MessageBodyCallbackData* callbackOwned)
+{
+    m_callback_set.insert(callbackOwned);
+}
+
+void LoadBodyProxy::removeCallback(MessageBodyCallbackData* callback)
+{
+    m_callback_set.erase(callback);
+}
+
+MessageBodyCallbackData* LoadBodyProxy::findCallbackByOpHandle(const int op_handle)
+{
+    CallbackSet::iterator it = m_callback_set.begin();
+    for (; it != m_callback_set.end(); ++it) {
+
+        MessageBodyCallbackData* callback = *it;
+        if (op_handle == callback->getOperationHandle()) {
+            return callback;
+        }
+    }
+
+    LOGW("Could not find callback with op_handle: %d", op_handle);
+    return NULL;
+}
+
+void LoadBodyProxy::handleEmailSignal(const int status,
+        const int mail_id,
+        const std::string& source,
+        const int op_handle,
+        const int error_code)
+{
+    switch(status) {
+        //We should handle this signal since it is DOWNLOAD_BODY_*
+        case NOTI_DOWNLOAD_BODY_START:
+        case NOTI_DOWNLOAD_BODY_FINISH:
+        case NOTI_DOWNLOAD_BODY_FAIL: {
+        } break;
+
+        // This values have not been explicitly handled in old implementation
+        //  NOTI_DOWNLOAD_BODY_CANCEL
+        //  NOTI_DOWNLOAD_MULTIPART_BODY
+        //
+        // 1. I assume that NOTI_DOWNLOAD_MULTIPART_BODY is called several times
+        // before final NOTI_DOWNLOAD_BODY_FINISH is called, thus we should not
+        // remove nor delete callback.
+        //
+        // 2. I assume that NOTI_DOWNLOAD_BODY_CANCEL is called before
+        // NOTI_DOWNLOAD_BODY_FAIL so we should do the same as in point 1.
+        case NOTI_DOWNLOAD_BODY_CANCEL:
+        case NOTI_DOWNLOAD_MULTIPART_BODY:
+        default: {
+            // This signal is not related with load message body or there is nothing
+            // to do so we can return now.
+            return;
+        } break;
+    }
+
+    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
+        "source: %s\n  op_handle: %d\n  error_code: %d",
+        status, mail_id, source.c_str(), op_handle, error_code);
+
+    if(NOTI_DOWNLOAD_BODY_START == status) {
+        LOGD("Download message body started ...");
+        // There is nothing more to do so we can return now.
+        return;
+    }
+
+    MessageBodyCallbackData* callback = NULL;
+    try {
+        callback = findCallbackByOpHandle(op_handle);
+        if (!callback) {
+            LOGE("Callback is null");
+        } else {
+            if( (NOTI_DOWNLOAD_BODY_FINISH == status) ||
+                (NOTI_DOWNLOAD_BODY_FAIL == status &&
+                         EMAIL_ERROR_MAIL_IS_ALREADY_DOWNLOADED == error_code)) {
+
+                // Old implementation is not verifying whether message update failed,
+                // it just calls success callback.
+                if(callback->getMessage()) {
+                    email_mail_data_t* mail_data = EmailManager::loadMessage(
+                             callback->getMessage()->getId());
+                    if (mail_data) {
+                        callback->getMessage()->updateEmailMessage(*mail_data);
+                        EmailManager::freeMessage(mail_data);
+                        mail_data = NULL;
+                    }
+
+                    //TODO: this should be reviewed when attachments and
+                    //      loadAttachments have been completed.
+                    //TODO: see old implementation lines 608-635 in MailSync.cpp
+                    /*
+                    * This is original Messaging implementation:
+                    *
+                    * std::vector<IAttachmentPtr> attachments = mail->getAttachments();
+                    * std::vector<IAttachmentPtr> inlineAttachments = mail->getInlineAttachments();
+                    *
+                    * for (unsigned int idx = 0; idx < attachments.size() ; idx++ )
+                    * {
+                    *   LoggerD("set Attachment ID = " << attachments[idx]->getAttachmentID());
+                    *   attachments[idx]->setMessage(event->m_message);
+                    *
+                    * }
+                    * for (unsigned int idx = 0; idx < inlineAttachments.size() ; idx++ )
+                    * {
+                    *   LoggerD("set inline Attachment ID = " << inlineAttachments[idx]->getAttachmentID());
+                    *   inlineAttachments[idx]->setMessage(event->m_message);
+                    * }
+                    */
+                }
+
+                LOGD("Message body downloaded!");
+                try {
+                    JSContextRef context = callback->getContext();
+                    JSObjectRef jsMessage = JSMessage::makeJSObject(context,
+                             callback->getMessage());
+                    callback->callSuccessCallback(jsMessage);
+                } catch (...) {
+                    LOGW("Couldn't create JSMessage object!");
+                    throw Common::UnknownException(
+                            "Couldn't create JSMessage object!");
+                }
+
+            } else if(NOTI_DOWNLOAD_BODY_FAIL == status) {
+                LOGD("Load message body failed!");
+                JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                        callback->getContext(),
+                        callback->getErrorName(),
+                        callback->getErrorMessage());
+                callback->callErrorCallback(errobj);
+            }
+        }
+    }
+    catch (const Common::BasePlatformException& e) {
+        LOGE("Exception in signal callback");
+        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                callback->getContext(), e);
+        callback->callErrorCallback(errobj);
+    }
+    catch (...) {
+        LOGE("Exception in signal callback");
+        JSObjectRef errobj = Common::JSWebAPIErrorFactory::makeErrorObject(
+                callback->getContext(),
+                Common::JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                "Handling signal callback failed");
+        callback->callErrorCallback(errobj);
+    }
+
+    if(callback) {
+        removeCallback(callback);
+        delete callback;
+    }
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/LoadBodyProxy.h b/src/messaging/old/DBus/LoadBodyProxy.h
new file mode 100644 (file)
index 0000000..2fffa37
--- /dev/null
@@ -0,0 +1,73 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        LoadBodyProxy.h
+ */
+
+#ifndef __TIZEN_DBUS_LOAD_BODY_PROXY_H__
+#define __TIZEN_DBUS_LOAD_BODY_PROXY_H__
+
+#include "EmailSignalProxy.h"
+#include <set>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageBodyCallbackData;
+
+namespace DBus {
+
+class LoadBodyProxy;
+typedef std::shared_ptr<LoadBodyProxy> LoadBodyProxyPtr;
+
+class LoadBodyProxy : public EmailSignalProxy {
+public:
+
+    // Callback is owned by this set
+    typedef std::set<MessageBodyCallbackData*> CallbackSet;
+
+    LoadBodyProxy(const std::string& path,
+            const std::string& iface);
+    virtual ~LoadBodyProxy();
+
+    //Passed callback will be owned by this proxy
+    void addCallback(MessageBodyCallbackData* callbackOwned);
+    void removeCallback(MessageBodyCallbackData* callback);
+
+protected:
+    virtual void handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code);
+
+private:
+    /**
+     * Find callback by operation handle returned from:
+     *  int email_download_body(..., int *handle);
+     */
+    MessageBodyCallbackData* findCallbackByOpHandle(const int op_handle);
+
+    CallbackSet m_callback_set;
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif // __TIZEN_DBUS_LOAD_BODY_PROXY_H__
diff --git a/src/messaging/old/DBus/MessageProxy.cpp b/src/messaging/old/DBus/MessageProxy.cpp
new file mode 100644 (file)
index 0000000..32d4782
--- /dev/null
@@ -0,0 +1,290 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "MessageProxy.h"
+#include "Connection.h"
+#include <Logger.h>
+#include <Message.h>
+#include <MessageEmail.h>
+#include <MessageConversation.h>
+#include <MessageFolder.h>
+#include <ChangeListenerContainer.h>
+#include <EmailManager.h>
+#include <PlatformException.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+MessageProxy::MessageProxy():
+        Proxy(Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE,
+                     Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE,
+                     Proxy::DBUS_NAME_SIGNAL_EMAIL,
+                     Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE,
+                     Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE)
+{
+}
+
+MessageProxy::~MessageProxy()
+{
+}
+
+void MessageProxy::signalCallback(GDBusConnection *connection,
+            const gchar *sender_name,
+            const gchar *object_path,
+            const gchar *interface_name,
+            const gchar *signal_name,
+            GVariant *parameters)
+{
+    LOGD("Enter");
+    int status, account_id, object_id, thread_id;
+    char* name;
+    g_variant_get(parameters, "(iiisi)",
+            &status,
+            &account_id,
+            &object_id,
+            &name,
+            &thread_id);
+    LOGD("status: %d", status);
+    LOGD("account_id: %d", account_id);
+    LOGD("object_id: %d", object_id);
+    LOGD("name: %s", name);
+    LOGD("thread_id: %d", thread_id);
+
+    try {
+        switch (status) {
+            case NOTI_MAIL_ADD:
+            case NOTI_MAIL_UPDATE:
+                handleEmailEvent(account_id, object_id, thread_id, status);
+                break;
+            case NOTI_MAIL_DELETE:
+                //ids of removing messages are sent with name in format:
+                //id1,id2,id3,
+                handleEmailRemoveEvent(account_id, name);
+                break;
+            case NOTI_MAIL_DELETE_FINISH:
+            case NOTI_MAIL_DELETE_FAIL:
+                //notify EmailManager, maybe it tries to delete mail
+                notifyEmailManager(name, static_cast<email_noti_on_storage_event>(status));
+                break;
+            case NOTI_THREAD_DELETE:
+                handleThreadRemoveEvent(account_id, object_id);
+                break;
+            case NOTI_MAILBOX_ADD:
+            case NOTI_MAILBOX_UPDATE:
+            case NOTI_MAILBOX_FIELD_UPDATE:
+            case NOTI_MAILBOX_RENAME:
+            case NOTI_MAILBOX_DELETE:
+                handleMailboxEvent(account_id, object_id, status);
+                break;
+            default:
+                LOGD("Unrecognized status: %d", status);
+        }
+    } catch (const Common::BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Failed to call callback");
+    }
+    g_free(name);
+}
+
+void MessageProxy::handleEmailEvent(int account_id, int mail_id, int thread_id, int event)
+{
+    LOGD("Enter");
+
+    if(NOTI_MAIL_UPDATE == event) {
+        //getting thread_id from message
+        email_mail_data_t *mail_data = NULL;
+
+        if(EMAIL_ERROR_NONE != email_get_mail_data(mail_id, &mail_data)) {
+            if (mail_data) email_free_mail_data(&mail_data, 1);
+
+            LOGE("Failed to get mail data during setting conversation id in MessageProxy.");
+            return;
+        }
+
+        thread_id = mail_data->thread_id;
+
+        if(EMAIL_ERROR_NONE != email_free_mail_data(&mail_data,1)) {
+            LOGE("Failed to free mail data memory");
+        }
+    }
+
+    email_mail_data_t* mail_data = EmailManager::getInstance().loadMessage(mail_id);
+    if (mail_data == NULL) {
+        throw Common::UnknownException("Failed to load email");
+    }
+    std::shared_ptr<Message> msg = Message::convertPlatformEmailToObject(*mail_data);
+    ConversationPtr conv = MessageConversation::convertEmailConversationToObject(
+            thread_id);
+
+    EventMessages* eventMsg = new EventMessages();
+    eventMsg->service_type = MessageType::EMAIL;
+    eventMsg->service_id = account_id;
+    eventMsg->items.push_back(msg);
+    EventConversations* eventConv = new EventConversations();
+    eventConv->service_type = MessageType::EMAIL;
+    eventConv->service_id = account_id;
+    eventConv->items.push_back(conv);
+    switch (event) {
+        case NOTI_MAIL_ADD:
+            ChangeListenerContainer::getInstance().callMessageAdded(eventMsg);
+            if (conv->getMessageCount() == 1) {
+                LOGD("This thread is new, triggering conversationAdded");
+                ChangeListenerContainer::getInstance().callConversationAdded(eventConv);
+            } else {
+                LOGD("This thread is not new, but it's updated");
+                ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
+            }
+            break;
+        case NOTI_MAIL_UPDATE:
+            ChangeListenerContainer::getInstance().callMessageUpdated(eventMsg);
+            ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
+            break;
+        default:
+            LOGW("Unknown event type: %d", event);
+            break;
+
+    }
+    delete eventMsg;
+    delete eventConv;
+
+    EmailManager::getInstance().freeMessage(mail_data);
+}
+
+std::vector<int> getMailIds(const std::string& idsString)
+{
+    std::stringstream idsStream(idsString);
+    std::string item;
+    std::vector<int> ids;
+    while (std::getline(idsStream, item, ',')) {
+        if (item.length() > 0) {
+            int id;
+            std::stringstream stream(item);
+            stream >> id;
+            if (stream) {
+                LOGD("Mail delete id: %d", id);
+                ids.push_back(id);
+            }
+        }
+    }
+    return ids;
+}
+
+void MessageProxy::handleEmailRemoveEvent(int account_id, const std::string& idsString)
+{
+    LOGD("Enter");
+    std::vector<int> ids = getMailIds(idsString);
+    if (ids.empty()) {
+        LOGD("Mail id list is empty.");
+        return;
+    }
+    EventMessages* eventMsg = new EventMessages();
+    eventMsg->service_type = MessageType::EMAIL;
+    eventMsg->service_id = account_id;
+    for (auto it = ids.begin(); it != ids.end(); ++it) {
+        //it turns out that this event is triggered after messages are removed
+        //so we just create empty messages with id and type
+        std::shared_ptr<Message> msg = std::make_shared<MessageEmail>();
+        msg->setId(*it);
+        eventMsg->items.push_back(msg);
+    }
+    ChangeListenerContainer::getInstance().callMessageRemoved(eventMsg);
+    delete eventMsg;
+    eventMsg = NULL;
+}
+
+void MessageProxy::notifyEmailManager(const std::string& idsString,
+        email_noti_on_storage_event status)
+{
+    LOGD("Enter");
+    std::vector<int> ids = getMailIds(idsString);
+    if (ids.empty()) {
+        LOGD("Mail id list is empty.");
+        return;
+    }
+    EmailManager::getInstance().removeStatusCallback(ids, status);
+}
+
+void MessageProxy::handleThreadRemoveEvent(int account_id, int thread_id)
+{
+    LOGD("Enter");
+    //event is called after thread is removed, so we just set thread id
+    ConversationPtr conv = std::make_shared<MessageConversation>();
+    conv->setConversationId(thread_id);
+
+    EventConversations* eventConv = new EventConversations();
+    eventConv->service_type = MessageType::EMAIL;
+    eventConv->service_id = account_id;
+    eventConv->items.push_back(conv);
+    ChangeListenerContainer::getInstance().callConversationRemoved(eventConv);
+    delete eventConv;
+    eventConv = NULL;
+}
+
+void MessageProxy::handleMailboxEvent(int account_id, int mailbox_id, int event)
+{
+    LOGD("Enter");
+
+    EventFolders* eventFolder = new EventFolders();
+    eventFolder->service_type = MessageType::EMAIL;
+    eventFolder->service_id = account_id;
+    FolderPtr folder;
+    if (event == NOTI_MAILBOX_DELETE) {
+        //this event is triggered after mailbox is removed
+        //so we just create folder with id
+        folder.reset(new MessageFolder(std::to_string(mailbox_id),
+                "", //parent_id
+                "", //service_id
+                "", //content_type
+                "", //name
+                "", //path
+                MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD,
+                false));
+    } else {
+        email_mailbox_t* mail_box = NULL;
+        if (EMAIL_ERROR_NONE != email_get_mailbox_by_mailbox_id(mailbox_id, &mail_box)) {
+            LOGE("Mailbox not retrieved");
+            delete eventFolder;
+            throw Common::UnknownException("Failed to load mailbox");
+        }
+        folder.reset(new MessageFolder(*mail_box));
+        if (EMAIL_ERROR_NONE != email_free_mailbox(&mail_box, 1)) {
+            LOGD("Failed to free email_free_mailbox");
+        }
+    }
+    eventFolder->items.push_back(folder);
+    switch (event) {
+        case NOTI_MAILBOX_ADD:
+            ChangeListenerContainer::getInstance().callFolderAdded(eventFolder);
+            break;
+        case NOTI_MAILBOX_UPDATE:
+        case NOTI_MAILBOX_FIELD_UPDATE:
+            ChangeListenerContainer::getInstance().callFolderUpdated(eventFolder);
+            break;
+        case NOTI_MAILBOX_DELETE:
+            ChangeListenerContainer::getInstance().callFolderRemoved(eventFolder);
+            break;
+        default:
+            LOGW("Unknown event type: %d", event);
+    }
+    delete eventFolder;
+}
+
+} //DBus
+} //Messaging
+} //DeviceAPI
diff --git a/src/messaging/old/DBus/MessageProxy.h b/src/messaging/old/DBus/MessageProxy.h
new file mode 100644 (file)
index 0000000..7b6d456
--- /dev/null
@@ -0,0 +1,65 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_PROXY_H
+#define __TIZEN_MESSAGE_PROXY_H
+
+#include <dbus/dbus.h>
+#include <dbus/dbus-glib.h>
+#include <gio/gio.h>
+#include <memory>
+#include <string>
+#include <email-types.h>
+#include "Proxy.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+class MessageProxy: public Proxy {
+public:
+    MessageProxy();
+    virtual ~MessageProxy();
+protected:
+    virtual void signalCallback(GDBusConnection *connection,
+            const gchar *sender_name,
+            const gchar *object_path,
+            const gchar *interface_name,
+            const gchar *signal_name,
+            GVariant *parameters);
+    /**
+     * Handles e-mail add and update only.
+     * @param account_id
+     * @param mail_id
+     * @param thread_id
+     * @param event
+     */
+    void handleEmailEvent(int account_id, int mail_id, int thread_id, int event);
+    void handleEmailRemoveEvent(int account_id, const std::string& idsString);
+    void notifyEmailManager(const std::string& idsString, email_noti_on_storage_event status);
+    void handleThreadRemoveEvent(int account_id, int thread_id);
+    void handleMailboxEvent(int account_id, int mailbox_id, int event);
+};
+
+typedef std::shared_ptr<MessageProxy> MessageProxyPtr;
+
+} //DBus
+} //Messaging
+} //DeviceAPI
+
+#endif /* __TIZEN_MESSAGE_PROXY_H */
+
diff --git a/src/messaging/old/DBus/Proxy.cpp b/src/messaging/old/DBus/Proxy.cpp
new file mode 100644 (file)
index 0000000..422ab07
--- /dev/null
@@ -0,0 +1,163 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        Proxy.cpp
+ */
+
+#include "Proxy.h"
+#include <Logger.h>
+#include <PlatformException.h>
+#include <cstring>
+#include <email-types.h>
+#include "MessageService.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+const char* Proxy::DBUS_PATH_NETWORK_STATUS = "/User/Email/NetworkStatus";
+const char* Proxy::DBUS_IFACE_NETWORK_STATUS = "User.Email.NetworkStatus";
+const char* Proxy::DBUS_PATH_EMAIL_STORAGE_CHANGE = "/User/Email/StorageChange";
+const char* Proxy::DBUS_IFACE_EMAIL_STORAGE_CHANGE = "User.Email.StorageChange";
+const char* Proxy::DBUS_NAME_SIGNAL_EMAIL = "email";
+
+Proxy::Proxy(const std::string& proxy_path,
+            const std::string& proxy_iface,
+            const std::string& signal_name,
+            const std::string& signal_path,
+            const std::string& signal_iface) :
+                m_conn(Connection::getInstance()),
+                m_sub_id(0),
+                m_path(proxy_path),
+                m_iface(proxy_iface),
+                m_signal_name(signal_name),
+                m_signal_path(signal_path),
+                m_signal_iface(signal_iface),
+                m_error(NULL),
+                m_dbus_signal_subscribed(false)
+{
+    LOGD("Proxy:\n"
+            "  proxy_path: %s\n  proxy_iface: %s"
+            "  signal_name: %s\n signal_path:%s\n signal_iface:%s",
+            m_path.c_str(), m_iface.c_str(),
+            m_signal_name.c_str(), m_signal_path.c_str(), m_signal_iface.c_str());
+
+    const gchar* unique_name = g_dbus_connection_get_unique_name(m_conn.getDBus());
+    LOGD("Generated unique name: %d", unique_name);
+
+    // path and interface are not obligatory to receive, but
+    // they should be set to send the signals.
+    m_proxy = g_dbus_proxy_new_sync(m_conn.getDBus(),
+            G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
+            NULL, unique_name, m_path.c_str(), m_iface.c_str(), NULL, &m_error);
+    if (!m_proxy || m_error) {
+        LOGE("Could not get proxy");
+        throw Common::UnknownException("Could not get proxy");
+    }
+}
+
+Proxy::~Proxy()
+{
+    signalUnsubscribe();
+}
+
+void Proxy::signalCallbackProxy(GDBusConnection *connection,
+        const gchar *sender_name,
+        const gchar *object_path,
+        const gchar *interface_name,
+        const gchar *signal_name,
+        GVariant *parameters,
+        gpointer user_data)
+{
+    Proxy* this_ptr = static_cast<Proxy*>(user_data);
+    if (!this_ptr) {
+        LOGW("Proxy is null, nothing to do");
+        return;
+    }
+
+    try {
+        //It is better to log this only when subclass is responsible of handling
+        //passed signal. If you need it put it into your signalCallback(...) method
+        //LOGD("signal: %s from: %s path: %s interface: %s",
+        //        signal_name, sender_name, object_path, interface_name);
+
+        this_ptr->signalCallback(connection, sender_name, object_path, interface_name,
+                signal_name, parameters);
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+}
+
+void Proxy::signalSubscribe()
+{
+    if(m_dbus_signal_subscribed) {
+        LOGW("Proxy has already subscribed for listening DBus signal");
+        return;
+    }
+
+    const char* sender = NULL;
+    m_sub_id = g_dbus_connection_signal_subscribe(m_conn.getDBus(),
+            sender,
+            m_signal_iface.c_str(),
+            m_signal_name.c_str(),
+            m_signal_path.c_str(),
+            NULL,
+            G_DBUS_SIGNAL_FLAGS_NONE,
+            signalCallbackProxy,
+            static_cast<gpointer>(this),
+            NULL);
+    LOGD("g_dbus_connection_signal_subscribe returned id: %d", m_sub_id);
+
+    m_dbus_signal_subscribed = true;
+}
+
+void Proxy::signalUnsubscribe()
+{
+    if (!m_dbus_signal_subscribed) {
+        LOGW("Proxy hasn't subscribed for listening DBus signal");
+        return;
+    }
+
+    g_dbus_connection_signal_unsubscribe(m_conn.getDBus(), m_sub_id);
+    LOGD("g_dbus_connection_signal_unsubscribe finished");
+
+    m_dbus_signal_subscribed = false;
+}
+
+const std::string& Proxy::getSignalName() const
+{
+    return m_signal_name;
+}
+
+const std::string& Proxy::getSignalPath() const
+{
+    return m_signal_path;
+}
+
+const std::string& Proxy::getSignalInterfaceName() const
+{
+    return m_signal_iface;
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/Proxy.h b/src/messaging/old/DBus/Proxy.h
new file mode 100644 (file)
index 0000000..f157f1e
--- /dev/null
@@ -0,0 +1,125 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        Proxy.h
+ */
+
+#ifndef __TIZEN_DBUS_PROXY_H__
+#define __TIZEN_DBUS_PROXY_H__
+
+#include "Connection.h"
+#include <memory>
+#include <string>
+#include <mutex>
+#include <map>
+#include <CallbackUserData.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+
+class Proxy;
+typedef std::shared_ptr<Proxy> ProxyPtr;
+
+/**
+ * This is generic dbus signal listener proxy.
+ */
+class Proxy {
+public:
+    /**
+     * List of Tizen path and interface names:
+     */
+    static const char* DBUS_PATH_NETWORK_STATUS;
+    static const char* DBUS_IFACE_NETWORK_STATUS;
+    static const char* DBUS_PATH_EMAIL_STORAGE_CHANGE;
+    static const char* DBUS_IFACE_EMAIL_STORAGE_CHANGE;
+    /**
+     * Name of email signal
+     */
+    static const char* DBUS_NAME_SIGNAL_EMAIL;
+
+    /**
+     * @param proxy_path - path of this proxy
+     * @param proxy_iface - interface name of this proxy
+     *
+     * @param signal_name - expected signal name
+     * @param signal_path - expected signal path
+     * @param signal_iface - expected signal interface name
+     */
+    Proxy(const std::string& proxy_path,
+            const std::string& proxy_iface,
+            const std::string& signal_name,
+            const std::string& signal_path,
+            const std::string& signal_iface);
+
+    virtual ~Proxy();
+
+    void signalSubscribe();
+    void signalUnsubscribe();
+
+    const std::string& getSignalName() const;
+    const std::string& getSignalPath() const;
+    const std::string& getSignalInterfaceName() const;
+
+protected:
+    /**
+     * Please implement this method in subclass to handle signal.
+     * Executed by static void signalCallbackProxy(...).
+     */
+    virtual void signalCallback(GDBusConnection *connection,
+            const gchar *sender_name,
+            const gchar *object_path,
+            const gchar *interface_name,
+            const gchar *signal_name,
+            GVariant *parameters) = 0;
+
+private:
+    /**
+     * This method (registered with g_dbus_connection_signal_subscribe) is executed by
+     * DBus when signal is received. It calls
+     * (static_cast<Proxy*>(user_data))->signalCallback(...)
+     */
+    static void signalCallbackProxy(GDBusConnection *connection,
+            const gchar *sender_name,
+            const gchar *object_path,
+            const gchar *interface_name,
+            const gchar *signal_name,
+            GVariant *parameters,
+            gpointer user_data);
+
+    Connection& m_conn;
+    guint m_sub_id;
+
+    std::string m_path;
+    std::string m_iface;
+
+    std::string m_signal_name;
+    std::string m_signal_path;
+    std::string m_signal_iface;
+
+    GError* m_error;
+    GDBusProxy* m_proxy;
+    bool m_dbus_signal_subscribed;
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif // __TIZEN_DBUS_PROXY_H__
diff --git a/src/messaging/old/DBus/SendProxy.cpp b/src/messaging/old/DBus/SendProxy.cpp
new file mode 100644 (file)
index 0000000..1e5a836
--- /dev/null
@@ -0,0 +1,64 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "SendProxy.h"
+
+#include <Logger.h>
+#include <email-types.h>
+#include <EmailManager.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+SendProxy::SendProxy():
+        EmailSignalProxy(Proxy::DBUS_PATH_NETWORK_STATUS,
+                     Proxy::DBUS_IFACE_NETWORK_STATUS)
+{
+}
+
+SendProxy::~SendProxy()
+{
+}
+
+void SendProxy::handleEmailSignal(const int status,
+            const int account_id,
+            const std::string& source,
+            const int mail_id,
+            const int error_code)
+{
+    LOGD("Enter");
+    switch (status) {
+        case NOTI_SEND_FINISH:
+        case NOTI_SEND_FAIL:
+            LOGD("Recognized status for email send");
+            LOGD("received email signal with:\n  status: %d\n  account_id: %d\n  "
+                "source: %s\n  mail_id: %d\n  error_code: %d",
+                status, account_id, source.c_str(), mail_id, error_code);
+            EmailManager::getInstance().sendStatusCallback(mail_id,
+                    static_cast<email_noti_on_network_event>(status),
+                    error_code);
+            break;
+        default:
+            LOGD("Unrecognized status %d, ignoring", status);
+    }
+}
+
+
+} //DBus
+} //Messaging
+} //DeviceAPI
\ No newline at end of file
diff --git a/src/messaging/old/DBus/SendProxy.h b/src/messaging/old/DBus/SendProxy.h
new file mode 100644 (file)
index 0000000..1493c8e
--- /dev/null
@@ -0,0 +1,47 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_SEND_PROXY_H
+#define __TIZEN_SEND_PROXY_H
+
+#include "EmailSignalProxy.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+class SendProxy: public EmailSignalProxy {
+public:
+    SendProxy();
+    virtual ~SendProxy();
+protected:
+    virtual void handleEmailSignal(const int status,
+            const int account_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code);
+
+};
+
+typedef std::shared_ptr<SendProxy> SendProxyPtr;
+
+} //DBus
+} //Messaging
+} //DeviceAPI
+
+#endif /* __TIZEN_SEND_PROXY_H */
+
diff --git a/src/messaging/old/DBus/SyncProxy.cpp b/src/messaging/old/DBus/SyncProxy.cpp
new file mode 100644 (file)
index 0000000..9e12d41
--- /dev/null
@@ -0,0 +1,166 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        SyncProxy.cpp
+ */
+
+#include "SyncProxy.h"
+#include <Logger.h>
+#include <PlatformException.h>
+#include <cstring>
+#include <email-types.h>
+#include "MessageService.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+SyncProxy::SyncProxy(const std::string& path,
+        const std::string& iface) :
+        EmailSignalProxy(path, iface)
+{
+
+}
+
+SyncProxy::~SyncProxy()
+{
+
+}
+
+void SyncProxy::addCallback(long op_id, Common::CallbackUserData* callbackOwned)
+{
+    m_callback_map.insert(std::make_pair(op_id, callbackOwned));
+}
+
+Common::CallbackUserData* SyncProxy::getCallback(long op_id)
+{
+    Common::CallbackUserData* cb = NULL;
+    CallbackMap::iterator it = m_callback_map.find(op_id);
+    if (it != m_callback_map.end()) {
+        cb = it->second;
+        return cb;
+    }
+    LOGE("Could not find callback");
+    throw Common::UnknownException("Could not find callback");
+    return cb;
+}
+
+void SyncProxy::removeCallback(long op_id){
+    CallbackMap::iterator it = m_callback_map.find(op_id);
+    if (it != m_callback_map.end()) {
+        Common::CallbackUserData* cb = it->second;
+        delete cb;
+        cb = NULL;
+        m_callback_map.erase(it);
+    }
+    else {
+        LOGE("Could not find callback");
+        throw Common::UnknownException("Could not find callback");
+    }
+}
+
+void SyncProxy::handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code)
+{
+    if( NOTI_DOWNLOAD_START != status &&
+            NOTI_DOWNLOAD_FINISH != status &&
+            NOTI_DOWNLOAD_FAIL != status ) {
+        // Nothing to do: this status is not related to sync nor syncFolder request
+        return;
+    }
+
+    LOGD("received email signal with:\n  status: %d\n  mail_id: %d\n  "
+            "source: %s\n  op_handle: %d\n  error_code: %d",
+            status, mail_id, source.c_str(), op_handle, error_code);
+
+    if (NOTI_DOWNLOAD_START == status) {
+        LOGD("Sync started...");
+        // There is nothing more to do so we can return now.
+        return;
+    }
+
+    Common::CallbackUserData* callback = NULL;
+    CallbackMap::iterator callback_it;
+
+    try {
+        callback_it =  findSyncCallbackByOpHandle(op_handle);
+        callback = callback_it->second;
+        if (!callback) {
+            LOGE("Callback is null");
+            throw Common::UnknownException("Callback is null");
+        }
+
+        switch (status) {
+            case NOTI_DOWNLOAD_FINISH:
+                LOGD("Sync finished!");
+                callback->callSuccessCallback();
+                break;
+
+            case NOTI_DOWNLOAD_FAIL:
+                LOGD("Sync failed!");
+                callback->callErrorCallback();
+                break;
+
+            default:
+                break;
+        }
+    }
+    catch (const Common::BasePlatformException& e) {
+        // this situation may occur when there is no callback in the
+        // map with specified opId (for example stopSync() has
+        // removed it), but sync() was already started - only
+        // warning here:
+        LOGE("Exception in signal callback");
+    }
+    catch(...)
+    {
+        LOGE("Exception in signal callback");
+    }
+
+    if(callback) {
+        delete callback;
+        m_callback_map.erase(callback_it);
+    }
+}
+
+SyncProxy::CallbackMap::iterator SyncProxy::findSyncCallbackByOpHandle(
+        const int op_handle)
+{
+    CallbackMap::iterator it = m_callback_map.begin();
+    for (; it != m_callback_map.end(); ++it) {
+        SyncCallbackData* cb = dynamic_cast<SyncCallbackData*>(it->second);
+        if (!cb) continue;
+
+        if (op_handle == cb->getOperationHandle()) {
+            return it;
+        }
+    }
+    // this situation may occur when there is no callback in the
+    // map with specified opId (for example stopSync() has
+    // removed it), but sync() was already started - only
+    // warning here:
+    LOGW("Could not find callback with op_handle: %d", op_handle);
+    throw Common::UnknownException("Could not find callback");
+}
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
diff --git a/src/messaging/old/DBus/SyncProxy.h b/src/messaging/old/DBus/SyncProxy.h
new file mode 100644 (file)
index 0000000..4953ff3
--- /dev/null
@@ -0,0 +1,70 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        SyncProxy.h
+ */
+
+#ifndef __TIZEN_DBUS_SYNC_PROXY_H__
+#define __TIZEN_DBUS_SYNC_PROXY_H__
+
+#include "EmailSignalProxy.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+namespace DBus {
+
+class SyncProxy;
+typedef std::shared_ptr<SyncProxy> SyncProxyPtr;
+
+class SyncProxy : public EmailSignalProxy {
+public:
+
+    // Callback is owned by this map
+    typedef std::map<long, Common::CallbackUserData*> CallbackMap;
+
+    SyncProxy(const std::string& path,
+            const std::string& iface);
+    virtual ~SyncProxy();
+
+    //Passed callback will be owned by this proxy
+    void addCallback(long op_id, Common::CallbackUserData* callbackOwned);
+    Common::CallbackUserData* getCallback(long op_id);
+    void removeCallback(long op_id);
+
+protected:
+    virtual void handleEmailSignal(const int status,
+            const int mail_id,
+            const std::string& source,
+            const int op_handle,
+            const int error_code);
+
+private:
+    /**
+     * Find callback by operation handle returned from:
+     *  int email_sync_header(..., int *handle);
+     */
+    CallbackMap::iterator findSyncCallbackByOpHandle(const int op_handle);
+
+    CallbackMap m_callback_map;
+};
+
+} //namespace DBus
+} //namespace Messaging
+} //namespace DeviceAPI
+
+#endif // __TIZEN_DBUS_SYNC_PROXY_H__
diff --git a/src/messaging/old/EmailManager.cpp b/src/messaging/old/EmailManager.cpp
new file mode 100644 (file)
index 0000000..0204522
--- /dev/null
@@ -0,0 +1,1408 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file: EmailManager.cpp
+ */
+
+#include <JSWebAPIErrorFactory.h>
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+#include <memory>
+#include <PlatformException.h>
+#include <sstream>
+#include <GlobalContextManager.h>
+
+#include <AbstractFilter.h>
+
+#include <email-api-network.h>
+#include <email-api-account.h>
+#include <email-api-mail.h>
+#include <email-api-mailbox.h>
+
+#include "EmailManager.h"
+#include "MessagingUtil.h"
+#include "MessageService.h"
+#include "Message.h"
+#include "MessageConversation.h"
+#include "MessageCallbackUserData.h"
+#include "MessagesCallbackUserData.h"
+#include "FindMsgCallbackUserData.h"
+#include "ConversationCallbackData.h"
+#include "MessageEmail.h"
+#include "MessagingDatabaseManager.h"
+
+#include "JSMessage.h"
+#include "JSMessageConversation.h"
+#include "JSMessageFolder.h"
+
+#include <email-api.h>
+#include <vconf.h>
+
+#include "DBus/SyncProxy.h"
+#include "DBus/LoadBodyProxy.h"
+#include "DBus/LoadAttachmentProxy.h"
+
+#include <sstream>
+#include <FilterIterator.h>
+
+using namespace DeviceAPI::Common;
+using namespace DeviceAPI::Tizen;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const int ACCOUNT_ID_NOT_INITIALIZED = -1;
+const std::string FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME  = "serviceId";
+} //anonymous namespace
+
+EmailManager& EmailManager::getInstance()
+{
+    LOGD("Entered");
+
+    static EmailManager instance;
+    return instance;
+}
+
+EmailManager::EmailManager()
+{
+    LOGD("Entered");
+    getUniqueOpId();
+    const int non_err = EMAIL_ERROR_NONE;
+
+    if(non_err != email_service_begin()){
+        LOGE("Email service failed to begin");
+        throw Common::UnknownException("Email service failed to begin");
+    }
+    if(non_err != email_open_db()){
+        LOGE("Email DB failed to open");
+        throw Common::UnknownException("Email DB failed to open");
+    }
+
+    int slot_size = -1;
+    vconf_get_int("db/private/email-service/slot_size", &(slot_size));
+    if (slot_size > 0) {
+        m_slot_size = slot_size;
+    }
+
+    m_proxy_sync = std::make_shared<DBus::SyncProxy>(
+                                      DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
+                                      DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
+    if (!m_proxy_sync) {
+        LOGE("Sync proxy is null");
+        throw Common::UnknownException("Sync proxy is null");
+    }
+    m_proxy_sync->signalSubscribe();
+
+    m_proxy_load_body = std::make_shared<DBus::LoadBodyProxy>(
+                                        DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
+                                        DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
+    if (!m_proxy_load_body) {
+        LOGE("Load body proxy is null");
+        throw Common::UnknownException("Load body proxy is null");
+    }
+    m_proxy_load_body->signalSubscribe();
+
+    m_proxy_load_attachment = std::make_shared<DBus::LoadAttachmentProxy>(
+                                        DBus::Proxy::DBUS_PATH_NETWORK_STATUS,
+                                        DBus::Proxy::DBUS_IFACE_NETWORK_STATUS);
+    if (!m_proxy_load_attachment) {
+        LOGE("Load attachment proxy is null");
+        throw Common::UnknownException("Load attachment proxy is null");
+    }
+    m_proxy_load_attachment->signalSubscribe();
+
+    m_proxy_messageStorage = std::make_shared<DBus::MessageProxy>();
+    if (!m_proxy_messageStorage) {
+        LOGE("Message proxy is null");
+        throw Common::UnknownException("Message proxy is null");
+    }
+    m_proxy_messageStorage->signalSubscribe();
+
+    m_proxy_send = std::make_shared<DBus::SendProxy>();
+    if (!m_proxy_send) {
+        LOGE("Send proxy is null");
+        throw Common::UnknownException("Send proxy is null");
+    }
+    m_proxy_send->signalSubscribe();
+}
+
+EmailManager::~EmailManager()
+{
+    LOGD("Entered");
+}
+
+void EmailManager::addDraftMessagePlatform(int account_id,
+    std::shared_ptr<Message> message)
+{
+    addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_DRAFT);
+}
+
+void EmailManager::addOutboxMessagePlatform(int account_id,
+    std::shared_ptr<Message> message)
+{
+    addMessagePlatform(account_id, message, EMAIL_MAILBOX_TYPE_OUTBOX);
+}
+
+void EmailManager::addMessagePlatform(int account_id,
+    std::shared_ptr<Message> message, email_mailbox_type_e mailbox_type)
+{
+    email_mail_data_t* mail_data = NULL;
+    email_mail_data_t* mail_data_final = NULL;
+    int err = EMAIL_ERROR_NONE;
+
+    mail_data = Message::convertPlatformEmail(message);
+
+    mail_data->account_id = account_id;
+
+    //Adding "from" email address
+    email_account_t* account = NULL;
+    err = email_get_account(account_id, EMAIL_ACC_GET_OPT_FULL_DATA, &account);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("email_get_account failed. [%d]\n",err);
+        err = email_free_mail_data(&mail_data,1);
+        if(EMAIL_ERROR_NONE != err) {
+            LOGE("Failed to free mail data memory");
+        }
+        throw UnknownException("Cannot retrieve email account information");
+    }
+    LOGE("FROM %s", account->user_email_address);
+    std::stringstream ss;
+    ss << "<" << account->user_email_address << ">";
+    std::string address_from;
+    ss >> address_from;
+    mail_data->full_address_from = strdup(address_from.c_str());
+    LOGE("FROM %s", mail_data->full_address_from);
+    err = email_free_account(&account,1);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to free account data memory");
+    }
+    //Setting mailbox id
+    email_mailbox_t *mailbox_data = NULL;
+    err = email_get_mailbox_by_mailbox_type(account_id, mailbox_type,
+            &mailbox_data);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGD("email_get_mailbox_by_mailbox_type failed. [%d]\n",err);
+        err = email_free_mail_data(&mail_data,1);
+        if(EMAIL_ERROR_NONE != err) {
+            LOGE("Failed to free mail data memory");
+        }
+        throw UnknownException("Cannot retrieve draft mailbox");
+    }
+    else {
+        LOGD("email_get_mailbox_by_mailbox_type success.\n");
+        mail_data->mailbox_id = mailbox_data->mailbox_id;
+        mail_data->mailbox_type = mailbox_data->mailbox_type;
+    }
+
+    mail_data->report_status = EMAIL_MAIL_REPORT_NONE;
+    mail_data->save_status = EMAIL_MAIL_STATUS_SAVED;
+    mail_data->flags_draft_field = 1;
+
+    //adding email without attachments
+    err = email_add_mail(mail_data, NULL, 0, NULL, 0);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGD("email_add_mail failed. [%d]\n",err);
+        err = email_free_mail_data(&mail_data,1);
+        if(EMAIL_ERROR_NONE != err) {
+            LOGE("Failed to free mail data memory");
+        }
+        err = email_free_mailbox(&mailbox_data, 1);
+        if (EMAIL_ERROR_NONE != err) {
+            LOGE("Failed to destroy mailbox");
+        }
+        throw UnknownException("Couldn't add message to draft mailbox");
+    }
+    else {
+        LOGD("email_add_mail success.\n");
+    }
+
+    LOGD("saved mail without attachments id = [%d]\n", mail_data->mail_id);
+
+    message->setId(mail_data->mail_id);
+    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
+
+    //Adding attachments
+    if (message->getHasAttachment()){
+        Message::addEmailAttachments(message);
+    }
+
+    err = email_get_mail_data(message->getId(), &mail_data_final);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to retrieve added mail data");
+        throw UnknownException("Couldn't retrieve added mail data");
+    }
+
+    message->updateEmailMessage(*mail_data_final);
+
+    err = email_free_mail_data(&mail_data_final,1);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to free mail data final memory");
+    }
+
+    err = email_free_mail_data(&mail_data,1);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to free mail data memory");
+    }
+
+    err = email_free_mailbox(&mailbox_data, 1);
+    if (EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to destroy mailbox");
+    }
+}
+
+static gboolean addDraftMessageCompleteCB(void *data)
+{
+    MessageCallbackUserData* callback =
+        static_cast<MessageCallbackUserData *>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        return false;
+    }
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return false;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, err);
+        callback->callErrorCallback(errobj);
+    } catch (...) {
+        LOGE("Message add draft failed");
+        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
+        callback->callErrorCallback(errobj);
+    }
+
+    delete callback;
+    callback = NULL;
+
+    return false;
+}
+
+void EmailManager::addDraftMessage(MessageCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::shared_ptr<Message> message = callback->getMessage();
+        addDraftMessagePlatform(callback->getAccountId(), message);
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Message add draft failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
+    }
+
+    //Complete task
+    if (!g_idle_add(addDraftMessageCompleteCB, static_cast<void *>(callback))) {
+        LOGE("g_idle addition failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+
+//**** sending email ****
+static gboolean sendEmailCompleteCB(void* data)
+{
+    LOGD("Entered");
+
+    MessageRecipientsCallbackData* callback =
+            static_cast<MessageRecipientsCallbackData*>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        return false;
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return false;
+    }
+
+    try {
+        if (callback->isError()) {
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
+        }
+        else {
+            std::shared_ptr<Message> message = callback->getMessage();
+            callback->callSuccessCallback(
+                    JSUtil::toJSValueRef(context, message->getTO()));
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT);
+        }
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error when calling send message callback");
+    }
+
+    delete callback;
+    callback = NULL;
+
+    return false;
+}
+
+void EmailManager::sendMessage(MessageRecipientsCallbackData* callback)
+{
+    LOGD("Entered");
+    int err = EMAIL_ERROR_NONE;
+    email_mail_data_t *mail_data = NULL;
+
+    try{
+        if(!callback){
+            LOGE("Callback is null");
+            throw UnknownException("Callback is null");
+        }
+
+        std::shared_ptr<Message> message = callback->getMessage();
+        if(!message) {
+            LOGE("Message is null");
+            throw UnknownException("Message is null");
+        }
+
+        if(!(message->is_id_set())) {
+            addOutboxMessagePlatform(callback->getAccountId(),message);
+        }
+
+        err = email_get_mail_data(message->getId(),&mail_data);
+        if(EMAIL_ERROR_NONE != err) {
+            LOGE("email_get_mail_data failed. [%d]\n",err);
+            throw UnknownException("Failed to get platform email structure");
+        }
+
+        LOGD("email_get_mail_data success.\n");
+
+        //Sending EMAIL
+        mail_data->save_status = EMAIL_MAIL_STATUS_SENDING;
+
+        int req_id = 0;
+        err = email_send_mail(mail_data->mail_id, &req_id);
+        if (EMAIL_ERROR_NONE != err) {
+            LOGE("Failed to send message %d", err);
+            throw UnknownException("Failed to send message");
+        }
+        LOGD("req_id: %d", req_id);
+        callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENDING);
+        m_sendRequests[req_id] = callback;
+
+    } catch (const BasePlatformException& ex) {
+         LOGE("%s (%s)", (ex.getName()).c_str(), (ex.getMessage()).c_str());
+         callback->setError(ex.getName(), ex.getMessage());
+         if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
+             LOGE("g_idle addition failed");
+             delete callback;
+             callback = NULL;
+         }
+    }catch (...) {
+        LOGE("Message send failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message send failed");
+        if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
+            LOGE("g_idle addition failed");
+            delete callback;
+            callback = NULL;
+        }
+    }
+
+    err = email_free_mail_data(&mail_data,1);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Failed to free mail data memory");
+    }
+
+    return;
+}
+
+void EmailManager::sendStatusCallback(int mail_id,
+        email_noti_on_network_event status,
+        int error_code)
+{
+    LOGD("Enter");
+
+    std::lock_guard<std::mutex> lock(m_mutex);
+    //find first request for this mail_id
+    SendReqMapIterator it = getSendRequest(mail_id);
+    if (it != m_sendRequests.end()) {
+        LOGD("Found request");
+        MessageRecipientsCallbackData* callback = it->second;
+        m_sendRequests.erase(it);
+
+        if (NOTI_SEND_FAIL == status) {
+            LOGD("Failed to send message, set proper error");
+            switch (error_code) {
+                case EMAIL_ERROR_NO_SIM_INSERTED:
+                case EMAIL_ERROR_SOCKET_FAILURE:
+                case EMAIL_ERROR_CONNECTION_FAILURE:
+                case EMAIL_ERROR_CONNECTION_BROKEN:
+                case EMAIL_ERROR_NO_SUCH_HOST:
+                case EMAIL_ERROR_NETWORK_NOT_AVAILABLE:
+                case EMAIL_ERROR_INVALID_STREAM:
+                case EMAIL_ERROR_NO_RESPONSE:
+                    LOGE("Network error %d", error_code);
+                    callback->setError(JSWebAPIErrorFactory::NETWORK_ERROR,
+                            "Failed to send message");
+                    break;
+                default:
+                    LOGE("Unknown error %d", error_code);
+                    callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                            "Failed to send message");
+            }
+        } else if (NOTI_SEND_FINISH == status) {
+            LOGD("Message sent successfully");
+        }
+
+        if (!g_idle_add(sendEmailCompleteCB, static_cast<void*>(callback))) {
+            LOGE("g_idle addition failed");
+            delete callback;
+            callback = NULL;
+        }
+    } else {
+        LOGW("No matching request found");
+    }
+}
+
+email_mail_data_t* EmailManager::loadMessage(int msg_id)
+{
+    email_mail_data_t* mail_data = NULL;
+    int err = EMAIL_ERROR_NONE;
+    err = email_get_mail_data(msg_id, &mail_data);
+    if (EMAIL_ERROR_NONE != err) {
+        LOGE("email_get_mail_data failed. [%d]", err);
+    } else {
+        LOGD("email_get_mail_data success.");
+    }
+    return mail_data;
+}
+
+EmailManager::SendReqMapIterator EmailManager::getSendRequest(int mail_id)
+{
+    for (auto it = m_sendRequests.begin(); it != m_sendRequests.end(); it++) {
+        if (it->second->getMessage()->getId() == mail_id) {
+            return it;
+        }
+    }
+    return m_sendRequests.end();
+}
+
+void EmailManager::freeMessage(email_mail_data_t* mail_data)
+{
+    if(!mail_data) {
+        return;
+    }
+
+    int err = email_free_mail_data(&mail_data,1);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Could not free mail data!");
+    }
+}
+
+void EmailManager::loadMessageBody(MessageBodyCallbackData* callback)
+{
+    LOGD("Entered");
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    if(!callback->getMessage()) {
+        LOGE("Callback's message is null");
+        return;
+    }
+
+    m_proxy_load_body->addCallback(callback);
+
+    const int mailId = callback->getMessage()->getId();
+    int err = EMAIL_ERROR_NONE;
+
+    int op_handle = -1;
+    err = email_download_body(mailId, 0, &op_handle);
+    if(EMAIL_ERROR_NONE != err){
+        LOGE("Email download body failed, %d", err);
+        m_proxy_load_body->removeCallback(callback);
+        return;
+    }
+    callback->setOperationHandle(op_handle);
+}
+
+void EmailManager::loadMessageAttachment(MessageAttachmentCallbackData* callback)
+{
+    LOGD("Entered");
+    if(!callback) {
+        LOGE("Callback is null");
+        throw Common::InvalidValuesException("Callback is null");
+    }
+    if(!callback->getMessageAttachment()) {
+        LOGE("Callback's message attachment is null");
+        throw Common::InvalidValuesException("Callback's message attachment is null");
+    }
+
+    std::shared_ptr<MessageAttachment> msgAttachment = callback->getMessageAttachment();
+    LOGD("attachmentId:%d mailId:%d", msgAttachment->getId(),
+            msgAttachment->getMessageId());
+
+    struct ScopedEmailMailData {
+        ScopedEmailMailData() : data(NULL) { }
+        ~ScopedEmailMailData() { EmailManager::freeMessage(data); }
+        email_mail_data_t* data;
+    } mail_data_holder;
+
+    mail_data_holder.data = EmailManager::loadMessage(msgAttachment->getMessageId());
+    if(!mail_data_holder.data) {
+        std::stringstream err_ss;
+        err_ss << "Couldn't get email_mail_data_t for messageId:"
+                << msgAttachment->getMessageId();
+        LOGE("%s",err_ss.str().c_str());
+        throw Common::UnknownException(err_ss.str().c_str());
+    }
+
+    AttachmentPtrVector attachments = Message::convertEmailToMessageAttachment(
+            *mail_data_holder.data);
+    LOGD("Mail:%d contain:%d attachments", msgAttachment->getMessageId(),
+        attachments.size());
+
+    AttachmentPtrVector::iterator it = attachments.begin();
+    int attachmentIndex = -1;
+    for(int i = 0; it != attachments.end(); ++i, ++it) {
+        if((*it)->getId() == msgAttachment->getId()) {
+            attachmentIndex = i;
+            break;
+        }
+    }
+
+    if(attachmentIndex < 0) {
+        std::stringstream err_ss;
+        err_ss << "Attachment with id:" << msgAttachment->getId() << "not found";
+        LOGE("%s",err_ss.str().c_str());
+        throw Common::UnknownException(err_ss.str().c_str());
+    }
+
+    LOGD("Attachment with id:%d is located at index:%d", msgAttachment->getId(),
+            attachmentIndex);
+
+    int op_handle = -1;
+    const int nth = attachmentIndex + 1; //in documentation: the minimum number is "1"
+    callback->setNth(nth);
+
+    int err = email_download_attachment(msgAttachment->getMessageId(), nth, &op_handle);
+    if (EMAIL_ERROR_NONE != err) {
+        std::stringstream err_ss;
+        err_ss << "Download email attachment failed with error: " << err;
+        LOGE("%s",err_ss.str().c_str());
+        throw Common::UnknownException(err_ss.str().c_str());
+    } else  {
+        LOGD("email_download_attachment returned handle:%d",op_handle);
+        callback->setOperationHandle(op_handle);
+        m_proxy_load_attachment->addCallback(callback);
+    }
+}
+//#################################### sync: ###################################
+
+void EmailManager::sync(void* data)
+{
+    LOGD("Entered");
+    SyncCallbackData* callback = static_cast<SyncCallbackData*>(data);
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+    long op_id = callback->getOpId();
+    m_proxy_sync->addCallback(op_id, callback);
+
+    int err = EMAIL_ERROR_NONE;
+    int limit = callback->getLimit();
+    int slot_size = -1;
+    int account_id = callback->getAccountId();
+
+    if (limit < 0) {
+        slot_size = m_slot_size;
+    }
+    else {
+        slot_size = limit;
+    }
+
+    err = email_set_mail_slot_size(0, 0, slot_size);
+    if(EMAIL_ERROR_NONE != err){
+        LOGE("Email set slot size failed, %d", err);
+        m_proxy_sync->removeCallback(op_id);
+        return;
+    }
+
+    int op_handle = -1;
+    err = email_sync_header(account_id, 0, &op_handle);
+    if(EMAIL_ERROR_NONE != err){
+        LOGE("Email sync header failed, %d", err);
+        m_proxy_sync->removeCallback(op_id);
+    }
+    callback->setOperationHandle(op_handle);
+}
+
+//#################################### ^sync ###################################
+
+//################################## syncFolder: ###############################
+
+void EmailManager::syncFolder(SyncFolderCallbackData* callback)
+{
+    LOGD("Entered");
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    const long op_id = callback->getOpId();
+    m_proxy_sync->addCallback(op_id, callback);
+
+    if(!callback->getMessageFolder())
+    {
+        LOGE("Callback's messageFolder is null");
+        m_proxy_sync->removeCallback(op_id);
+        return;
+    }
+
+    int err = EMAIL_ERROR_NONE;
+
+    email_mailbox_t* mailbox = NULL;
+
+    const std::string folder_id_str = callback->getMessageFolder()->getId();
+    int folder_id = 0;
+    std::istringstream(folder_id_str) >> folder_id;
+
+    err = email_get_mailbox_by_mailbox_id(folder_id, &mailbox);
+    if (EMAIL_ERROR_NONE != err || NULL == mailbox) {
+        LOGE("Couldn't get mailbox, error code: %d", err);
+        m_proxy_sync->removeCallback(op_id);
+        return;
+    }
+
+    try {
+        const int limit = callback->getLimit();
+        int slot_size = -1;
+
+        if (limit < 0) {
+            slot_size = m_slot_size;
+        }
+        else {
+            slot_size = limit;
+        }
+
+        err = email_set_mail_slot_size(0, 0, slot_size);
+        if(EMAIL_ERROR_NONE != err){
+            LOGE("Email set slot size failed, %d", err);
+            throw UnknownException("Email set slot size failed");
+        }
+
+        int op_handle = -1;
+        const int account_id = callback->getAccountId();
+        err = email_sync_header(account_id, mailbox->mailbox_id, &op_handle);
+        if(EMAIL_ERROR_NONE != err) {
+            LOGE("Email sync header failed, %d", err);
+            m_proxy_sync->removeCallback(op_id);
+            throw UnknownException("Email sync header failed");
+        }
+        callback->setOperationHandle(op_handle);
+    }
+    catch (const BasePlatformException& e) {
+        LOGE("Exception in syncFolder");
+    }
+
+    if (NULL != mailbox)
+    {
+        err = email_free_mailbox(&mailbox , 1);
+        if  (EMAIL_ERROR_NONE !=  err) {
+            LOGD("Failed to email_free_mailbox - err:%d ", err);
+        }
+        mailbox = NULL;
+    }
+}
+
+//#################################### ^syncFolder #############################
+
+//################################## stopSync: #################################
+
+void EmailManager::stopSync(long op_id)
+{
+    LOGD("Entered");
+    SyncCallbackData* callback = NULL;
+    try {
+        callback = dynamic_cast<SyncCallbackData*>(
+                m_proxy_sync->getCallback(op_id));
+    }
+    catch (const BasePlatformException& e) {
+        LOGE("Could not get callback");
+    }
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int err = EMAIL_ERROR_NONE;
+    err = email_cancel_job(callback->getAccountId(), callback->getOperationHandle(),
+            EMAIL_CANCELED_BY_USER);
+    if(EMAIL_ERROR_NONE != err){
+        LOGE("Email cancel job failed, %d", err);
+    }
+    JSObjectRef err_obj =
+            JSWebAPIErrorFactory::makeErrorObject(callback->getContext(),
+                    JSWebAPIErrorFactory::ABORT_ERROR,
+                    "Sync aborted by user");
+    callback->callErrorCallback(err_obj);
+    m_proxy_sync->removeCallback(op_id);
+}
+
+//################################## ^stopSync #################################
+
+void removeEmailCompleteCB(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+    if (!callback) {
+        LOGE("Callback is null");
+        return;
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling removeEmail callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling removeEmail callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+EmailManager::DeleteReqVector::iterator EmailManager::getDeleteRequest(
+        const std::vector<int> &ids)
+{
+    for (auto idIt = ids.begin(); idIt != ids.end(); ++idIt) {
+        for (auto reqIt = m_deleteRequests.begin(); reqIt != m_deleteRequests.end(); ++reqIt) {
+            MessagePtrVector msgs = reqIt->callback->getMessages();
+            for (auto msgIt = msgs.begin(); msgIt != msgs.end(); ++msgIt) {
+                if ((*msgIt)->getId() == *idIt) {
+                    return reqIt;
+                }
+            }
+        }
+    }
+    return m_deleteRequests.end();
+}
+
+void EmailManager::removeStatusCallback(const std::vector<int> &ids,
+            email_noti_on_storage_event status)
+{
+    LOGD("Enter");
+    std::lock_guard<std::mutex> lock(m_mutex);
+    DeleteReqVector::iterator it = getDeleteRequest(ids);
+    if (it != m_deleteRequests.end()) {
+        LOGD("Found request");
+        if (NOTI_MAIL_DELETE_FINISH == status) {
+            LOGD("Successfully removed %d mails", ids.size());
+            it->messagesDeleted += ids.size();
+        }
+        MessagesCallbackUserData* callback = it->callback;
+        if (NOTI_MAIL_DELETE_FAIL == status) {
+            LOGD("Failed to remove mail");
+            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
+        }
+        //if one of mails failed, call error callback
+        //if all mails are deleted, call success.
+        // >= is used in case of duplicated dbus messages
+        if (NOTI_MAIL_DELETE_FAIL == status ||
+                static_cast<unsigned int>(it->messagesDeleted) >= it->callback->getMessages().size()) {
+            LOGD("Calling callback");
+            m_deleteRequests.erase(it);
+            m_mutex.unlock();
+            removeEmailCompleteCB(callback);
+        } else {
+            LOGD("Not all messages are removed, waiting for next callback");
+        }
+    } else {
+        LOGD("Request not found, ignoring");
+    }
+}
+
+void EmailManager::removeMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int error;
+    email_mail_data_t *mail = NULL;
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
+        MessageType type = callback->getMessageServiceType();
+        for(auto it = messages.begin() ; it != messages.end(); ++it) {
+            if((*it)->getType() != type) {
+                LOGE("Invalid message type");
+                throw TypeMismatchException("Error while deleting email");
+            }
+        }
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+            error = email_get_mail_data((*it)->getId(), &mail);
+            if (EMAIL_ERROR_NONE != error) {
+                LOGE("Couldn't retrieve mail data");
+                throw UnknownException("Error while deleting mail");
+            }
+
+            //This task (_EMAIL_API_DELETE_MAIL) is for async
+            error = email_delete_mail(mail->mailbox_id, &mail->mail_id, 1, 0);
+            if (EMAIL_ERROR_NONE != error) {
+                email_free_mail_data(&mail, 1);
+                LOGE("Error while deleting mail");
+                throw UnknownException("Error while deleting mail");
+            }
+            email_free_mail_data(&mail, 1);
+        }
+        //store delete request and wait for dbus response
+        DeleteReq request;
+        request.callback = callback;
+        request.messagesDeleted = 0;
+        m_deleteRequests.push_back(request);
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+        removeEmailCompleteCB(callback);
+    } catch (...) {
+        LOGE("Messages remove failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
+        removeEmailCompleteCB(callback);
+    }
+}
+
+void EmailManager::updateMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int error;
+    email_mail_data_t *mail = NULL;
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
+        MessageType type = callback->getMessageServiceType();
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+            if ((*it)->getType() != type) {
+                LOGE("Invalid message type");
+                throw TypeMismatchException("Error while updating message");
+            }
+        }
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+
+            mail = Message::convertPlatformEmail((*it));
+
+            if((*it)->getHasAttachment())
+            {
+                LOGD("Message has attachments. Workaround need to be used.");
+                //Update of mail on server using function email_update_mail() is not possible.
+                //Attachment is updated only locally (can't be later loaded from server),
+                //so use of workaround is needed:
+                //1. add new mail
+                //2. delete old mail
+
+                //adding message again after changes
+                addDraftMessagePlatform(mail->account_id, (*it));
+                LOGD("mail added - new id = [%d]\n", (*it)->getId());
+
+                //deleting old mail
+                LOGD("mail deleted = [%d]\n", mail->mail_id);
+                error = email_delete_mail(mail->mailbox_id,&mail->mail_id,1,1);
+                if (EMAIL_ERROR_NONE != error) {
+                    email_free_mail_data(&mail, 1);
+                    LOGE("Error while deleting old mail on update: %d", error);
+                    throw Common::UnknownException("Error while deleting old mail on update");
+                }
+            } else {
+                LOGD("There are no attachments, updating only email data.");
+                error = email_update_mail(mail, NULL, 0, NULL, 0);
+                if (EMAIL_ERROR_NONE != error) {
+                    email_free_mail_data(&mail, 1);
+                    LOGE("Error while updating mail");
+                    throw UnknownException("Error while updating mail");
+                }
+            }
+
+            email_free_mail_data(&mail, 1);
+        }
+
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages update failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages update failed");
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling updateEmail callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling updateEmail callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+
+void EmailManager::findMessages(FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    email_mail_data_t* mailList = NULL;
+    int mailListCount = 0;
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::pair<int, email_mail_data_t*> emails =
+                MessagingDatabaseManager::getInstance().findEmails(callback);
+        mailListCount = emails.first;
+        LOGD("Found %d mails", mailListCount);
+
+        mailList = emails.second;
+        email_mail_data_t* nth_email = mailList;
+
+        for (int i = 0; i < mailListCount; ++i) {
+            std::shared_ptr<Message> email =
+                    Message::convertPlatformEmailToObject(*nth_email);
+            callback->addMessage(email);
+            nth_email++;
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Message find failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message find failed");
+    }
+
+    if (mailListCount > 0 && mailList != NULL) {
+        if (EMAIL_ERROR_NONE != email_free_mail_data(&mailList, mailListCount)) {
+            LOGW("Failed to free mailList");
+        }
+    }
+
+    //Complete task
+    LOGD("callback: %p error:%d messages.size()=%d", callback, callback->isError(),
+            callback->getMessages().size());
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback(JSMessage::messageVectorToJSObjectArray(context,
+                    callback->getMessages()));
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling findMessages callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Failed to call findMessages callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+void EmailManager::findConversations(ConversationCallbackData* callback)
+{
+    LOGE("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int convListCount = 0;
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<EmailConversationInfo> conversationsInfo =
+                MessagingDatabaseManager::getInstance().findEmailConversations(callback);
+        convListCount = conversationsInfo.size();
+        LOGD("Found %d conversations", convListCount);
+
+        for (int i = 0; i < convListCount; ++i) {
+            std::shared_ptr<MessageConversation> conversation =
+                    MessageConversation::convertEmailConversationToObject(conversationsInfo.at(i).id);
+            conversation->setUnreadMessages(conversationsInfo.at(i).unreadMessages);
+            callback->addConversation(conversation);
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Conversation find failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Conversation find failed");
+    }
+
+    //Complete task
+    LOGD("callback: %p error:%d conversations.size()=%d", callback, callback->isError(),
+            callback->getConversations().size());
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback(
+                    MessagingUtil::vectorToJSObjectArray<ConversationPtr,
+                    JSMessageConversation>(context,
+                            callback->getConversations()));
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling findConversations callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Failed to call findConversations callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+long EmailManager::getUniqueOpId()
+{
+    // mutex is created only on first call (first call added to constructor
+    // to initialize mutex correctly)
+    static std::mutex op_id_mutex;
+    std::lock_guard<std::mutex> lock(op_id_mutex);
+    static long op_id = 0;
+    return op_id++;
+}
+
+void EmailManager::findFolders(FoldersCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int ret = EMAIL_ERROR_UNKNOWN;
+    int account_id = ACCOUNT_ID_NOT_INITIALIZED;
+    email_mailbox_t* mailboxes = NULL;
+    email_mailbox_t* nth_mailbox = NULL;
+    int mailboxes_count;
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+
+        Tizen::AbstractFilterPtr filter = callback->getFilter();
+        if (!filter) {
+            LOGE("Filter not provided");
+            throw UnknownException("Filter not provided");
+        }
+
+        for(FilterIterator it(filter); false == it.isEnd(); it++) {
+
+            if(FIS_COMPOSITE_START == it.getState()) {
+                CompositeFilterPtr cf = castToCompositeFilter((*it));
+                if(cf && INTERSECTION != cf->getType()) {
+                    LOGE("[ERROR] >>> invalid Filter type: %d", cf->getType());
+                    throw TypeMismatchException("Invalid Filter Type");
+                }
+            }
+            else if(FIS_ATTRIBUTE_FILTER == it.getState()) {
+                AttributeFilterPtr attrf = castToAttributeFilter((*it));
+                if(attrf) {
+                    const std::string attr_name = attrf->getAttributeName();
+                    if (FIND_FOLDERS_ATTRIBUTE_ACCOUNTID_NAME == attr_name) {
+                        account_id = static_cast<int>(attrf->getMatchValue()->toLong());
+                    } else {
+                        LOGE("The attribute name: %s is invalid", attr_name.c_str());
+                        throw InvalidValuesException("The attribute name is invalid");
+                    }
+                }
+            }
+        }
+
+        LOGD("Listing folders for account ID: %d", account_id);
+        if (account_id > 0) {
+            ret = email_get_mailbox_list(account_id,
+                    -1,
+                    &mailboxes,
+                    &mailboxes_count);
+            if (EMAIL_ERROR_NONE != ret || !mailboxes) {
+                LOGE("Cannot get folders: %d", ret);
+                throw Common::UnknownException(
+                        "Platform error, cannot get folders");
+            }
+
+            if (mailboxes_count <= 0) {
+                LOGD("Empty mailboxes");
+            }
+            else {
+                LOGD("Founded mailboxes: %d", mailboxes_count);
+
+                nth_mailbox = mailboxes;
+                for (int i = 0; i < mailboxes_count; ++i) {
+                    std::shared_ptr<MessageFolder> fd;
+                    fd = std::make_shared<MessageFolder>(*nth_mailbox);
+                    callback->addFolder(fd);
+                    nth_mailbox++;
+                }
+            }
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages update failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                "Messages update failed");
+    }
+
+    if (mailboxes != NULL) {
+        if (EMAIL_ERROR_NONE != email_free_mailbox(&mailboxes,
+                mailboxes_count)) {
+            LOGW("Free mailboxes failed: %d", ret);
+        }
+    }
+
+    //Complete task
+    LOGD("callback: %p error:%d folders.size()=%d", callback, callback->isError(),
+            callback->getFolders().size());
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,
+                    JSMessageFolder>(context, callback->getFolders());
+            callback->callSuccessCallback(js_obj);
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling findFolders callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling findFolders callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+void EmailManager::removeConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int error;
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<std::shared_ptr<MessageConversation>> conversations =
+                callback->getConversations();
+        MessageType type = callback->getMessageServiceType();
+
+        int thread_id = 0;
+        for(auto it = conversations.begin() ; it != conversations.end(); ++it) {
+            if((*it)->getType() != type) {
+                LOGE("Invalid message type");
+                throw TypeMismatchException("Error while deleting email conversation");
+            }
+        }
+
+        for (auto it = conversations.begin() ; it != conversations.end(); ++it) {
+            thread_id = (*it)->getConversationId();
+            error = email_delete_thread(thread_id, false);
+            if (EMAIL_ERROR_NONE != error) {
+                LOGE("Couldn't delete conversation data");
+                throw UnknownException("Error while deleting mail conversation");
+            }
+
+            // for now, there is no way to recognize deleting email thread job is completed.
+            // so use polling to wait the thread is removed.
+            email_mail_data_t *thread_info = NULL;
+            do {
+                usleep(300 * 1000);
+                LOGD("Waiting to delete this email thread...");
+                error = email_get_thread_information_by_thread_id(
+                    thread_id, &thread_info);
+
+                if (thread_info != NULL) {
+                    free(thread_info);
+                    thread_info = NULL;
+                }
+            } while (error != EMAIL_ERROR_MAIL_NOT_FOUND);
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages remove failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling removeConversations callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling removeConversations callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/EmailManager.h b/src/messaging/old/EmailManager.h
new file mode 100644 (file)
index 0000000..9513ce6
--- /dev/null
@@ -0,0 +1,134 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file: EmailManager.h
+ */
+
+#ifndef __TIZEN_EMAIL_MANAGER_H__
+#define __TIZEN_EMAIL_MANAGER_H__
+
+#include <glib.h>
+#include <mutex>
+#include <string>
+#include <map>
+#include <vector>
+
+#include "email-api-network.h"
+#include "email-api-account.h"
+#include "email-api-mail.h"
+#include "email-api-mailbox.h"
+
+#include <CallbackUserData.h>
+#include <PlatformException.h>
+
+#include "MessagingUtil.h"
+#include "MessageService.h"
+
+#include "DBus/Connection.h"
+#include "DBus/SyncProxy.h"
+#include "DBus/LoadBodyProxy.h"
+#include "DBus/LoadAttachmentProxy.h"
+#include "DBus/MessageProxy.h"
+#include "DBus/SendProxy.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+class MessageCallbackUserData;
+class FindMsgCallbackUserData;
+class SyncFolderCallbackData;
+
+class EmailManager {
+public:
+    static EmailManager& getInstance();
+
+    void addDraftMessage(MessageCallbackUserData* callback);
+    void removeMessages(MessagesCallbackUserData* callback);
+    void updateMessages(MessagesCallbackUserData* callback);
+    void findMessages(FindMsgCallbackUserData* callback);
+    void findConversations(ConversationCallbackData* callback);
+    void findFolders(FoldersCallbackData* callback);
+    void removeConversations(ConversationCallbackData* callback);
+
+    void sendMessage(MessageRecipientsCallbackData* callback);
+    void sendStatusCallback(int mail_id, email_noti_on_network_event status,
+            int error_code);
+    void removeStatusCallback(const std::vector<int> &ids,
+            email_noti_on_storage_event status);
+
+    void loadMessageBody(MessageBodyCallbackData* callback);
+    void loadMessageAttachment(MessageAttachmentCallbackData* callback);
+
+    void sync(void* data);
+    void syncFolder(SyncFolderCallbackData* callback);
+    void stopSync(long op_id);
+
+    void registerStatusCallback(msg_handle_t msg_handle);
+
+    /**
+     * Use freeMessage() to release returned email_mail_data_t object.
+     */
+    static email_mail_data_t* loadMessage(int msg_id);
+    static void freeMessage(email_mail_data_t*);
+
+    long getUniqueOpId();
+
+private:
+    EmailManager();
+    EmailManager(const EmailManager &);
+    void operator=(const EmailManager &);
+    virtual ~EmailManager();
+    void addDraftMessagePlatform(int account_id,
+        std::shared_ptr<Message> message);
+    void addOutboxMessagePlatform(int account_id,
+        std::shared_ptr<Message> message);
+    void addMessagePlatform(int account_id, std::shared_ptr<Message> message,
+        email_mailbox_type_e mailbox_type);
+
+    typedef std::map<int, MessageRecipientsCallbackData*> SendReqMap;
+    typedef SendReqMap::iterator SendReqMapIterator;
+    SendReqMapIterator getSendRequest(int mail_id);
+    SendReqMap m_sendRequests;
+    struct DeleteReq {
+        MessagesCallbackUserData* callback;
+        int messagesDeleted;
+    };
+    typedef std::vector<DeleteReq> DeleteReqVector;
+    /**
+     * Find first request containing at least one message id
+     * @param ids
+     * @return
+     */
+    DeleteReqVector::iterator getDeleteRequest(const std::vector<int> &ids);
+    DeleteReqVector m_deleteRequests;
+
+    int m_slot_size;
+
+    DBus::SyncProxyPtr m_proxy_sync;
+    DBus::LoadBodyProxyPtr m_proxy_load_body;
+    DBus::LoadAttachmentProxyPtr m_proxy_load_attachment;
+    DBus::MessageProxyPtr m_proxy_messageStorage;
+    DBus::SendProxyPtr m_proxy_send;
+
+    std::mutex m_mutex;
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_EMAIL_MANAGER_H__
diff --git a/src/messaging/old/FindMsgCallbackUserData.cpp b/src/messaging/old/FindMsgCallbackUserData.cpp
new file mode 100644 (file)
index 0000000..ab296ff
--- /dev/null
@@ -0,0 +1,136 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file: FindMsgCallbackUserData.cpp
+ */
+
+#include "FindMsgCallbackUserData.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+FindMsgCallbackUserData::FindMsgCallbackUserData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_limit(0),
+        m_offset(0),
+        m_is_error(false),
+        m_account_id(0),
+        m_service_type(UNDEFINED)
+{
+}
+
+FindMsgCallbackUserData::~FindMsgCallbackUserData()
+{
+}
+
+void FindMsgCallbackUserData::setFilter(Tizen::AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+void FindMsgCallbackUserData::setSortMode(Tizen::SortModePtr sortMode)
+{
+    m_sort = sortMode;
+}
+
+void FindMsgCallbackUserData::setLimit(long limit)
+{
+    m_limit = limit;
+}
+
+void FindMsgCallbackUserData::setOffset(long offset)
+{
+    m_offset = offset;
+}
+
+void FindMsgCallbackUserData::addMessage(std::shared_ptr<Message> msg)
+{
+    m_messages.push_back(msg);
+}
+
+std::vector<std::shared_ptr<Message>> FindMsgCallbackUserData::getMessages() const
+{
+    return m_messages;
+}
+
+void FindMsgCallbackUserData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool FindMsgCallbackUserData::isError() const
+{
+    return m_is_error;
+}
+
+std::string FindMsgCallbackUserData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string FindMsgCallbackUserData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void FindMsgCallbackUserData::setAccountId(int account_id){
+    m_account_id = account_id;
+}
+
+int FindMsgCallbackUserData::getAccountId() const
+{
+    return m_account_id;
+}
+
+void FindMsgCallbackUserData::setMessageServiceType(MessageType m_msg_type)
+{
+    m_service_type = m_msg_type;
+}
+
+MessageType FindMsgCallbackUserData::getMessageServiceType() const
+{
+    return m_service_type;
+}
+
+Tizen::AbstractFilterPtr FindMsgCallbackUserData::getFilter() const
+{
+    return m_filter;
+}
+
+Tizen::SortModePtr FindMsgCallbackUserData::getSortMode() const
+{
+    return m_sort;
+}
+
+long FindMsgCallbackUserData::getLimit() const
+{
+    return m_limit;
+}
+
+long FindMsgCallbackUserData::getOffset() const
+{
+    return m_offset;
+}
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/FindMsgCallbackUserData.h b/src/messaging/old/FindMsgCallbackUserData.h
new file mode 100644 (file)
index 0000000..d434b74
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file: FindMsgCallbackUserData.h
+ */
+
+#ifndef __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H
+#define __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H
+
+#include <CallbackUserData.h>
+#include <memory>
+#include <string>
+#include <vector>
+#include <AttributeFilter.h>
+#include <SortMode.h>
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+
+class FindMsgCallbackUserData: public Common::CallbackUserData {
+public:
+    FindMsgCallbackUserData(JSContextRef globalCtx);
+    virtual ~FindMsgCallbackUserData();
+
+    void setFilter(Tizen::AbstractFilterPtr filter);
+    void setSortMode(Tizen::SortModePtr sortMode);
+    void setLimit(long limit);
+    void setOffset(long offset);
+    void addMessage(std::shared_ptr<Message> msg);
+    std::vector<std::shared_ptr<Message>> getMessages() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void setAccountId(int account_id);
+    int getAccountId() const;
+
+    void setMessageServiceType(MessageType m_msg_type);
+    MessageType getMessageServiceType() const;
+    Tizen::AbstractFilterPtr getFilter() const;
+    Tizen::SortModePtr getSortMode() const;
+    long getLimit() const;
+    long getOffset() const;
+private:
+    //@TODO replace dpl shared_ptr when JSAttributeFilter is changed
+    Tizen::AbstractFilterPtr m_filter;
+    Tizen::SortModePtr m_sort;
+    long m_limit;
+    long m_offset;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    std::vector<std::shared_ptr<Message>> m_messages;
+    int m_account_id;
+    MessageType m_service_type;
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_FIND_MSG_CALLBACK_USER_DATA_H */
diff --git a/src/messaging/old/FoldersCallbackData.cpp b/src/messaging/old/FoldersCallbackData.cpp
new file mode 100644 (file)
index 0000000..4f067ff
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "FoldersCallbackData.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+
+FoldersCallbackData::FoldersCallbackData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_is_error(false)
+{
+}
+
+FoldersCallbackData::~FoldersCallbackData() {
+}
+
+void FoldersCallbackData::addFolder(std::shared_ptr<MessageFolder> folder)
+{
+    m_folders.push_back(folder);
+}
+
+const std::vector<std::shared_ptr<MessageFolder>>& FoldersCallbackData::getFolders() const
+{
+    return m_folders;
+}
+
+void FoldersCallbackData::setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+DeviceAPI::Tizen::AbstractFilterPtr FoldersCallbackData::getFilter() const
+{
+    return m_filter;
+}
+
+void FoldersCallbackData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool FoldersCallbackData::isError() const
+{
+    return m_is_error;
+}
+
+std::string FoldersCallbackData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string FoldersCallbackData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/FoldersCallbackData.h b/src/messaging/old/FoldersCallbackData.h
new file mode 100644 (file)
index 0000000..bf444cf
--- /dev/null
@@ -0,0 +1,62 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_FOLDERS_CALLBACK_DATA_H__
+#define __TIZEN_FOLDERS_CALLBACK_DATA_H__
+
+#include <CallbackUserData.h>
+#include <memory>
+#include <vector>
+#include <string>
+
+#include <AbstractFilter.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageFolder;
+
+class FoldersCallbackData: public Common::CallbackUserData {
+public:
+    FoldersCallbackData(JSContextRef globalCtx);
+    virtual ~FoldersCallbackData();
+
+    void addFolder(std::shared_ptr<MessageFolder> folder);
+    const std::vector<std::shared_ptr<MessageFolder>>& getFolders() const;
+
+    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
+    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+private:
+    std::vector<std::shared_ptr<MessageFolder>> m_folders;
+    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_FOLDERS_CALLBACK_DATA_H__ */
diff --git a/src/messaging/old/FoldersChangeCallback.cpp b/src/messaging/old/FoldersChangeCallback.cpp
new file mode 100644 (file)
index 0000000..269b6b2
--- /dev/null
@@ -0,0 +1,191 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <PlatformException.h>
+#include <JSUtil.h>
+#include <GlobalContextManager.h>
+
+#include "FoldersChangeCallback.h"
+#include "JSMessageFolder.h"
+#include "MessagingUtil.h"
+#include <Logger.h>
+
+using namespace DeviceAPI::Common;
+using namespace DeviceAPI::Tizen;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+const char* FOLDERSADDED = "foldersadded";
+const char* FOLDERSUPDATED = "foldersupdated";
+const char* FOLDERSREMOVED = "foldersremoved";
+
+FoldersChangeCallback::FoldersChangeCallback(JSContextRef global_ctx,
+        JSObjectRef on_added_obj,
+        JSObjectRef on_updated_obj,
+        JSObjectRef on_removed_obj,
+        int service_id,
+        MessageType service_type):
+    m_callback_data(global_ctx),
+    m_id(service_id),
+    m_msg_type(service_type),
+    m_is_act(true)
+{
+    LOGD("Entered");
+
+    m_callback_data.setCallback(FOLDERSADDED, on_added_obj);
+    m_callback_data.setCallback(FOLDERSUPDATED, on_updated_obj);
+    m_callback_data.setCallback(FOLDERSREMOVED, on_removed_obj);
+}
+
+FoldersChangeCallback::~FoldersChangeCallback()
+{
+    LOGD("Entered");
+}
+
+FolderPtrVector FoldersChangeCallback::filterFolders(
+        AbstractFilterPtr filter,
+        const FolderPtrVector& source_folders)
+{
+    if (filter) {
+        FolderPtrVector filtered_folders;
+        FolderPtrVector::const_iterator it = source_folders.begin();
+        FolderPtrVector::const_iterator end_it = source_folders.end();
+
+        for(int i = 0; it != end_it; ++i, ++it) {
+            const FolderPtr& folder = *it;
+            const bool matched = filter->isMatching(folder.get());
+            if (matched) {
+                filtered_folders.push_back(folder);
+            }
+
+            LOGD("[%d] folder id:%s", i, folder->getId().c_str());
+            LOGD("[%d] folder name:%s", i, folder->getName().c_str());
+            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
+        }
+
+        return filtered_folders;
+    }
+    else {
+        return source_folders;
+    }
+}
+
+void FoldersChangeCallback::added(const FolderPtrVector& folders)
+{
+    LOGD("Entered folders.size()=%d", folders.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    FolderPtrVector filtered = filterFolders(m_filter, folders);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
+            ctx, filtered);
+
+    LOGD("Calling:%s with:%d added folders", FOLDERSADDED,
+            filtered.size());
+
+    m_callback_data.invokeCallback(FOLDERSADDED, js_obj);
+}
+
+void FoldersChangeCallback::updated(const FolderPtrVector& folders)
+{
+    LOGD("Entered folders.size()=%d", folders.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    FolderPtrVector filtered = filterFolders(m_filter, folders);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
+            ctx, filtered);
+
+    LOGD("Calling:%s with:%d updated folders", FOLDERSUPDATED,
+            filtered.size());
+
+    m_callback_data.invokeCallback(FOLDERSUPDATED, js_obj);
+}
+
+void FoldersChangeCallback::removed(const FolderPtrVector& folders)
+{
+    LOGD("Entered folders.size()=%d", folders.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    FolderPtrVector filtered = filterFolders(m_filter, folders);
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,JSMessageFolder>(
+            ctx, filtered);
+
+    LOGD("Calling:%s with:%d removed folders", FOLDERSREMOVED,
+            filtered.size());
+
+    m_callback_data.invokeCallback(FOLDERSREMOVED, js_obj);
+}
+
+void FoldersChangeCallback::setFilter(AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+AbstractFilterPtr FoldersChangeCallback::getFilter() const
+{
+    return m_filter;
+}
+
+int FoldersChangeCallback::getServiceId() const
+{
+    return m_id;
+}
+
+MessageType FoldersChangeCallback::getServiceType() const
+{
+    return m_msg_type;
+}
+
+void FoldersChangeCallback::setActive(bool act) {
+    m_is_act = act;
+}
+
+bool FoldersChangeCallback::isActive() {
+    return m_is_act;
+}
+
+void FoldersChangeCallback::setItems(FolderPtrVector& items)
+{
+    m_items = items;
+}
+FolderPtrVector FoldersChangeCallback::getItems()
+{
+    return m_items;
+}
+
+JSContextRef FoldersChangeCallback::getContext() const
+{
+    return m_callback_data.getContext();
+}
+
+} // Messaging
+} // DeviceAPI
+
+
diff --git a/src/messaging/old/FoldersChangeCallback.h b/src/messaging/old/FoldersChangeCallback.h
new file mode 100644 (file)
index 0000000..fc2a888
--- /dev/null
@@ -0,0 +1,78 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
+#define __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+#include <MultiCallbackUserData.h>
+
+#include <AbstractFilter.h>
+
+#include "MessageFolder.h"
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+extern const char* FOLDERSADDED;
+extern const char* FOLDERSUPDATED;
+extern const char* FOLDERSREMOVED;
+
+class FoldersChangeCallback {
+public:
+    FoldersChangeCallback(JSContextRef global_ctx,
+            JSObjectRef on_added_obj,
+            JSObjectRef on_updated_obj,
+            JSObjectRef on_removed_obj,
+            int service_id,
+            MessageType service_type);
+    virtual ~FoldersChangeCallback();
+
+    void added(const FolderPtrVector& folders);
+    void updated(const FolderPtrVector& folders);
+    void removed(const FolderPtrVector& folders);
+
+    void setFilter(Tizen::AbstractFilterPtr filter);
+    Tizen::AbstractFilterPtr getFilter() const;
+
+    int getServiceId() const;
+    MessageType getServiceType() const;
+
+    void setActive(bool act);
+    bool isActive();
+
+    void setItems(FolderPtrVector& items);
+    FolderPtrVector getItems();
+    JSContextRef getContext() const;
+private:
+    static FolderPtrVector filterFolders(Tizen::AbstractFilterPtr filter,
+            const FolderPtrVector& source_folders);
+
+    Common::MultiCallbackUserData m_callback_data;
+    Tizen::AbstractFilterPtr m_filter;
+    int m_id;
+    MessageType m_msg_type;
+    bool m_is_act;
+    FolderPtrVector m_items;
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_FOLDERS_CHANGE_CALLBACK_H__
diff --git a/src/messaging/old/JSMessage.cpp b/src/messaging/old/JSMessage.cpp
new file mode 100644 (file)
index 0000000..3325dcb
--- /dev/null
@@ -0,0 +1,923 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <PlatformException.h>
+#include <JSUtil.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+
+#include "JSMessage.h"
+#include "JSMessageBody.h"
+#include "JSMessageAttachment.h"
+
+#include "plugin_config.h"
+
+#include "MessagingUtil.h"
+#include "Message.h"
+#include "MessageSMS.h"
+#include "MessageMMS.h"
+#include "MessageEmail.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE = "Message";
+
+const char* MESSAGE_DICTIONARY_ATTRIBUTE_PLAIN_BODY = "plainBody";
+const char* MESSAGE_DICTIONARY_ATTRIBUTE_HTML_BODY = "htmlBody";
+}
+
+namespace JSMessageKeys {
+const char* MESSAGE_ATTRIBUTE_ID = "id";
+const char* MESSAGE_ATTRIBUTE_CONVERSATION_ID = "conversationId";
+const char* MESSAGE_ATTRIBUTE_FOLDER_ID = "folderId";
+const char* MESSAGE_ATTRIBUTE_TYPE = "type";
+const char* MESSAGE_ATTRIBUTE_TIMESTAMP = "timestamp";
+const char* MESSAGE_ATTRIBUTE_FROM = "from";
+const char* MESSAGE_ATTRIBUTE_TO = "to"; // used also in dictionary
+const char* MESSAGE_ATTRIBUTE_CC = "cc"; // used also in dictionary
+const char* MESSAGE_ATTRIBUTE_BCC = "bcc"; // used also in dictionary
+const char* MESSAGE_ATTRIBUTE_BODY = "body";
+const char* MESSAGE_ATTRIBUTE_IS_READ = "isRead";
+const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY = "isHighPriority"; // used also in dictionary
+const char* MESSAGE_ATTRIBUTE_SUBJECT = "subject"; // used also in dictionary
+const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO = "inResponseTo";
+const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS = "messageStatus";
+const char* MESSAGE_ATTRIBUTE_ATTACHMENTS = "attachments";
+const char* MESSAGE_ATTRIBUTE_HAS_ATTACHMENT = "hasAttachment";
+} // namespace JSMessage
+
+using namespace JSMessageKeys;
+
+JSClassRef JSMessage::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessage::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE,
+    NULL,
+    JSMessage::m_property,
+    NULL, // m_function
+    JSMessage::initialize,
+    JSMessage::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL, //callAsFunction,
+    NULL, //callAsConstructor,
+    NULL, //hasInstance,
+    NULL, //convertToType,
+};
+
+JSStaticValue JSMessage::m_property[] = {
+    { MESSAGE_ATTRIBUTE_ID, getMessageId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_CONVERSATION_ID, getConversationId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_FOLDER_ID, getFolder, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_TYPE, getMessageType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_TIMESTAMP, getTime, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_FROM, getSourceAddress, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTRIBUTE_TO, getDestinationAddress, setDestinationAddress, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_CC, getCcAddress, setCcAddress, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_BCC, getBccAddress, setBccAddress, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_BODY, getMessageBody, setMessageBody, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_IS_READ, getIsRead, setIsRead, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY, getMessagePriority, setMessagePriority, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_SUBJECT, getSubject, setSubject, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_IN_RESPONSE_TO, getInResponseTo, NULL, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_MESSAGE_STATUS, getMessageStatus, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly},
+    { MESSAGE_ATTRIBUTE_ATTACHMENTS, getAttachments, setAttachments, kJSPropertyAttributeDontDelete },
+    { MESSAGE_ATTRIBUTE_HAS_ATTACHMENT, hasAttachment, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly},
+    { 0, 0, 0, 0 }
+};
+
+const JSClassDefinition* JSMessage::getClassInfo()
+{
+    LOGD("Entered");
+    return &(m_classInfo);
+}
+
+JSClassRef DLL_EXPORT JSMessage::getClassRef()
+{
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+JSObjectRef DLL_EXPORT JSMessage::constructor(JSContextRef context,
+        JSObjectRef constructor,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+
+    ArgumentValidator validator(context, argumentCount, arguments);
+
+    JSObjectRef jsObjRef = JSObjectMake(context, JSMessage::getClassRef(), NULL);
+
+    // constructor
+    JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor");
+    JSObjectSetProperty(context, jsObjRef, ctorName, constructor,
+        kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL);
+    JSStringRelease(ctorName);
+
+    try {
+        std::shared_ptr<Message> priv;
+
+        std::string msgTypeString = validator.toString(0);
+        LOGD(" Message type : %s", msgTypeString.c_str());
+        JSObjectRef dictionary = validator.toObject(1, true);
+
+        try {
+            MessageType msgtype = MessagingUtil::stringToMessageType(msgTypeString);
+            switch(msgtype) {
+                case MessageType(SMS):
+                    priv = std::make_shared<MessageSMS>();
+                    break;
+                case MessageType(MMS):
+                    priv = std::make_shared<MessageMMS>();
+                    break;
+                case MessageType(EMAIL):
+                    priv = std::make_shared<MessageEmail>();
+                    break;
+                default:
+                    break;
+            }
+        }
+        catch(const BasePlatformException &ex) {
+            LOGE("Invalid message type given: %s.", msgTypeString.c_str());
+            throw ex;
+        }
+
+        setPrivateObject(jsObjRef, priv);
+
+        // both - dictionary and private object - have to be not NULL
+        if (dictionary != NULL && priv.get() != NULL) {
+            JSValueRef subjectData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_ATTRIBUTE_SUBJECT);
+            JSValueRef toData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_ATTRIBUTE_TO);
+            JSValueRef ccData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_ATTRIBUTE_CC);
+            JSValueRef bccData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_ATTRIBUTE_BCC);
+            JSValueRef plainBodyData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_DICTIONARY_ATTRIBUTE_PLAIN_BODY);
+            JSValueRef htmlBodyData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_DICTIONARY_ATTRIBUTE_HTML_BODY);
+            JSValueRef priorityData = JSUtil::getProperty(context, dictionary,
+                    MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY);
+
+            if (!JSValueIsUndefined(context, subjectData)) {
+                std::string subject = JSUtil::JSValueToString(context, subjectData);
+                LOGD(" Subject: %s", subject.c_str());
+                priv->setSubject(subject);
+            }
+            if (!JSValueIsUndefined(context, toData)) {
+                std::vector<std::string> to = JSUtil::JSArrayToStringVector(
+                        context, toData);
+                priv->setTO(to);
+            }
+            if (!JSValueIsUndefined(context, ccData)) {
+                std::vector<std::string> cc = JSUtil::JSArrayToStringVector(
+                        context, ccData);
+                priv->setCC(cc);
+            }
+            if (!JSValueIsUndefined(context, bccData)) {
+                std::vector<std::string> bcc = JSUtil::JSArrayToStringVector(
+                        context, bccData);
+                priv->setBCC(bcc);
+            }
+            if (!JSValueIsUndefined(context, htmlBodyData)) {
+                std::string htmlBody = JSUtil::JSValueToString(context, htmlBodyData);
+                LOGD(" htmlBody: %s", htmlBody.c_str());
+                priv->getBody()->setHtmlBody(htmlBody);
+            }
+            if (!JSValueIsUndefined(context, priorityData)) {
+                priv->setIsHighPriority(JSUtil::JSValueToBoolean(context, priorityData));
+            }
+            if (!JSValueIsUndefined(context, plainBodyData)) {
+                std::string plainBody = JSUtil::JSValueToString(context, plainBodyData);
+                LOGD(" plainBody: %s", plainBody.c_str());
+                priv->getBody()->setPlainBody(plainBody);
+            }
+        }
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Message creation failed: %s", err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Message creation failed - unsupported error.");
+    }
+
+    return jsObjRef;
+}
+
+void JSMessage::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessage::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    // Below holder is fetched from JSObject because holder
+    // with last shared_ptr instace should be removed
+    MessageHolder* priv = static_cast<MessageHolder*>(JSObjectGetPrivate(object));
+    JSObjectSetPrivate(object, NULL);
+    delete priv;
+}
+
+std::shared_ptr<Message> JSMessage::getPrivateObject(JSContextRef context,
+        JSValueRef value)
+{
+    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGE("Object type do not match");
+        throw TypeMismatchException("Object type is not Message");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+    MessageHolder* priv = static_cast<MessageHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw UnknownException("Private data holder is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessage::setPrivateObject(JSObjectRef object, std::shared_ptr<Message> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw UnknownException("NULL private data given");
+    }
+    MessageHolder* priv = static_cast<MessageHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    }
+    else {
+        priv = new(std::nothrow) MessageHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in Message");
+            throw UnknownException(
+                    "Failed to set Message private data");
+        }
+    }
+}
+
+JSObjectRef JSMessage::makeJSObject(JSContextRef context,
+        std::shared_ptr<Message> ptr)
+{
+    if (!ptr) {
+        LOGE("NULL pointer to message given");
+        throw UnknownException("NULL pointer to message given");
+    }
+
+    MessageHolder* priv = new(std::nothrow) MessageHolder();
+    if (!priv) {
+        LOGW("Failed to allocate memory for MessageHolder");
+        throw UnknownException("Priv is null");
+    }
+    priv->ptr = ptr;
+
+    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
+    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
+        LOGE("Failed to set private in Message");
+        throw UnknownException("Private data not set");
+    }
+    return obj;
+}
+
+JSObjectRef JSMessage::messageVectorToJSObjectArray(JSContextRef context,
+        const MessagePtrVector& messages)
+{
+    size_t count = messages.size();
+
+    JSObjectRef array[count];
+    for (size_t i = 0; i < count; i++) {
+        array[i] = JSMessage::makeJSObject(context, messages[i]);
+    }
+    JSObjectRef result = JSObjectMakeArray(context, count,
+            count > 0 ? array : NULL, NULL);
+    if (!result) {
+        LOGW("Failed to create Message array");
+        throw UnknownException("Message array is null");
+    }
+    return result;
+}
+
+JSValueRef JSMessage::getAttachments(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return priv->getJSMessageAttachments(
+            Common::GlobalContextManager::getInstance()
+                ->getGlobalContext(context));
+    }
+    catch(const BasePlatformException& err) {
+        LOGE("Failed to get attachments: %s", err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message attachment.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getBccAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return priv->getJSBCC(
+            Common::GlobalContextManager::getInstance()
+                ->getGlobalContext(context));
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get BCC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting BCC.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getCcAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return priv->getJSCC(
+            Common::GlobalContextManager::getInstance()
+                ->getGlobalContext(context));
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get CC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting CC.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getDestinationAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return priv->getJSTO(
+            Common::GlobalContextManager::getInstance()
+                ->getGlobalContext(context));
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get TO. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting TO.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getIsRead(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getIsRead());
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get is_read flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getMessageId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_id_set()) {
+            std::string stringid = std::to_string(priv->getId());
+            return JSUtil::toJSValueRef(context, stringid);
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get message id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting message id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getMessagePriority(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getIsHighPriority());
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get priority. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getMessageType(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context,
+                MessagingUtil::messageTypeToString(priv->getType()));
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get message type. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting message type.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getSourceAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_from_set()) {
+            return JSUtil::toJSValueRef(context, priv->getFrom());
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get source address. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting source address.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getSubject(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getSubject());
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get subject. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting subject.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getTime(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_timestamp_set()) {
+            return JSUtil::makeDateObject(context, priv->getTimestamp());
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get timestamp. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting timestamp.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getFolder(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_folder_id_set()) {
+            std::string stringid = std::to_string(priv->getFolderId());
+            return JSUtil::toJSValueRef(context, stringid);
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get folder id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting subject.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getMessageBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSMessageBody::makeJSObject(context, priv->getBody());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get MessageBody: %s", err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting BCC.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+bool JSMessage::setAttachments(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        if(!JSIsArrayValue(context,value)) {
+            return true;
+        }
+
+        auto priv = getPrivateObject(context, object);
+
+        AttachmentPtrVector atts;
+        atts = JSUtil::JSArrayToType_<std::shared_ptr<MessageAttachment>>(
+                context, value, JSMessageAttachment::getPrivateObject);
+        priv->setMessageAttachments(atts);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to set Attachments: %s", err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting Attachments.");
+    }
+    return true;
+}
+
+bool JSMessage::setBccAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        if(!JSIsArrayValue(context,value)) {
+            return true;
+        }
+
+        auto priv = getPrivateObject(context, object);
+
+        std::vector<std::string> bcc = JSUtil::JSArrayToStringVector(
+                context, value);
+        priv->setBCC(bcc);
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set BCC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting BCC.");
+    }
+    return true;
+}
+
+bool JSMessage::setCcAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        if(!JSIsArrayValue(context,value)) {
+            return true;
+        }
+
+        auto priv = getPrivateObject(context, object);
+
+        std::vector<std::string> cc = JSUtil::JSArrayToStringVector(
+                context, value);
+        priv->setCC(cc);
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set CC. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting CC.");
+    }
+    return true;
+}
+
+bool JSMessage::setDestinationAddress(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef * exception)
+{
+    LOGD("Entered");
+    try {
+        if(!JSIsArrayValue(context,value)) {
+            return true;
+        }
+
+        auto priv = getPrivateObject(context, object);
+
+        std::vector<std::string> to = JSUtil::JSArrayToStringVector(
+                context, value);
+        priv->setTO(to);
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set TO. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting TO.");
+    }
+    return true;
+}
+
+bool JSMessage::setIsRead(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef * exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        priv->setIsRead(JSUtil::JSValueToBoolean(context, value));
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set isRead flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return true;
+}
+
+bool JSMessage::setMessagePriority(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef * exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        priv->setIsHighPriority(JSUtil::JSValueToBoolean(context, value));
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set priority. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return true;
+}
+
+bool JSMessage::setSubject(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef * exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        priv->setSubject(JSUtil::JSValueToString(context, value));
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("Failed to set subject. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while setting subject.");
+    }
+    return true;
+}
+
+bool JSMessage::setMessageBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    // TODO: MessageBody setting problem should be solved in spec or implementation
+    return true;
+}
+
+JSValueRef JSMessage::getConversationId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_conversation_id_set()) {
+            std::string stringid = std::to_string(priv->getConversationId());
+            return JSUtil::toJSValueRef(context, stringid);
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get conversation id. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting conversation id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getInResponseTo(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_in_response_set()) {
+            std::string stringid = std::to_string(priv->getInResponseTo());
+            return JSUtil::toJSValueRef(context, stringid);
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get inResponeTo. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting inResponseTo.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::getMessageStatus(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context,
+                MessagingUtil::messageStatusToString(priv->getMessageStatus()));
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get message status. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    // Catch all exceptions not related to platform API execution failures
+    catch(...) {
+        LOGE("Unsupported error while getting message status.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessage::hasAttachment(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getHasAttachment());
+    }
+    catch(const BasePlatformException &err) {
+        LOGE("Failed to get hasAttachment flag. %s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessage.h b/src/messaging/old/JSMessage.h
new file mode 100644 (file)
index 0000000..4caa3ae
--- /dev/null
@@ -0,0 +1,253 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_H__
+#define __TIZEN_JS_MESSAGE_H__
+
+#include <JavaScriptCore/JavaScript.h>
+#include <Logger.h>
+#include "Message.h"
+// headers below needed to declare function that converts vector of
+// MessageAttachment into JSArray
+#include <vector>
+#include <memory>
+#include "MessageAttachment.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace JSMessageKeys {
+extern const char* MESSAGE_ATTRIBUTE_ID;
+extern const char* MESSAGE_ATTRIBUTE_CONVERSATION_ID;
+extern const char* MESSAGE_ATTRIBUTE_FOLDER_ID;
+extern const char* MESSAGE_ATTRIBUTE_TYPE;
+extern const char* MESSAGE_ATTRIBUTE_TIMESTAMP;
+extern const char* MESSAGE_ATTRIBUTE_FROM;
+extern const char* MESSAGE_ATTRIBUTE_TO;
+extern const char* MESSAGE_ATTRIBUTE_CC;
+extern const char* MESSAGE_ATTRIBUTE_BCC;
+extern const char* MESSAGE_ATTRIBUTE_BODY;
+extern const char* MESSAGE_ATTRIBUTE_IS_READ;
+extern const char* MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY;
+extern const char* MESSAGE_ATTRIBUTE_SUBJECT;
+extern const char* MESSAGE_ATTRIBUTE_IN_RESPONSE_TO;
+extern const char* MESSAGE_ATTRIBUTE_MESSAGE_STATUS;
+extern const char* MESSAGE_ATTRIBUTE_ATTACHMENTS;
+extern const char* MESSAGE_ATTRIBUTE_HAS_ATTACHMENT;
+} //namespace MESSAGE_ATTRIBUTE
+
+class JSMessage
+{
+public:
+    static const JSClassDefinition* getClassInfo();
+
+    static JSClassRef getClassRef();
+
+    static JSObjectRef constructor(JSContextRef ctx,
+            JSObjectRef constructor,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static std::shared_ptr<Message> getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<Message> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+            std::shared_ptr<Message> ptr);
+
+    /**
+     * Function converts vector of shared_pointers with Message into JSArray
+     */
+    static JSObjectRef messageVectorToJSObjectArray(JSContextRef context,
+            const MessagePtrVector& messages);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context,
+            JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getAttachments(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getBccAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getCcAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getDestinationAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getIsRead(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMessageId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMessagePriority(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMessageType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getSourceAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getSubject(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getTime(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getFolder(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMessageBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static bool setAttachments(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setBccAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setCcAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setDestinationAddress(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setIsRead(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setMessagePriority(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setSubject(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setMessageBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static JSValueRef getConversationId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getInResponseTo(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMessageStatus(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef hasAttachment(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSStaticFunction m_function[];
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This member variable contains the initialization values for the static properties of this class.
+     * The values are given according to the data structure JSPropertySpec
+     */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_H__
+
diff --git a/src/messaging/old/JSMessageAttachment.cpp b/src/messaging/old/JSMessageAttachment.cpp
new file mode 100644 (file)
index 0000000..62ee120
--- /dev/null
@@ -0,0 +1,350 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <SecurityExceptions.h>
+
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+
+#include "JSMessageAttachment.h"
+#include "MessageAttachment.h"
+
+#include "plugin_config.h"
+
+#include <JSUtil.h>
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE_ATTACHMENT = "MessageAttachment";
+
+const char* MESSAGE_ATTACHMENT_ID = "id";
+const char* MESSAGE_ATTACHMENT_MSG_ID = "messageId";
+const char* MESSAGE_ATTACHMENT_MIME_TYPE = "mimeType";
+const char* MESSAGE_ATTACHMENT_FILE_PATH = "filePath";
+}
+
+JSClassRef JSMessageAttachment::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageAttachment::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_ATTACHMENT,
+    NULL,
+    JSMessageAttachment::m_property,
+    NULL,
+    JSMessageAttachment::initialize,
+    JSMessageAttachment::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL, //callAsFunction,
+    NULL, //callAsConstructor,
+    NULL, //hasInstance,
+    NULL, //convertToType,
+};
+
+JSStaticValue JSMessageAttachment::m_property[] = {
+    { MESSAGE_ATTACHMENT_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTACHMENT_MSG_ID, getMsgId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTACHMENT_MIME_TYPE, getMimeType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_ATTACHMENT_FILE_PATH, getFilePath, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { 0, 0, 0, 0 }
+};
+
+const JSClassDefinition* JSMessageAttachment::getClassInfo()
+{
+    LOGD("Entered");
+    return &(m_classInfo);
+}
+
+JSClassRef DLL_EXPORT JSMessageAttachment::getClassRef()
+{
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+void JSMessageAttachment::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageAttachment::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    // Below holder is fetched from JSObject because holder
+    // with last shared_ptr instace should be removed
+    MessageAttachmentHolder* priv =
+            static_cast<MessageAttachmentHolder*>(JSObjectGetPrivate(object));
+    JSObjectSetPrivate(object, NULL);
+    delete priv;
+}
+
+std::shared_ptr<MessageAttachment> JSMessageAttachment::getPrivateObject(
+        JSContextRef context,
+        JSValueRef value)
+{
+    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGE("Object type do not match");
+        throw TypeMismatchException("Object type is not MessageAttachment");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+    MessageAttachmentHolder* priv = static_cast<MessageAttachmentHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw UnknownException("Private data holder is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessageAttachment::setPrivateObject(JSObjectRef object,
+        std::shared_ptr<MessageAttachment> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw UnknownException("NULL private data given");
+    }
+    MessageAttachmentHolder* priv = static_cast<MessageAttachmentHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    }
+    else {
+        priv = new(std::nothrow) MessageAttachmentHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in MessageAttachment");
+            throw UnknownException("Failed to set MessageAttachment private data");
+        }
+    }
+}
+
+JSObjectRef JSMessageAttachment::makeJSObject(JSContextRef context,
+        std::shared_ptr<MessageAttachment> native)
+{
+    if (!native) {
+        LOGE("NULL pointer to attachment given");
+        throw UnknownException("NULL pointer to attachment given");
+    }
+
+    MessageAttachmentHolder* priv = new(std::nothrow) MessageAttachmentHolder();
+    if (!priv) {
+        LOGW("Failed to allocate memory for AttachmentHolder");
+        throw UnknownException("Priv is null");
+    }
+    priv->ptr = native;
+
+    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
+    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
+        LOGE("Failed to set private in MessageAttachment");
+        throw UnknownException("Private data not set");
+    }
+    return obj;
+}
+
+JSObjectRef JSMessageAttachment::attachmentVectorToJSObjectArray(
+        JSContextRef context, const AttachmentPtrVector& atts)
+{
+    size_t count = atts.size();
+
+    JSObjectRef array[count];
+    for (size_t i = 0; i < count; i++) {
+        array[i] = JSMessageAttachment::makeJSObject(context, atts[i]);
+    }
+    JSObjectRef result = JSObjectMakeArray(context, count,
+            count > 0 ? array : NULL, NULL);
+    if (!result) {
+        LOGW("Failed to create MessageAttachment array");
+        throw UnknownException("MessageAttachment array is null");
+    }
+    return result;
+}
+
+JSObjectRef DLL_EXPORT JSMessageAttachment::constructor(JSContextRef context,
+            JSObjectRef constructor,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception)
+{
+    LOGD("Entered");
+
+    ArgumentValidator validator(context, argumentCount, arguments);
+
+    JSObjectRef jsObjRef = JSObjectMake(context, JSMessageAttachment::getClassRef(), NULL);
+
+    // constructor
+    JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor");
+    JSObjectSetProperty(context, jsObjRef, ctorName, constructor,
+        kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL);
+    JSStringRelease(ctorName);
+
+    try {
+        std::string filePath = validator.toString(0);
+        LOGD(" filePath: %s", filePath.c_str());
+
+        auto priv = std::shared_ptr<MessageAttachment>(new (std::nothrow)
+                MessageAttachment());
+        if(!priv) {
+            LOGE("Failed to allocate memory for private data");
+            throw UnknownException("Memory allocation failuer");
+        }
+
+        priv->setFilePath(filePath);
+        if (!validator.isNull(1) && !validator.isOmitted(1)) {
+            std::string mimeType = validator.toString(1, true);
+            LOGD(" mimeType: %s", mimeType.c_str());
+            priv->setMimeType(mimeType);
+        }
+
+        JSMessageAttachment::setPrivateObject(jsObjRef, priv);
+    }
+    catch (BasePlatformException &err) {
+        LOGE("MessageAttachment creation failed: %s", err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("MessageAttachment creation failed: Unknown exception.");
+    }
+
+    return jsObjRef;
+}
+
+JSValueRef JSMessageAttachment::getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception)
+{
+    LOGD("Entered");
+
+    try {
+        auto priv = JSMessageAttachment::getPrivateObject(context, object);
+
+        if (priv->isIdSet()) {
+            std::string stringid = std::to_string(priv->getId());
+            return JSUtil::toJSValueRef(context, stringid);
+        }else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("getMessageAttachmentId - unknown exception.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageAttachment::getMsgId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = JSMessageAttachment::getPrivateObject(context, object);
+
+        if (priv->isMessageIdSet()) {
+            std::string stringid = std::to_string(priv->getMessageId());
+            return JSUtil::toJSValueRef(context, stringid);
+        } else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("getMessageAttachmentMsgId - unknown exception.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageAttachment::getMimeType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = JSMessageAttachment::getPrivateObject(context, object);
+
+        if (priv->isMimeTypeSet()) {
+            return JSUtil::toJSValueRef(context, priv->getMimeType());
+        } else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("getMessageAttachmentMimeType - unknown exception.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageAttachment::getFilePath(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = JSMessageAttachment::getPrivateObject(context, object);
+
+        if (priv->isFilePathSet() && priv->isSaved()) {
+            return JSUtil::toJSValueRef(context, priv->getFilePath());
+        } else {
+            return JSValueMakeNull(context);
+        }
+
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("getMessageAttachmentFilePath - unknown exception.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessageAttachment.h b/src/messaging/old/JSMessageAttachment.h
new file mode 100755 (executable)
index 0000000..cfda6c7
--- /dev/null
@@ -0,0 +1,118 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_ATTACHMENT_H__
+#define __TIZEN_JS_MESSAGE_ATTACHMENT_H__
+
+#include <JavaScriptCore/JavaScript.h>
+#include <memory>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageAttachment;
+typedef std::vector<std::shared_ptr<MessageAttachment>> AttachmentPtrVector;
+
+class JSMessageAttachment
+{
+public:
+    static const JSClassDefinition* getClassInfo();
+
+    static JSClassRef getClassRef();
+
+    static JSObjectRef constructor(JSContextRef ctx,
+            JSObjectRef constructor,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static std::shared_ptr<MessageAttachment> getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<MessageAttachment> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+        std::shared_ptr<MessageAttachment> attptr);
+
+    /**
+     * Function converts vector of shared_pointers with MessageAttachment
+     * into JSArray
+     */
+    static JSObjectRef attachmentVectorToJSObjectArray(JSContextRef context,
+            const AttachmentPtrVector& atts);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context,
+            JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMsgId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMimeType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getFilePath(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    /**
+    * This structure describes a statically declared function property.
+    */
+    static JSStaticFunction m_function[];
+
+    /**
+    * This structure contains properties and callbacks that define a type of object.
+    */
+    static JSClassDefinition m_classInfo;
+
+    /**
+    * This member variable contains the initialization values for the static properties of this class.
+    * The values are given according to the data structure JSPropertySpec
+    */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_ATTACHMENT_H__
+
diff --git a/src/messaging/old/JSMessageBody.cpp b/src/messaging/old/JSMessageBody.cpp
new file mode 100644 (file)
index 0000000..afd250c
--- /dev/null
@@ -0,0 +1,342 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <JSUtil.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+
+#include "JSMessageBody.h"
+#include "MessageBody.h"
+#include "JSMessageAttachment.h"
+
+#include "plugin_config.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE_BODY = "MessageBody";
+
+const char* MESSAGE_BODY_ID = "messageId";
+const char* MESSAGE_BODY_LOADED = "loaded";
+const char* MESSAGE_BODY_PLAIN_BODY = "plainBody";
+const char* MESSAGE_BODY_HTML_BODY = "htmlBody";
+const char* MESSAGE_BODY_INLINE_ATT = "inlineAttachments";
+}
+
+JSClassRef JSMessageBody::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageBody::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_BODY,
+    NULL,
+    JSMessageBody::m_property,
+    NULL,
+    JSMessageBody::initialize,
+    JSMessageBody::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty
+    NULL, //setProperty
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames
+    NULL, //callAsFunction,
+    NULL, //callAsConstructor,
+    NULL, //hasInstance,
+    NULL, //convertToType,
+};
+
+JSStaticValue JSMessageBody::m_property[] = {
+    { MESSAGE_BODY_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_BODY_LOADED, getLoaded, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_BODY_PLAIN_BODY, getPlainBody, setPlainBody, kJSPropertyAttributeDontDelete },
+    { MESSAGE_BODY_HTML_BODY, getHTMLBody, setHTMLBody, kJSPropertyAttributeDontDelete },
+    { MESSAGE_BODY_INLINE_ATT, getInlineAtt, setInlineAtt, kJSPropertyAttributeDontDelete },
+    { 0, 0, 0, 0 }
+};
+
+const JSClassDefinition* JSMessageBody::getClassInfo()
+{
+    return &(m_classInfo);
+}
+
+JSClassRef JSMessageBody::getClassRef()
+{
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+void JSMessageBody::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageBody::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    // Below holder is fetched and deleted from JSObject because last shared_ptr
+    // instace should be removed
+    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
+            JSObjectGetPrivate(object));
+    JSObjectSetPrivate(object, NULL);
+    delete priv;
+}
+
+std::shared_ptr<MessageBody> JSMessageBody::getPrivateObject(
+        JSContextRef context,
+        JSValueRef value)
+{
+    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGE("Object type do not match");
+        throw TypeMismatchException("Object type is not MessageBody");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw UnknownException("Private data holder is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessageBody::setPrivateObject(JSObjectRef object,
+        std::shared_ptr<MessageBody> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw UnknownException("NULL private data given");
+    }
+    MessageBodyHolder* priv = static_cast<MessageBodyHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    }
+    else {
+        priv = new(std::nothrow) MessageBodyHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in MessageBody");
+            throw UnknownException(
+                    "Failed to set MessageBody private data");
+        }
+    }
+}
+
+JSObjectRef JSMessageBody::makeJSObject(JSContextRef context,
+        std::shared_ptr<MessageBody> ptr)
+{
+    if (!ptr) {
+        LOGE("NULL pointer to message body given");
+        throw UnknownException("NULL pointer to message body given");
+    }
+
+    MessageBodyHolder* priv = new(std::nothrow) MessageBodyHolder();
+    if (!priv) {
+        LOGW("Failed to allocate memory for MessageBodyHolder");
+        throw UnknownException("Priv is null");
+    }
+    priv->ptr = ptr;
+
+    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
+    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
+        LOGE("Failed to set private in MessageBody");
+        throw UnknownException("Private data not set");
+    }
+    return obj;
+}
+
+JSValueRef JSMessageBody::getId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        if(priv->is_message_id_set()) {
+            std::string stringid = std::to_string(priv->getMessageId());
+            return JSUtil::toJSValueRef(context, stringid);
+        }
+        else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageBody::getLoaded(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getLoaded());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageBody::getPlainBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getPlainBody());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageBody::getHTMLBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getHtmlBody());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageBody::getInlineAtt(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        return priv->getJSInlineAttachments(
+            Common::GlobalContextManager::getInstance()
+                ->getGlobalContext(context));
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+bool JSMessageBody::setPlainBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        std::string c_value = JSUtil::JSValueToString(context, value);
+        priv->setPlainBody(c_value);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return true;
+}
+
+bool JSMessageBody::setHTMLBody(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+
+        std::string c_value = JSUtil::JSValueToString(context, value);
+        priv->setHtmlBody(c_value);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return true;
+}
+
+bool JSMessageBody::setInlineAtt(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        if(!JSIsArrayValue(context,value)) {
+            return true;
+        }
+
+        auto priv = getPrivateObject(context, object);
+
+        AttachmentPtrVector atts;
+        atts = JSUtil::JSArrayToType_<std::shared_ptr<MessageAttachment>>(
+                context, value, JSMessageAttachment::getPrivateObject);
+        priv->setInlineAttachments(atts);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return true;
+}
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessageBody.h b/src/messaging/old/JSMessageBody.h
new file mode 100755 (executable)
index 0000000..29448ca
--- /dev/null
@@ -0,0 +1,125 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_BODY_H__
+#define __TIZEN_JS_MESSAGE_BODY_H__
+
+#include <JavaScriptCore/JavaScript.h>
+#include "MessageBody.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class JSMessageBody
+{
+public:
+    static const JSClassDefinition* getClassInfo();
+
+    static JSClassRef getClassRef();
+
+    static std::shared_ptr<MessageBody> getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<MessageBody> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+            std::shared_ptr<MessageBody> ptr);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context,
+            JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getLoaded(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getPlainBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getHTMLBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getInlineAtt(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static bool setPlainBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setHTMLBody(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setInlineAtt(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSStaticFunction m_function[];
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+    * This member variable contains the initialization values for the static properties of this class.
+    * The values are given according to the data structure JSPropertySpec
+    */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_BODY_H__
+
diff --git a/src/messaging/old/JSMessageConversation.cpp b/src/messaging/old/JSMessageConversation.cpp
new file mode 100644 (file)
index 0000000..360e54d
--- /dev/null
@@ -0,0 +1,444 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <SecurityExceptions.h>
+#include <PlatformException.h>
+#include <JSUtil.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+
+#include "JSMessageConversation.h"
+#include "MessageConversation.h"
+
+#include "plugin_config.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+using namespace DeviceAPI::Common;
+using namespace WrtDeviceApis::Commons;
+
+namespace {
+const char* MESSAGE_CONVERSATION = "MessageConversation";
+}
+
+namespace JSMessageConversationKeys {
+const char* MESSAGE_CONVERSATION_ID = "id";
+const char* MESSAGE_CONVERSATION_TYPE = "type";
+const char* MESSAGE_CONVERSATION_TIMESTAMP = "timestamp";
+const char* MESSAGE_CONVERSATION_MSG_COUNT = "messageCount";
+const char* MESSAGE_CONVERSATION_UNREAD_MSG = "unreadMessages";
+const char* MESSAGE_CONVERSATION_PREVIEW = "preview";
+const char* MESSAGE_CONVERSATION_SUBJECT = "subject";
+const char* MESSAGE_CONVERSATION_IS_READ = "isRead";
+const char* MESSAGE_CONVERSATION_FROM = "from";
+const char* MESSAGE_CONVERSATION_TO = "to";
+const char* MESSAGE_CONVERSATION_CC = "cc";
+const char* MESSAGE_CONVERSATION_BCC = "bcc";
+const char* MESSAGE_CONVERSATION_LAST_MSG_ID = "lastMessageId";
+}
+
+using namespace JSMessageConversationKeys;
+
+JSClassRef JSMessageConversation::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageConversation::m_classInfo =
+{
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_CONVERSATION,
+    NULL,
+    JSMessageConversation::m_property,
+    NULL,
+    JSMessageConversation::initialize,
+    JSMessageConversation::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL,
+    NULL,
+    NULL, //hasInstance,
+    NULL
+};
+
+JSStaticValue JSMessageConversation::m_property[] = {
+    { MESSAGE_CONVERSATION_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_TYPE, getType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_TIMESTAMP, getTimestamp, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_MSG_COUNT, getMsgCount, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_UNREAD_MSG, getUnreadMsg, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_PREVIEW, getPreview, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_SUBJECT, getSubject, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_IS_READ, getIsRead, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_FROM, getFrom, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_TO, getTo, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_CC, getCC, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_BCC, getBCC, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_CONVERSATION_LAST_MSG_ID, getLastMsgId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { 0, 0, 0, 0 }
+};
+
+JSClassRef DLL_EXPORT JSMessageConversation::getClassRef()
+{
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+const JSClassDefinition* JSMessageConversation::getClassInfo()
+{
+    LOGD("Entered");
+    return &m_classInfo;
+}
+
+void JSMessageConversation::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageConversation::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    MessageConversationHolder* priv =
+            static_cast<MessageConversationHolder*>(JSObjectGetPrivate(object));
+    JSObjectSetPrivate(object,NULL);
+    delete priv;
+}
+
+std::shared_ptr<MessageConversation> JSMessageConversation::getPrivateObject(
+        JSContextRef context, JSValueRef value)
+{
+    if(!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGW("Type mismatch");
+        throw TypeMismatchException("Type mismatch");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+
+    MessageConversationHolder* priv = static_cast<MessageConversationHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw UnknownException("Private data is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessageConversation::setPrivateObject(JSObjectRef object, std::shared_ptr<MessageConversation> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw UnknownException("NULL private data given");
+    }
+    MessageConversationHolder* priv = static_cast<MessageConversationHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    }
+    else {
+        priv = new(std::nothrow) MessageConversationHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in MessageConversation");
+            throw UnknownException(
+                    "Failed to set MessageConversation private data");
+        }
+    }
+}
+
+JSObjectRef JSMessageConversation::makeJSObject(JSContextRef context,
+        std::shared_ptr<MessageConversation> ptr)
+{
+    if (!ptr) {
+        LOGE("NULL pointer to message conversation given");
+        throw UnknownException("NULL pointer to message conversation given");
+    }
+
+    MessageConversationHolder* priv = new(std::nothrow) MessageConversationHolder();
+    if (!priv) {
+        LOGW("Failed to allocate memory for MessageConversationHolder");
+        throw UnknownException("Priv is null");
+    }
+    priv->ptr = ptr;
+
+    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
+    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
+        LOGE("Failed to set private in MessageConversation");
+        throw UnknownException("Private data not set");
+    }
+    return obj;
+}
+
+JSValueRef JSMessageConversation::getId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        std::string stringid = std::to_string(priv->getConversationId());
+        return JSUtil::toJSValueRef(context, stringid);
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getType(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, MessagingUtil::messageTypeToString(priv->getType()));
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation type.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getTimestamp(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::makeDateObject(context, priv->getTimestamp());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getMsgCount(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getMessageCount());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getUnreadMsg(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getUnreadMessages());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getPreview(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getPreview());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation preview.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getSubject(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getSubject());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation subject.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getIsRead(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getIsRead());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation isRead flag.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getFrom(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getFrom());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation source address.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getTo(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getTo());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting message conversation destination address.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getCC(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getCC());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting CC.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getBCC(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getBCC());
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting BCC.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageConversation::getLastMsgId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        std::string stringid = std::to_string(priv->getLastMessageId());
+        return JSUtil::toJSValueRef(context, stringid);
+    }
+    catch (const BasePlatformException &err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while getting last message id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+} //Messaging
+} //DeviceAPI
diff --git a/src/messaging/old/JSMessageConversation.h b/src/messaging/old/JSMessageConversation.h
new file mode 100755 (executable)
index 0000000..dd2c221
--- /dev/null
@@ -0,0 +1,162 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_CONVERSATION_H__
+#define __TIZEN_JS_MESSAGE_CONVERSATION_H__
+
+#include <JavaScriptCore/JavaScript.h>
+#include "MessageConversation.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace JSMessageConversationKeys {
+extern const char* MESSAGE_CONVERSATION_ID;
+extern const char* MESSAGE_CONVERSATION_TYPE;
+extern const char* MESSAGE_CONVERSATION_TIMESTAMP;
+extern const char* MESSAGE_CONVERSATION_MSG_COUNT;
+extern const char* MESSAGE_CONVERSATION_UNREAD_MSG;
+extern const char* MESSAGE_CONVERSATION_PREVIEW;
+extern const char* MESSAGE_CONVERSATION_SUBJECT;
+extern const char* MESSAGE_CONVERSATION_IS_READ;
+extern const char* MESSAGE_CONVERSATION_FROM;
+extern const char* MESSAGE_CONVERSATION_TO;
+extern const char* MESSAGE_CONVERSATION_CC;
+extern const char* MESSAGE_CONVERSATION_BCC;
+extern const char* MESSAGE_CONVERSATION_LAST_MSG_ID;
+}
+
+class JSMessageConversation
+{
+public:
+/* @struct JSClassDefinition
+ *@abstract This structure contains properties and callbacks that define a type of object.
+ *@abstract All fields other than the version field are optional. Any pointer may be NULL.
+ */
+    static const JSClassDefinition* getClassInfo();
+
+    static JSClassRef getClassRef();
+
+    static std::shared_ptr<MessageConversation> getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<MessageConversation> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+            std::shared_ptr<MessageConversation> ptr);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context, JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getTimestamp(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMsgCount(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getUnreadMsg(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getPreview(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getSubject(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getIsRead(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getFrom(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getTo(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getCC(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getBCC(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getLastMsgId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This member variable contains the initialization values for the static properties
+     * of this class.
+     * The values are given according to the data structure JSPropertySpec
+     */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_CONVERSATION_H__
diff --git a/src/messaging/old/JSMessageFolder.cpp b/src/messaging/old/JSMessageFolder.cpp
new file mode 100644 (file)
index 0000000..e9c977b
--- /dev/null
@@ -0,0 +1,402 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        JSMessageFolder.cpp
+ */
+
+
+#include <JSUtil.h>
+#include <SecurityExceptions.h>
+
+#include <Export.h>
+#include <Logger.h>
+
+#include "JSMessageFolder.h"
+#include "MessageFolder.h"
+#include "MessagingUtil.h"
+#include "MessageFolder.h"
+
+#include "plugin_config.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE_FOLDER = "MessageFolder";
+
+const char* MESSAGE_FOLDER_ID = "id";
+const char* MESSAGE_FOLDER_PARENT_ID = "parentId";
+const char* MESSAGE_FOLDER_SERVICE_ID = "serviceId";
+const char* MESSAGE_FOLDER_CONTENT_TYPE = "contentType";
+const char* MESSAGE_FOLDER_NAME = "name";
+const char* MESSAGE_FOLDER_PATH = "path";
+const char* MESSAGE_FOLDER_TYPE = "type";
+const char* MESSAGE_FOLDER_SYNCHRONIZABLE = "synchronizable";
+}
+
+JSClassRef JSMessageFolder::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageFolder::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_FOLDER,
+    NULL,
+    JSMessageFolder::m_property,
+    NULL,
+    JSMessageFolder::initialize,
+    JSMessageFolder::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL, //callAsFunction,
+    NULL, //callAsConstructor,
+    NULL, //hasInstance,
+    NULL, //convertToType,
+};
+
+JSStaticValue JSMessageFolder::m_property[] = {
+    { MESSAGE_FOLDER_ID, getId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_PARENT_ID, getParentId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_SERVICE_ID, getServiceId, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_CONTENT_TYPE, getContentType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_NAME, getName, setName, kJSPropertyAttributeDontDelete },
+    { MESSAGE_FOLDER_PATH, getPath, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_TYPE, getType, NULL, kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly },
+    { MESSAGE_FOLDER_SYNCHRONIZABLE, getSynchronizable, setSynchronizable, kJSPropertyAttributeDontDelete },
+    { 0, 0, 0, 0 }
+};
+
+JSClassRef JSMessageFolder::getClassRef() {
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+const JSClassDefinition* JSMessageFolder::getClassInfo() {
+    LOGD("Entered");
+    return &(m_classInfo);
+}
+
+void JSMessageFolder::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageFolder::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(JSObjectGetPrivate(object));
+    if(priv)
+    {
+        JSObjectSetPrivate(object,NULL);
+        delete priv;
+        priv = NULL;
+    }
+}
+
+std::shared_ptr<MessageFolder> JSMessageFolder::getPrivateObject(JSContextRef context,
+        JSValueRef value)
+{
+    if(!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGW("Type mismatch");
+        throw TypeMismatchException("Type mismatch");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+
+    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw UnknownException("Private data is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessageFolder::setPrivateObject(JSObjectRef object, std::shared_ptr<MessageFolder> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw UnknownException("NULL private data given");
+    }
+    MessageFolderHolder* priv = static_cast<MessageFolderHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    }
+    else {
+        priv = new(std::nothrow) MessageFolderHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in MessageFolder");
+            throw UnknownException(
+                    "Failed to set MessageFolder private data");
+        }
+    }
+}
+
+JSObjectRef JSMessageFolder::makeJSObject(JSContextRef context,
+        std::shared_ptr<MessageFolder> ptr)
+{
+    if (!ptr) {
+        LOGE("NULL pointer to message folder given");
+        throw UnknownException("NULL pointer to message folder given");
+    }
+
+    MessageFolderHolder* priv = new(std::nothrow) MessageFolderHolder();
+    if (!priv) {
+        LOGW("Failed to allocate memory for MessageFolderHolder");
+        throw UnknownException("Priv is null");
+    }
+    priv->ptr = ptr;
+
+    JSObjectRef obj = JSObjectMake(context, getClassRef(), NULL);
+    if(!JSObjectSetPrivate(obj, static_cast<void*>(priv))) {
+        LOGE("Failed to set private in MessageFolder");
+        throw UnknownException("Private data not set");
+    }
+    return obj;
+}
+
+JSValueRef JSMessageFolder::getId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getId());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder id. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getParentId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        if (priv->isParentIdSet()) {
+            return JSUtil::toJSValueRef(context, priv->getParentId());
+        } else {
+            return JSValueMakeNull(context);
+        }
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder parent id. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder parent id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getServiceId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getServiceId());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder service id. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder service id.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getContentType(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getContentType());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder content type. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder content type.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getName(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getName());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder name. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder name.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getPath(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getPath());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder path. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder path.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getType(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context,
+                MessagingUtil::messageFolderTypeToString(priv->getType()));
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder type. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while getting message folder type.");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageFolder::getSynchronizable(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        return JSUtil::toJSValueRef(context, priv->getSynchronizable());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to get message folder is synchronizable flag. %s : %s",
+                err.getName().c_str(), err.getMessage().c_str());
+    }
+    return JSValueMakeUndefined(context);
+}
+
+bool JSMessageFolder::setName(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        std::string c_value = JSUtil::JSValueToString(context, value);
+        priv->setName(c_value);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to set message folder name. %s : %s", err.getName().c_str(),
+                err.getMessage().c_str());
+    }
+    catch (...) {
+        LOGE("Unsupported error while setting message folder name.");
+    }
+    return true;
+}
+
+bool JSMessageFolder::setSynchronizable(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef value,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        auto priv = getPrivateObject(context, object);
+        bool c_value = JSUtil::JSValueToBoolean(context, value);
+        priv->setSynchronizable(c_value);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Failed to set message folder is synchronizable flag. %s : %s",
+                err.getName().c_str(), err.getMessage().c_str());
+    }
+    catch(...) {
+        LOGE("Unsupported error while setting message folder is synchronizable flag.");
+    }
+    return true;
+}
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessageFolder.h b/src/messaging/old/JSMessageFolder.h
new file mode 100755 (executable)
index 0000000..892474b
--- /dev/null
@@ -0,0 +1,133 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        JSMessageFolder.h
+ */
+
+
+#ifndef __TIZEN_JS_MESSAGE_FOLDER_H__
+#define __TIZEN_JS_MESSAGE_FOLDER_H__
+
+#include <JavaScriptCore/JavaScript.h>
+#include "MessageFolder.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class JSMessageFolder
+{
+public:
+    static const JSClassDefinition* getClassInfo();
+
+    static JSClassRef getClassRef();
+
+    static std::shared_ptr<MessageFolder> getPrivateObject(JSContextRef context, JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<MessageFolder> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+            std::shared_ptr<MessageFolder> ptr);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context, JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getParentId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getServiceId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getContentType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getName(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getPath(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getSynchronizable(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static bool setName(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    static bool setSynchronizable(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef value,
+            JSValueRef* exception);
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This member variable contains the initialization values for the static properties
+     * of this class.
+     * The values are given according to the data structure JSPropertySpec
+     */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_FOLDER_H__
+
diff --git a/src/messaging/old/JSMessageService.cpp b/src/messaging/old/JSMessageService.cpp
new file mode 100644 (file)
index 0000000..717d3d3
--- /dev/null
@@ -0,0 +1,587 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <SecurityExceptions.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <JSUtil.h>
+#include <Export.h>
+#include <Logger.h>
+#include <PlatformException.h>
+#include <TimeTracer.h>
+#include <tapi_common.h>
+
+#include "JSMessage.h"
+#include "JSMessageService.h"
+#include "MessageService.h"
+#include "MessagingUtil.h"
+
+#include "plugin_config.h"
+#include "JSMessageStorage.h"
+
+#include "JSMessageFolder.h"
+#include "JSMessageAttachment.h"
+
+#include "MessagingManager.h"
+
+using namespace std;
+using namespace DeviceAPI::Common;
+using namespace WrtDeviceApis::Commons;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE_SERVICE = "MessageService";
+
+const char* MESSAGE_SERVICE_ID = "id";
+const char* MESSAGE_SERVICE_TYPE = "type";
+const char* MESSAGE_SERVICE_NAME = "name";
+const char* MESSAGE_SERVICE_MSG_STORAGE = "messageStorage";
+}
+
+JSClassRef JSMessageService::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageService::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_SERVICE,
+    NULL,
+    JSMessageService::m_property,
+    JSMessageService::m_function,
+    JSMessageService::initialize,
+    JSMessageService::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL,
+    NULL,
+    NULL, //hasInstance,
+    NULL
+};
+
+JSStaticValue JSMessageService::m_property[] = {
+    { MESSAGE_SERVICE_ID, getId, NULL, kJSPropertyAttributeDontDelete
+            | kJSPropertyAttributeReadOnly },
+    { MESSAGE_SERVICE_TYPE, getType, NULL, kJSPropertyAttributeDontDelete
+            | kJSPropertyAttributeReadOnly },
+    { MESSAGE_SERVICE_NAME, getName, NULL, kJSPropertyAttributeDontDelete
+            | kJSPropertyAttributeReadOnly },
+    { MESSAGE_SERVICE_MSG_STORAGE, getMsgStorage, NULL, kJSPropertyAttributeDontDelete
+            | kJSPropertyAttributeReadOnly },
+    { 0, 0, 0, 0 }
+};
+
+JSStaticFunction JSMessageService::m_function[] = {
+    { MESSAGING_FUNCTION_API_SEND_MESSAGE, JSMessageService::sendMessage,
+            kJSPropertyAttributeNone },
+    { MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY, JSMessageService::loadMessageBody,
+            kJSPropertyAttributeNone },
+    { MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
+            JSMessageService::loadMessageAttachment, kJSPropertyAttributeNone },
+    { MESSAGING_FUNCTION_API_SYNC, JSMessageService::sync,
+            kJSPropertyAttributeNone },
+    { MESSAGING_FUNCTION_API_SYNC_FOLDER, JSMessageService::syncFolder,
+            kJSPropertyAttributeNone },
+    { MESSAGING_FUNCTION_API_STOP_SYNC, JSMessageService::stopSync,
+            kJSPropertyAttributeNone },
+    { 0, 0, 0 }
+};
+
+const JSClassRef JSMessageService::getClassRef()
+{
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+MessageService* JSMessageService::getPrivateObject(
+        JSContextRef context,
+        JSValueRef value)
+{
+    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGE("Object type do not match");
+        throw Common::TypeMismatchException("Object type is not MessageService");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+    MessageService* priv = static_cast<MessageService*>(JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw Common::UnknownException("Private data is null");
+    }
+
+    return priv;
+}
+
+JSObjectRef JSMessageService::createJSObject(JSContextRef context,
+        MessageService* priv)
+{
+    LOGD("Entered");
+    if (!priv) {
+        LOGE("Private data is null");
+        return NULL;
+    }
+    priv->copyAceCheckAccessFunction(MessagingManager::getInstance());
+    JSObjectRef jsObject = JSObjectMake(context, getClassRef(),
+            static_cast<void*>(priv));
+    if (NULL == jsObject) {
+        LOGE("object creation error");
+    }
+
+    return jsObject;
+}
+
+void JSMessageService::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageService::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    MessageService* priv = static_cast<MessageService*>(JSObjectGetPrivate(object));
+    if (priv) {
+        JSObjectSetPrivate(object, NULL);
+        delete priv;
+        priv = NULL;
+    }
+}
+
+JSValueRef JSMessageService::getType(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        MessageService* priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context,
+            MessagingUtil::messageTypeToString(priv->getMsgServiceType()));
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error, cannot get property");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::getName(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        MessageService* priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getMsgServiceName());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error, cannot get property");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::getId(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        MessageService* priv = getPrivateObject(context, object);
+
+        return JSUtil::toJSValueRef(context, priv->getMsgServiceIdStr());
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error, cannot get property");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::getMsgStorage(JSContextRef context,
+        JSObjectRef object,
+        JSStringRef propertyName,
+        JSValueRef* exception)
+{
+    LOGD("Entered");
+    try {
+        MessageService* priv = getPrivateObject(context, object);
+
+        std::shared_ptr<MessageStorage> storage = priv->getMsgStorage();
+        storage->copyAceCheckAccessFunction(priv);
+
+        return JSMessageStorage::makeJSObject(context, storage);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error, cannot get property");
+    }
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::sendMessage(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessageRecipientsCallbackData *callback = NULL;
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_SEND_MESSAGE);
+
+        // void sendMessage(Message message,
+        //         optional MessageRecipientsCallback successCallback,
+        //         optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
+                validator.toJSValueRef(0));
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) MessageRecipientsCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setMessage(message);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        // internally TelNetworkDefaultDataSubs_t consists of -1(unknown), 0(sim_1), 1(sim_2)
+        // but in spec, simIndex parameter starts with 1.
+        // so if user set simIndex param, then minus 1 on it.
+        long tmp = validator.toLong(3, true, 0);
+        char **cp_list = tel_get_cp_name_list();
+        int sim_count = 0;
+
+        if (cp_list) {
+            while (cp_list[sim_count]) {
+                sim_count++;
+            }
+            g_strfreev(cp_list);
+        } else {
+            LOGD("Empty cp name list");
+        }
+
+        tmp--;
+        if (tmp >= sim_count || tmp < -1) {
+            LOGE("Sim index out of bound %d : %d", tmp, sim_count);
+            Common::InvalidValuesException err("The index of sim is out of bound");
+            callback->setError(err.getName().c_str(), err.getMessage().c_str());
+            callback->callErrorCallback();
+
+            delete callback;
+            callback = NULL;
+            return JSValueMakeUndefined(context);
+        }
+
+        callback->setSimIndex(static_cast<TelNetworkDefaultDataSubs_t>(tmp));
+        priv->sendMessage(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Unknown error, cannot send message");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::loadMessageBody(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+
+    MessageBodyCallbackData *callback = NULL;
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY);
+        // void loadMessageBody(Message message,
+        //         MessageBodySuccessCallback successCallback,
+        //         optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
+                validator.toJSValueRef(0));
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) MessageBodyCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setMessage(message);
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->loadMessageBody(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        Common::UnknownException err("Cannot load message body");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::loadMessageAttachment(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessageAttachmentCallbackData *callback = NULL;
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT);
+        // void loadMessageAttachment(MessageAttachment attachment,
+        //         MessageAttachmentSuccessCallback successCallback,
+        //         optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        JSValueRef jsMsgAttachment = validator.toJSValueRef(0);
+        std::shared_ptr<MessageAttachment> attachment =
+                JSMessageAttachment::getPrivateObject(context, jsMsgAttachment);
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) MessageAttachmentCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setMessageAttachment(attachment);
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->loadMessageAttachment(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        Common::UnknownException err("Cannot load message attachment");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageService::sync(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    SyncCallbackData *callback = NULL;
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_SYNC);
+        // long sync(optional SuccessCallback? successCallback,
+        //           optional ErrorCallback? errorCallback,
+        //           optional unsigned long? limit);
+        ArgumentValidator validator(context, argumentCount, arguments);
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) SyncCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setSuccessCallback(validator.toFunction(0, true));
+        callback->setErrorCallback(validator.toFunction(1, true));
+        // if limit is not provided or is null
+        // default value is used in MessageService
+        if (!validator.isOmitted(2) && !validator.isNull(2)) {
+            callback->setLimit(validator.toULong(2));
+        }
+
+        long op_id = priv->sync(callback);
+        return JSUtil::toJSValueRef(context, op_id);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        Common::UnknownException err("Cannot sync with external mail server");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+}
+
+JSValueRef JSMessageService::syncFolder(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    SyncFolderCallbackData *callback = NULL;
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_SYNC_FOLDER);
+        // long syncFolder(MessageFolder folder,
+        //         optional SuccessCallback? successCallback,
+        //         optional ErrorCallback? errorCallback,
+        //         optional unsigned long? limit);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::shared_ptr<MessageFolder> messageFolder =
+                JSMessageFolder::getPrivateObject(context, validator.toJSValueRef(0));
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) SyncFolderCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setMessageFolder(messageFolder);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+        // if limit is not provided or is null
+        // default value is used in MessageService
+        if (!validator.isOmitted(3) && !validator.isNull(3)) {
+            callback->setLimit(validator.toULong(3));
+        }
+
+        long op_id = priv->syncFolder(callback);
+        return JSUtil::toJSValueRef(context, op_id);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        Common::UnknownException err("Cannot sync folder with external server");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+}
+
+JSValueRef JSMessageService::stopSync(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    try {
+        MessageService* priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv,
+                MESSAGING_FUNCTION_API_STOP_SYNC);
+
+        // void stopSync(long opId);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        long opId = validator.toLong(0);
+
+        priv->stopSync(opId);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        Common::UnknownException err("Cannot stop sync with external server");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessageService.h b/src/messaging/old/JSMessageService.h
new file mode 100755 (executable)
index 0000000..d0c091d
--- /dev/null
@@ -0,0 +1,141 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_SERVICE_H__
+#define __TIZEN_JS_MESSAGE_SERVICE_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+#include "MessageService.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class JSMessageService
+{
+public :
+    static const JSClassDefinition* getClassInfo();
+
+    static const JSClassRef getClassRef();
+
+    static MessageService* getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static JSObjectRef createJSObject(JSContextRef context,
+            MessageService* priv);
+
+private :
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context, JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef getId(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getType(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getName(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef getMsgStorage(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName,
+            JSValueRef* exception);
+
+    static JSValueRef sendMessage(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef loadMessageBody(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef loadMessageAttachment(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef sync(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef syncFolder(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef stopSync(JSContextRef context,
+            JSObjectRef function,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This member variable contains the initialization values for the static properties of this class.
+     * The values are given according to the data structure JSPropertySpec
+     */
+    static JSStaticValue m_property[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSStaticFunction m_function[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+}; //JSMessageService
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_SERVICE_H__
+
diff --git a/src/messaging/old/JSMessageStorage.cpp b/src/messaging/old/JSMessageStorage.cpp
new file mode 100644 (file)
index 0000000..1ee110b
--- /dev/null
@@ -0,0 +1,882 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <SecurityExceptions.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+#include <PlatformException.h>
+#include <JSAttributeFilter.h>
+#include <JSSortMode.h>
+#include <JSUtil.h>
+#include <vector>
+#include <TimeTracer.h>
+
+
+#include "JSMessage.h"
+#include "JSMessageConversation.h"
+#include "Message.h"
+#include "MessageCallbackUserData.h"
+#include "JSMessageStorage.h"
+#include "MessagesChangeCallback.h"
+#include "ConversationsChangeCallback.h"
+#include "FoldersChangeCallback.h"
+#include "AbstractFilter.h"
+
+#include "plugin_config_impl.h"
+#include "MessagesCallbackUserData.h"
+#include "FindMsgCallbackUserData.h"
+#include "ConversationCallbackData.h"
+
+using namespace std;
+using namespace DeviceAPI::Common;
+using namespace WrtDeviceApis::Commons;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGE_STORAGE = "MessageStorage";
+}
+
+JSClassRef JSMessageStorage::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessageStorage::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGE_STORAGE,
+    NULL,
+    NULL,
+    JSMessageStorage::m_function,
+    JSMessageStorage::initialize,
+    JSMessageStorage::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL,
+    NULL,
+    NULL,
+    NULL
+};
+
+JSStaticFunction JSMessageStorage::m_function[] = {
+    { MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE, JSMessageStorage::addDraftMessage, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_FIND_MESSAGES, JSMessageStorage::findMessages, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_REMOVE_MESSAGES, JSMessageStorage::removeMessages, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_UPDATE_MESSAGES, JSMessageStorage::updateMessages, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_FIND_CONVERSATIONS, JSMessageStorage::findConversations, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS, JSMessageStorage::removeConversations, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_FIND_FOLDERS, JSMessageStorage::findFolders, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER, JSMessageStorage::addMessagesChangeListener, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER, JSMessageStorage::addConversationsChangeListener, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER, JSMessageStorage::addFoldersChangeListener, kJSPropertyAttributeDontDelete },
+    { MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER, JSMessageStorage::removeChangeListener, kJSPropertyAttributeDontDelete },
+    { 0, 0, 0 }
+};
+
+const JSClassRef JSMessageStorage::getClassRef()
+{
+    LOGD("Entered");
+    if (!m_jsClassRef)
+    {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+std::shared_ptr<MessageStorage> JSMessageStorage::getPrivateObject(
+        JSContextRef context,
+        JSValueRef value)
+{
+    if (!JSValueIsObjectOfClass(context, value, getClassRef())) {
+        LOGE("Object type do not match");
+        throw Common::TypeMismatchException("Object type is not MessageStorage");
+    }
+
+    JSObjectRef object = JSUtil::JSValueToObject(context, value);
+    MessageStorageHolder* priv = static_cast<MessageStorageHolder*>(
+            JSObjectGetPrivate(object));
+    if (!priv) {
+        LOGE("NULL private data");
+        throw Common::UnknownException("Private data holder is null");
+    }
+    if (!(priv->ptr)) {
+        LOGE("NULL shared pointer in private data");
+        throw Common::UnknownException("Private data is null");
+    }
+
+    return priv->ptr;
+}
+
+void JSMessageStorage::setPrivateObject(JSObjectRef object,
+        std::shared_ptr<MessageStorage> data)
+{
+    if (!data) {
+        LOGE("NULL shared pointer given to set as private data");
+        throw Common::UnknownException("NULL private data given");
+    }
+    MessageStorageHolder* priv = static_cast<MessageStorageHolder*>(
+            JSObjectGetPrivate(object));
+    if (priv) {
+        priv->ptr = data;
+    } else {
+        priv = new(std::nothrow) MessageStorageHolder();
+        if (!priv) {
+            LOGE("Memory allocation failure");
+            throw Common::UnknownException("Failed to allocate memory");
+        }
+        priv->ptr = data;
+        if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) {
+            delete priv;
+            priv = NULL;
+            LOGE("Failed to set private data in MessageStorage");
+            throw Common::UnknownException(
+                    "Failed to set MessageStorage private data");
+        }
+    }
+}
+
+JSObjectRef JSMessageStorage::makeJSObject(JSContextRef context,
+    std::shared_ptr<MessageStorage> ptr)
+{
+    LOGD("Entered");
+    if (!ptr) {
+        LOGE("Private data is null");
+        throw Common::UnknownException("Private object is NULL");
+    }
+
+    MessageStorageHolder* priv = new(std::nothrow) MessageStorageHolder();
+    if (!priv) {
+        LOGE("Failed to allocate memory for MessageStorageHolder");
+        throw Common::UnknownException("Failed to allocate memory");
+    }
+    priv->ptr = ptr;
+
+    JSObjectRef jsObject = JSObjectMake(context, getClassRef(),
+            static_cast<void*>(priv));
+    if (!jsObject) {
+        LOGE("Object creation failed");
+        throw Common::UnknownException("Object creation failed");
+    }
+
+    return jsObject;
+}
+
+void JSMessageStorage::initialize(JSContextRef context, JSObjectRef object)
+{
+    LOGD("Entered");
+}
+
+void JSMessageStorage::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    MessageStorageHolder* priv =
+            static_cast<MessageStorageHolder*>(JSObjectGetPrivate(object));
+    if (priv) {
+        JSObjectSetPrivate(object, NULL);
+        delete priv;
+        priv = NULL;
+    }
+}
+
+JSValueRef JSMessageStorage::addDraftMessage(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessageCallbackUserData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE);
+
+        // void addDraftMessage(Message message,
+        //         optional SuccessCallback? successCallback,
+        //.        optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::shared_ptr<Message> message = JSMessage::getPrivateObject(context,
+                validator.toJSValueRef(0));
+
+        JSContextRef g_ctx = GlobalContextManager::getInstance()
+                ->getGlobalContext(context);
+        callback = new(std::nothrow) MessageCallbackUserData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setMessage(message);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->addDraftMessage(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Unknown error, cannot add draft message");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::findMessages(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    FindMsgCallbackUserData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_FIND_MESSAGES);
+        /*
+         * void findMessages(AbstractFilter filter,
+         *          MessageArraySuccessCallback successCallback,
+         *          optional ErrorCallback? errorCallback,
+         *          optional SortMode? sort,
+         *          optional unsigned long? limit,
+         *          optional unsigned long? offset);
+         */
+        JSContextRef g_ctx = GlobalContextManager::getInstance()
+                ->getGlobalContext(context);
+        callback = new FindMsgCallbackUserData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        ArgumentValidator validator(context, argumentCount, arguments);
+
+        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                getPrivateObject(context, validator.toJSValueRef(0));
+
+        if (!filter) {
+            LOGE("Wrong filter");
+            throw Common::TypeMismatchException("Invalid filter");
+        }
+        callback->setFilter(filter);
+
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        JSObjectRef sortmodeobj = validator.toObject(3, true);
+        if(sortmodeobj != NULL){
+            DeviceAPI::Tizen::SortModePtr sortMode =
+                    Tizen::JSSortMode::getPrivateObject(context, sortmodeobj);
+            LOGD("sort mode is set");
+            callback->setSortMode(sortMode);
+        }
+
+        callback->setLimit(validator.toULong(4, true, 0));
+        callback->setOffset(validator.toULong(5, true, 0));
+        priv->findMessages(callback);
+    }
+    catch (const WrtDeviceApis::Commons::Exception& exc) {
+        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
+        Common::TypeMismatchException err(exc.GetMessage().c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }catch (...) {
+        Common::UnknownException err("Unknown error, cannot find messages");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::removeMessages(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessagesCallbackUserData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_REMOVE_MESSAGES);
+        /**
+         * void removeMessages(Message[] messages,
+         *          optional SuccessCallback? successCallback,
+         *          optional ErrorCallback? errorCallback);
+         */
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::vector<JSValueRef> messages = validator.toJSValueRefVector(0);
+        JSContextRef g_ctx = GlobalContextManager::getInstance()
+                ->getGlobalContext(context);
+        callback = new MessagesCallbackUserData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        callback->addMessages(context, messages);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->removeMessages(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Unknown error, cannot remove messages");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::updateMessages(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessagesCallbackUserData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_UPDATE_MESSAGES);
+        /**
+         * void updateMessages (Message[] messages,
+         *          optional SuccessCallback? successCallback,
+         *          optional ErrorCallback? errorCallback)
+         */
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::vector<JSValueRef> messages = validator.toJSValueRefVector(0);
+        JSContextRef g_ctx = GlobalContextManager::getInstance()
+                ->getGlobalContext(context);
+        callback = new MessagesCallbackUserData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        callback->addMessages(context, messages);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->updateMessages(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Unknown error, cannot update messages");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::findConversations(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    ConversationCallbackData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_FIND_CONVERSATIONS);
+        // void findConversations (AbstractFilter filter,
+        //         MessageConversationArraySuccessCallback successCallback,
+        //         optional ErrorCallback? errorCallback,
+        //         optional SortMode? sort,
+        //         optional unsigned long? limit,
+        //         optional unsigned long? offset)
+        ArgumentValidator validator(context, argumentCount, arguments);
+
+        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                getPrivateObject(context, validator.toJSValueRef(0));
+        if (!filter) {
+            LOGE("Wrong filter");
+            throw Common::TypeMismatchException("Invalid filter");
+        }
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new ConversationCallbackData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        callback->setFilter(filter);
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        JSObjectRef sortmodeobj = validator.toObject(3, true);
+        if(sortmodeobj != NULL){
+            DeviceAPI::Tizen::SortModePtr sortMode =
+                    Tizen::JSSortMode::getPrivateObject(context, sortmodeobj);
+            if (!sortMode) {
+                LOGE("Wrong sort mode");
+                throw Common::TypeMismatchException("Invalid sort mode");
+            }
+            LOGD("sort mode is set");
+            callback->setSortMode(sortMode);
+        }
+
+        callback->setLimit(validator.toULong(4, true, 0));
+        callback->setOffset(validator.toULong(5, true, 0));
+
+        priv->findConversations(callback);
+    }
+    catch (const WrtDeviceApis::Commons::Exception& exc) {
+        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
+        Common::TypeMismatchException err(exc.GetMessage().c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot find conversations");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::removeConversations(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    ConversationCallbackData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
+                thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS);
+        // void removeConversation(MessageConversation[] conversations,
+        //         optional SuccessCallback? successCallback,
+        //         optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        std::vector<JSValueRef> conversations = validator.toJSValueRefVector(0);
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new ConversationCallbackData(g_ctx);
+        LOGD("created new callback: %p", callback);
+
+        callback->addConversations(context, conversations);
+        callback->setSuccessCallback(validator.toFunction(1, true));
+        callback->setErrorCallback(validator.toFunction(2, true));
+
+        priv->removeConversations(callback);
+    } catch (const BasePlatformException& err) {
+        LOGE("%s : %s", err.getName().c_str(), err.getMessage().c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    } catch (...) {
+        LOGE("Unknown error while removing conversation");
+        delete callback;
+        callback = NULL;
+        Common::UnknownException err("Cannot remove conversations");
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::findFolders(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    FoldersCallbackData* callback = NULL;
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_FIND_FOLDERS);
+        // void findFolders(AbstractFilter filter,
+        //         MessageFolderArraySuccessCallback successCallback,
+        //         optional ErrorCallback? errorCallback);
+        ArgumentValidator validator(context, argumentCount, arguments);
+
+        DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                getPrivateObject(context, validator.toJSValueRef(0));
+        if (!filter) {
+            LOGE("Wrong filter");
+            throw Common::TypeMismatchException("Invalid filter");
+        }
+
+        JSContextRef global_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+
+        callback = new FoldersCallbackData(global_ctx);
+        LOGD("created new callback: %p", callback);
+
+        callback->setFilter(filter);
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+        priv->findFolders(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot find folders");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSValueRef JSMessageStorage::addMessagesChangeListener(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context, thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER);
+        // long addMessagesChangeListener (
+        //         MessagesChangeCallback messagesChangeCallback,
+        //         optional AbstractFilter filter)
+        ArgumentValidator validator(context, argumentCount, arguments);
+        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0, false,
+                MESSAGESADDED, MESSAGESUPDATED, MESSAGESREMOVED, NULL);
+
+        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, MESSAGESADDED);
+        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, MESSAGESUPDATED);
+        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, MESSAGESREMOVED);
+
+
+        JSContextRef global_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+
+        auto callback = std::make_shared<MessagesChangeCallback>(
+                global_ctx,
+                on_added_obj,
+                on_updateded_obj,
+                on_removed_obj,
+                priv->getMsgServiceId(),
+                priv->getMsgServiceType());
+
+        JSObjectRef filterobj = validator.toObject(1, true);
+        if (filterobj != NULL) {
+            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                    getPrivateObject(context, validator.toJSValueRef(1));
+            if (!filter) {
+                LOGE("Wrong filter");
+                throw Common::TypeMismatchException("Invalid filter");
+            }
+            LOGD("filter is set");
+            callback->setFilter(filter);
+        }
+        return JSValueMakeNumber(context, priv->addMessagesChangeListener(callback));
+    }
+    catch (const WrtDeviceApis::Commons::Exception& exc) {
+        LOGE("Wrong sort/filer mode: %s", exc.GetMessage().c_str());
+        Common::TypeMismatchException err(exc.GetMessage().c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot add listener for messages");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+}
+
+JSValueRef JSMessageStorage::addConversationsChangeListener(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
+                thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER);
+        // long addConversationsChangeListener(
+        //         MessageConversationsChangeCallback conversationsChangeCallback,
+        //         optional AbstractFilter? filter)
+        ArgumentValidator validator(context, argumentCount, arguments);
+        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0,false,
+                CONVERSATIONSADDED, CONVERSATIONSUPDATED, CONVERSATIONSREMOVED,
+                NULL);
+
+        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, CONVERSATIONSADDED);
+        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, CONVERSATIONSUPDATED);
+        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, CONVERSATIONSREMOVED);
+
+        JSContextRef global_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+
+        auto callback = std::make_shared<ConversationsChangeCallback>(
+                global_ctx,
+                on_added_obj,
+                on_updateded_obj,
+                on_removed_obj,
+                priv->getMsgServiceId(),
+                priv->getMsgServiceType());
+
+        JSObjectRef filterobj = validator.toObject(1, true);
+        if (filterobj != NULL) {
+            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                    getPrivateObject(context, validator.toJSValueRef(1));
+            if (!filter) {
+                LOGE("Wrong filter");
+                throw Common::TypeMismatchException("Invalid filter");
+            }
+            LOGD("filter is set");
+            callback->setFilter(filter);
+        }
+
+        return JSValueMakeNumber(context,
+                priv->addConversationsChangeListener(callback));
+    }
+    catch (const WrtDeviceApis::Commons::Exception& exc) {
+        LOGE("Wrong filer mode: %s", exc.GetMessage().c_str());
+        Common::TypeMismatchException err(exc.GetMessage().c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot add listener for conversations");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+}
+
+
+JSValueRef JSMessageStorage::addFoldersChangeListener(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
+                thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER);
+        // long addFoldersChangeListener(
+        //         MessageFoldersChangeCallback foldersChangeCallback,
+        //         optional AbstractFilter? filter);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        JSObjectRef js_callbacks_obj = validator.toCallbackObject(0, false,
+                FOLDERSADDED, FOLDERSUPDATED, FOLDERSREMOVED, NULL);
+
+        JSObjectRef on_added_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, FOLDERSADDED);
+        JSObjectRef on_updateded_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, FOLDERSUPDATED);
+        JSObjectRef on_removed_obj = getFunctionFromCallbackObj(context,
+                js_callbacks_obj, FOLDERSREMOVED);
+
+        JSContextRef global_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+
+        auto callback = std::make_shared<FoldersChangeCallback>(
+                global_ctx,
+                on_added_obj,
+                on_updateded_obj,
+                on_removed_obj,
+                priv->getMsgServiceId(),
+                priv->getMsgServiceType());
+
+        JSObjectRef filterobj = validator.toObject(1, true);
+        if (filterobj != NULL) {
+            DeviceAPI::Tizen::AbstractFilterPtr filter = Tizen::AbstractFilter::
+                    getPrivateObject(context, validator.toJSValueRef(1));
+            if (!filter) {
+                LOGE("Wrong filter");
+                throw Common::TypeMismatchException("Invalid filter");
+            }
+            LOGD("filter is set");
+            callback->setFilter(filter);
+        }
+
+        return JSValueMakeNumber(context, priv->addFoldersChangeListener(callback));
+    }
+    catch (const WrtDeviceApis::Commons::Exception& exc) {
+        LOGE("Wrong filer mode: %s", exc.GetMessage().c_str());
+        Common::TypeMismatchException err(exc.GetMessage().c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot add listener for folders");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+}
+
+JSValueRef JSMessageStorage::removeChangeListener(JSContextRef context,
+        JSObjectRef function,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    try {
+        std::shared_ptr<MessageStorage> priv = getPrivateObject(context,
+                thisObject);
+        TIZEN_CHECK_ACCESS(context, exception, priv.get(),
+                MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER);
+        // void removeChangeListener(long watchId);
+        ArgumentValidator validator(context, argumentCount, arguments);
+        long watchId = validator.toLong(0);
+
+        priv->removeChangeListener(context, watchId);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Cannot add listener for folders");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+JSObjectRef JSMessageStorage::getFunctionFromCallbackObj(JSContextRef context,
+        JSObjectRef obj,
+        const char* name)
+{
+    JSObjectRef function_obj = NULL;
+    JSStringRef propertyName = JSStringCreateWithUTF8CString(name);
+    bool has = JSObjectHasProperty(context, obj, propertyName);
+    JSStringRelease(propertyName);
+    if (has) {
+        JSValueRef value = JSUtil::getProperty(context, obj, name);
+        function_obj = JSUtil::JSValueToObject(context, value);
+    }
+    return function_obj;
+}
+
+} //Messaging
+} //DeviceAPI
+
diff --git a/src/messaging/old/JSMessageStorage.h b/src/messaging/old/JSMessageStorage.h
new file mode 100755 (executable)
index 0000000..c841e08
--- /dev/null
@@ -0,0 +1,160 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGE_STORAGE_H__
+#define __TIZEN_JS_MESSAGE_STORAGE_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+#include <memory>
+
+#include "MessageStorage.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class JSMessageStorage
+{
+public:
+// @struct JSClassDefinition
+// @abstract This structure contains properties and callbacks that define a type of object. All fields other than the version field are optional. Any pointer may be NULL.
+    static const JSClassDefinition* getClassInfo();
+
+    static const JSClassRef getClassRef();
+
+    static std::shared_ptr<MessageStorage> getPrivateObject(JSContextRef context,
+            JSValueRef value);
+
+    static void setPrivateObject(JSObjectRef object,
+            std::shared_ptr<MessageStorage> data);
+
+    static JSObjectRef makeJSObject(JSContextRef context,
+            std::shared_ptr<MessageStorage> ptr);
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context, JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    static JSValueRef addDraftMessage(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef findMessages(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef findConversations(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef removeConversations(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef findFolders(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+     static JSValueRef removeMessages(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+     static JSValueRef updateMessages(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef addMessagesChangeListener(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef addConversationsChangeListener(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef addFoldersChangeListener(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    static JSValueRef removeChangeListener(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSStaticFunction m_function[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+    static JSObjectRef getFunctionFromCallbackObj(JSContextRef context,
+            JSObjectRef obj,
+            const char* name);
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGE_STORAGE_H__
+
diff --git a/src/messaging/old/JSMessagingManager.cpp b/src/messaging/old/JSMessagingManager.cpp
new file mode 100755 (executable)
index 0000000..70c00d8
--- /dev/null
@@ -0,0 +1,182 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <string.h>
+
+#include <JSWebAPIErrorFactory.h>
+
+#include <GlobalContextManager.h>
+#include <ArgumentValidator.h>
+#include <Export.h>
+#include <Logger.h>
+#include <TimeTracer.h>
+#include <system_info.h>
+
+#include "JSMessagingManager.h"
+#include "MessagingManager.h"
+#include "MessagingUtil.h"
+
+#include "plugin_config_impl.h"
+
+using namespace std;
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const char* MESSAGING = "Messaging";
+}
+
+JSClassRef JSMessagingManager::m_jsClassRef = NULL;
+
+JSClassDefinition JSMessagingManager::m_classInfo = {
+    0,
+    kJSClassAttributeNone,
+    MESSAGING,
+    NULL,
+    NULL,
+    JSMessagingManager::m_function,
+    JSMessagingManager::initialize,
+    JSMessagingManager::finalize,
+    NULL, //hasProperty,
+    NULL, //getProperty,
+    NULL, //setProperty,
+    NULL, //deleteProperty,
+    NULL, //getPropertyNames,
+    NULL,
+    NULL,
+    NULL, //hasInstance,
+    NULL
+};
+
+JSStaticFunction JSMessagingManager::m_function[] = {
+        { MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
+                JSMessagingManager::getMessageServices, kJSPropertyAttributeNone },
+        { 0, 0, 0 }
+};
+
+const JSClassDefinition* JSMessagingManager::getClassInfo() {
+    LOGD("Entered");
+    return &(m_classInfo);
+}
+
+const JSClassRef DLL_EXPORT JSMessagingManager::getClassRef() {
+    LOGD("Entered");
+    if (!m_jsClassRef) {
+        m_jsClassRef = JSClassCreate(&m_classInfo);
+    }
+    return m_jsClassRef;
+}
+
+void JSMessagingManager::initialize(JSContextRef context,
+        JSObjectRef object)
+{
+    LOGD("Entered");
+    JSObjectSetPrivate(object, static_cast<void*>(&(MessagingManager::getInstance())));
+}
+
+void JSMessagingManager::finalize(JSObjectRef object)
+{
+    LOGD("Entered");
+    JSObjectSetPrivate(object, NULL);
+}
+
+JSValueRef JSMessagingManager::getMessageServices(JSContextRef context,
+        JSObjectRef object,
+        JSObjectRef thisObject,
+        size_t argumentCount,
+        const JSValueRef arguments[],
+        JSValueRef* exception)
+{
+    SET_TIME_TRACER_ITEM(0);
+    LOGD("Entered");
+
+    MessageServiceCallbackData *callback = NULL;
+    bool isSupported = false;
+
+    try {
+        ArgumentValidator validator(context, argumentCount, arguments);
+        MessageType msgTag = MessagingUtil::stringToMessageType(validator.toString(0));
+        LOGD("Messaging Service Type: %d", msgTag);
+
+        JSContextRef g_ctx =
+                GlobalContextManager::getInstance()->getGlobalContext(context);
+        callback = new(std::nothrow) MessageServiceCallbackData(g_ctx);
+        if (!callback) {
+            LOGE("Callback data creation failed");
+            throw Common::UnknownException("Callback data creation failed");
+        }
+        callback->setSuccessCallback(validator.toFunction(1));
+        callback->setErrorCallback(validator.toFunction(2, true));
+        callback->setMessageType(msgTag);
+
+        MessageType msgType = callback->getMessageType();
+        switch (msgType) {
+            case MessageType::SMS:
+                if (system_info_get_platform_bool("tizen.org/feature/network.telephony", &isSupported) != SYSTEM_INFO_ERROR_NONE) {
+                    LoggerE("Can't know whether SMS is supported or not");
+                    //TODO: need to throw unknown error
+                }
+                LoggerD("isSMSSupported " << isSupported);
+
+                if (isSupported == false) {
+                    LoggerE("SMS is not supported");
+                    throw DeviceAPI::Common::NotSupportedException("Unsupported message type (SMS)");
+                }
+                break;
+            case MessageType::MMS:
+                if (system_info_get_platform_bool("tizen.org/feature/network.telephony.mms", &isSupported) != SYSTEM_INFO_ERROR_NONE) {
+                    LoggerE("Can't know whether mms is supported or not");
+                    //TODO: need to throw unknown error
+                }
+                LoggerD("isSupported " << isSupported);
+
+                if (isSupported == false) {
+                    LoggerE("mms is not supported");
+                    throw DeviceAPI::Common::NotSupportedException("Unsupported message type (MMS)");
+                }
+                break;
+            case MessageType::EMAIL:
+                LoggerD("Email type");
+                break;
+            default:
+                LoggerE("This type is not supported");
+                throw DeviceAPI::Common::TypeMismatchException("Unsupported message type");
+        }
+        MessagingManager::getInstance().getMessageServices(callback);
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+    catch (...) {
+        Common::UnknownException err("Unknown error, cannot get message services");
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete callback;
+        callback = NULL;
+        return JSWebAPIErrorFactory::postException(context, exception, err);
+    }
+
+    return JSValueMakeUndefined(context);
+}
+
+} // Messaging
+} // DeviceAPI
+
diff --git a/src/messaging/old/JSMessagingManager.h b/src/messaging/old/JSMessagingManager.h
new file mode 100755 (executable)
index 0000000..ad6850b
--- /dev/null
@@ -0,0 +1,81 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_JS_MESSAGING_MANAGER_H__
+#define __TIZEN_JS_MESSAGING_MANAGER_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class JSMessagingManager
+{
+public:
+// @struct JSClassDefinition
+// @abstract This structure contains properties and callbacks that define a type of object.
+//           All fields other than the version field are optional. Any pointer may be NULL.
+    static const JSClassDefinition* getClassInfo();
+    static const JSClassRef getClassRef();
+
+private:
+    /**
+     * The callback invoked when an object is first created.
+     */
+    static void initialize(JSContextRef context, JSObjectRef object);
+
+    /**
+     * The callback invoked when an object is finalized.
+     */
+    static void finalize(JSObjectRef object);
+
+    /**
+    * The callback invoked when determining whether an object has a property.
+    */
+    static bool hasProperty(JSContextRef context,
+            JSObjectRef object,
+            JSStringRef propertyName);
+
+    static JSValueRef getMessageServices(JSContextRef context,
+            JSObjectRef object,
+            JSObjectRef thisObject,
+            size_t argumentCount,
+            const JSValueRef arguments[],
+            JSValueRef* exception);
+
+    /**
+     * This structure contains properties and callbacks that define a type of object.
+     */
+    static JSClassDefinition m_classInfo;
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSStaticFunction m_function[];
+
+    /**
+     * This structure describes a statically declared function property.
+     */
+    static JSClassRef m_jsClassRef;
+
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif //__TIZEN_JS_MESSAGING_MANAGER_H__
+
diff --git a/src/messaging/old/Message.cpp b/src/messaging/old/Message.cpp
new file mode 100644 (file)
index 0000000..388c5f6
--- /dev/null
@@ -0,0 +1,1628 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        Message.cpp
+ */
+
+#include "Message.h"
+#include "MessageSMS.h"
+#include "MessageMMS.h"
+#include "MessageEmail.h"
+#include "MessagingUtil.h"
+#include "FilesystemExternalUtils.h"
+#include "FilesystemUtils.h"
+#include "Ecore_File.h"
+#include "JSMessage.h"
+
+#include <PlatformException.h>
+#include <Logger.h>
+#include <time.h>
+#include <sys/stat.h>
+#include <sstream>
+
+namespace DeviceAPI {
+
+using namespace Tizen;
+
+namespace Messaging {
+
+// *** constructor
+Message::Message():
+    m_id(-1), m_id_set(false), m_conversation_id(-1),
+    m_conversation_id_set(false), m_folder_id(-1), m_folder_id_set(false),
+    m_type(UNDEFINED), m_timestamp_set(false), m_from_set(false),
+    m_body(new(std::nothrow) MessageBody()),
+    m_service_id(0), m_is_read(false), m_has_attachment(false),
+    m_high_priority(false), m_in_response(-1), m_in_response_set(false),
+    m_service_id_set(false), m_status(STATUS_UNDEFINED),
+    m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN)
+{
+    LOGD("Message constructor (%p)", this);
+}
+
+Message::~Message()
+{
+    LOGD("Message destructor (%p)", this);
+}
+
+// *** attribute getters
+int Message::getId() const
+{
+    return m_id;
+}
+
+int Message::getConversationId() const
+{
+    return m_conversation_id;
+}
+
+int Message::getFolderId() const
+{
+    // TODO: folderId is supported different way in SMS/MMS and email
+    return m_folder_id;
+}
+
+MessageType Message::getType() const
+{
+    return m_type;
+}
+
+time_t Message::getTimestamp() const
+{
+    return m_timestamp;
+}
+
+std::string Message::getFrom() const
+{
+    return m_from;
+}
+
+std::vector<std::string> Message::getTO() const
+{
+    return m_to;
+}
+
+JSObjectRef Message::getJSTO(JSContextRef global_ctx)
+{
+    return m_to.getJSArray(global_ctx);
+}
+
+std::vector<std::string> Message::getCC() const
+{
+    return m_cc;
+}
+
+JSObjectRef Message::getJSCC(JSContextRef global_ctx)
+{
+    return m_cc.getJSArray(global_ctx);
+}
+
+std::vector<std::string> Message::getBCC() const
+{
+    return m_bcc;
+}
+
+JSObjectRef Message::getJSBCC(JSContextRef global_ctx)
+{
+    return m_bcc.getJSArray(global_ctx);
+}
+
+std::shared_ptr<MessageBody> Message::getBody() const
+{
+    return m_body;
+}
+
+bool Message::getIsRead() const
+{
+    return m_is_read;
+}
+
+bool Message::getHasAttachment() const
+{
+    // This function should be reimplemented for MMS and email
+    return m_has_attachment;
+}
+
+bool Message::getIsHighPriority() const
+{
+    return m_high_priority;
+}
+
+std::string Message::getSubject() const
+{
+    return m_subject;
+}
+
+int Message::getInResponseTo() const
+{
+    return m_in_response;
+}
+
+MessageStatus Message::getMessageStatus() const
+{
+    return m_status;
+}
+
+AttachmentPtrVector Message::getMessageAttachments() const
+{
+    return m_attachments;
+}
+
+JSObjectRef Message::getJSMessageAttachments(JSContextRef global_ctx)
+{
+    return m_attachments.getJSArray(global_ctx);
+}
+
+int Message::getServiceId() const
+{
+    return m_service_id;
+}
+
+TelNetworkDefaultDataSubs_t Message::getSimIndex() const
+{
+    return m_sim_index;
+}
+
+// *** attributes setters
+void Message::setId(int id)
+{
+    m_id = id;
+    m_id_set = true;
+    m_body->setMessageId(m_id);
+}
+
+void Message::setConversationId(int id)
+{
+    m_conversation_id = id;
+    m_conversation_id_set = true;
+}
+
+void Message::setFolderId(int id)
+{
+    m_folder_id = id;
+    m_folder_id_set = true;
+}
+
+// type setting not allowed - no setter for type
+
+void Message::setTimeStamp(time_t timestamp)
+{
+    m_timestamp = timestamp;
+    m_timestamp_set = true;
+}
+
+void Message::setFrom(std::string from)
+{
+    m_from = from;
+    m_from_set = true;
+}
+
+void Message::setTO(std::vector<std::string> &to)
+{
+    // Recipient's format validation should be done by Core API service
+    m_to = to;
+
+    if(m_to.empty()) {
+        LOGD("Recipient's list cleared");
+        return;
+    }
+}
+
+void Message::setCC(std::vector<std::string> &cc)
+{
+    // implementation (address/number format checking) is message specific
+}
+
+void Message::setBCC(std::vector<std::string> &bcc)
+{
+    // implementation (address/number format checking) is message specific
+}
+
+void Message::setBody(std::shared_ptr<MessageBody>& body)
+{
+    // while replacing message body old body should have some invalid id mark
+    m_body->setMessageId(-1);
+    m_body = body;
+    if(m_id_set) {
+        m_body->setMessageId(m_id);
+    }
+}
+
+void Message::setIsRead(bool read)
+{
+    m_is_read = read;
+}
+
+// has attachment can't be set explicity -> no setter for this flag
+
+void Message::setIsHighPriority(bool highpriority)
+{
+    // High priority field is used only in MessageEmail
+    m_high_priority = highpriority;
+}
+
+void Message::setSubject(std::string subject)
+{
+    // Subject is used only in MessageEmail and MessageMMS
+}
+
+void Message::setInResponseTo(int inresp)
+{
+    m_in_response = inresp;
+    m_in_response_set = true;
+}
+
+void Message::setMessageStatus(MessageStatus status)
+{
+    m_status = status;
+}
+
+void Message::setMessageAttachments(AttachmentPtrVector &attachments)
+{
+    // implementation provided only for MMS and email
+}
+
+
+void Message::setServiceId(int service_id)
+{
+    m_service_id = service_id;
+    m_service_id_set = true;
+}
+
+void Message::setSimIndex(TelNetworkDefaultDataSubs_t sim_index)
+{
+    m_sim_index = sim_index;
+}
+
+// ***  support for optional, nullable (at JS layer) attibutes
+bool Message::is_id_set() const
+{
+    return m_id_set;
+}
+
+bool Message::is_conversation_id_set() const
+{
+    return m_conversation_id_set;
+}
+
+bool Message::is_folder_id_set() const
+{
+    return m_folder_id_set;
+}
+
+bool Message::is_timestamp_set() const
+{
+    return m_timestamp_set;
+}
+
+bool Message::is_from_set() const
+{
+    return m_from_set;
+}
+
+bool Message::is_in_response_set() const
+{
+    return m_in_response_set;
+}
+
+bool Message::is_service_is_set() const
+{
+    return m_service_id_set;
+}
+
+std::string Message::convertEmailRecipients(const std::vector<std::string> &recipients)
+{
+    std::string address = "";
+    unsigned size = recipients.size();
+    for (unsigned i=0; i<size; ++i)
+    {
+        address += "<"+recipients[i]+">; ";
+    }
+
+    return address;
+}
+
+std::string saveToTempFile(const std::string &data)
+{
+    char buf[] = "XXXXXX";
+    int res = 0;
+
+    mode_t mask = umask(S_IWGRP | S_IWOTH);
+    res = mkstemp(buf);   //Just generate unique name
+
+    std::string fileName = std::string("/tmp/") + buf;
+
+    mode_t old_mask = umask(mask);
+    FILE *file = fopen(fileName.c_str(), "w");
+    umask(old_mask);
+
+    if (NULL == file) {
+        LOGE("Failed to create file");
+        throw Common::UnknownException("Failed to create file");
+    }
+    if (fprintf(file, "%s", data.c_str()) < 0) {
+        LOGE("Failed to write data into file");
+        throw Common::UnknownException("Failed to write data into file");
+    }
+    fflush(file);
+    fclose(file);
+    return fileName;
+}
+
+std::string copyFileToTemp(const std::string& sourcePath)
+{
+    LOGD("Entered");
+    char buf[] = "XXXXXX";
+    std::string dirPath, fileName, attPath, tmpPath;
+
+    mode_t mask = umask(S_IWGRP | S_IWOTH);
+    int err = mkstemp(buf);
+    if (-1 == err) {
+        LOGW("Failed to create unique filename");
+    }
+
+    umask(mask);
+    dirPath = "/tmp/" + std::string(buf);
+
+    if ( sourcePath[0] != '/' ) {
+        attPath = Filesystem::External::fromVirtualPath(sourcePath);
+    } else { // Assuming that the path is a real path
+        attPath = sourcePath;
+    }
+
+    // Looking for the last occurrence of slash in source path
+    std::size_t slashPos;
+    if ((slashPos = attPath.find_last_of('/')) == std::string::npos) {
+        throw Common::UnknownException(
+                "Error while copying file to temp: the source path is invalid.");
+    }
+
+    fileName = attPath.substr(slashPos + 1);
+    tmpPath = dirPath + "/" + fileName;
+
+    LOGD("attPath: %s, tmpPath: %s", attPath.c_str(), tmpPath.c_str());
+    if(EINA_TRUE != ecore_file_mkdir(dirPath.c_str())) {
+        throw Common::UnknownException("Unknown error while creating temp directory.");
+    }
+
+    if(EINA_TRUE != ecore_file_cp(attPath.c_str(), tmpPath.c_str())) {
+        throw Common::UnknownException("Unknown error while copying file to temp.");
+    }
+
+    return dirPath;
+}
+
+void removeDirFromTemp(const std::string& dirPath)
+{
+    if(EINA_TRUE != ecore_file_rmdir(dirPath.c_str())) {
+        throw Common::UnknownException("Unknown error while deleting temp directory.");
+    }
+}
+
+email_mail_data_t* Message::convertPlatformEmail(std::shared_ptr<Message> message)
+{
+    if(EMAIL != message->getType()) {
+        LOGE("Invalid type");
+        throw Common::InvalidValuesException("Invalid type.");
+    }
+
+    email_mail_data_t *mail_data = NULL;
+
+    if(message->is_id_set()) {
+        email_get_mail_data(message->getId(), &mail_data);
+    } else {
+        mail_data = (email_mail_data_t*)malloc(
+                sizeof(email_mail_data_t));
+        memset(mail_data, 0x00, sizeof(email_mail_data_t));
+    }
+
+    if(!message->getFrom().empty()) {
+        std::string from = "<"+message->getFrom()+">";
+        mail_data->full_address_from = strdup(from.c_str());
+    }
+
+    if(!message->getTO().empty()) {
+        std::string to = Message::convertEmailRecipients(message->getTO());
+        mail_data->full_address_to = strdup(to.c_str());
+    }
+
+    if(!message->getCC().empty()) {
+        std::string cc = Message::convertEmailRecipients(message->getCC());
+        mail_data->full_address_cc = strdup(cc.c_str());
+    }
+
+    if(!message->getBCC().empty()) {
+        std::string bcc = Message::convertEmailRecipients(message->getBCC());
+        mail_data->full_address_bcc = strdup(bcc.c_str());
+    }
+
+    if(!message->getSubject().empty()) {
+        std::string subject = message->getSubject();
+        mail_data->subject = strdup(subject.c_str());
+    }
+
+    if(message->getBody()) {
+        std::shared_ptr<MessageBody> body;
+        body = message->getBody();
+        if(!body->getPlainBody().empty()) {
+            std::string body_file_path = saveToTempFile(body->getPlainBody());
+            mail_data->file_path_plain = strdup(body_file_path.c_str());
+            if(!mail_data->file_path_plain)
+            {
+                LOGE("Plain Body file is NULL.");
+                free(mail_data);
+                mail_data = NULL;
+                throw Common::UnknownException("Plain Body file is NULL.");
+            }
+        }
+
+        if(!body->getHtmlBody().empty()) {
+            std::string html_file_path = saveToTempFile(body->getHtmlBody());
+            mail_data->file_path_html = strdup(html_file_path.c_str());
+            if(!mail_data->file_path_html)
+            {
+                LOGE("Html Body file is NULL.");
+                free(mail_data);
+                mail_data = NULL;
+                throw Common::UnknownException("Html Body file is NULL.");
+            }
+        } else if(!body->getPlainBody().empty()) {
+            // check html data is exist if not exist copy plain body to html body
+            std::string html_file_path = saveToTempFile(body->getPlainBody());
+            mail_data->file_path_html = strdup(html_file_path.c_str());
+            if(!mail_data->file_path_html)
+            {
+                LOGE("Plain Body file is NULL.");
+                free(mail_data);
+                mail_data = NULL;
+                throw Common::UnknownException("Plain Body file is NULL.");
+            }
+        }
+    }
+
+    mail_data->flags_seen_field = message->getIsRead()?1:0;
+
+    if(message->getIsHighPriority()) {
+        mail_data->priority = EMAIL_MAIL_PRIORITY_HIGH;
+    } else {
+        mail_data->priority = EMAIL_MAIL_PRIORITY_NORMAL;
+    }
+
+    return mail_data;
+}
+
+void addSingleEmailAttachment(std::shared_ptr<Message> message,
+        std::shared_ptr<MessageAttachment> att, AttachmentType attType)
+{
+    std::string dirPath = copyFileToTemp(att->getFilePath());
+
+    email_attachment_data_t* tmp = new email_attachment_data_t();
+    tmp->attachment_name = strdup(att->getShortFileName().c_str());
+    tmp->attachment_path  = strdup(std::string(dirPath + "/"
+            + att->getShortFileName()).c_str());
+    tmp->save_status = 1;
+    tmp->inline_content_status = attType;
+
+    int id = message->getId();
+    int err = email_add_attachment(id, tmp);
+    if(EMAIL_ERROR_NONE != err) {
+        LOGE("Error while adding attachment %d", err);
+        err = email_free_attachment_data(&tmp, 1);
+        if (EMAIL_ERROR_NONE != err) {
+            LOGW("Failed to free attachment data");
+        }
+        throw Common::UnknownException("Unknown error while adding attachment");
+    }
+
+    att->setId(tmp->attachment_id);
+    att->setMessageId(id);
+    err = email_free_attachment_data(&tmp, 1);
+    if (EMAIL_ERROR_NONE != err) {
+        LOGW("Failed to free attachment data");
+    }
+
+    removeDirFromTemp(dirPath);
+}
+
+void Message::addEmailAttachments(std::shared_ptr<Message> message)
+{
+    LOGD("Entered");
+
+    int attachment_data_count = 0, error;
+    email_mail_data_t *mail = NULL;
+    email_attachment_data_t *attachment_data_list = NULL;
+    email_meeting_request_t *meeting_req = NULL;
+
+
+    AttachmentPtrVector attachments = message->getMessageAttachments();
+    AttachmentPtrVector inlineAttachments = message->getBody()->getInlineAttachments();
+    LOGD("Attachments size: %d", attachments.size());
+    LOGD("Inline attachments size: %d", inlineAttachments.size());
+    LOGD("Adding attachments for mail id = [%d]\n", message->getId());
+    for (auto it = attachments.begin(); it != attachments.end(); ++it) {
+        addSingleEmailAttachment(message, *it, AttachmentType::EXTERNAL);
+    }
+    for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) {
+        addSingleEmailAttachment(message, *it, AttachmentType::INLINE);
+    }
+
+    //Update of mail on server using function email_update_mail() is not possible.
+    //Attachment is updated only locally, so there is need to use workaround:
+    //1. add new mail with null attachments list
+    //2. add attachments to mail (locally)
+    //3. create new email with attachments and add it to server
+    //4. delete mail without attachments
+
+    //getting mail and attachments data
+    mail = Message::convertPlatformEmail(message);
+    error = email_get_attachment_data_list(mail->mail_id, &attachment_data_list, &attachment_data_count);
+    if (EMAIL_ERROR_NONE != error) {
+        email_free_mail_data(&mail, 1);
+        email_free_attachment_data(&attachment_data_list,attachment_data_count);
+        LOGE("Error while adding attachments. Failed to get attachment list.");
+        throw Common::UnknownException("Error while adding attachments. Failed to get attachment list.");
+    }
+
+    //save mail without attachments id
+    int tmp_id = mail->mail_id;
+
+    //adding new mail with attachments
+    error = email_add_mail(mail, attachment_data_list, attachment_data_count, meeting_req, 0);
+    if (EMAIL_ERROR_NONE != error) {
+        email_free_mail_data(&mail, 1);
+        email_free_attachment_data(&attachment_data_list,attachment_data_count);
+        LOGE("Error while re-adding mail: %d", error);
+        throw Common::UnknownException("Error while re-adding mail");
+    }
+    LOGD("mail added - new id = [%d]\n", mail->mail_id);
+
+    //refresh message object
+    message->setId(mail->mail_id);
+    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
+    for (auto it = attachments.begin(); it != attachments.end(); ++it) {
+        (*it)->setMessageId(mail->mail_id);
+    }
+    for (auto it = inlineAttachments.begin(); it != inlineAttachments.end(); ++it) {
+        (*it)->setMessageId(mail->mail_id);
+    }
+    email_free_attachment_data(&attachment_data_list,attachment_data_count);
+
+    //deleting mail without attachments
+    error = email_delete_mail(mail->mailbox_id,&tmp_id,1,1);
+    if (EMAIL_ERROR_NONE != error) {
+        email_free_mail_data(&mail, 1);
+        LOGE("Error while deleting mail from server: %d", error);
+        throw Common::UnknownException("Error while deleting mail from server");
+    }
+    email_free_mail_data(&mail, 1);
+}
+
+void Message::addSMSRecipientsToStruct(const std::vector<std::string> &recipients,
+        msg_struct_t &msg)
+{
+    const unsigned size = recipients.size();
+    for (unsigned int i = 0; i < size; ++i) {
+        char *address = const_cast<char *>(recipients.at(i).c_str());
+
+        LOGD("[%d] address:[%s]", i, address);
+        msg_struct_t tmpAddr = NULL;
+        if (MSG_SUCCESS
+                == msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr)) {
+            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT,
+                    MSG_ADDRESS_TYPE_PLMN);
+            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
+                    MSG_RECIPIENTS_TYPE_TO);
+            msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
+                    address, strlen(address));
+        }
+        else {
+            LOGE("failed to add address[%d] %s", i, address);
+            throw Common::UnknownException("failed to add address");
+        }
+    }
+}
+
+void Message::addMMSRecipientsToStruct(const std::vector<std::string> &recipients,
+        msg_struct_t &msg, int type)
+{
+    const unsigned size = recipients.size();
+    for (unsigned int i = 0; i < size; ++i) {
+
+        msg_struct_t tmpAddr = NULL;
+        int address_type = MSG_ADDRESS_TYPE_PLMN;
+        const std::size_t found = recipients[i].find("@");
+        if (std::string::npos != found) {
+            address_type = MSG_ADDRESS_TYPE_EMAIL;
+        }
+
+        char *address = const_cast<char *>(recipients.at(i).c_str());
+        LOGD("[%d] address:[%s] address_type:%d type:%d", i, address, address_type, type);
+
+        int error = msg_list_add_item(msg, MSG_MESSAGE_ADDR_LIST_HND, &tmpAddr);
+        if (MSG_SUCCESS == error) {
+            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_TYPE_INT,
+                    address_type);
+            msg_set_int_value(tmpAddr, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
+                    type);
+            msg_set_str_value(tmpAddr, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
+                    address, strlen(address));
+        }
+        else {
+            LOGE("[%d] failed to add address: [%s], error: %d", i, address, error);
+            throw Common::UnknownException("failed to add address");
+        }
+    }
+}
+
+void Message::addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector attach,
+        msg_struct_t &mms_struct, Message* message)
+{
+    LOGD("Entered with %d attachments", attach.size());
+
+    int size = attach.size();
+    for (int i = 0; i < size; i++) {
+
+        msg_struct_t tmpAtt = NULL;
+        int error = msg_list_add_item(mms_struct, MSG_STRUCT_MMS_ATTACH, &tmpAtt);
+        if (MSG_SUCCESS == error) {
+
+            //Ensure we have right id set
+            attach[i]->setId(i+1);
+            attach[i]->setMessageId(message->getId());
+
+            //-------------------------------------------------------------------------
+            // set file path, file name, file size
+            if (attach.at(i)->isFilePathSet()) {
+                std::string filepath = attach.at(i)->getFilePath();
+                LOGD("att[%d]: org filepath: %s", i, filepath.c_str());
+                if(Filesystem::External::isVirtualPath(filepath)) {
+                    // TODO
+                    // When introducing below line fromVirtualPath() function
+                    // needed context, but never used it - allowing for null
+                    // context pointer. If it appears to need a real context
+                    // it will need a fix here.
+                    filepath = Filesystem::External::fromVirtualPath(filepath);
+                    LOGD("att[%d]: org virtual filepath: %s", i, filepath.c_str());
+                }
+                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILEPATH_STR,
+                        const_cast<char*>(filepath.c_str()), filepath.size());
+                const size_t last_slash_idx = filepath.find_last_of("\\/");
+                if (std::string::npos != last_slash_idx) {
+                    filepath.erase(0, last_slash_idx + 1);
+                }
+
+                LOGD("att[%d] filename: %s", i, filepath.c_str());
+                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_FILENAME_STR,
+                        const_cast<char*>(filepath.c_str()), filepath.size());
+                struct stat st;
+                if (stat(const_cast<char*>(filepath.c_str()), &st)) {
+                    LOGE("Stat error");
+                }
+                const int fsize = st.st_size;
+                msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_FILESIZE_INT, fsize);
+                LOGD("att[%d]: filesize: %d", i,fsize);
+            }
+
+            //-------------------------------------------------------------------------
+            //set mime type
+            if (attach.at(i)->isMimeTypeSet()) {
+                unsigned int type = MessageAttachment::MIMETypeStringToEnum(
+                        attach.at(i)->getMimeType());
+                msg_set_int_value(tmpAtt, MSG_MMS_ATTACH_MIME_TYPE_INT, type);
+                msg_set_str_value(tmpAtt, MSG_MMS_ATTACH_CONTENT_TYPE_STR,
+                                    const_cast<char*>(attach.at(i)->getMimeType().c_str()),
+                                    MSG_MSG_ID_LEN);
+
+
+                LOGD("att[%d]: setting mime type:0x%x (orignal:%s)", i, type,
+                    attach.at(i)->getMimeType().c_str());
+            }
+        } else {
+            LOGE("att[%d]: failed to add attachment");
+            throw Common::UnknownException("failed to add attachment");
+        }
+    }
+}
+
+msg_struct_t Message::convertPlatformShortMessageToStruct(Message* message,
+        msg_handle_t handle)
+{
+    LOGD("Entered");
+
+    if (message->getType() != SMS && message->getType() != MMS) {
+        LOGD("Invalid type");
+        throw Common::InvalidValuesException("Invalid type");
+    }
+
+    msg_error_t err = MSG_SUCCESS;
+    msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
+    msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+
+    if (message->is_id_set()) { // id is set - the message exists in database
+        msg_message_id_t id = (msg_message_id_t) message->getId();
+        err = msg_get_message(handle, id, msg, sendOpt);
+        if (err != MSG_SUCCESS) {
+            msg_release_struct(&sendOpt);
+            msg_release_struct(&msg);
+            LOGD("msg_get_message() Fail [%d]", err);
+            throw Common::UnknownException("msg_get_message() Fail");
+        }
+        LOGD("Using existing msg for id: %d", id);
+    } else { // id is not set - the message does not exist in database
+        MessageType msgType = message->getType();
+        if (msgType == MessageType::SMS) {
+            // Set message type to SMS
+            if (MSG_SUCCESS
+                    != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_SMS)) {
+                msg_release_struct(&sendOpt);
+                msg_release_struct(&msg);
+                LOGE("Set SMS type error");
+                throw Common::UnknownException("Set SMS type error");
+            }
+        } else {
+            // Set message type to MMS
+            if (MSG_SUCCESS
+                    != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS)) {
+                msg_release_struct(&sendOpt);
+                msg_release_struct(&msg);
+                LOGE("Set MMS type error");
+                throw Common::UnknownException("Set MMS type error");
+            }
+        }
+    }
+    msg_release_struct(&sendOpt);
+
+    int type;
+    msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &type);
+    LOGD("Message(%p): MSG_MESSAGE_TYPE = %d", message, type);
+
+    if (type == MSG_TYPE_SMS) {
+        // Set SMS message body text
+        std::shared_ptr<MessageBody> body;
+        body = message->getBody();
+        if (!body->getPlainBody().empty()) {
+            msg_set_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, const_cast<char*>
+                    (body->getPlainBody().c_str()), body->getPlainBody().size());
+        }
+
+        // Reset SMS recipients
+        int error = msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND);
+        if( MSG_SUCCESS != error) {
+            LOGE("Failed to clear address list, error: %d", error);
+            throw Common::UnknownException("Failed to clear address list");
+        }
+
+        // Set SMS recipients
+        std::vector<std::string> recp_list = message->getTO();
+        if (!recp_list.empty()) {
+            message->addSMSRecipientsToStruct(recp_list, msg);
+        }
+
+    } else if (type == MSG_TYPE_MMS) {
+        // Set message type to MMS
+        if (MSG_SUCCESS
+                != msg_set_int_value(msg, MSG_MESSAGE_TYPE_INT, MSG_TYPE_MMS)) {
+            LOGE("Message(%p): Set MMS type error", message);
+            throw Common::UnknownException("Set MMS type error");
+        }
+        // Create MMS data
+        msg_struct_t mms_data = msg_create_struct(MSG_STRUCT_MMS);
+        if (mms_data == NULL) {
+            LOGE("Message(%p): Set MMS data error", message);
+            throw Common::UnknownException("Set MMS data error");
+        }
+        // Set MMS message subject
+        std::string subject = message->getSubject();
+        if (subject != "") {
+            int r = msg_set_str_value(msg, MSG_MESSAGE_SUBJECT_STR,
+                    const_cast<char*>(subject.c_str()), subject.size());
+            if (r != MSG_SUCCESS) {
+                LOGE("Message(%p): Set MMS subject error: %d", message, r);
+                throw Common::UnknownException("Set MMS subject error");
+            }
+        }
+        // Set MMS message text
+        std::shared_ptr<MessageBody> body;
+        body = message->getBody();
+        if (!body->getPlainBody().empty()) {
+            LOGD("Message(%p): PlainBody is NOT empty", message);
+
+            static const int ROOT_LAYOUT_WIDTH = 100;
+            static const int ROOT_LAYOUT_HEIGHT = 100;
+            static const int WHITE_COLOR = 0xffffff;
+            static const int BLACK_COLOR = 0x000000;
+
+            //----------------------------------------------------------------------------
+            //Region
+            msg_struct_t region;
+            msg_list_add_item(mms_data, MSG_STRUCT_MMS_REGION, &region);
+            msg_set_str_value(region, MSG_MMS_REGION_ID_STR, const_cast<char*>("Text"), 4);
+
+            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_LEFT_INT, 0);
+            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_TOP_INT, 0);
+            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_WIDTH_INT,
+                    ROOT_LAYOUT_WIDTH);
+            msg_set_int_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_INT,
+                    ROOT_LAYOUT_HEIGHT);
+            msg_set_int_value(region, MSG_MMS_REGION_BGCOLOR_INT, WHITE_COLOR);
+
+            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_LEFT_PERCENT_BOOL, true);
+            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_TOP_PERCENT_BOOL, true);
+            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_WIDTH_PERCENT_BOOL, true);
+            msg_set_bool_value(region, MSG_MMS_REGION_LENGTH_HEIGHT_PERCENT_BOOL, true);
+
+            //----------------------------------------------------------------------------
+            //Page
+            msg_struct_t page;
+            msg_list_add_item(mms_data, MSG_STRUCT_MMS_PAGE, &page);
+            msg_set_int_value(page, MSG_MMS_PAGE_PAGE_DURATION_INT, 0);
+
+            //----------------------------------------------------------------------------
+            //Media
+            msg_struct_t media;
+            msg_list_add_item(page, MSG_STRUCT_MMS_MEDIA, &media);
+            msg_set_int_value(media, MSG_MMS_MEDIA_TYPE_INT, MMS_SMIL_MEDIA_TEXT);
+            msg_set_str_value(media, MSG_MMS_MEDIA_REGION_ID_STR,
+                    const_cast<char*>("Text"), 4);
+
+            std::string body_file_path = saveToTempFile(body->getPlainBody());
+            int error = msg_set_str_value(media,
+                    MSG_MMS_MEDIA_FILEPATH_STR,
+                    const_cast<char*>(body_file_path.c_str()),
+                    body_file_path.size());
+            if (error != MSG_SUCCESS) {
+                LOGE("Message(%p): Failed to set mms body filepath", message);
+                throw Common::UnknownException("Failed to set mms body filepath");
+            }
+            msg_set_str_value(media, MSG_MMS_MEDIA_CONTENT_TYPE_STR,
+                "text/plain", 10);
+
+            //----------------------------------------------------------------------------
+            //Smile text
+            msg_struct_t smil_text;
+            msg_get_struct_handle(media, MSG_MMS_MEDIA_SMIL_TEXT_HND, &smil_text);
+            msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_COLOR_INT, BLACK_COLOR);
+            msg_set_int_value(smil_text, MSG_MMS_SMIL_TEXT_SIZE_INT,
+                    MMS_SMIL_FONT_SIZE_NORMAL);
+            msg_set_bool_value(smil_text, MSG_MMS_SMIL_TEXT_BOLD_BOOL, true);
+        } else {
+            LOGD("Message(%p): PlainBody is EMPTY", message);
+        }
+        // Set MMS attachments
+        AttachmentPtrVector attach_list = message->getMessageAttachments();
+        LOGD("Message(%p): id:%d subject:[%s] plainBody:[%s] contains %d attachments",
+                message, message->getId(), message->getSubject().c_str(),
+                message->getBody()->getPlainBody().c_str(), attach_list.size());
+
+        msg_set_int_value(mms_data, MSG_MESSAGE_ATTACH_COUNT_INT,
+                attach_list.size());
+        if (!attach_list.empty()) {
+            addMMSBodyAndAttachmentsToStruct(attach_list, mms_data, message);
+        }
+        // Set MMS body
+        int r = msg_set_mms_struct(msg, mms_data);
+        if (r != MSG_SUCCESS) {
+            LOGE("Message(%p): Set MMS body error: %d", message, r);
+            throw Common::UnknownException("Set MMS body error");
+        }
+        msg_release_struct(&mms_data);
+
+        // Reset MMS recipients
+        msg_list_clear(msg, MSG_MESSAGE_ADDR_LIST_HND);
+
+        std::vector<std::string> recp_list = message->getTO();
+        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_TO);
+
+        recp_list = message->getCC();
+        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_CC);
+
+        recp_list = message->getBCC();
+        message->addMMSRecipientsToStruct(recp_list, msg, MSG_RECIPIENTS_TYPE_BCC);
+    }
+    else {
+        msg_release_struct(&msg);
+        LOGE("Message(%p): Invalid message type", message);
+        throw Common::InvalidValuesException("Invalid message type");
+    }
+
+    // set common attributes for SMS and MMS
+    // Set message conversation id
+    if (message->is_conversation_id_set()) {
+        msg_set_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, message->getConversationId());
+    }
+    // Set message folder id
+    if (message->is_folder_id_set()) {
+        msg_set_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, message->getFolderId());
+    }
+    // Set message timestamp
+    if (message->is_timestamp_set()) {
+        msg_set_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, message->getTimestamp());
+    }
+    // Set message from
+    if (message->is_from_set()) {
+        msg_set_str_value(msg, MSG_MESSAGE_REPLY_ADDR_STR, const_cast<char*>
+                (message->getFrom().c_str()), message->getFrom().size());
+    }
+    // Set message if is response
+    if (message->is_in_response_set()) {
+        msg_set_int_value(msg, MSG_MESSAGE_DIRECTION_INT, message->getInResponseTo());
+    }
+
+    // Set SIM index
+    // -1 means unknown - so do not set simindex in that case.
+    int sim_index = static_cast<int>(message->getSimIndex());
+    if (sim_index != -1) {
+        int error =
+            msg_set_int_value(msg, MSG_MESSAGE_SIM_INDEX_INT, sim_index+1);
+        if ( MSG_SUCCESS != error) {
+            LOGE("Failed to set sim index, error: %d", error);
+            throw Common::UnknownException("Failed to set sim index");
+        }
+    }
+
+    // Set message if is read
+    msg_set_bool_value(msg, MSG_MESSAGE_READ_BOOL, message->getIsRead());
+
+    LOGD("End");
+    return msg;
+}
+
+std::string Message::getShortMsgSenderFromStruct(msg_struct_t &msg)
+{
+    msg_list_handle_t addr_list = NULL;
+    msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list);
+
+    char str_phone_number[MAX_ADDRESS_VAL_LEN];
+    const int count = msg_list_length(addr_list);
+    LOGD("Number of addresses: %d", count);
+
+    for (int i = 0; i < count; ++i)
+    {
+        int tempInt = 0;
+        msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &tempInt);
+        const int type = tempInt;
+
+        if (MSG_DIRECTION_TYPE_MT == type)
+        {
+            msg_struct_t cur_addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
+            msg_get_str_value(cur_addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
+                    str_phone_number, MAX_ADDRESS_VAL_LEN);
+
+            LOGD("[%d/%d] is TYPE_MT, phone number is: %s", i, count, str_phone_number);
+
+            if(0 != str_phone_number[0]) {
+                return std::string(str_phone_number);
+            }
+        } else {
+            LOGD("[%d/%d] is NOT of TYPE_MT skipping, is:%d", i, count, type);
+        }
+    }
+
+    return std::string();
+}
+
+std::vector<std::string> Message::getSMSRecipientsFromStruct(msg_struct_t &msg)
+{
+    std::vector<std::string> address;
+    msg_list_handle_t addr_list = NULL;
+    if (MSG_SUCCESS
+            == msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND,
+                    (void **) &addr_list)) {
+        unsigned size = msg_list_length(addr_list);
+        for (unsigned int i = 0; i < size; i++) {
+            msg_struct_t addr_info = NULL;
+            char infoStr[MAX_ADDRESS_VAL_LEN];
+            //get address
+            addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
+            msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
+                    infoStr, MAX_ADDRESS_VAL_LEN);
+            address.push_back(std::string(infoStr));
+        }
+    } else {
+        LOGE("failed to get recipients");
+        throw Common::UnknownException("failed to add recipients");
+    }
+    return address;
+}
+
+std::vector<std::string> Message::getMMSRecipientsFromStruct(msg_struct_t &msg,
+        int type)
+{
+    std::vector<std::string> address;
+    msg_list_handle_t addr_list = NULL;
+    if (MSG_SUCCESS
+            == msg_get_list_handle(msg, MSG_MESSAGE_ADDR_LIST_HND,
+                    (void **) &addr_list)) {
+        unsigned size = msg_list_length(addr_list);
+        for (unsigned int i = 0; i < size; i++) {
+            msg_struct_t addr_info = NULL;
+            char infoStr[MAX_ADDRESS_VAL_LEN];
+            int tempInt;
+            //get address
+            addr_info = (msg_struct_t) msg_list_nth_data(addr_list, i);
+            msg_get_int_value(addr_info, MSG_ADDRESS_INFO_RECIPIENT_TYPE_INT,
+                    &tempInt);
+            if (tempInt == type) {
+                msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR,
+                        infoStr, MAX_ADDRESS_VAL_LEN);
+                address.push_back(std::string(infoStr));
+            }
+        }
+    } else {
+        LOGE("failed to get recipients");
+        throw Common::UnknownException("failed to add recipients");
+    }
+    return address;
+}
+
+void Message::setMMSBodyAndAttachmentsFromStruct(Message* message,
+        msg_struct_t &msg)
+{
+    LOGD("Entered message(%p)", message);
+    int tempInt = 0;
+    char infoStr[MSG_FILEPATH_LEN_MAX + 1];
+
+    msg_struct_t mms_struct = msg_create_struct(MSG_STRUCT_MMS);
+    int error = msg_get_mms_struct(msg, mms_struct);
+    if (MSG_SUCCESS != error) {
+        LOGE("Cannot get mms struct, error:%d", error);
+        msg_release_struct(&mms_struct);
+        throw Common::UnknownException("cannot get mms struct");
+    }
+
+    bool body_has_been_set = false;
+    // if there are some pages in msg_struct_t
+    msg_list_handle_t page_list = NULL;
+    error = msg_get_list_handle(mms_struct, MSG_MMS_PAGE_LIST_HND, (void **) &page_list);
+    if (MSG_SUCCESS == error) {
+        int pageLen = msg_list_length(page_list);
+        LOGD("MSG_MMS_PAGE_LIST length:%d", pageLen);
+
+        for (int p = 0; p < pageLen; ++p) {
+            msg_struct_t page = (msg_struct_t) msg_list_nth_data(page_list, p);
+            if (!page) {
+                LOGE("returned page is null, continue");
+                continue;
+            }
+
+            msg_list_handle_t media_list = NULL;
+            error = msg_get_list_handle(page, MSG_MMS_PAGE_MEDIA_LIST_HND,
+                    (void **) &media_list);
+            if (MSG_SUCCESS == error) {
+                int mediaLen = msg_list_length(media_list);
+                LOGD("[p:%d] MSG_MMS_PAGE_MEDIA_LIST length:%d", p, mediaLen);
+
+                for (int m = 0; m < mediaLen; ++m) {
+                    msg_struct_t media = (msg_struct_t) msg_list_nth_data(media_list, m);
+                    if (NULL == media) {
+                        LOGE("returned media is null, continue");
+                        continue;
+                    }
+                    // add media from pages to attachments vector
+                    //set file path
+                    memset(infoStr, 0, MSG_FILEPATH_LEN_MAX + 1);
+                    msg_get_str_value(media, MSG_MMS_MEDIA_FILEPATH_STR, infoStr,
+                            MSG_FILEPATH_LEN_MAX);
+                    LOGD("[p:%d, m:%d] attachment file path:%s", p, m, infoStr);
+
+                    msg_get_int_value(media, MSG_MMS_MEDIA_TYPE_INT, &tempInt);
+                    const int msg_media_type = tempInt;
+                    std::string msg_media_type_str =
+                            MessageAttachment::MIMETypeEnumToString(msg_media_type);
+
+                    LOGD("[p:%d, m:%d] MSG_MMS_MEDIA_TYPE: %d (%s)", p, m, msg_media_type,
+                            msg_media_type_str.c_str());
+
+                    //According to old implementation
+                    // "text value on first page goes to body attribute"
+                    if ((0 == p) && (MMS_SMIL_MEDIA_TEXT == msg_media_type)) {
+                        LOGD("Loading body from file: %s ", infoStr);
+
+                        try {
+                            message->getBody()->setPlainBody(
+                                    MessagingUtil::loadFileContentToString(infoStr));
+                            body_has_been_set = true;
+
+                            LOGD("Loaded body: %s",
+                                    message->getBody()->getPlainBody().c_str());
+
+                        } catch(const Common::BasePlatformException& exception) {
+                            LOGE("Unhandled exception: %s (%s)!",
+                                 (exception.getName()).c_str(),
+                                 (exception.getMessage()).c_str());
+                            LOGD("[p:%d, m:%d] body is not set", p, m);
+                        }
+                        catch (...) {
+                            LOGE("Unknown exception occured during plain body loading");
+                            LOGD("[p:%d, m:%d] body is not set", p, m);
+                        }
+
+                    } else {
+                        std::shared_ptr<MessageAttachment> ma (new MessageAttachment());
+                        ma->setFilePath(infoStr);
+
+                        //set message id
+                        msg_get_int_value(msg, MSG_MESSAGE_STORAGE_ID_INT, &tempInt);
+                        ma->setMessageId(tempInt);
+
+                        //set id
+                        ma->setId(message->m_attachments.size() + 1);
+                        message->m_attachments.push_back(ma);
+                        message->m_has_attachment = true;
+
+                        //set mime type
+                        ma->setMimeType(msg_media_type_str);
+
+                        MessageAttachment* att = ma.get();
+                        LOGD("[p:%d, m:%d] added attachment: %p "
+                                "(mime:0x%x mime:%s messageId:%d)", p, m, att,
+                                msg_media_type, msg_media_type_str.c_str(),
+                                ma->getMessageId());
+                    }
+
+                    msg_release_struct(&media);
+                }
+            } else {
+                msg_release_struct(&mms_struct);
+                LOGE("failed to get attachment");
+                throw Common::UnknownException("failed to get attachment");
+            }
+            msg_release_struct(&page);
+        }
+    } else {
+        msg_release_struct(&mms_struct);
+        LOGE("failed to get attachment");
+        throw Common::UnknownException("failed to get attachment");
+    }
+
+    if(false == body_has_been_set) {
+        LOGW("Warning: body has not been set!");
+    }
+
+    LOGD("after MSG_MMS_PAGE_LIST attachments count is:%d",
+            message->m_attachments.size());
+
+    // if there are some other attachments add it to attachments vector
+    msg_list_handle_t attach_list = NULL;
+    error = msg_get_list_handle(mms_struct, MSG_MMS_ATTACH_LIST_HND, (void **)
+            &attach_list);
+    if (MSG_SUCCESS == error) {
+
+        unsigned size = msg_list_length(attach_list);
+        LOGD("MSG_MMS_ATTACH_LIST length:%d", size);
+
+        for (unsigned int i = 0; i < size; i++) {
+            msg_struct_t attach_info = NULL;
+            attach_info = (msg_struct_t) msg_list_nth_data(attach_list, i);
+            if(!attach_info) {
+                LOGW("[att:%d] attach_info is NULL!", i);
+                continue;
+            }
+
+            std::shared_ptr<MessageAttachment> ma (new MessageAttachment());
+
+            //set message id
+            msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &tempInt);
+            ma->setMessageId(tempInt);
+
+            //set file path
+            msg_get_str_value(attach_info, MSG_MMS_ATTACH_FILEPATH_STR, infoStr,
+                    MSG_FILEPATH_LEN_MAX);
+            ma->setFilePath(infoStr);
+
+            //set attachment id
+            ma->setId(message->m_attachments.size() + 1);
+
+            //set mime type
+            msg_get_int_value(attach_info, MSG_MMS_ATTACH_MIME_TYPE_INT, &tempInt);
+            std::string type = MessageAttachment::MIMETypeEnumToString(tempInt);
+            ma->setMimeType(type);
+
+            MessageAttachment* att = ma.get();
+            LOGD("[att:%d] added attachement: %p (mime:0x%x mime:%s path:%s id:%d)",
+                i, att, tempInt, type.c_str(), infoStr, ma->getId());
+
+            message->m_attachments.push_back(ma);
+            message->m_has_attachment = true;
+
+            msg_release_struct(&attach_info);
+        }
+    } else {
+        msg_release_struct(&mms_struct);
+        LOGE("failed to get attachment");
+        throw Common::UnknownException("failed to add attachment");
+    }
+
+    LOGD("after MSG_MMS_ATTACH_LIST attachments count is:%d",
+            message->m_attachments.size());
+    msg_release_struct(&mms_struct);
+}
+
+Message* Message::convertPlatformShortMessageToObject(msg_struct_t msg){
+    Message *message = NULL;
+    int infoInt;
+    bool infoBool;
+    char infoStr[MAX_ADDRESS_VAL_LEN + 1];
+    //get type
+    msg_get_int_value(msg, MSG_MESSAGE_TYPE_INT, &infoInt);
+    if (infoInt == MSG_TYPE_SMS) {
+        message = new MessageSMS();
+        // get SMS body
+        std::shared_ptr<MessageBody> body(new MessageBody());
+        char msgInfoStr[MAX_MSG_TEXT_LEN + 1];
+        msg_get_str_value(msg, MSG_MESSAGE_SMS_DATA_STR, msgInfoStr, MAX_MSG_TEXT_LEN);
+        body->setPlainBody(std::string(msgInfoStr));
+        message->setBody(body);
+        // get recipients
+        std::vector<std::string> recp_list = message->getSMSRecipientsFromStruct(msg);
+        message->setTO(recp_list);
+    } else if (infoInt == MSG_TYPE_MMS) {
+        message = new MessageMMS();
+
+        // get MMS body
+        msg_get_int_value(msg, MSG_MESSAGE_DATA_SIZE_INT, &infoInt);
+        const int mms_body_length = infoInt;
+
+        if(mms_body_length > 0) {
+            std::unique_ptr<char[]> mms_body_str(new char[mms_body_length + 1]);
+            memset(mms_body_str.get(), 0, (mms_body_length + 1) * sizeof(char));
+
+            int error = msg_get_str_value(msg, MSG_MESSAGE_MMS_TEXT_STR,
+                    mms_body_str.get(), mms_body_length);
+            if(MSG_SUCCESS != error) {
+                LOGE("Error:%d occured during: "
+                        "msg_get_str_value(...,MSG_MESSAGE_MMS_TEXT_STR,...)", error);
+            } else {
+                //Check if fetched string is not empty
+                if((mms_body_str.get())[0] != 0) {
+                    LOGD("Fetched plain body (with MSG_MESSAGE_MMS_TEXT_STR):"
+                            "[%s] length:%d", mms_body_str.get(), mms_body_length);
+
+                    std::shared_ptr<MessageBody> body (new MessageBody());
+                    std::string infoString;
+                    infoString.assign(mms_body_str.get());
+                    body->setPlainBody(infoString);
+                    message->setBody(body);
+                } else {
+                    LOGW("Warning: fetched plain body is empty "
+                            "despite reported length is:%d!", mms_body_length);
+                }
+
+                LOGD("Set plain body: [%s]", message->getBody()->getPlainBody().c_str());
+            }
+        } else {
+            LOGW("Warning: mms plain body length is 0!");
+        }
+
+        // get recipients
+        std::vector<std::string> recp_list = getMMSRecipientsFromStruct(msg,
+                MSG_RECIPIENTS_TYPE_TO);
+        message->setTO(recp_list);
+        recp_list = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_CC);
+        message->setCC(recp_list);
+        recp_list = getMMSRecipientsFromStruct(msg, MSG_RECIPIENTS_TYPE_BCC);
+        message->setBCC(recp_list);
+        // get subject
+        memset(infoStr, 0, MAX_ADDRESS_VAL_LEN + 1);
+        msg_get_str_value(msg, MSG_MESSAGE_SUBJECT_STR, infoStr, MAX_SUBJECT_LEN);
+        message->setSubject(infoStr);
+        //set attachments
+        setMMSBodyAndAttachmentsFromStruct(message, msg);
+    } else {
+        LOGE("Invalid Message type: %d", infoInt);
+        throw Common::InvalidValuesException("Invalid Message type");
+    }
+
+    // get id
+    msg_get_int_value(msg, MSG_MESSAGE_ID_INT, &infoInt);
+    message->setId(infoInt);
+    // get conversation id
+    msg_get_int_value(msg, MSG_MESSAGE_THREAD_ID_INT, &infoInt);
+    message->setConversationId(infoInt);
+    // get folder id
+    msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt);
+    message->setFolderId(infoInt);
+    // get timestamp
+    msg_get_int_value(msg, MSG_MESSAGE_DISPLAY_TIME_INT, &infoInt);
+    message->setTimeStamp(infoInt);
+    // get from
+    const std::string& from = Message::getShortMsgSenderFromStruct(msg);
+    message->setFrom(from);
+    LOGD("Message(%p) from is: %s", message, message->getFrom().c_str());
+    // get if is in response
+    msg_get_int_value(msg, MSG_MESSAGE_DIRECTION_INT, &infoInt);
+    LOGD("Message(%p) direction is: %d", message, infoInt);
+    message->setInResponseTo(infoInt);
+    // get is read
+    msg_get_bool_value(msg, MSG_MESSAGE_READ_BOOL, &infoBool);
+    message->setIsRead(infoBool);
+
+    // get status
+
+    // This "strange" fix has been taken from old implementation:
+    // void Mms::readMessageStatus(msg_struct_t& messageData)
+    //
+    int error = msg_get_int_value(msg, MSG_MESSAGE_FOLDER_ID_INT, &infoInt);
+    if(MSG_SUCCESS == error) {
+        MessageStatus msg_status;
+        switch (infoInt) {
+            case MSG_INBOX_ID: msg_status = MessageStatus::STATUS_LOADED; break;
+            case MSG_OUTBOX_ID: msg_status = MessageStatus::STATUS_SENDING; break;
+            case MSG_SENTBOX_ID: msg_status = MessageStatus::STATUS_SENT; break;
+            case MSG_DRAFT_ID: msg_status = MessageStatus::STATUS_DRAFT; break;
+            default: msg_status = MessageStatus::STATUS_LOADED; break;
+        }
+        message->setMessageStatus(msg_status);
+
+        LOGD("MSG_MESSAGE_FOLDER_ID:%d -> messageStatus:%s", infoInt,
+                MessagingUtil::messageStatusToString(msg_status).c_str());
+    }
+    else
+    {
+        LOGE("Couldn't get MSG_MESSAGE_FOLDER_ID_INT, error:%d", error);
+        error = msg_get_int_value(msg, MSG_SENT_STATUS_NETWORK_STATUS_INT, &infoInt);
+
+        if(MSG_SUCCESS == error) {
+            MessageStatus msg_status;
+            if (infoInt == MSG_NETWORK_SEND_SUCCESS) {
+                msg_status = MessageStatus::STATUS_SENT;
+            } else if (infoInt == MSG_NETWORK_SENDING) {
+                msg_status = MessageStatus::STATUS_SENDING;
+            } else if (infoInt == MSG_NETWORK_SEND_FAIL) {
+                msg_status = MessageStatus::STATUS_FAILED;
+            } else if (infoInt == MSG_NETWORK_NOT_SEND) {
+                msg_status = MessageStatus::STATUS_DRAFT;
+            } else {
+                LOGW("warning undefined messageStatus: %d!", infoInt);
+                msg_status = MessageStatus::STATUS_UNDEFINED;
+            }
+            message->setMessageStatus(msg_status);
+
+            LOGD("MSG_SENT_STATUS_NETWORK_STATUS:%d MessageStatus:%s", infoInt,
+                MessagingUtil::messageStatusToString(msg_status).c_str());
+        } else {
+            LOGE("Couldn't get MSG_SENT_STATUS_NETWORK_STATUS_INT, error:%d", error);
+
+            if(0 == message->getId()) {
+                LOGW("Both MSG_SENT_STATUS_NETWORK_STATUS_INT and "
+                        "MSG_MESSAGE_FOLDER_ID_INT failed, messageId == 0 ASSUMING that"
+                        "this message is in DRAFT");
+                message->setMessageStatus(MessageStatus::STATUS_DRAFT);
+            }
+        }
+    }
+
+    LOGD("End");
+    return message;
+}
+
+std::vector<std::string> Message::split(const std::string& input,
+        char delimiter)
+{
+    std::vector<std::string> ret;
+    std::stringstream stream(input);
+    std::string item;
+    while (getline(stream, item, delimiter)) {
+        ret.push_back(item);
+    }
+    return ret;
+}
+
+std::vector<std::string> Message::getEmailRecipientsFromStruct(const char *recipients)
+{
+    std::vector<std::string> tmp = Message::split(recipients, ';');
+    for (std::vector<std::string>::iterator it = tmp.begin(); it != tmp.end(); ++it) {
+        *it = MessagingUtil::ltrim(*it);
+    }
+
+    if (tmp.begin() != tmp.end()) {
+        if (*(tmp.begin()) == "") {
+            tmp.erase(tmp.begin());
+        }
+
+        if (*(tmp.end() - 1) == "") {
+            tmp.erase(tmp.end() - 1);
+        }
+    }
+
+    // remove '<' and '>'
+    tmp = MessagingUtil::extractEmailAddresses(tmp);
+    return tmp;
+}
+
+std::shared_ptr<MessageBody> Message::convertEmailToMessageBody(
+        email_mail_data_t& mail)
+{
+    LOGD("Enter");
+    std::shared_ptr<MessageBody> body (new MessageBody());
+    body->updateBody(mail);
+    return body;
+}
+
+AttachmentPtrVector Message::convertEmailToMessageAttachment(email_mail_data_t& mail)
+{
+    LOGD("Enter");
+    email_attachment_data_t* attachment = NULL;
+    int attachmentCount = 0;
+
+    AttachmentPtrVector att;
+
+    if (EMAIL_ERROR_NONE != email_get_attachment_data_list(mail.mail_id,
+            &attachment, &attachmentCount)) {
+        throw Common::UnknownException("Couldn't get attachment.");
+    }
+    if ( attachment && attachmentCount > 0) {
+        for (int i = 0; i < attachmentCount; i++) {
+            std::shared_ptr<MessageAttachment> tmp_att (new MessageAttachment());
+            tmp_att->updateWithAttachmentData(attachment[i]);
+            att.push_back(tmp_att);
+        }
+    }
+
+    email_free_attachment_data(&attachment, attachmentCount);
+    return att;
+}
+
+std::shared_ptr<Message> Message::convertPlatformEmailToObject(
+        email_mail_data_t& mail)
+{
+    LOGD("Enter");
+    std::shared_ptr<Message> message(new MessageEmail());
+    message->updateEmailMessage(mail);
+    return message;
+}
+
+void Message::updateEmailMessage(email_mail_data_t& mail)
+{
+    LOGW("This should be called on MessageEmail instance");
+}
+
+/**
+ *  Attribute      | Attribute filter| Attribute range filter
+ *                 | supported       | supported
+ * ----------------+-----------------+------------------------
+ *  id             | Yes             | No
+ *  serviceId      | Yes             | No
+ *  conversationId | No              | No
+ *  folderId       | Yes             | No
+ *  type           | Yes             | No
+ *  timestamp      | No              | Yes
+ *  from           | Yes             | No
+ *  to             | Yes             | No
+ *  cc             | Yes             | No
+ *  bcc            | Yes             | No
+ *  body.plainBody | Yes             | No
+ *  isRead         | Yes             | No
+ *  hasAttachment  | Yes             | No
+ *  isHighPriority | Yes             | No
+ *  subject        | Yes             | No
+ *  isResponseTo   | No              | No
+ *  messageStatus  | No              | No
+ *  attachments    | No              | No
+ **/
+namespace MESSAGE_FILTER_ATTRIBUTE {
+
+const std::string ID = JSMessageKeys::MESSAGE_ATTRIBUTE_ID;
+const std::string SERVICE_ID = "serviceId";
+const std::string CONVERSATION_ID = JSMessageKeys::MESSAGE_ATTRIBUTE_CONVERSATION_ID;
+const std::string FOLDER_ID = JSMessageKeys::MESSAGE_ATTRIBUTE_FOLDER_ID;
+const std::string TYPE = JSMessageKeys::MESSAGE_ATTRIBUTE_TYPE;
+const std::string TIMESTAMP = JSMessageKeys::MESSAGE_ATTRIBUTE_TIMESTAMP;
+const std::string FROM = JSMessageKeys::MESSAGE_ATTRIBUTE_FROM;
+const std::string TO = JSMessageKeys::MESSAGE_ATTRIBUTE_TO;
+const std::string CC = JSMessageKeys::MESSAGE_ATTRIBUTE_CC;
+const std::string BCC = JSMessageKeys::MESSAGE_ATTRIBUTE_BCC;
+const std::string BODY_PLAIN_BODY = "body.plainBody";
+const std::string IS_READ = JSMessageKeys::MESSAGE_ATTRIBUTE_IS_READ;
+const std::string HAS_ATTACHMENT = JSMessageKeys::MESSAGE_ATTRIBUTE_HAS_ATTACHMENT;
+const std::string IS_HIGH_PRIORITY = JSMessageKeys::MESSAGE_ATTRIBUTE_IS_HIGH_PRIORITY;
+const std::string SUBJECT = JSMessageKeys::MESSAGE_ATTRIBUTE_SUBJECT;
+
+} //namespace MESSAGE_FILTER_ATTRIBUTE
+
+bool Message::isMatchingAttribute(const std::string& attribute_name,
+            const FilterMatchFlag match_flag,
+            AnyPtr match_value) const
+{
+    LOGD("Entered");
+    auto key = match_value->toString();
+    LOGD("attribute_name:%s match_flag:%d matchValue:%s", attribute_name.c_str(),
+            match_flag, key.c_str());
+
+    using namespace MESSAGE_FILTER_ATTRIBUTE;
+
+    if (ID == attribute_name) {
+        return FilterUtils::isStringMatching(key, std::to_string(getId()),
+                match_flag);
+    }
+    else if (SERVICE_ID == attribute_name) {
+        if(is_service_is_set()) {
+            return FilterUtils::isStringMatching(key, std::to_string(getServiceId()),
+                    match_flag);
+        }
+    }
+    else if (FOLDER_ID == attribute_name) {
+        return FilterUtils::isStringMatching(key, std::to_string(getFolderId()),
+                match_flag);
+    }
+    else if (TYPE == attribute_name) {
+        const std::string msgTypeStr = MessagingUtil::messageTypeToString(getType());
+        return FilterUtils::isStringMatching(key, msgTypeStr, match_flag);
+    }
+    else if (FROM == attribute_name) {
+        return FilterUtils::isStringMatching(key, getFrom() , match_flag);
+    }
+    else if (TO == attribute_name) {
+        return FilterUtils::isAnyStringMatching(key, getTO(), match_flag);
+    }
+    else if (CC == attribute_name) {
+        return FilterUtils::isAnyStringMatching(key, getCC(), match_flag);
+    }
+    else if (BCC == attribute_name) {
+        return FilterUtils::isAnyStringMatching(key, getBCC(), match_flag);
+    }
+    else if (BODY_PLAIN_BODY == attribute_name) {
+        if(getBody()) {
+            return FilterUtils::isStringMatching(key, getBody()->getPlainBody(),
+                    match_flag);
+        }
+    }
+    else if (IS_READ == attribute_name) {
+        return FilterUtils::isStringMatching(key, FilterUtils::boolToString(getIsRead()),
+                match_flag);
+    }
+    else if (HAS_ATTACHMENT == attribute_name) {
+        return FilterUtils::isStringMatching(key,
+                FilterUtils::boolToString(getHasAttachment()),
+                match_flag);
+    }
+    else if (IS_HIGH_PRIORITY == attribute_name) {
+        return FilterUtils::isStringMatching(key,
+                FilterUtils::boolToString(getIsHighPriority()),
+                match_flag);
+    }
+    else if (SUBJECT == attribute_name) {
+        return FilterUtils::isStringMatching(key, getSubject(), match_flag);
+    }
+    else {
+        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
+    }
+
+    return false;
+}
+
+bool Message::isMatchingAttributeRange(const std::string& attribute_name,
+            AnyPtr initial_value,
+            AnyPtr end_value) const
+{
+    LOGD("Entered attribute_name: %s", attribute_name.c_str());
+
+    using namespace MESSAGE_FILTER_ATTRIBUTE;
+    if(TIMESTAMP == attribute_name) {
+        return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value,
+                end_value);
+    }
+    else {
+        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
+    }
+
+    return false;
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/Message.h b/src/messaging/old/Message.h
new file mode 100644 (file)
index 0000000..eefd089
--- /dev/null
@@ -0,0 +1,230 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        Message.h
+ */
+
+#ifndef __TIZEN_MESSAGE_H__
+#define __TIZEN_MESSAGE_H__
+
+#include <time.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <string>
+#include <vector>
+#include <memory>
+#include <msg_product.h>
+#include <msg_storage.h>
+#include "MessagingUtil.h"
+#include "MessageAttachment.h"
+#include "MessageBody.h"
+#include "JSVector.h"
+#include <email-api.h>
+#include <AbstractFilter.h>
+#include <TelNetwork.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+
+struct MessageHolder {
+    std::shared_ptr<Message> ptr;
+};
+
+typedef std::shared_ptr<Message> MessagePtr;
+typedef std::vector<MessagePtr> MessagePtrVector;
+
+enum AttachmentType {
+    EXTERNAL = 0,
+    INLINE = 1
+};
+
+class Message : public Tizen::FilterableObject {
+public:
+// constructor
+    Message();
+    virtual ~Message();
+
+// attributes getters
+    int getId() const;
+    int getConversationId() const;
+    int getFolderId() const;
+    MessageType getType() const;
+    time_t getTimestamp() const;
+    std::string getFrom() const;
+    std::vector<std::string> getTO() const;
+    JSObjectRef getJSTO(JSContextRef global_ctx);
+    std::vector<std::string> getCC() const;
+    JSObjectRef getJSCC(JSContextRef global_ctx);
+    std::vector<std::string> getBCC() const;
+    JSObjectRef getJSBCC(JSContextRef global_ctx);
+    std::shared_ptr<MessageBody> getBody() const;
+    bool getIsRead() const;
+     // getHasAttachment() is virtual to support MMS and email differently
+    virtual bool getHasAttachment() const;
+    bool getIsHighPriority() const;
+    std::string getSubject() const;
+    int getInResponseTo() const;
+    MessageStatus getMessageStatus() const;
+    AttachmentPtrVector getMessageAttachments() const;
+    JSObjectRef getJSMessageAttachments(JSContextRef global_ctx);
+    int getServiceId() const;
+    TelNetworkDefaultDataSubs_t getSimIndex() const;
+
+// attributes setters (virtual because some of them can be overriden in sub classes)
+    virtual void setId(int id);
+    virtual void setConversationId(int id);
+    virtual void setFolderId(int id);
+    // type setting not allowed so no setter provided
+    virtual void setTimeStamp(time_t timestamp);
+    virtual void setFrom(std::string from);
+    virtual void setTO(std::vector<std::string> &to);
+    virtual void setCC(std::vector<std::string> &cc);
+    virtual void setBCC(std::vector<std::string> &bcc);
+    virtual void setBody(std::shared_ptr<MessageBody>& body);
+    virtual void setIsRead(bool read);
+    // has attachment can't be set explicity -> no setter for this flag
+    virtual void setIsHighPriority(bool highpriority);
+    virtual void setSubject(std::string subject);
+    virtual void setInResponseTo(int inresp);
+    virtual void setMessageStatus(MessageStatus status);
+    virtual void setMessageAttachments(AttachmentPtrVector &attachments);
+    virtual void setServiceId(int service_id);
+    virtual void setSimIndex(TelNetworkDefaultDataSubs_t sim_index);
+
+// support for optional, nullable (at JS layer) attibutes
+    // message id
+    bool is_id_set() const;
+    // conversation id
+    bool is_conversation_id_set() const;
+    // folder id
+    bool is_folder_id_set() const;
+    // timestamp
+    bool is_timestamp_set() const;
+    // message sender
+    bool is_from_set() const;
+    // related message ("parent" message)
+    bool is_in_response_set() const;
+    // service id
+    bool is_service_is_set() const;
+    // gets recipients list for SMS message
+    void addSMSRecipientsToStruct(const std::vector<std::string> &recipients,
+            msg_struct_t &msg);
+    // gets recipients list for SMS message
+    void addMMSRecipientsToStruct(const std::vector<std::string> &recipients,
+            msg_struct_t &msg, int type);
+    /**
+     * Updates message with data from email_mail_data_t structure.
+     * @param mail
+     */
+    virtual void updateEmailMessage(email_mail_data_t& mail);
+
+    // gets from(sender) address from short msg struct
+    static std::string getShortMsgSenderFromStruct(msg_struct_t &msg);
+    // function for filling msg_struct_t fields
+    static msg_struct_t convertPlatformShortMessageToStruct(Message* message,
+            msg_handle_t handle);
+    // gets recipients list for SMS message
+    std::vector<std::string> getSMSRecipientsFromStruct(msg_struct_t &msg);
+    // gets recipients list for MMS message
+    static std::vector<std::string> getMMSRecipientsFromStruct(msg_struct_t &msg, int type);
+    // function for filling Message attributes
+    static Message* convertPlatformShortMessageToObject(msg_struct_t msg);
+    static void addMMSBodyAndAttachmentsToStruct(const AttachmentPtrVector attach,
+            msg_struct_t &mms_struct, Message* message);
+    static void setMMSBodyAndAttachmentsFromStruct(Message *message, msg_struct_t &msg);
+
+    static email_mail_data_t* convertPlatformEmail(std::shared_ptr<Message> message);
+    static void addEmailAttachments(std::shared_ptr<Message> message);
+    static std::string convertEmailRecipients(const std::vector<std::string> &recipients);
+    static std::vector<std::string> getEmailRecipientsFromStruct(const char *recipients);
+    static std::shared_ptr<Message> convertPlatformEmailToObject(email_mail_data_t& mail);
+    static std::shared_ptr<MessageBody> convertEmailToMessageBody(email_mail_data_t& mail);
+    static AttachmentPtrVector convertEmailToMessageAttachment(email_mail_data_t& mail);
+
+    // Tizen::FilterableObject
+    virtual bool isMatchingAttribute(const std::string& attribute_name,
+            const Tizen::FilterMatchFlag match_flag,
+            Tizen::AnyPtr match_value) const;
+
+    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
+            Tizen::AnyPtr initial_value,
+            Tizen::AnyPtr end_value) const;
+protected:
+    //! Message id
+    int m_id;
+    //! Flag for checking if id is set (false means: not set)
+    bool m_id_set;
+    //! Conversation id
+    int m_conversation_id;
+    //! Flag for checking if conversation id is set (false means: not set)
+    bool m_conversation_id_set;
+    //! Folder id
+    int m_folder_id;
+    //! Flag for checking if folder id is set (false means: not set)
+    bool m_folder_id_set;
+    //! Message type (messaging.sms, messaging.mms, messaging.email)
+    MessageType m_type;
+    //! Timestamp - time when message has been sent/received
+    time_t m_timestamp;
+    //! Flag for checking if timestamp is set (false means: not set)
+    bool m_timestamp_set;
+    //! Message sender address (email) or number (SMS, MMS)
+    std::string m_from;
+    //! Flag for checking if sender is set (false means: not set)
+    bool m_from_set;
+    //! Message recipients
+    Common::JSStringVector m_to;
+    //! Message CarbonCopy recipients (used only for email)
+    Common::JSStringVector m_cc;
+    //! Message BlindCarbonCopy recipients (used only for email)
+    Common::JSStringVector m_bcc;
+    //! MessageBody (object containg plainBody and htmlBody for emails)
+    std::shared_ptr<MessageBody> m_body;
+    //! Service id
+    int m_service_id;
+    //! Message isRead flag
+    bool m_is_read;
+    //! Message hasAttachment flag
+    bool m_has_attachment;
+    //! Message isHighPriority flag
+    bool m_high_priority;
+    //! Message subject (used in MMS and email)
+    std::string m_subject;
+    //! Id of original message when message is a reply or forward
+    int m_in_response;
+    //! Flag for checking if id of related message is set (false means: not set)
+    bool m_in_response_set;
+    //! Flag for checking if service id is set
+    bool m_service_id_set;
+    //! Outgoing Message status (SENT, SENDING, DRAFT etc)
+    MessageStatus m_status;
+    //! Attachments attached to this message
+    JSAttachmentsVector m_attachments;
+    //! SIM index which indicate a sim to send message.
+    TelNetworkDefaultDataSubs_t m_sim_index;
+private:
+    static std::vector<std::string> split(const std::string& input,
+            char delimiter);
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_H__
diff --git a/src/messaging/old/MessageAttachment.cpp b/src/messaging/old/MessageAttachment.cpp
new file mode 100755 (executable)
index 0000000..68d6844
--- /dev/null
@@ -0,0 +1,590 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageAttachment.cpp
+ */
+
+#include "MessageAttachment.h"
+#include <email-api.h>
+#include <PlatformException.h>
+#include <Logger.h>
+namespace DeviceAPI {
+namespace Messaging {
+
+std::map<std::string,unsigned int>& MessageAttachment::MIMETypeStringToEnumMap = initializeMIMETypeStringToEnumMap();
+std::map<unsigned int, std::string>& MessageAttachment::MIMETypeEnumToStringMap = initializeMIMETypeEnumToStringMap();
+
+
+
+MessageAttachment::MessageAttachment()
+{
+    LOGD("MessageAttachment constructor (%p)", this);
+    m_id = -1;
+    m_isIdSet = false;
+    m_messageId = -1;
+    m_isMessageIdSet = false;
+    m_mimeType = "";
+    m_isMimeTypeSet = false;
+    m_filePath = "";
+    m_isFilePathSet = false;
+    m_isSaved = true;
+}
+
+MessageAttachment::~MessageAttachment()
+{
+    LOGD("MessageAttachment destructor (%p)", this);
+}
+
+// id
+
+int MessageAttachment::getId()
+{
+    return m_id;
+}
+
+void MessageAttachment::setId(int value)
+{
+    m_id = value;
+    m_isIdSet = true;
+}
+
+bool MessageAttachment::isIdSet()
+{
+    return m_isIdSet;
+}
+
+void MessageAttachment::unsetId()
+{
+    m_isIdSet = false;
+}
+
+// messageId
+
+int MessageAttachment::getMessageId()
+{
+    return m_messageId;
+}
+
+void MessageAttachment::setMessageId(int value)
+{
+    m_messageId = value;
+    m_isMessageIdSet = true;
+}
+
+bool MessageAttachment::isMessageIdSet()
+{
+    return m_isMessageIdSet;
+}
+
+void MessageAttachment::unsetMessageId()
+{
+    m_isMessageIdSet = false;
+}
+
+// mimeType
+
+std::string MessageAttachment::getMimeType()
+{
+    return m_mimeType;
+}
+
+void MessageAttachment::setMimeType(const std::string &value)
+{
+    m_mimeType = value;
+    m_isMimeTypeSet = true;
+}
+
+bool MessageAttachment::isMimeTypeSet()
+{
+    return m_isMimeTypeSet;
+}
+
+void MessageAttachment::unsetMimeType()
+{
+    m_isMimeTypeSet = false;
+}
+
+// filePath
+
+std::string MessageAttachment::getFilePath()
+{
+    return m_filePath;
+}
+
+std::string MessageAttachment::getShortFileName() const
+{
+    if (!m_isFilePathSet) {
+        return "";
+    }
+    size_t pos;
+    // find position of last occurence of / sign (get only file name from all path
+    pos = m_filePath.find_last_of("/");
+
+    if ((pos + 1) >= m_filePath.size() || pos == std::string::npos) {
+        return m_filePath;
+    }
+    return m_filePath.substr(pos + 1);
+}
+
+void MessageAttachment::setFilePath(const std::string &value)
+{
+    m_filePath = value;
+    m_isFilePathSet = true;
+}
+
+bool MessageAttachment::isFilePathSet()
+{
+    return m_isFilePathSet;
+}
+
+void MessageAttachment::unsetFilePath()
+{
+    m_isFilePathSet = false;
+}
+
+void MessageAttachment::setIsSaved(bool isSaved)
+{
+    m_isSaved = isSaved;
+}
+
+bool MessageAttachment::isSaved() const
+{
+    return m_isSaved;
+}
+
+std::map<unsigned int, std::string>& MessageAttachment::initializeMIMETypeEnumToStringMap(){
+    static std::map<unsigned int, std::string> enumToString;
+    //0
+    enumToString[MIME_ASTERISK] = "*/*";
+    //1
+    enumToString[MIME_APPLICATION_XML] = "application/xml";
+    enumToString[MIME_APPLICATION_WML_XML] = "application/wml+xml";
+    enumToString[MIME_APPLICATION_XHTML_XML] = "application/xhtml+xml";
+    enumToString[MIME_APPLICATION_JAVA_VM] = "application/java-vm";
+    enumToString[MIME_APPLICATION_SMIL] = "application/smil";
+    enumToString[MIME_APPLICATION_JAVA_ARCHIVE] = "application/java-archive";
+    enumToString[MIME_APPLICATION_JAVA] = "application/java";
+    enumToString[MIME_APPLICATION_OCTET_STREAM] = "application/octet-stream";
+    enumToString[MIME_APPLICATION_STUDIOM] = "application/studiom";
+    enumToString[MIME_APPLICATION_FUNMEDIA] = "application/funMedia";
+    enumToString[MIME_APPLICATION_MSWORD] = "application/msword";
+    enumToString[MIME_APPLICATION_PDF] = "application/pdf";
+    enumToString[MIME_APPLICATION_SDP] = "application/sdp";
+    enumToString[MIME_APPLICATION_RAM] = "application/ram";
+    enumToString[MIME_APPLICATION_ASTERIC] = "application/*";
+    //16
+    enumToString[MIME_APPLICATION_VND_WAP_XHTMLXML] = "application/vnd.wap.xhtml+xml";
+    enumToString[MIME_APPLICATION_VND_WAP_WMLC] = "application/vnd.wap.wmlc";
+    enumToString[MIME_APPLICATION_VND_WAP_WMLSCRIPTC] = "application/vnd.wap.wmlscriptc";
+    enumToString[MIME_APPLICATION_VND_WAP_WTA_EVENTC] = "application/vnd.wap.wta-eventc";
+    enumToString[MIME_APPLICATION_VND_WAP_UAPROF] = "application/vnd.wap.uaprof";
+    enumToString[MIME_APPLICATION_VND_WAP_SIC] = "application/vnd.wap.sic";
+    enumToString[MIME_APPLICATION_VND_WAP_SLC] = "application/vnd.wap.slc";
+    enumToString[MIME_APPLICATION_VND_WAP_COC] = "application/vnd.wap.coc";
+    enumToString[MIME_APPLICATION_VND_WAP_SIA] = "application/vnd.wap.sia";
+    enumToString[MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML] = "application/vnd.wap.connectivity-wbxml";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA] = "application/vnd.wap.multipart.form-data";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES] = "application/vnd.wap.multipart.byteranges";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_MIXED] = "application/vnd.wap.multipart.mixed";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_RELATED] = "application/vnd.wap.multipart.related";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE] = "application/vnd.wap.multipart.alternative";
+    enumToString[MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC] = "application/vnd.wap.multipart.*";
+    enumToString[MIME_APPLICATION_VND_WAP_WBXML] = "application/vnd.wap.wbxml";
+    enumToString[MIME_APPLICATION_VND_OMA_DD_XML] = "application/vnd.oma.dd+xml";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_MESSAGE] = "application/vnd.oma.drm.message";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_CONTENT] = "application/vnd.oma.drm.content";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML] = "application/vnd.oma.drm.rights+xml";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML] = "application/vnd.oma.drm.rights+wbxml";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_RO_XML] = "application/vnd.oma.drm.ro+xml";
+    enumToString[MIME_APPLICATION_VND_OMA_DRM_DCF] = "application/vnd.oma.drm.dcf";
+    enumToString[MIME_APPLICATION_VND_OMA_ROAPPDU_XML] = "application/vnd.oma.drm.roap-pdu+xml";
+    enumToString[MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML] = "application/vnd.oma.drm.roap-trigger+xml";
+    enumToString[MIME_APPLICATION_VND_SMAF] = "application/vnd.smaf";
+    enumToString[MIME_APPLICATION_VND_RN_REALMEDIA] = "application/vnd.rn-realmedia";
+    enumToString[MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE] = "application/vnd.sun.j2me.java-archive";
+    enumToString[MIME_APPLICATION_VND_SAMSUNG_THEME] = "application/vnd.samsung.theme";
+    enumToString[MIME_APPLICATION_VND_EXCEL] = "application/vnd.ms-excel";
+    enumToString[MIME_APPLICATION_VND_POWERPOINT] = "application/vnd.ms-powerpoint";
+    enumToString[MIME_APPLICATION_VND_MSWORD] = "applcation/vnd.ms-word";
+    //49
+    enumToString[MIME_APPLICATION_X_HDMLC] = "application/x-hdmlc";
+    enumToString[MIME_APPLICATION_X_X968_USERCERT] = "application/x-x968-user-cert";
+    enumToString[MIME_APPLICATION_X_WWW_FORM_URLENCODED] = "application/x-www-form-urlencoded";
+    enumToString[MIME_APPLICATION_X_SMAF] = "application/x-smaf";
+    enumToString[MIME_APPLICATION_X_FLASH] = "application/x-shockwave-flash";
+    enumToString[MIME_APPLICATION_X_EXCEL] = "application/x-msexcel";
+    enumToString[MIME_APPLICATION_X_POWERPOINT] = "application/x-mspowerpoint";
+    //56
+    enumToString[MIME_AUDIO_BASIC] = "audio/basic";
+    enumToString[MIME_AUDIO_MPEG] = "audio/mpeg";
+    enumToString[MIME_AUDIO_MP3] = "audio/mp3";
+    enumToString[MIME_AUDIO_MPG3] = "audio/mpg3";
+    enumToString[MIME_AUDIO_MPEG3] = "audio/mpeg3";
+    enumToString[MIME_AUDIO_MPG] = "audio/mpg";
+    enumToString[MIME_AUDIO_AAC] = "audio/aac";
+    enumToString[MIME_AUDIO_G72] = "audio/g72";
+    enumToString[MIME_AUDIO_AMR] = "audio/amr";
+    enumToString[MIME_AUDIO_AMR_WB] = "audio/amr-wb";
+    enumToString[MIME_AUDIO_MMF] = "audio/mmf";
+    enumToString[MIME_AUDIO_SMAF] = "audio/smaf";
+    enumToString[MIME_AUDIO_IMELODY] = "audio/iMelody";
+    enumToString[MIME_AUDIO_IMELODY2] = "audio/imelody";
+    enumToString[MIME_AUDIO_MELODY] = "audio/melody";
+    enumToString[MIME_AUDIO_MID] = "audio/mid";
+    enumToString[MIME_AUDIO_MIDI] = "audio/midi";
+    enumToString[MIME_AUDIO_SP_MIDI] = "audio/sp-midi";
+    enumToString[MIME_AUDIO_WAVE] = "audio/wave";
+    enumToString[MIME_AUDIO_WAV] = "audio/wav";
+    enumToString[MIME_AUDIO_3GPP] = "audio/3gpp";
+    enumToString[MIME_AUDIO_MP4] = "audio/mp4";
+    enumToString[MIME_AUDIO_MP4A_LATM] = "audio/MP4A-LATM";
+    enumToString[MIME_AUDIO_M4A] = "audio/m4a";
+    enumToString[MIME_AUDIO_MPEG4] = "audio/mpeg4";
+    enumToString[MIME_AUDIO_WMA] = "audio/wma";
+    enumToString[MIME_AUDIO_XMF] = "audio/xmf";
+    enumToString[MIME_AUDIO_IMY] = "audio/imy";
+    enumToString[MIME_AUDIO_MOBILE_XMF] = "audio/mobile-xmf";
+    //85
+    enumToString[MIME_AUDIO_VND_RN_REALAUDIO] = "audio/vnd.rn-realaudio";
+    //86
+    enumToString[MIME_AUDIO_X_MPEG] = "audio/x-mpeg";
+    enumToString[MIME_AUDIO_X_MP3] = "audio/x-mp3";
+    enumToString[MIME_AUDIO_X_MPEG3] = "audio/x-mpeg3";
+    enumToString[MIME_AUDIO_X_MPG] = "audio/x-mpg";
+    enumToString[MIME_AUDIO_X_AMR] = "audio/x-amr";
+    enumToString[MIME_AUDIO_X_MMF] = "audio/x-mmf";
+    enumToString[MIME_AUDIO_X_SMAF] = "audio/x-smaf";
+    enumToString[MIME_AUDIO_X_IMELODY] = "audio/x-iMelody";
+    enumToString[MIME_AUDIO_X_MIDI] = "audio/x-midi";
+    enumToString[MIME_AUDIO_X_MPEGAUDIO] = "audio/x-mpegaudio";
+    enumToString[MIME_AUDIO_X_PN_REALAUDIO] = "audio/x-pn-realaudio";
+    enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO] = "audio/x-pn-multirate-realaudio";
+    enumToString[MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE] = "audio/x-pn-multirate-realaudio-live";
+    enumToString[MIME_AUDIO_X_WAVE] = "audio/x-wave";
+    enumToString[MIME_AUDIO_X_WAV] = "audio/x-wav";
+    enumToString[MIME_AUDIO_X_MS_WMA] = "audio/x-ms-wma";
+    enumToString[MIME_AUDIO_X_MID] = "audio/x-mid";
+    enumToString[MIME_AUDIO_X_MS_ASF] = "audio/x-ms-asf";
+    enumToString[MIME_AUDIO_X_XMF] = "audio/x-xmf";
+    //105
+    enumToString[MIME_IMAGE_GIF] = "image/gif";
+    enumToString[MIME_IMAGE_JPEG] = "image/jpeg";
+    enumToString[MIME_IMAGE_JPG] = "image/jpg";
+    enumToString[MIME_IMAGE_TIFF] = "image/tiff";
+    enumToString[MIME_IMAGE_TIF] = "image/tif";
+    enumToString[MIME_IMAGE_PNG] = "image/png";
+    enumToString[MIME_IMAGE_WBMP] = "image/wbmp";
+    enumToString[MIME_IMAGE_PJPEG] = "image/pjpeg";
+    enumToString[MIME_IMAGE_BMP] = "image/bmp";
+    enumToString[MIME_IMAGE_SVG] = "image/svg+xml";
+    enumToString[MIME_IMAGE_SVG1] = "image/svg-xml";
+    //116
+    enumToString[MIME_IMAGE_VND_WAP_WBMP] = "image/vnd.wap.wbmp";
+    enumToString[MIME_IMAGE_VND_TMO_GIF] = "image/vnd.tmo.my5-gif";
+    enumToString[MIME_IMAGE_VND_TMO_JPG] = "image/vnd.tmo.my5-jpg";
+    //119
+    enumToString[MIME_IMAGE_X_BMP] = "image/x-bmp";
+    //120
+    enumToString[MIME_MESSAGE_RFC822] = "message/rfc822";
+    //121
+    enumToString[MIME_MULTIPART_MIXED] = "multipart/mixed";
+    enumToString[MIME_MULTIPART_RELATED] = "multipart/related";
+    enumToString[MIME_MULTIPART_ALTERNATIVE] = "multipart/alternative";
+    enumToString[MIME_MULTIPART_FORM_DATA] = "multipart/form-data";
+    enumToString[MIME_MULTIPART_BYTERANGE] = "multipart/byterange";
+    enumToString[MIME_MULTIPART_REPORT] = "multipart/report";
+    enumToString[MIME_MULTIPART_VOICE_MESSAGE] = "multipart/voice-message";
+    //128
+    enumToString[MIME_TEXT_TXT] = "text/txt";
+    enumToString[MIME_TEXT_HTML] = "text/html";
+    enumToString[MIME_TEXT_PLAIN] = "text/plain";
+    enumToString[MIME_TEXT_CSS] = "text/css";
+    enumToString[MIME_TEXT_XML] = "text/xml";
+    enumToString[MIME_TEXT_IMELODY] = "text/iMelody";
+    //134
+    enumToString[MIME_TEXT_VND_WAP_WMLSCRIPT] = "text/vnd.wap.wmlscript";
+    enumToString[MIME_TEXT_VND_WAP_WML] = "text/vnd.wap.wml";
+    enumToString[MIME_TEXT_VND_WAP_WTA_EVENT] = "text/vnd.wap.wta-event";
+    enumToString[MIME_TEXT_VND_WAP_CONNECTIVITY_XML] = "text/vnd.wap.connectivity-xml";
+    enumToString[MIME_TEXT_VND_WAP_SI] = "text/vnd.wap.si";
+    enumToString[MIME_TEXT_VND_WAP_SL] = "text/vnd.wap.sl";
+    enumToString[MIME_TEXT_VND_WAP_CO] = "text/vnd.wap.co";
+    enumToString[MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR] = "text/vnd.sun.j2me.app-descriptor";
+    //142
+    enumToString[MIME_TEXT_X_HDML] = "text/x-hdml";
+    enumToString[MIME_TEXT_X_VCALENDAR] = "text/x-vCalendar";
+    enumToString[MIME_TEXT_X_VCARD] = "text/x-vCard";
+    enumToString[MIME_TEXT_X_IMELODY] = "text/x-iMelody";
+    enumToString[MIME_TEXT_X_IMELODY2] = "text/x-imelody";
+    enumToString[MIME_TEXT_X_VNOTE] = "text/x-vnote";
+    //148
+    enumToString[MIME_VIDEO_MPEG4] = "video/mpeg4";
+    enumToString[MIME_VIDEO_MP4] = "video/mp4";
+    enumToString[MIME_VIDEO_H263] = "video/h263";
+    enumToString[MIME_VIDEO_3GPP] = "video/3gpp";
+    enumToString[MIME_VIDEO_3GP] = "video/3gp";
+    enumToString[MIME_VIDEO_AVI] = "video/avi";
+    enumToString[MIME_VIDEO_SDP] = "video/sdp";
+    enumToString[MIME_VIDEO_MP4_ES] = "video/mp4v-es";
+    enumToString[MIME_VIDEO_MPEG] = "video/mpeg";
+    //157
+    enumToString[MIME_VIDEO_VND_RN_REALVIDEO] = "video/vnd.rn-realvideo";
+    enumToString[MIME_VIDEO_VND_RN_REALMEDIA] = "video/vnd.rn-realmedia";
+    //159
+    enumToString[MIME_VIDEO_X_MP4] = "video/x-mp4";
+    enumToString[MIME_VIDEO_X_PV_MP4] = "video/x-pv-mp4";
+    enumToString[MIME_VIDEO_X_PN_REALVIDEO] = "video/x-pn-realvideo";
+    enumToString[MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO] = "video/x-pn-multirate-realvideo";
+    enumToString[MIME_VIDEO_X_MS_WMV] = "video/x-ms-wmv";
+    enumToString[MIME_VIDEO_X_MS_ASF] = "video/x-ms-asf";
+    enumToString[MIME_VIDEO_X_PV_PVX] = "video/x-pv-pvx";
+
+    return enumToString;
+}
+
+std::map<std::string,unsigned int>& MessageAttachment::initializeMIMETypeStringToEnumMap(){
+    static std::map<std::string,unsigned int> stringToEnum;
+    //0
+    stringToEnum["*/*"] = MIME_ASTERISK;
+    //1
+    stringToEnum["application/xml"] = MIME_APPLICATION_XML;
+    stringToEnum["application/wml+xml"] = MIME_APPLICATION_WML_XML;
+    stringToEnum["application/xhtml+xml"] = MIME_APPLICATION_XHTML_XML;
+    stringToEnum["application/java-vm"] = MIME_APPLICATION_JAVA_VM;
+    stringToEnum["application/smil"] = MIME_APPLICATION_SMIL;
+    stringToEnum["application/java-archive"] = MIME_APPLICATION_JAVA_ARCHIVE;
+    stringToEnum["application"] = MIME_APPLICATION_JAVA;
+    stringToEnum["application/octet-stream"] = MIME_APPLICATION_OCTET_STREAM;
+    stringToEnum["application/studiom"] = MIME_APPLICATION_STUDIOM;
+    stringToEnum["application/funMedia"] = MIME_APPLICATION_FUNMEDIA;
+    stringToEnum["application/msword"] = MIME_APPLICATION_MSWORD;
+    stringToEnum["application/pdf"] = MIME_APPLICATION_PDF;
+    stringToEnum["application/sdp"] = MIME_APPLICATION_SDP;
+    stringToEnum["application/ram"] = MIME_APPLICATION_RAM;
+    stringToEnum["application/*"] = MIME_APPLICATION_ASTERIC;
+    //16
+    stringToEnum["application/vnd.wap.xhtml+xml"] = MIME_APPLICATION_VND_WAP_XHTMLXML;
+    stringToEnum["application/vnd.wap.wmlc"] = MIME_APPLICATION_VND_WAP_WMLC;
+    stringToEnum["application/vnd.wap.wmlscriptc"] = MIME_APPLICATION_VND_WAP_WMLSCRIPTC;
+    stringToEnum["application/vnd.wap.wta-eventc"] = MIME_APPLICATION_VND_WAP_WTA_EVENTC;
+    stringToEnum["application/vnd.wap.uaprof"] = MIME_APPLICATION_VND_WAP_UAPROF;
+    stringToEnum["application/vnd.wap.sic"] = MIME_APPLICATION_VND_WAP_SIC;
+    stringToEnum["application/vnd.wap.slc"] = MIME_APPLICATION_VND_WAP_SLC;
+    stringToEnum["application/vnd.wap.coc"] = MIME_APPLICATION_VND_WAP_COC;
+    stringToEnum["application/vnd.wap.sia"] = MIME_APPLICATION_VND_WAP_SIA;
+    stringToEnum["application/vnd.wap.connectivity-wbxml"] = MIME_APPLICATION_VND_WAP_CONNECTIVITY_WBXML;
+    stringToEnum["application/vnd.wap.multipart.form-data"] = MIME_APPLICATION_VND_WAP_MULTIPART_FORM_DATA;
+    stringToEnum["application/vnd.wap.multipart.byteranges"] = MIME_APPLICATION_VND_WAP_MULTIPART_BYTERANGES;
+    stringToEnum["application/vnd.wap.multipart.mixed"] = MIME_APPLICATION_VND_WAP_MULTIPART_MIXED;
+    stringToEnum["application/vnd.wap.multipart.related"] = MIME_APPLICATION_VND_WAP_MULTIPART_RELATED;
+    stringToEnum["application/vnd.wap.multipart.alternative"] = MIME_APPLICATION_VND_WAP_MULTIPART_ALTERNATIVE;
+    stringToEnum["application/vnd.wap.multipart.*"] = MIME_APPLICATION_VND_WAP_MULTIPART_ASTERIC;
+    stringToEnum["application/vnd.wap.wbxml"] = MIME_APPLICATION_VND_WAP_WBXML;
+    stringToEnum["application/vnd.oma.dd+xml"] = MIME_APPLICATION_VND_OMA_DD_XML;
+    stringToEnum["application/vnd.oma.drm.message"] = MIME_APPLICATION_VND_OMA_DRM_MESSAGE;
+    stringToEnum["application/vnd.oma.drm.content"] = MIME_APPLICATION_VND_OMA_DRM_CONTENT;
+    stringToEnum["application/vnd.oma.drm.rights+xml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_XML;
+    stringToEnum["application/vnd.oma.drm.rights+wbxml"] = MIME_APPLICATION_VND_OMA_DRM_RIGHTS_WBXML;
+    stringToEnum["application/vnd.oma.drm.ro+xml"] = MIME_APPLICATION_VND_OMA_DRM_RO_XML;
+    stringToEnum["application/vnd.oma.drm.dcf"] = MIME_APPLICATION_VND_OMA_DRM_DCF;
+    stringToEnum["application/vnd.oma.drm.roap-pdu+xml"] = MIME_APPLICATION_VND_OMA_ROAPPDU_XML;
+    stringToEnum["application/vnd.oma.drm.roap-trigger+xml"] = MIME_APPLICATION_VND_OMA_ROAPTRIGGER_XML;
+    stringToEnum["application/vnd.smaf"] = MIME_APPLICATION_VND_SMAF;
+    stringToEnum["application/vnd.rn-realmedia"] = MIME_APPLICATION_VND_RN_REALMEDIA;
+    stringToEnum["application/vnd.sun.j2me.java-archive"] = MIME_APPLICATION_VND_SUN_J2ME_JAVA_ARCHIVE;
+    stringToEnum["application/vnd.samsung.theme"] = MIME_APPLICATION_VND_SAMSUNG_THEME;
+    stringToEnum["application/vnd.ms-excel"] = MIME_APPLICATION_VND_EXCEL;
+    stringToEnum["application/vnd.ms-powerpoint"] = MIME_APPLICATION_VND_POWERPOINT;
+    stringToEnum["applcation/vnd.ms-word"] = MIME_APPLICATION_VND_MSWORD;
+    //49
+    stringToEnum["application/x-hdmlc"] = MIME_APPLICATION_X_HDMLC;
+    stringToEnum["application/x-x968-user-cert"] = MIME_APPLICATION_X_X968_USERCERT;
+    stringToEnum["application/x-www-form-urlencoded"] = MIME_APPLICATION_X_WWW_FORM_URLENCODED;
+    stringToEnum["application/x-smaf"] = MIME_APPLICATION_X_SMAF;
+    stringToEnum["application/x-shockwave-flash"] = MIME_APPLICATION_X_FLASH;
+    stringToEnum["application/x-msexcel"] = MIME_APPLICATION_X_EXCEL;
+    stringToEnum["application/x-mspowerpoint"] = MIME_APPLICATION_X_POWERPOINT;
+    //56
+    stringToEnum["audio/basic"] = MIME_AUDIO_BASIC;
+    stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG;
+    stringToEnum["audio/mp3"] = MIME_AUDIO_MP3;
+    stringToEnum["audio/mpg3"] = MIME_AUDIO_MPG3;
+    stringToEnum["audio/mpeg"] = MIME_AUDIO_MPEG3;
+    stringToEnum["audio/mpg"] = MIME_AUDIO_MPG;
+    stringToEnum["audio/aac"] = MIME_AUDIO_AAC;
+    stringToEnum["audio/g72"] = MIME_AUDIO_G72;
+    stringToEnum["audio/amr"] = MIME_AUDIO_AMR;
+    stringToEnum["audio/amr-wb"] = MIME_AUDIO_AMR_WB;
+    stringToEnum["audio/mmf"] = MIME_AUDIO_MMF;
+    stringToEnum["audio/smaf"] = MIME_AUDIO_SMAF;
+    stringToEnum["audio/iMelody"] = MIME_AUDIO_IMELODY;
+    stringToEnum["audio/imelody"] = MIME_AUDIO_IMELODY2;
+    stringToEnum["audio/melody"] = MIME_AUDIO_MELODY;
+    stringToEnum["audio/mid"] = MIME_AUDIO_MID;
+    stringToEnum["audio/midi"] = MIME_AUDIO_MIDI;
+    stringToEnum["audio/sp-midi"] = MIME_AUDIO_SP_MIDI;
+    stringToEnum["audio/wave"] = MIME_AUDIO_WAVE;
+    stringToEnum["audio/wav"] = MIME_AUDIO_WAV;
+    stringToEnum["audio/3gpp"] = MIME_AUDIO_3GPP;
+    stringToEnum["audio/mp4"] = MIME_AUDIO_MP4;
+    stringToEnum["audio/MP4A-LATM"] = MIME_AUDIO_MP4A_LATM;
+    stringToEnum["audio/m4a"] = MIME_AUDIO_M4A;
+    stringToEnum["audio/mpeg4"] = MIME_AUDIO_MPEG4;
+    stringToEnum["audio/wma"] = MIME_AUDIO_WMA;
+    stringToEnum["audio/xmf"] = MIME_AUDIO_XMF;
+    stringToEnum["audio/imy"] = MIME_AUDIO_IMY;
+    stringToEnum["audio/mobile-xmf"] = MIME_AUDIO_MOBILE_XMF;
+    //85
+    stringToEnum["audio/vnd.rn-realaudio"] = MIME_AUDIO_VND_RN_REALAUDIO;
+    //86
+    stringToEnum["audio/x-mpeg"] = MIME_AUDIO_X_MPEG;
+    stringToEnum["audio/x-mp3"] = MIME_AUDIO_X_MP3;
+    stringToEnum["audio/x-mpeg3"] = MIME_AUDIO_X_MPEG3;
+    stringToEnum["audio/x-mpg"] = MIME_AUDIO_X_MPG;
+    stringToEnum["audio/x-amr"] = MIME_AUDIO_X_AMR;
+    stringToEnum["audio/x-mmf"] = MIME_AUDIO_X_MMF;
+    stringToEnum["audio/x-smaf"] = MIME_AUDIO_X_SMAF;
+    stringToEnum["audio/x-iMelody"] = MIME_AUDIO_X_IMELODY;
+    stringToEnum["audio/x-midi"] = MIME_AUDIO_X_MIDI;
+    stringToEnum["audio/x-mpegaudio"] = MIME_AUDIO_X_MPEGAUDIO;
+    stringToEnum["audio/x-pn-realaudio"] = MIME_AUDIO_X_PN_REALAUDIO;
+    stringToEnum["audio/x-pn-multirate-realaudio"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO;
+    stringToEnum["audio/x-pn-multirate-realaudio-live"] = MIME_AUDIO_X_PN_MULTIRATE_REALAUDIO_LIVE;
+    stringToEnum["audio/x-wave"] = MIME_AUDIO_X_WAVE;
+    stringToEnum["audio/x-wav"] = MIME_AUDIO_X_WAV;
+    stringToEnum["audio/x-ms-wma"] = MIME_AUDIO_X_MS_WMA;
+    stringToEnum["audio/x-mid"] = MIME_AUDIO_X_MID;
+    stringToEnum["audio/x-ms-asf"] = MIME_AUDIO_X_MS_ASF;
+    stringToEnum["audio/x-xmf"] = MIME_AUDIO_X_XMF;
+    //105
+    stringToEnum["image/gif"] = MIME_IMAGE_GIF;
+    stringToEnum["image/jpeg"] = MIME_IMAGE_JPEG;
+    stringToEnum["image/jpga"] = MIME_IMAGE_JPG;
+    stringToEnum["image/tiff"] = MIME_IMAGE_TIFF;
+    stringToEnum["image/tif"] = MIME_IMAGE_TIF;
+    stringToEnum["image/png"] = MIME_IMAGE_PNG;
+    stringToEnum["image/wbmp"] = MIME_IMAGE_WBMP;
+    stringToEnum["image/pjpeg"] = MIME_IMAGE_PJPEG;
+    stringToEnum["image/bmp"] = MIME_IMAGE_BMP;
+    stringToEnum["image/svg+xml"] = MIME_IMAGE_SVG;
+    stringToEnum["image/svg-xml"] = MIME_IMAGE_SVG1;
+    //116
+    stringToEnum["image/vnd.wap.wbmp"] = MIME_IMAGE_VND_WAP_WBMP;
+    stringToEnum["image/vnd.tmo.my5-gif"] = MIME_IMAGE_VND_TMO_GIF;
+    stringToEnum["image/vnd.tmo.my5-jpg"] = MIME_IMAGE_VND_TMO_JPG;
+    //119
+    stringToEnum["image/x-bmp"] = MIME_IMAGE_X_BMP;
+    //120
+    stringToEnum["message/rfc822"] = MIME_MESSAGE_RFC822;
+    //121
+    stringToEnum["multipart/mixed"] = MIME_MULTIPART_MIXED;
+    stringToEnum["multipart/related"] = MIME_MULTIPART_RELATED;
+    stringToEnum["multipart/alternative"] = MIME_MULTIPART_ALTERNATIVE;
+    stringToEnum["multipart/form-data"] = MIME_MULTIPART_FORM_DATA;
+    stringToEnum["multipart/byterange"] = MIME_MULTIPART_BYTERANGE;
+    stringToEnum["multipart/report"] = MIME_MULTIPART_REPORT;
+    stringToEnum["multipart/voice-message"] = MIME_MULTIPART_VOICE_MESSAGE;
+    //128
+    stringToEnum["text/txt"] = MIME_TEXT_TXT;
+    stringToEnum["text/html"] = MIME_TEXT_HTML;
+    stringToEnum["text/plain"] = MIME_TEXT_PLAIN;
+    stringToEnum["text/css"] = MIME_TEXT_CSS;
+    stringToEnum["text/xml"] = MIME_TEXT_XML;
+    stringToEnum["text/iMelody"] = MIME_TEXT_IMELODY;
+    //134
+    stringToEnum["text/vnd.wap.wmlscript"] = MIME_TEXT_VND_WAP_WMLSCRIPT;
+    stringToEnum["text/vnd.wap.wml"] = MIME_TEXT_VND_WAP_WML;
+    stringToEnum["text/vnd.wap.wta-event"] = MIME_TEXT_VND_WAP_WTA_EVENT;
+    stringToEnum["text/vnd.wap.connectivity-xml"] = MIME_TEXT_VND_WAP_CONNECTIVITY_XML;
+    stringToEnum["text/vnd.wap.si"] = MIME_TEXT_VND_WAP_SI;
+    stringToEnum["text/vnd.wap.sl"] = MIME_TEXT_VND_WAP_SL;
+    stringToEnum["text/vnd.wap.co"] = MIME_TEXT_VND_WAP_CO;
+    stringToEnum["text/vnd.sun.j2me.app-descriptor"] = MIME_TEXT_VND_SUN_J2ME_APP_DESCRIPTOR;
+    //142
+    stringToEnum["text/x-hdml"] = MIME_TEXT_X_HDML;
+    stringToEnum["text/x-vCalendar"] = MIME_TEXT_X_VCALENDAR;
+    stringToEnum["text/x-vCard"] = MIME_TEXT_X_VCARD;
+    stringToEnum["text/x-iMelody"] = MIME_TEXT_X_IMELODY;
+    stringToEnum["text/x-imelody"] = MIME_TEXT_X_IMELODY2;
+    stringToEnum["text/x-vnote"] = MIME_TEXT_X_VNOTE;
+    //148
+    stringToEnum["video/mpeg4"] = MIME_VIDEO_MPEG4;
+    stringToEnum["video/mp4"] = MIME_VIDEO_MP4;
+    stringToEnum["video/h263"] = MIME_VIDEO_H263;
+    stringToEnum["video/3gpp"] = MIME_VIDEO_3GPP;
+    stringToEnum["video/3gp"] = MIME_VIDEO_3GP;
+    stringToEnum["video/avi"] = MIME_VIDEO_AVI;
+    stringToEnum["video/sdp"] = MIME_VIDEO_SDP;
+    stringToEnum["video/mp4v-es"] = MIME_VIDEO_MP4_ES;
+    stringToEnum["video/mpeg"] = MIME_VIDEO_MPEG;
+    //157
+    stringToEnum["video/vnd.rn-realvideo"] = MIME_VIDEO_VND_RN_REALVIDEO;
+    stringToEnum["video/vnd.rn-realmedia"] = MIME_VIDEO_VND_RN_REALMEDIA;
+    //159
+    stringToEnum["video/x-mp4"] = MIME_VIDEO_X_MP4;
+    stringToEnum["video/x-pv-mp4"] = MIME_VIDEO_X_PV_MP4;
+    stringToEnum["video/x-pn-realvideo"] = MIME_VIDEO_X_PN_REALVIDEO;
+    stringToEnum["video/x-pn-multirate-realvideo"] = MIME_VIDEO_X_PN_MULTIRATE_REALVIDEO;
+    stringToEnum["video/x-ms-wmv"] = MIME_VIDEO_X_MS_WMV;
+    stringToEnum["video/x-ms-asf"] = MIME_VIDEO_X_MS_ASF;
+    stringToEnum["video/x-pv-pvx"] = MIME_VIDEO_X_PV_PVX;
+    stringToEnum[""] = MIME_UNKNOWN;
+
+    return stringToEnum;
+}
+
+
+unsigned int MessageAttachment::MIMETypeStringToEnum(std::string str){
+    std::map<std::string,unsigned int>::iterator it = MIMETypeStringToEnumMap.find(str);
+    if(it != MIMETypeStringToEnumMap.end()){
+        return it->second;
+    }
+    return MIME_UNKNOWN;
+}
+
+std::string MessageAttachment::MIMETypeEnumToString(unsigned int num){
+    std::map<unsigned int, std::string>::iterator it = MIMETypeEnumToStringMap.find(num);
+    if(it != MIMETypeEnumToStringMap.end()){
+        return it->second;
+    }
+    return std::string();
+}
+
+void MessageAttachment::updateWithAttachmentData(
+        const email_attachment_data_t& attachment_data)
+{
+    setId(attachment_data.attachment_id);
+    setMessageId(attachment_data.mail_id);
+    if(attachment_data.attachment_mime_type) {
+        setMimeType(attachment_data.attachment_mime_type);
+    }
+
+    bool isSaved = false;
+    if (attachment_data.attachment_path) {
+        setFilePath(attachment_data.attachment_path);
+
+        LOGD("save status: %d", attachment_data.save_status);
+        LOGD("attachment_size : %d", attachment_data.attachment_size);
+        isSaved = attachment_data.save_status;
+    }
+
+    setIsSaved(isSaved);
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessageAttachment.h b/src/messaging/old/MessageAttachment.h
new file mode 100755 (executable)
index 0000000..9ed4cfe
--- /dev/null
@@ -0,0 +1,102 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageAttachment.h
+ */
+
+#ifndef __TIZEN_MESSAGE_ATTACHMENT_H__
+#define __TIZEN_MESSAGE_ATTACHMENT_H__
+
+#include <string>
+#include <memory>
+#include <vector>
+#include <map>
+#include <msg_types.h>
+#include <email-types.h>
+#include "JSVector.h"
+#include "JSMessageAttachment.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageAttachment;
+
+struct MessageAttachmentHolder {
+    std::shared_ptr<MessageAttachment> ptr;
+};
+
+typedef Common::JSObjectVector<std::shared_ptr<MessageAttachment>,
+    JSMessageAttachment> JSAttachmentsVector;
+
+typedef std::vector<std::shared_ptr<MessageAttachment>> AttachmentPtrVector;
+
+class MessageAttachment {
+private:
+    static std::map<std::string,unsigned int>& MIMETypeStringToEnumMap;
+    static std::map<unsigned int, std::string>& MIMETypeEnumToStringMap;
+    static std::map<std::string,unsigned int>& initializeMIMETypeStringToEnumMap();
+    static std::map<unsigned int, std::string>& initializeMIMETypeEnumToStringMap();
+    int m_id;
+    bool m_isIdSet;
+    int m_messageId;
+    bool m_isMessageIdSet;
+    std::string m_mimeType;
+    bool m_isMimeTypeSet;
+    std::string m_filePath;
+    bool m_isFilePathSet;
+    bool m_isSaved;
+public:
+    MessageAttachment();
+    ~MessageAttachment();
+
+    int getId();
+    void setId(int value);
+    bool isIdSet();
+    void unsetId();
+    int getMessageId();
+    void setMessageId(int value);
+    bool isMessageIdSet();
+    void unsetMessageId();
+    std::string getMimeType();
+    void setMimeType(const std::string &value);
+    bool isMimeTypeSet();
+    void unsetMimeType();
+    std::string getFilePath();
+    std::string getShortFileName() const;
+    void setFilePath(const std::string &value);
+    bool isFilePathSet();
+    void unsetFilePath();
+    void setIsSaved(const bool isSaved);
+    bool isSaved() const;
+    static unsigned int MIMETypeStringToEnum(std::string str);
+    static std::string MIMETypeEnumToString(unsigned int num);
+
+    /**
+     * This methods updates:
+     *      setId(attachment_data.attachment_id);
+     *      setMessageId(attachment_data.mail_id);
+     *      setMimeType(attachment_data.attachment_mime_type);
+     *      setFilePath(attachment_data.attachment_path);
+     */
+    void updateWithAttachmentData(const email_attachment_data_t& attachment_data);
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_ATTACHMENT_H__
diff --git a/src/messaging/old/MessageBody.cpp b/src/messaging/old/MessageBody.cpp
new file mode 100644 (file)
index 0000000..d203ab7
--- /dev/null
@@ -0,0 +1,143 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageBody.cpp
+ */
+
+#include "MessageBody.h"
+#include "MessagingUtil.h"
+#include <Logger.h>
+#include <PlatformException.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageBody::MessageBody() : m_messageId(1),
+                             m_messageId_set(false),
+                             m_loaded(false),
+                             m_plainBody(""),
+                             m_htmlBody("")
+{
+}
+
+MessageBody::~MessageBody()
+{
+}
+
+// messageId
+
+int MessageBody::getMessageId() const
+{
+
+    return m_messageId;
+}
+
+void MessageBody::setMessageId(int value)
+{
+    m_messageId = value;
+    m_messageId_set = true;
+}
+
+// loaded
+
+bool MessageBody::getLoaded() const
+{
+    return m_loaded;
+}
+
+void MessageBody::setLoaded(bool value)
+{
+    m_loaded = value;
+}
+
+// plainBody
+
+std::string MessageBody::getPlainBody() const
+{
+    return m_plainBody;
+}
+
+void MessageBody::setPlainBody(const std::string &value)
+{
+    m_plainBody = value;
+}
+
+// htmlBody
+
+std::string MessageBody::getHtmlBody() const
+{
+    return m_htmlBody;
+}
+
+void MessageBody::setHtmlBody(const std::string &value)
+{
+    m_htmlBody = value;
+}
+
+// inlineAttachments
+
+AttachmentPtrVector MessageBody::getInlineAttachments() const
+{
+    return m_inlineAttachments;
+}
+
+JSObjectRef MessageBody::getJSInlineAttachments(JSContextRef global_ctx)
+{
+    return m_inlineAttachments.getJSArray(global_ctx);
+}
+
+void MessageBody::setInlineAttachments(const AttachmentPtrVector& attachments)
+{
+    m_inlineAttachments = attachments;
+}
+
+// ***  support for optional, nullable (at JS layer) attibutes
+bool MessageBody::is_message_id_set() const
+{
+    return m_messageId_set;
+}
+
+void MessageBody::updateBody(email_mail_data_t& mail)
+{
+    LOGD("Enter");
+    setMessageId(mail.mail_id);
+    setLoaded(mail.body_download_status);
+
+    if (mail.file_path_plain) {
+        try {
+            LOGD("Plain body");
+            setPlainBody(MessagingUtil::loadFileContentToString(mail.file_path_plain));
+        } catch (...) {
+            LOGE("Fail to open plain body.");
+            throw Common::UnknownException("Fail to open plain body.");
+        }
+    }
+
+    if (mail.file_path_html) {
+        try {
+            LOGD("Html body");
+            setHtmlBody(MessagingUtil::loadFileContentToString(mail.file_path_html));
+        } catch (...) {
+            LOGE("Fail to open html body.");
+            throw Common::UnknownException("Fail to open html body.");
+        }
+    }
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessageBody.h b/src/messaging/old/MessageBody.h
new file mode 100644 (file)
index 0000000..1fb297a
--- /dev/null
@@ -0,0 +1,76 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageBody.h
+ */
+
+#ifndef __TIZEN_MESSAGING_MESSAGE_BODY_H__
+#define __TIZEN_MESSAGING_MESSAGE_BODY_H__
+
+#include <vector>
+#include <string>
+#include "MessageAttachment.h"
+#include <email-types.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageBody;
+
+struct MessageBodyHolder {
+    std::shared_ptr<MessageBody> ptr;
+};
+
+class MessageBody {
+public:
+    explicit MessageBody();
+    ~MessageBody();
+    int getMessageId()  const;
+    void setMessageId(int value);
+    bool getLoaded()  const;
+    void setLoaded(bool value);
+    std::string getPlainBody()  const;
+    void setPlainBody(const std::string &value);
+    std::string getHtmlBody()  const;
+    void setHtmlBody(const std::string &value);
+    AttachmentPtrVector getInlineAttachments()  const;
+    JSObjectRef getJSInlineAttachments(JSContextRef global_ctx);
+    void setInlineAttachments(const AttachmentPtrVector& attachments);
+
+    // support for optional, nullable (at JS layer) attibutes
+    bool is_message_id_set() const;
+    /**
+     * Updates body with data from email_mail_data_t structure.
+     * @param mail
+     */
+    void updateBody(email_mail_data_t& mail);
+
+private:
+    int m_messageId;
+    bool m_messageId_set;
+    bool m_loaded;
+    std::string m_plainBody;
+    std::string m_htmlBody;
+    JSAttachmentsVector m_inlineAttachments;
+    JSContextRef m_context;
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGING_MESSAGE_BODY_H__
diff --git a/src/messaging/old/MessageCallbackUserData.cpp b/src/messaging/old/MessageCallbackUserData.cpp
new file mode 100644 (file)
index 0000000..97539b6
--- /dev/null
@@ -0,0 +1,79 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "MessageCallbackUserData.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+
+MessageCallbackUserData::MessageCallbackUserData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_is_error(false)
+{
+}
+
+MessageCallbackUserData::~MessageCallbackUserData() {
+}
+
+void MessageCallbackUserData::setMessage(std::shared_ptr<Message> message) {
+    m_message = message;
+}
+
+std::shared_ptr<Message> MessageCallbackUserData::getMessage() const {
+    return m_message;
+}
+
+void MessageCallbackUserData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool MessageCallbackUserData::isError() const
+{
+    return m_is_error;
+}
+
+std::string MessageCallbackUserData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string MessageCallbackUserData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void MessageCallbackUserData::setAccountId(int account_id){
+    m_account_id = account_id;
+}
+
+int MessageCallbackUserData::getAccountId() const
+{
+    return m_account_id;
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/MessageCallbackUserData.h b/src/messaging/old/MessageCallbackUserData.h
new file mode 100644 (file)
index 0000000..eb11724
--- /dev/null
@@ -0,0 +1,58 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H
+#define __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H
+
+#include <CallbackUserData.h>
+#include <memory>
+#include <string>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+
+class MessageCallbackUserData: public Common::CallbackUserData {
+public:
+    MessageCallbackUserData(JSContextRef globalCtx);
+    virtual ~MessageCallbackUserData();
+
+    void setMessage(std::shared_ptr<Message> message);
+    std::shared_ptr<Message> getMessage() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void setAccountId(int account_id);
+    int getAccountId() const;
+private:
+    std::shared_ptr<Message> m_message;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    int m_account_id;
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_ADD_DRAFT_MESSAGE_CALLBACK_USER_DATA_H */
+
diff --git a/src/messaging/old/MessageConversation.cpp b/src/messaging/old/MessageConversation.cpp
new file mode 100644 (file)
index 0000000..2037bea
--- /dev/null
@@ -0,0 +1,522 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageConversation.cpp
+ */
+
+#include <PlatformException.h>
+#include <Logger.h>
+#include "Message.h"
+#include "MessageConversation.h"
+#include "MessagingUtil.h"
+#include "JSMessageConversation.h"
+#include "MessagingUtil.h"
+
+#define MAX_THREAD_DATA_LEN 128
+
+namespace DeviceAPI {
+
+using namespace Tizen;
+
+namespace Messaging {
+
+// *** constructor
+MessageConversation::MessageConversation():
+    m_conversation_id(-1),
+    m_conversation_type(UNDEFINED),
+    m_count(0),
+    m_unread_messages(0),
+    m_is_read(false)
+{
+    LOGD("Message Conversation constructor.");
+}
+
+MessageConversation::~MessageConversation()
+{
+    LOGD("Message Conversation destructor.");
+}
+// *** attributes getters
+int MessageConversation::getConversationId() const
+{
+    return m_conversation_id;
+}
+
+MessageType MessageConversation::getType() const
+{
+    return m_conversation_type;
+}
+
+time_t MessageConversation::getTimestamp() const
+{
+    return m_timestamp;
+}
+
+unsigned long MessageConversation::getMessageCount() const
+{
+    return m_count;
+}
+
+unsigned long MessageConversation::getUnreadMessages() const
+{
+    return m_unread_messages;
+}
+
+std::string MessageConversation::getPreview() const
+{
+    return m_preview;
+}
+
+std::string MessageConversation::getSubject() const
+{
+    return m_conversation_subject;
+}
+
+bool MessageConversation::getIsRead() const
+{
+    return m_is_read;
+}
+
+std::string MessageConversation::getFrom() const
+{
+    return m_from;
+}
+
+std::vector<std::string> MessageConversation::getTo() const
+{
+    return m_to;
+}
+
+std::vector<std::string> MessageConversation::getCC() const
+{
+    return m_cc;
+}
+
+std::vector<std::string> MessageConversation::getBCC() const
+{
+    return m_bcc;
+}
+
+int MessageConversation::getLastMessageId() const
+{
+    return m_last_message_id;
+}
+
+std::shared_ptr<MessageConversation> MessageConversation::convertMsgConversationToObject(
+        unsigned int threadId, msg_handle_t handle)
+{
+    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
+
+    msg_struct_t msgInfo = NULL;
+    msg_struct_t sendOpt = NULL;
+
+    msg_struct_t msg_thread = NULL;
+
+    msg_struct_list_s convViewList;
+    msg_list_handle_t addr_list = NULL;
+    msg_struct_t addr_info = NULL;
+
+    msg_error_t err = MSG_SUCCESS;
+
+    int tempInt;
+    bool tempBool;
+    int nToCnt;
+    unsigned int lastMsgIndex = 0;
+    char msgData[MAX_THREAD_DATA_LEN] = {0,};
+
+    try {
+        msgInfo = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+        sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
+
+        conversation->m_conversation_id = threadId;
+
+        msg_thread = msg_create_struct(MSG_STRUCT_THREAD_INFO);
+        err = msg_get_thread(handle, conversation->m_conversation_id, msg_thread);
+        if (err != MSG_SUCCESS)
+        {
+            LOGE("Failed to retrieve thread.");
+            throw Common::UnknownException("Failed to retrieve thread.");
+        }
+        msg_get_int_value(msg_thread, MSG_THREAD_MSG_TYPE_INT, &tempInt);
+        switch(tempInt)
+        {
+            case MSG_TYPE_SMS:
+            case MSG_TYPE_SMS_CB:
+            case MSG_TYPE_SMS_JAVACB:
+            case MSG_TYPE_SMS_WAPPUSH:
+            case MSG_TYPE_SMS_MWI:
+            case MSG_TYPE_SMS_SYNCML:
+            case MSG_TYPE_SMS_REJECT:
+                conversation->m_conversation_type = SMS;
+                break;
+            case MSG_TYPE_MMS:
+            case MSG_TYPE_MMS_JAVA:
+            case MSG_TYPE_MMS_NOTI:
+                conversation->m_conversation_type = MMS;
+                break;
+        }
+
+        msg_get_int_value(msg_thread, MSG_THREAD_MSG_TIME_INT, &tempInt);
+        conversation->m_timestamp = tempInt;
+
+        msg_get_int_value(msg_thread, MSG_THREAD_UNREAD_COUNT_INT, &tempInt);
+        conversation->m_unread_messages = tempInt;
+
+        msg_get_str_value(msg_thread, MSG_THREAD_MSG_DATA_STR, msgData, MAX_THREAD_DATA_LEN);
+
+        conversation->m_preview = msgData;
+
+        err = msg_get_conversation_view_list(handle, conversation->m_conversation_id,
+            &convViewList);
+        if (err != MSG_SUCCESS)
+        {
+            LOGE("Get conversation(msg) view list fail.");
+            throw Common::UnknownException("Get conversation(msg) view list fail.");
+        }
+
+        lastMsgIndex = convViewList.nCount - 1;
+        conversation->m_count = convViewList.nCount;
+
+        msg_get_bool_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_READ_BOOL, &tempBool);
+        conversation->m_is_read = tempBool;
+
+        msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_ID_INT, &tempInt);
+        conversation->m_last_message_id = tempInt;
+
+        if (msg_get_message(handle, conversation->m_last_message_id, msgInfo,
+            sendOpt) != MSG_SUCCESS)
+        {
+            LOGE("Get message fail.");
+            throw Common::UnknownException("get message fail.");
+        }
+
+        msg_get_int_value(convViewList.msg_struct_info[lastMsgIndex], MSG_CONV_MSG_DIRECTION_INT, &tempInt);
+
+        msg_get_list_handle(msgInfo, MSG_MESSAGE_ADDR_LIST_HND, (void **)&addr_list);
+        nToCnt = msg_list_length(addr_list);
+
+        if (MSG_DIRECTION_TYPE_MT == tempInt)
+        {
+            if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT )
+            {
+                char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
+                addr_info = (msg_struct_t)msg_list_nth_data(addr_list, nToCnt-1);
+                msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
+
+                if (strNumber[0] != '\0')
+                {
+                    conversation->m_from = strNumber;
+                }
+                else
+                {
+                    LOGD("address is null ");
+                }
+            }
+            else
+            {
+                LOGD("address count index fail");
+            }
+        }
+        else
+        {
+            if (nToCnt > 0 && nToCnt < MAX_TO_ADDRESS_CNT )
+            {
+                for (int index = 0; index < nToCnt; index++)
+                {
+                    addr_info = (msg_struct_t)msg_list_nth_data(addr_list, index);
+                    char strNumber[MAX_ADDRESS_VAL_LEN] = {0,};
+                    msg_get_str_value(addr_info, MSG_ADDRESS_INFO_ADDRESS_VALUE_STR, strNumber, MAX_ADDRESS_VAL_LEN);
+
+                    conversation->m_to.push_back(strNumber);
+                }
+            }
+            else
+            {
+                LOGD("address fetch fail");
+            }
+        }
+
+        char strTemp[MAX_SUBJECT_LEN] = {0};
+        msg_get_str_value(msgInfo, MSG_MESSAGE_SUBJECT_STR, strTemp, MAX_SUBJECT_LEN);
+
+        conversation->m_conversation_subject = strTemp;
+        msg_release_list_struct(&convViewList);
+        msg_release_struct(&msgInfo);
+        msg_release_struct(&sendOpt);
+        msg_release_struct(&msg_thread);
+    } catch (const Common::BasePlatformException& ex) {
+        msg_release_list_struct(&convViewList);
+        msg_release_struct(&msgInfo);
+        msg_release_struct(&sendOpt);
+        msg_release_struct(&msg_thread);
+        LOGE("%s (%s)", (ex.getName()).c_str(), (ex.getMessage()).c_str());
+        throw Common::UnknownException("Unable to convert short message conversation.");
+    } catch (...) {
+        msg_release_list_struct(&convViewList);
+        msg_release_struct(&msgInfo);
+        msg_release_struct(&sendOpt);
+        msg_release_struct(&msg_thread);
+        throw Common::UnknownException("Unable to convert short message conversation.");
+    }
+
+    return conversation;
+}
+
+std::shared_ptr<MessageConversation> MessageConversation::convertEmailConversationToObject(
+        unsigned int threadId)
+{
+    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
+
+    email_mail_list_item_t *resultMail = NULL;
+
+    if(email_get_thread_information_ex(threadId, &resultMail) != EMAIL_ERROR_NONE)
+    {
+        LOGE("Couldn't get conversation");
+        throw Common::UnknownException("Couldn't get conversation.");
+    } else {
+        if (!resultMail)
+        {
+            LOGE("Data is null");
+            throw Common::UnknownException("Get email data fail.");
+        }
+
+        email_mail_data_t* mailData = NULL;
+
+        if (email_get_mail_data(resultMail->mail_id,
+                &mailData) != EMAIL_ERROR_NONE)
+        {
+            free(resultMail);
+            throw Common::UnknownException("Get email data fail.");
+        }
+
+        if (!mailData) {
+            free(resultMail);
+            throw Common::UnknownException("Get email data fail.");
+        }
+
+        int index = 0;
+        int count = 0;
+        conversation->m_unread_messages = 0;
+        email_mail_list_item_t *mailList = NULL;
+
+        if (email_get_mail_list(mailData->account_id, 0, threadId, 0,
+            resultMail->thread_item_count, EMAIL_SORT_DATETIME_HIGH, &mailList,
+            &count) != EMAIL_ERROR_NONE)
+        {
+            email_free_mail_data(&mailData , 1);
+            free(resultMail);
+            throw Common::UnknownException("Get email data list fail.");
+        }
+
+        for (index = 0; index < count; index++)
+        {
+            if (mailList[index].flags_seen_field)
+            {
+                conversation->m_unread_messages++;
+            }
+        }
+        conversation->m_count = resultMail->thread_item_count;
+
+        conversation->m_conversation_id = threadId;
+
+        conversation->m_conversation_type = EMAIL;
+
+        conversation->m_timestamp = resultMail->date_time;
+
+        if (resultMail->preview_text[0] != '\0')
+        {
+            conversation->m_preview = resultMail->preview_text;
+        }
+
+        if (resultMail->subject[0] != '\0')
+        {
+            conversation->m_conversation_subject = resultMail->subject;
+        }
+
+        conversation->m_is_read = (bool)resultMail->flags_seen_field;
+
+        if (resultMail->full_address_from[0] != '\0')
+        {
+            conversation->m_from = MessagingUtil::extractSingleEmailAddress(
+                    resultMail->full_address_from);
+        }
+
+        if (mailData->full_address_to != NULL)
+        {
+            conversation->m_to = Message::getEmailRecipientsFromStruct(
+                mailData->full_address_to);
+        }
+
+        if (mailData->full_address_cc != NULL)
+        {
+            conversation->m_cc = Message::getEmailRecipientsFromStruct(
+                mailData->full_address_cc);
+        }
+
+        if (mailData->full_address_bcc != NULL)
+        {
+            conversation->m_bcc = Message::getEmailRecipientsFromStruct(
+                mailData->full_address_bcc);
+        }
+
+        conversation->m_last_message_id = resultMail->mail_id;
+
+        if (mailData != NULL)
+        {
+            email_free_mail_data(&mailData , 1);
+        }
+    }
+
+    if (resultMail != NULL)
+    {
+        free(resultMail);
+    }
+
+    return conversation;
+}
+
+std::shared_ptr<MessageConversation> MessageConversation::convertConversationStructToObject(
+        unsigned int threadId, MessageType msgType, msg_handle_t handle)
+{
+    std::shared_ptr<MessageConversation> conversation (new MessageConversation());
+
+    if (EMAIL == msgType) {
+        conversation = convertEmailConversationToObject(threadId);
+    } else {
+        if(handle != NULL) {
+            conversation = convertMsgConversationToObject(threadId, handle);
+        } else {
+            LOGE("Handle has not been sent.");
+            throw Common::UnknownException("Handle has not been sent.");
+        }
+    }
+
+    return conversation;
+}
+
+void MessageConversation::setConversationId(int id)
+{
+    m_conversation_id = id;
+}
+void MessageConversation::setMessageCount(int count)
+{
+    m_count = count;
+}
+
+void MessageConversation::setUnreadMessages(int count)
+{
+    m_unread_messages = count;
+}
+
+/**
+ *
+ *  Attribute      | Attribute filter| Attribute range filter
+ *                 | supported       | supported
+ * ----------------+-----------------+------------------------
+ * id              | Yes             | No
+ * type            | Yes             | No
+ * timestamp       | No              | Yes
+ * messageCount    | Yes             | No
+ * unreadMessages  | Yes             | No
+ * preview         | Yes             | No
+ * subject         | No              | No
+ * isRead          | No              | No
+ * from            | Yes             | No
+ * to              | Yes             | No
+ * cc              | No              | No
+ * bcc             | No              | No
+ * lastMessageId   | No              | No
+ */
+
+namespace CONVERSATION_FILTER_ATTRIBUTE {
+const std::string ID = JSMessageConversationKeys::MESSAGE_CONVERSATION_ID;
+const std::string TYPE = JSMessageConversationKeys::MESSAGE_CONVERSATION_TYPE;
+const std::string TIMESTAMP = JSMessageConversationKeys::MESSAGE_CONVERSATION_TIMESTAMP;
+const std::string MESSAGE_COUNT =
+        JSMessageConversationKeys::MESSAGE_CONVERSATION_MSG_COUNT;
+
+const std::string UNREAD_MESSAGES =
+        JSMessageConversationKeys::MESSAGE_CONVERSATION_UNREAD_MSG;
+
+const std::string PREVIEW = JSMessageConversationKeys::MESSAGE_CONVERSATION_PREVIEW;
+const std::string FROM = JSMessageConversationKeys::MESSAGE_CONVERSATION_FROM;
+const std::string TO = JSMessageConversationKeys::MESSAGE_CONVERSATION_TO;
+} //namespace CONVERSATION_FILTER_ATTRIBUTE
+
+bool MessageConversation::isMatchingAttribute(const std::string& attribute_name,
+            const FilterMatchFlag match_flag,
+            AnyPtr match_value) const
+{
+    LOGD("Entered");
+    auto key = match_value->toString();
+    LOGD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(),
+            match_flag, key.c_str());
+
+    using namespace CONVERSATION_FILTER_ATTRIBUTE;
+
+    if(ID == attribute_name) {
+        return FilterUtils::isStringMatching(key, std::to_string(getConversationId()),
+                match_flag);
+    }
+    else if(TYPE == attribute_name) {
+        const MessageType msg_type = getType();
+        const std::string msg_type_str = MessagingUtil::messageTypeToString(msg_type);
+        return FilterUtils::isStringMatching(key, msg_type_str, match_flag);
+    }
+    else if(MESSAGE_COUNT == attribute_name) {
+        return FilterUtils::isStringMatching(key, std::to_string(getMessageCount()),
+                match_flag);
+    }
+    else if(UNREAD_MESSAGES == attribute_name) {
+        return FilterUtils::isStringMatching(key, std::to_string(getUnreadMessages()),
+                match_flag);
+    }
+    else if(PREVIEW == attribute_name) {
+        return FilterUtils::isStringMatching(key, getPreview(), match_flag);
+    }
+    else if(FROM == attribute_name) {
+        return FilterUtils::isStringMatching(key, getFrom(), match_flag);
+    }
+    else if(TO == attribute_name) {
+        return FilterUtils::isAnyStringMatching(key, getTo(), match_flag);
+    }
+    else {
+        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
+    }
+
+    return false;
+}
+
+bool MessageConversation::isMatchingAttributeRange(const std::string& attribute_name,
+            AnyPtr initial_value,
+            AnyPtr end_value) const
+{
+    LOGD("Entered attribute_name: %s", attribute_name.c_str());
+
+    using namespace CONVERSATION_FILTER_ATTRIBUTE;
+
+    if(TIMESTAMP == attribute_name) {
+        return FilterUtils::isTimeStampInRange(getTimestamp(), initial_value, end_value);
+    }
+    else {
+        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
+    }
+    return false;
+}
+
+} //Messaging
+} //DeviceAPI
diff --git a/src/messaging/old/MessageConversation.h b/src/messaging/old/MessageConversation.h
new file mode 100644 (file)
index 0000000..568c32d
--- /dev/null
@@ -0,0 +1,112 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageConversation.h
+ */
+
+#ifndef __TIZEN_MESSAGE_CONVERSATION_H__
+#define __TIZEN_MESSAGE_CONVERSATION_H__
+
+#include <memory>
+#include <string>
+#include <time.h>
+#include <vector>
+#include <email-api.h>
+#include <msg.h>
+#include <msg_storage.h>
+#include "MessagingUtil.h"
+#include <AbstractFilter.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageConversation;
+
+struct MessageConversationHolder {
+    std::shared_ptr<MessageConversation>ptr;
+};
+
+typedef std::shared_ptr<MessageConversation> ConversationPtr;
+
+typedef std::vector<ConversationPtr> ConversationPtrVector;
+
+class MessageConversation : public Tizen::FilterableObject {
+public:
+    MessageConversation();
+    ~MessageConversation();
+
+    // attributes getters
+    int getConversationId() const;
+    MessageType getType() const;
+    time_t getTimestamp() const;
+    unsigned long getMessageCount() const;
+    unsigned long getUnreadMessages() const;
+    std::string getPreview() const;
+    std::string getSubject() const;
+    bool getIsRead() const;
+    std::string getFrom() const;
+    std::vector<std::string> getTo() const;
+    std::vector<std::string> getCC() const;
+    std::vector<std::string> getBCC() const;
+    int getLastMessageId() const;
+
+    static std::shared_ptr<MessageConversation> convertConversationStructToObject(
+        unsigned int threadId, MessageType msgType, msg_handle_t handle = NULL);
+    static std::shared_ptr<MessageConversation> convertEmailConversationToObject(
+        unsigned int threadId);
+    /**
+     *
+     * @param threadId Id of Message (not Conversation)
+     * @param handle
+     * @return
+     */
+    static std::shared_ptr<MessageConversation> convertMsgConversationToObject(
+        unsigned int threadId, msg_handle_t handle);
+
+    virtual void setConversationId(int id);
+    virtual void setMessageCount(int count);
+    virtual void setUnreadMessages(int count);
+
+    // Tizen::FilterableObject
+    virtual bool isMatchingAttribute(const std::string& attribute_name,
+            const Tizen::FilterMatchFlag match_flag,
+            Tizen::AnyPtr match_value) const;
+
+    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
+            Tizen::AnyPtr initial_value,
+            Tizen::AnyPtr end_value) const;
+
+private:
+    int m_conversation_id;
+    MessageType m_conversation_type;
+    time_t m_timestamp;
+    unsigned long m_count;
+    unsigned long m_unread_messages;
+    std::string m_preview;
+    std::string m_conversation_subject;
+    bool m_is_read;
+    std::string m_from;
+    std::vector<std::string> m_to;
+    std::vector<std::string> m_cc;
+    std::vector<std::string> m_bcc;
+    int m_last_message_id;
+};
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_CONVERSATION_H__
diff --git a/src/messaging/old/MessageEmail.cpp b/src/messaging/old/MessageEmail.cpp
new file mode 100644 (file)
index 0000000..fd6699f
--- /dev/null
@@ -0,0 +1,166 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageEmail.cpp
+ */
+
+#include <PlatformException.h>
+#include <Logger.h>
+#include "MessageEmail.h"
+#include <GlobalContextManager.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageEmail::MessageEmail():
+    Message()
+{
+    LOGD("MessageEmail constructor.");
+    this->m_type = MessageType(EMAIL);
+}
+
+MessageEmail::~MessageEmail()
+{
+    LOGD("MessageEmail destructor.");
+}
+
+// *** overrided methods
+void MessageEmail::setCC(std::vector<std::string> &cc)
+{
+    // CC recipient's format validation should be done by email service
+    m_cc = cc;
+
+    if(m_cc.empty()) {
+        LOGD("Recipient's list cleared");
+        return;
+    }
+}
+
+void MessageEmail::setBCC(std::vector<std::string> &bcc)
+{
+    // BCC recipient's format validation should be done by email service
+    m_bcc = bcc;
+
+    if(m_bcc.empty()) {
+        LOGD("Recipient's list cleared");
+        return;
+    }
+}
+
+void MessageEmail::setSubject(std::string subject)
+{
+    m_subject = subject;
+}
+
+void MessageEmail::setIsHighPriority(bool highpriority)
+{
+    m_high_priority = highpriority;
+}
+
+void MessageEmail::setMessageAttachments(AttachmentPtrVector &attachments)
+{
+    m_attachments = attachments;
+
+    m_has_attachment = true;
+    if(m_attachments.empty()) {
+        LOGD("Recipient's list cleared");
+        m_has_attachment = false;
+    }
+}
+
+bool MessageEmail::getHasAttachment() const
+{
+    LOGD("MessageEmail::getHasAttachment()");
+    return m_has_attachment || !m_body->getInlineAttachments().empty();
+}
+
+void MessageEmail::updateEmailMessage(email_mail_data_t& mail)
+{
+    LOGD("Enter");
+    std::vector<std::string> recp_list;
+
+    setId(mail.mail_id);
+
+    setFolderId(mail.mailbox_id);
+
+    setConversationId(mail.thread_id);
+
+    if(mail.full_address_from) {
+        setFrom(MessagingUtil::extractSingleEmailAddress(mail.full_address_from));
+    }
+
+    if(mail.full_address_to) {
+        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_to);
+        setTO(recp_list);
+    }
+
+    if(mail.full_address_cc) {
+        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_cc);
+        setCC(recp_list);
+    }
+
+    if(mail.full_address_bcc) {
+        recp_list = Message::getEmailRecipientsFromStruct(mail.full_address_bcc);
+        setBCC(recp_list);
+    }
+
+    setTimeStamp(mail.date_time);
+
+    setIsRead(mail.flags_seen_field);
+
+    setIsHighPriority((EMAIL_MAIL_PRIORITY_HIGH == mail.priority) ? true : false);
+
+    if (mail.subject == NULL) {
+        LOGW("Subject is null");
+    } else {
+        LOGD("Subject: %s", mail.subject);
+        setSubject(mail.subject);
+    }
+
+    getBody()->updateBody(mail);
+
+    if (mail.mail_id != mail.thread_id) {
+        setInResponseTo(mail.thread_id);
+    }
+
+    switch(mail.save_status)
+    {
+        case EMAIL_MAIL_STATUS_SENT:
+            setMessageStatus(MessageStatus::STATUS_SENT);
+        break;
+        case EMAIL_MAIL_STATUS_SENDING:
+            setMessageStatus(MessageStatus::STATUS_SENDING);
+        break;
+        case EMAIL_MAIL_STATUS_SAVED:
+            setMessageStatus(MessageStatus::STATUS_DRAFT);
+        break;
+        case EMAIL_MAIL_STATUS_SEND_FAILURE:
+            setMessageStatus(MessageStatus::STATUS_FAILED);
+        break;
+        default:
+            setMessageStatus(MessageStatus::STATUS_UNDEFINED);
+        break;
+    }
+
+    AttachmentPtrVector att = convertEmailToMessageAttachment(mail);
+
+    setMessageAttachments(att);
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessageEmail.h b/src/messaging/old/MessageEmail.h
new file mode 100644 (file)
index 0000000..aacf1b0
--- /dev/null
@@ -0,0 +1,60 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageEmail.h
+ */
+
+
+#ifndef __TIZEN_MESSAGE_EMAIL_H__
+#define __TIZEN_MESSAGE_EMAIL_H__
+
+#include "Message.h"
+#include "MessageAttachment.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageEmail: public Message {
+public:
+// constructor
+    MessageEmail();
+    ~MessageEmail();
+
+//overrided base class functions
+    void setCC(std::vector<std::string> &cc);
+    void setBCC(std::vector<std::string> &bcc);
+    void setSubject(std::string subject);
+    void setIsHighPriority(bool highpriority);
+    void setMessageAttachments(AttachmentPtrVector &attachments);
+
+    bool getHasAttachment() const;
+    /**
+     * Updates message with data from email_mail_data_t structure.
+     * @param mail
+     */
+    virtual void updateEmailMessage(email_mail_data_t& mail);
+
+private:
+    // function that verifies recipient's list validity
+    bool isValidRecpientsVector(std::vector<std::string> &recipients);
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_EMAIL_H__
diff --git a/src/messaging/old/MessageFolder.cpp b/src/messaging/old/MessageFolder.cpp
new file mode 100644 (file)
index 0000000..420006f
--- /dev/null
@@ -0,0 +1,200 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageFolder.cpp
+ */
+
+#include "MessageFolder.h"
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+
+using namespace Tizen;
+
+namespace Messaging {
+
+MessageFolder::MessageFolder(
+        std::string id,
+        std::string parent_id,
+        std::string service_id,
+        std::string content_type,
+        std::string name,
+        std::string path,
+        MessageFolderType type,
+        bool synchronizable):
+    m_id(id),
+    m_parent_id(parent_id),
+    m_parent_id_set(true),
+    m_service_id(service_id),
+    m_content_type(content_type),
+    m_name(name),
+    m_path(path),
+    m_type(type),
+    m_synchronizable(synchronizable)
+{
+}
+
+MessageFolder::MessageFolder(email_mailbox_t mailbox)
+{
+    m_id = std::to_string(mailbox.mailbox_id);
+    m_parent_id_set = false;
+    m_service_id = std::to_string(mailbox.account_id);
+    m_content_type = MessagingUtil::messageTypeToString(EMAIL);
+    m_name = mailbox.alias;
+    m_path = mailbox.mailbox_name;
+    m_type = convertPlatformFolderType(mailbox.mailbox_type);
+    if (0 == mailbox.local) {
+        m_synchronizable = true;
+    }
+    else {
+        m_synchronizable = false;
+    }
+}
+
+std::string MessageFolder::getId() const
+{
+    return m_id;
+}
+
+std::string MessageFolder::getParentId() const
+{
+    return m_parent_id;
+}
+
+bool MessageFolder::isParentIdSet() const
+{
+    return m_parent_id_set;
+}
+
+void MessageFolder::setParentId(const std::string& parentId)
+{
+    m_parent_id = parentId;
+    m_parent_id_set = true;
+}
+
+std::string MessageFolder::getServiceId() const
+{
+    return m_service_id;
+}
+
+std::string MessageFolder::getContentType() const
+{
+    return m_content_type;
+}
+
+std::string MessageFolder::getName() const
+{
+    return m_name;
+}
+
+std::string MessageFolder::getPath() const
+{
+    return m_path;
+}
+
+MessageFolderType MessageFolder::getType() const
+{
+    return m_type;
+}
+
+bool MessageFolder::getSynchronizable() const
+{
+    return m_synchronizable;
+}
+
+void MessageFolder::setName(const std::string &value)
+{
+    m_name = value;
+}
+
+void MessageFolder::setSynchronizable(const bool &value)
+{
+    m_synchronizable = value;
+}
+
+MessageFolderType MessageFolder::convertPlatformFolderType(
+        email_mailbox_type_e folderType)
+{
+    switch (folderType) {
+        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_INBOX:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX;
+        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_SENTBOX:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX;
+        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_DRAFT:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS;
+        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_OUTBOX:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX;
+        case email_mailbox_type_e::EMAIL_MAILBOX_TYPE_ALL_EMAILS:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD;
+        default:
+            return MessageFolderType::MESSAGE_FOLDER_TYPE_NOTSTANDARD;
+    }
+}
+
+/**
+ *
+ *  Attribute      | Attribute filter| Attribute range filter
+ *                 | supported       | supported
+ * ----------------+-----------------+------------------------
+ *  id             | No              | No
+ *  parentId       | No              | No
+ *  serviceId      | Yes             | No
+ *  contentType    | No              | No
+ *  name           | No              | No
+ *  path           | No              | No
+ *  type           | No              | No
+ *  synchronizable | No              | No
+ */
+
+namespace FOLDER_FILTER_ATTRIBUTE {
+const std::string SERVICE_ID = "serviceId";
+} //namespace FOLDER_FILTER_ATTRIBUTE
+
+bool MessageFolder::isMatchingAttribute(const std::string& attribute_name,
+            const FilterMatchFlag match_flag,
+            AnyPtr match_value) const
+{
+    LOGD("Entered");
+    auto key = match_value->toString();
+    LOGD("attribute_name: %s match_flag:%d match_value:%s", attribute_name.c_str(),
+            match_flag, key.c_str());
+
+    using namespace FOLDER_FILTER_ATTRIBUTE;
+
+    if (SERVICE_ID == attribute_name) {
+        return FilterUtils::isStringMatching(key, getServiceId() , match_flag);
+    }
+    else {
+        LOGD("attribute:%s is NOT SUPPORTED", attribute_name.c_str());
+    }
+
+    return false;
+}
+
+
+bool MessageFolder::isMatchingAttributeRange(const std::string& attribute_name,
+            AnyPtr initial_value,
+            AnyPtr end_value) const
+{
+    LOGD("Entered");
+    LOGD("attribute_name: %s NOT SUPPORTED", attribute_name.c_str());
+    return false;
+}
+
+} //Messaging
+} //DeviceAPI
diff --git a/src/messaging/old/MessageFolder.h b/src/messaging/old/MessageFolder.h
new file mode 100644 (file)
index 0000000..dfb02f7
--- /dev/null
@@ -0,0 +1,106 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageFolder.h
+ */
+
+#ifndef __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
+#define __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
+
+#include <string>
+#include <memory>
+#include <vector>
+
+#include <email-types.h>
+#include <AbstractFilter.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+enum MessageFolderType {
+    MESSAGE_FOLDER_TYPE_INBOX,
+    MESSAGE_FOLDER_TYPE_OUTBOX,
+    MESSAGE_FOLDER_TYPE_DRAFTS,
+    MESSAGE_FOLDER_TYPE_SENTBOX,
+    MESSAGE_FOLDER_TYPE_NOTSTANDARD
+};
+
+class MessageFolder;
+
+struct MessageFolderHolder {
+    std::shared_ptr<MessageFolder> ptr;
+};
+
+typedef std::shared_ptr<MessageFolder> FolderPtr;
+
+typedef std::vector<FolderPtr> FolderPtrVector;
+
+class MessageFolder : public Tizen::FilterableObject{
+
+public:
+    MessageFolder(
+            std::string id,
+            std::string parent_id,
+            std::string service_id,
+            std::string content_type,
+            std::string name,
+            std::string path,
+            MessageFolderType type,
+            bool synchronizable);
+    MessageFolder(email_mailbox_t mailbox);
+
+    std::string getId() const;
+    std::string getParentId() const;
+    bool isParentIdSet() const;
+    void setParentId(const std::string& parentId);
+    std::string getServiceId() const;
+    std::string getContentType() const;
+    std::string getName() const;
+    void setName(const std::string &value);
+    std::string getPath() const;
+    MessageFolderType getType() const;
+    bool getSynchronizable() const;
+    void setSynchronizable(const bool &value);
+
+    // Tizen::FilterableObject
+    virtual bool isMatchingAttribute(const std::string& attribute_name,
+            const Tizen::FilterMatchFlag match_flag,
+            Tizen::AnyPtr match_value) const;
+
+    virtual bool isMatchingAttributeRange(const std::string& attribute_name,
+            Tizen::AnyPtr initial_value,
+            Tizen::AnyPtr end_value) const;
+private:
+    MessageFolderType convertPlatformFolderType(
+            email_mailbox_type_e folderType);
+
+    std::string m_id;
+    std::string m_parent_id;
+    bool m_parent_id_set;
+    std::string m_service_id;
+    std::string m_content_type;
+    std::string m_name;
+    std::string m_path;
+    MessageFolderType m_type;
+    bool m_synchronizable;
+};
+
+} //Messaging
+} //DeviceAPI
+
+#endif // __TIZEN_MESSAGING_MESSAGE_FOLDER_H__
diff --git a/src/messaging/old/MessageMMS.cpp b/src/messaging/old/MessageMMS.cpp
new file mode 100644 (file)
index 0000000..c6dfa13
--- /dev/null
@@ -0,0 +1,89 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageMMS.cpp
+ */
+
+#include <PlatformException.h>
+#include <Logger.h>
+#include "MessageMMS.h"
+#include <GlobalContextManager.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageMMS::MessageMMS():
+    Message()
+{
+    LOGD("MessageMMS constructor.");
+    this->m_type = MessageType(MessageType(MMS));
+}
+
+MessageMMS::~MessageMMS()
+{
+    LOGD("MessageMMS destructor.");
+}
+
+// *** overrided methods
+void MessageMMS::setCC(std::vector<std::string> &cc)
+{
+    // CC recipient's format validation should be done by email service
+    m_cc = cc;
+
+    if(m_cc.empty()) {
+        LOGD("Recipient's list cleared");
+        return;
+    }
+}
+
+void MessageMMS::setBCC(std::vector<std::string> &bcc)
+{
+    // BCC recipient's format validation should be done by email service
+    m_bcc = bcc;
+
+    if(m_bcc.empty()) {
+        LOGD("Recipient's list cleared");
+        return;
+    }
+}
+
+void MessageMMS::setSubject(std::string subject)
+{
+    m_subject = subject;
+}
+
+void MessageMMS::setMessageAttachments(AttachmentPtrVector &attachments)
+{
+    m_attachments = attachments;
+
+    m_has_attachment = true;
+    if(m_attachments.empty()) {
+        LOGD("Recipient's list cleared");
+        m_has_attachment = false;
+    }
+}
+
+bool MessageMMS::getHasAttachment() const
+{
+    LOGD("MessageMMS::getHasAttachment()");
+    // TODO: Analyze relation between hasAttachment flag and inlineAttachments
+    return m_has_attachment;
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessageMMS.h b/src/messaging/old/MessageMMS.h
new file mode 100644 (file)
index 0000000..799f309
--- /dev/null
@@ -0,0 +1,52 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageMMS.h
+ */
+
+#ifndef __TIZEN_MESSAGE_MMS_H__
+#define __TIZEN_MESSAGE_MMS_H__
+
+// Header with core msg-service declarations
+#include <msg.h>
+
+#include "Message.h"
+#include "MessageAttachment.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageMMS: public Message {
+public:
+// constructor
+    MessageMMS();
+    ~MessageMMS();
+
+//overrided base class functions
+    void setCC(std::vector<std::string> &cc);
+    void setBCC(std::vector<std::string> &bcc);
+    void setSubject(std::string subject);
+    void setMessageAttachments(AttachmentPtrVector &attachments);
+
+    bool getHasAttachment() const;
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_MMS_H__
diff --git a/src/messaging/old/MessageSMS.cpp b/src/messaging/old/MessageSMS.cpp
new file mode 100644 (file)
index 0000000..4204035
--- /dev/null
@@ -0,0 +1,43 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageSMS.cpp
+ */
+
+#include <iterator>
+#include <PlatformException.h>
+#include <Logger.h>
+#include "MessageSMS.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageSMS::MessageSMS():
+    Message()
+{
+    LOGD("MessageSMS constructor.");
+    this->m_type = MessageType(MessageType(SMS));
+}
+
+MessageSMS::~MessageSMS()
+{
+    LOGD("MessageSMS destructor.");
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessageSMS.h b/src/messaging/old/MessageSMS.h
new file mode 100644 (file)
index 0000000..e2afcc0
--- /dev/null
@@ -0,0 +1,44 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessageSMS.h
+ */
+
+#ifndef __TIZEN_MESSAGE_SMS_H__
+#define __TIZEN_MESSAGE_SMS_H__
+
+// Header with core msg-service declarations
+#include <msg.h>
+
+#include "Message.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageSMS: public Message {
+public:
+// constructor
+    MessageSMS();
+    ~MessageSMS();
+
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MESSAGE_SMS_H__
diff --git a/src/messaging/old/MessageService.cpp b/src/messaging/old/MessageService.cpp
new file mode 100644 (file)
index 0000000..00c5460
--- /dev/null
@@ -0,0 +1,442 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+
+#include "MessageService.h"
+#include "MessageStorageShortMsg.h"
+#include "MessageStorageEmail.h"
+
+using namespace std;
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+//#################### MessageRecipientsCallbackData ####################
+
+MessageRecipientsCallbackData::MessageRecipientsCallbackData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_is_error(false),
+        m_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN),
+        m_default_sim_index(TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN)
+{
+    LOGD("Entered");
+}
+
+MessageRecipientsCallbackData::~MessageRecipientsCallbackData()
+{
+    LOGD("Entered");
+}
+
+void MessageRecipientsCallbackData::setMessage(std::shared_ptr<Message> message)
+{
+    m_message = message;
+}
+
+std::shared_ptr<Message> MessageRecipientsCallbackData::getMessage() const
+{
+    return m_message;
+}
+
+void MessageRecipientsCallbackData::setMessageRecipients(
+        const std::vector<std::string>& msgRecipients)
+{
+    m_msg_recipients = msgRecipients;
+}
+
+const std::vector<std::string>& MessageRecipientsCallbackData::getMessageRecipients() const
+{
+    return m_msg_recipients;
+}
+
+void MessageRecipientsCallbackData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+        if (m_message) {
+            m_err_message += " for: ";
+            // platform issue: we cannot get error per recipient
+            // so all recipients are added to error message
+            std::vector<std::string> recp_list = m_message->getTO();
+            unsigned int count = recp_list.size();
+            for (unsigned int i = 0; i < count; ++i) {
+                m_err_message += recp_list.at(i) + ", ";
+            }
+            recp_list = m_message->getCC();
+            count = recp_list.size();
+            for (unsigned int i = 0; i < count; ++i) {
+                m_err_message += recp_list.at(i) + ", ";
+            }
+            recp_list = m_message->getBCC();
+            count = recp_list.size();
+            for (unsigned int i = 0; i < count; ++i) {
+                m_err_message += recp_list.at(i) + ", ";
+            }
+
+        }
+    }
+}
+
+bool MessageRecipientsCallbackData::isError() const
+{
+    return m_is_error;
+}
+
+std::string MessageRecipientsCallbackData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string MessageRecipientsCallbackData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void MessageRecipientsCallbackData::setAccountId(int account_id){
+    m_account_id = account_id;
+}
+
+int MessageRecipientsCallbackData::getAccountId() const
+{
+    return m_account_id;
+}
+
+void MessageRecipientsCallbackData::setSimIndex(
+    TelNetworkDefaultDataSubs_t sim_index)
+{
+    m_sim_index = sim_index;
+}
+
+TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getSimIndex() const
+{
+    return m_sim_index;
+}
+
+bool MessageRecipientsCallbackData::isSetSimIndex() const
+{
+    return m_sim_index != TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN;
+}
+
+void MessageRecipientsCallbackData::setDefaultSimIndex(
+    TelNetworkDefaultDataSubs_t sim_index)
+{
+    m_default_sim_index = sim_index;
+}
+
+TelNetworkDefaultDataSubs_t MessageRecipientsCallbackData::getDefaultSimIndex() const
+{
+    return m_default_sim_index;
+}
+
+//#################### BaseMessageServiceCallbackData ####################
+
+BaseMessageServiceCallbackData::BaseMessageServiceCallbackData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_is_error(false),
+        m_op_handle(-1)
+{
+    LOGD("Entered");
+}
+
+BaseMessageServiceCallbackData::~BaseMessageServiceCallbackData()
+{
+    LOGD("Entered");
+}
+
+void BaseMessageServiceCallbackData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool BaseMessageServiceCallbackData::isError() const
+{
+    return m_is_error;
+}
+
+std::string BaseMessageServiceCallbackData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string BaseMessageServiceCallbackData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void BaseMessageServiceCallbackData::setOperationHandle(const int op_handle)
+{
+    m_op_handle = op_handle;
+}
+
+int BaseMessageServiceCallbackData::getOperationHandle() const
+{
+    return m_op_handle;
+}
+
+//#################### MessageBodyCallbackData ####################
+
+MessageBodyCallbackData::MessageBodyCallbackData(JSContextRef globalCtx):
+        BaseMessageServiceCallbackData(globalCtx)
+{
+    LOGD("Entered");
+}
+
+MessageBodyCallbackData::~MessageBodyCallbackData()
+{
+    LOGD("Entered");
+}
+
+void MessageBodyCallbackData::setMessage(std::shared_ptr<Message> message)
+{
+    m_message = message;
+}
+
+std::shared_ptr<Message> MessageBodyCallbackData::getMessage() const
+{
+    return m_message;
+}
+
+//#################### MessageAttachmentCallbackData ####################
+
+MessageAttachmentCallbackData::MessageAttachmentCallbackData(JSContextRef globalCtx):
+        BaseMessageServiceCallbackData(globalCtx),
+        m_nth(0)
+{
+    LOGD("Entered");
+}
+
+
+MessageAttachmentCallbackData::~MessageAttachmentCallbackData()
+{
+    LOGD("Entered");
+}
+
+void MessageAttachmentCallbackData::setMessageAttachment(
+        std::shared_ptr<MessageAttachment> messageAttachment)
+{
+    m_message_attachment = messageAttachment;
+}
+
+std::shared_ptr<MessageAttachment> MessageAttachmentCallbackData::
+    getMessageAttachment() const
+{
+    return m_message_attachment;
+}
+
+void MessageAttachmentCallbackData::setNth(const int nth)
+{
+    m_nth = nth;
+}
+
+int MessageAttachmentCallbackData::getNth() const
+{
+    return m_nth;
+}
+
+//#################### SyncCallbackData ####################
+
+SyncCallbackData::SyncCallbackData(JSContextRef globalCtx):
+        BaseMessageServiceCallbackData(globalCtx),
+        m_is_limit(false),
+        m_limit(0),
+        m_account_id(-1)
+{
+    LOGD("Entered");
+}
+
+SyncCallbackData::~SyncCallbackData()
+{
+    LOGD("Entered");
+}
+
+void SyncCallbackData::setLimit(const unsigned long limit)
+{
+    m_is_limit = true;
+    m_limit = limit;
+}
+
+bool SyncCallbackData::isLimit() const
+{
+    return m_is_limit;
+}
+
+unsigned long SyncCallbackData::getLimit() const
+{
+    return m_limit;
+}
+
+void SyncCallbackData::setOpId(long op_id)
+{
+    m_op_id = op_id;
+}
+
+long SyncCallbackData::getOpId()
+{
+    return m_op_id;
+}
+
+void SyncCallbackData::setAccountId(int account_id)
+{
+    m_account_id = account_id;
+}
+
+int SyncCallbackData::getAccountId() const
+{
+    return m_account_id;
+}
+
+//#################### SyncFolderCallbackData ####################
+
+SyncFolderCallbackData::SyncFolderCallbackData(JSContextRef globalCtx):
+        SyncCallbackData(globalCtx)
+{
+    LOGD("Entered");
+}
+
+SyncFolderCallbackData::~SyncFolderCallbackData()
+{
+    LOGD("Entered");
+}
+
+void SyncFolderCallbackData::setMessageFolder(
+        std::shared_ptr<MessageFolder> message_folder)
+{
+    m_message_folder = message_folder;
+}
+
+std::shared_ptr<MessageFolder> SyncFolderCallbackData::getMessageFolder() const
+{
+    return m_message_folder;
+}
+
+//#################### MessageService ####################
+
+MessageService::MessageService(int id,
+                    MessageType msgType,
+                    string name):
+        SecurityAccessor(),
+        m_id(id),
+        m_msg_type(msgType),
+        m_name(name)
+{
+    LOGD("Entered");
+    switch (msgType) {
+        case MessageType::SMS:
+        case MessageType::MMS:
+            m_storage.reset(new MessageStorageShortMsg(id, msgType));
+            break;
+        case MessageType::EMAIL:
+            m_storage.reset(new MessageStorageEmail(id));
+            break;
+        default:
+            LOGE("Undefined message type");
+            throw InvalidValuesException("Undefined message type");
+    }
+}
+
+MessageService::~MessageService()
+{
+    LOGD("Entered");
+}
+
+int MessageService::getMsgServiceId() const
+{
+    return m_id;
+}
+
+string MessageService::getMsgServiceIdStr() const
+{
+    return to_string(m_id);
+}
+
+MessageType MessageService::getMsgServiceType() const
+{
+    return m_msg_type;
+}
+
+std::string MessageService::getMsgServiceName() const
+{
+    return m_name;
+}
+
+std::shared_ptr<MessageStorage> MessageService::getMsgStorage() const
+{
+    return m_storage;
+}
+
+void MessageService::sendMessage(MessageRecipientsCallbackData *callback)
+{
+    // this method should be overwritten be specific services
+    LOGE("Cannot send message");
+    throw NotSupportedException("Cannot send message");
+}
+
+void MessageService::loadMessageBody(MessageBodyCallbackData *callback)
+{
+    // this method should be overwritten by specific services
+    LOGE("Cannot load message body");
+    throw NotSupportedException("Cannot load message body");
+}
+
+void MessageService::loadMessageAttachment(MessageAttachmentCallbackData *callback)
+{
+    // this method should be overwritten by email service
+    // for MMS and SMS this function is not supported
+    LOGE("Cannot load message attachment");
+    throw NotSupportedException("Cannot load message attachment");
+}
+
+long MessageService::sync(SyncCallbackData *callback)
+{
+    // this method should be overwritten by email service
+    // for MMS and SMS this function is not supported
+    LOGE("Cannot sync with external server");
+    throw NotSupportedException("Cannot sync with external server");
+}
+
+long MessageService::syncFolder(SyncFolderCallbackData *callback)
+{
+    // this method should be overwritten by email service
+    // for MMS and SMS this function is not supported
+    LOGE("Cannot sync folder with external server");
+    throw NotSupportedException("Cannot sync folder with external server");
+}
+
+void MessageService::stopSync(long op_id)
+{
+    // this method should be overwritten by email service
+    // for MMS and SMS this function is not supported
+    LOGE("Cannot stop sync with external server");
+    throw NotSupportedException("Cannot stop sync with external server");
+}
+
+} // Messaging
+} // DeviceAPI
+
diff --git a/src/messaging/old/MessageService.h b/src/messaging/old/MessageService.h
new file mode 100755 (executable)
index 0000000..e710792
--- /dev/null
@@ -0,0 +1,229 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_SERVICE_H__
+#define __TIZEN_MESSAGE_SERVICE_H__
+
+#include <msg.h>
+#include <msg_transport.h>
+#include <msg_storage.h>
+#include <memory>
+#include <ITapiNetwork.h>
+
+#include <CallbackUserData.h>
+#include <PlatformException.h>
+#include <Security.h>
+
+#include "MessagingUtil.h"
+#include "Message.h"
+#include "MessageStorage.h"
+#include "MessageFolder.h"
+
+#include "DBus/Connection.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+enum MessageServiceAccountId
+{
+    UNKNOWN_ACCOUNT_ID = 0,
+    SMS_ACCOUNT_ID = 101,
+    MMS_ACCOUNT_ID = 102
+};
+
+class MessageRecipientsCallbackData : public Common::CallbackUserData {
+public:
+    MessageRecipientsCallbackData(JSContextRef globalCtx);
+    virtual ~MessageRecipientsCallbackData();
+
+    void setMessage(std::shared_ptr<Message> message);
+    std::shared_ptr<Message> getMessage() const;
+
+    void setMessageRecipients(const std::vector<std::string>& msgRecipients);
+    const std::vector<std::string>& getMessageRecipients() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void setAccountId(int account_id);
+    int getAccountId() const;
+
+    void setSimIndex(TelNetworkDefaultDataSubs_t sim_index);
+    TelNetworkDefaultDataSubs_t getSimIndex() const;
+    void setDefaultSimIndex(TelNetworkDefaultDataSubs_t sim_index);
+    TelNetworkDefaultDataSubs_t getDefaultSimIndex() const;
+    bool isSetSimIndex() const;
+
+private:
+    std::shared_ptr<Message> m_message;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    std::vector<std::string> m_msg_recipients;
+    int m_account_id;
+    TelNetworkDefaultDataSubs_t m_sim_index;
+    TelNetworkDefaultDataSubs_t m_default_sim_index;
+};
+
+
+class BaseMessageServiceCallbackData : public Common::CallbackUserData {
+public:
+    BaseMessageServiceCallbackData(JSContextRef globalCtx);
+    virtual ~BaseMessageServiceCallbackData();
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    /**
+     * This handle is returned from various native API functions:
+     *   int email_sync_header(..., int *handle);
+     *   int email_download_body(..., int *handle);
+     *   int email_download_attachment(..., int *handle);
+     *
+     * It is used to stop and identify request.
+     */
+    void setOperationHandle(const int op_handle);
+    int getOperationHandle() const;
+
+protected:
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+
+    int m_op_handle;
+};
+
+class MessageBodyCallbackData : public BaseMessageServiceCallbackData {
+public:
+    MessageBodyCallbackData(JSContextRef globalCtx);
+    virtual ~MessageBodyCallbackData();
+
+    void setMessage(std::shared_ptr<Message> message);
+    std::shared_ptr<Message> getMessage() const;
+
+private:
+    std::shared_ptr<Message> m_message;
+};
+
+class MessageAttachmentCallbackData : public BaseMessageServiceCallbackData {
+public:
+    MessageAttachmentCallbackData(JSContextRef globalCtx);
+    virtual ~MessageAttachmentCallbackData();
+
+    void setMessageAttachment(std::shared_ptr<MessageAttachment> messageAttachment);
+    std::shared_ptr<MessageAttachment> getMessageAttachment() const;
+
+    /**
+     * nth is used in native api call:
+     * int email_download_attachment(int mail_id, int nth, int *handle);
+     *
+     * nth is equal to attachment index+1 (starts from 1 not 0) see
+     * email-api-network.h for details.
+     * */
+    void setNth(const int nth);
+    int getNth() const;
+
+private:
+    std::shared_ptr<MessageAttachment> m_message_attachment;
+    int m_nth;
+};
+
+class SyncCallbackData : public BaseMessageServiceCallbackData {
+public:
+    SyncCallbackData(JSContextRef globalCtx);
+    virtual ~SyncCallbackData();
+
+    void setLimit(const unsigned long limit);
+    bool isLimit() const;
+    unsigned long getLimit() const;
+
+    void setOpId(long op_id);
+    long getOpId();
+    void setAccountId(int account_id);
+    int getAccountId() const;
+
+protected:
+    bool m_is_limit;
+    unsigned long m_limit;
+
+    long m_op_id;
+    int m_account_id;
+};
+
+class SyncFolderCallbackData : public SyncCallbackData {
+public:
+    SyncFolderCallbackData(JSContextRef globalCtx);
+    virtual ~SyncFolderCallbackData();
+
+    void setMessageFolder(std::shared_ptr<MessageFolder> message_folder);
+    std::shared_ptr<MessageFolder> getMessageFolder() const;
+
+private:
+    std::shared_ptr<MessageFolder> m_message_folder;
+};
+
+
+class MessageService : public Common::SecurityAccessor
+{
+public:
+    virtual ~MessageService();
+
+    virtual int getMsgServiceId() const;
+    virtual std::string getMsgServiceIdStr() const;
+    virtual MessageType getMsgServiceType() const;
+    virtual std::string getMsgServiceName() const;
+    virtual std::shared_ptr<MessageStorage> getMsgStorage() const;
+
+    virtual void sendMessage(MessageRecipientsCallbackData *callback);
+    virtual void loadMessageBody(MessageBodyCallbackData *callback);
+    virtual void loadMessageAttachment(MessageAttachmentCallbackData *callback);
+    virtual long sync(SyncCallbackData *callback);
+
+    /**
+     * @param callback - owned by this method unless exception is thrown
+     * @return opId - "long Identifier which can be used to stop this service operation"
+     *                (form JS documentation)
+     *
+     */
+    virtual long syncFolder(SyncFolderCallbackData *callback);
+
+    virtual void stopSync(long op_id);
+
+protected:
+    /**
+     * We have child classes MessageServiceEmail and MessageServiceShortMsg which
+     * should provide specialized implementation.
+     */
+    MessageService(int id,
+            MessageType msgType,
+            std::string name);
+
+    int m_id;
+    MessageType m_msg_type;
+    std::string m_name;
+    std::shared_ptr<MessageStorage> m_storage;
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_MESSAGE_SERVICE_H__
diff --git a/src/messaging/old/MessageServiceEmail.cpp b/src/messaging/old/MessageServiceEmail.cpp
new file mode 100644 (file)
index 0000000..ca45652
--- /dev/null
@@ -0,0 +1,288 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+#include <PlatformException.h>
+
+#include "MessageServiceEmail.h"
+#include "EmailManager.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageServiceEmail::MessageServiceEmail(int id, std::string name)
+        : MessageService(id,
+                MessageType::EMAIL,
+                name)
+{
+    LOGD("Entered");
+}
+
+MessageServiceEmail::~MessageServiceEmail()
+{
+    LOGD("Entered");
+}
+
+static gboolean sendMessageTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        EmailManager::getInstance().sendMessage(
+                static_cast<MessageRecipientsCallbackData*>(data));
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    return FALSE;
+}
+
+void MessageServiceEmail::sendMessage(MessageRecipientsCallbackData *callback)
+{
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    if (m_msg_type != callback->getMessage()->getType()) {
+
+        LOGE("Incorrect message type");
+        throw Common::TypeMismatchException("Incorrect message type");
+    }
+
+    callback->setAccountId(m_id);
+
+    guint id = g_idle_add(sendMessageTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add fails");
+        delete callback;
+        throw Common::UnknownException("Could not add task");
+    }
+}
+
+static gboolean loadMessageBodyTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        EmailManager::getInstance().loadMessageBody(
+                static_cast<MessageBodyCallbackData*>(data));
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    return FALSE;
+}
+
+void MessageServiceEmail::loadMessageBody(MessageBodyCallbackData *callback)
+{
+    LOGD("Entered");
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    guint id = g_idle_add(loadMessageBodyTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        throw Common::UnknownException("Could not add task");
+    }
+}
+
+static gboolean loadMessageAttachmentTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        MessageAttachmentCallbackData *callback =
+                static_cast<MessageAttachmentCallbackData *>(data);
+        if (!callback) {
+            LOGE("Callback is null");
+            throw Common::UnknownException("Callback is null");
+        }
+
+        std::shared_ptr<MessageAttachment> att =  callback->getMessageAttachment();
+
+        // if the attachment is already saved, then it doesn't need to load again.
+        if (att->isFilePathSet() && att->isSaved()){
+            JSContextRef context = callback->getContext();
+            JSObjectRef jsMessageAtt = JSMessageAttachment::makeJSObject(context, att);
+            callback->callSuccessCallback(jsMessageAtt);
+
+            delete callback;
+            callback = NULL;
+            return FALSE;
+        }
+
+        EmailManager::getInstance().loadMessageAttachment(
+                static_cast<MessageAttachmentCallbackData*>(data));
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+                (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+    return FALSE;
+}
+
+void MessageServiceEmail::loadMessageAttachment(MessageAttachmentCallbackData *callback)
+{
+    LOGD("Entered");
+    guint id = g_idle_add(loadMessageAttachmentTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        throw Common::UnknownException("Could not add task");
+    }
+}
+
+static gboolean syncTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        EmailManager::getInstance().sync(data);
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    return FALSE;
+}
+
+long MessageServiceEmail::sync(SyncCallbackData *callback)
+{
+    LOGD("Entered");
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    long op_id = EmailManager::getInstance().getUniqueOpId();
+    callback->setOpId(op_id);
+    callback->setAccountId(m_id);
+
+    guint id = g_idle_add(syncTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        throw Common::UnknownException("Could not add task");
+    }
+    return op_id;
+}
+
+static gboolean syncFolderTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        EmailManager::getInstance().syncFolder(
+                static_cast<SyncFolderCallbackData*>(data));
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    return FALSE;
+}
+
+long MessageServiceEmail::syncFolder(SyncFolderCallbackData *callback)
+{
+    LOGD("Entered");
+    if(!callback){
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    if(!callback->getMessageFolder()) {
+        LOGE("Message folder is null");
+        throw Common::TypeMismatchException("Message folder is null");
+    }
+
+    long op_id = EmailManager::getInstance().getUniqueOpId();
+    callback->setOpId(op_id);
+    callback->setAccountId(m_id);
+
+    guint id = g_idle_add(syncFolderTask, callback);
+    if (!id) {
+        LOGE("g_idle_add fails");
+        delete callback;
+    }
+
+    return op_id;
+}
+
+static gboolean stopSyncTask(void* data)
+{
+    LOGD("Entered");
+
+    try {
+        if (!data) {
+            LOGE("opId is null");
+            return FALSE;
+        }
+
+        const long op_id = *(static_cast<long*>(data));
+        delete static_cast<long*>(data);
+        data = NULL;
+        EmailManager::getInstance().stopSync(op_id);
+
+    } catch(const Common::BasePlatformException& exception) {
+        LOGE("Unhandled exception: %s (%s)!", (exception.getName()).c_str(),
+             (exception.getMessage()).c_str());
+    } catch(...) {
+        LOGE("Unhandled exception!");
+    }
+
+    return FALSE;
+}
+
+void MessageServiceEmail::stopSync(long data)
+{
+    LOGD("Entered");
+    long* op_id = new long();
+    *op_id = data;
+    guint id = g_idle_add(stopSyncTask, static_cast<void*>(op_id));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete op_id;
+        op_id = NULL;
+        throw Common::UnknownException("Could not add task");
+    }
+}
+
+
+} // Messaging
+} // DeviceAPI
+
diff --git a/src/messaging/old/MessageServiceEmail.h b/src/messaging/old/MessageServiceEmail.h
new file mode 100755 (executable)
index 0000000..f8dfd9b
--- /dev/null
@@ -0,0 +1,50 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_SERVICE_EMAIL_H__
+#define __TIZEN_MESSAGE_SERVICE_EMAIL_H__
+
+#include "MessageService.h"
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageServiceEmail : public MessageService {
+public:
+    MessageServiceEmail(int id, std::string name);
+    virtual ~MessageServiceEmail();
+
+    virtual void sendMessage(MessageRecipientsCallbackData *callback);
+    virtual void loadMessageBody(MessageBodyCallbackData *callback);
+    virtual void loadMessageAttachment(MessageAttachmentCallbackData *callback);
+    virtual long sync(SyncCallbackData *callback);
+
+   /**
+     * @param callback - owned by this method unless exception is thrown
+     * @return opId - "long Identifier which can be used to stop this service operation"
+     *                (form JS documentation)
+     *
+     */
+    virtual long syncFolder(SyncFolderCallbackData *callback);
+
+    virtual void stopSync(long op_id);
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_MESSAGE_SERVICE_EMAIL_H__
diff --git a/src/messaging/old/MessageServiceShortMsg.cpp b/src/messaging/old/MessageServiceShortMsg.cpp
new file mode 100755 (executable)
index 0000000..dcf3a00
--- /dev/null
@@ -0,0 +1,166 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+#include <tapi_common.h>
+#include <ITapiSim.h>
+#include <ITapiNetwork.h>
+#include "MessageServiceShortMsg.h"
+#include "ShortMsgManager.h"
+#include "JSMessage.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageServiceShortMsg::MessageServiceShortMsg(int id, MessageType msgType)
+        : MessageService(id,
+                msgType,
+                MessagingUtil::messageTypeToString(msgType))
+{
+    LOGD("Entered");
+}
+
+MessageServiceShortMsg::~MessageServiceShortMsg()
+{
+    LOGD("Entered");
+}
+
+static gboolean sendMessageThread(void* data)
+{
+    LOGD("Entered");
+
+    auto callback = static_cast<MessageRecipientsCallbackData *>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    ShortMsgManager::getInstance().sendMessage(callback);
+    return FALSE;
+}
+
+void MessageServiceShortMsg::sendMessage(MessageRecipientsCallbackData *callback)
+{
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    if (m_msg_type != callback->getMessage()->getType()) {
+        LOGE("Incorrect message type");
+        throw Common::TypeMismatchException("Incorrect message type");
+    }
+
+    /*
+     * Set sim index.
+     * If user has set sim index manually, check sim index is valid.
+     * Otherwise, use default sim which is already set.
+     */
+    TelNetworkDefaultDataSubs_t default_sim =
+        TAPI_NETWORK_DEFAULT_DATA_SUBS_UNKNOWN;
+    TapiHandle *handle = tel_init(NULL);
+
+    int ret = tel_get_network_default_data_subscription(handle, &default_sim);
+    if (ret != TAPI_API_SUCCESS) {
+        LOGE("Failed to find default sim index %d", ret);
+    }
+
+    LOGD("Default sim index: %d", default_sim);
+    callback->setDefaultSimIndex(default_sim);
+    tel_deinit(handle);
+
+    // simIndex parameter is only available for sms message.
+    // In case of mms, the parameter is silently ignored.
+    if (callback->isSetSimIndex() &&
+        callback->getMessage()->getType() == MessageType::SMS) {
+        char **cp_list = tel_get_cp_name_list();
+        TelNetworkDefaultDataSubs_t sim_index = callback->getSimIndex();
+        int sim_count = 0;
+
+        if (cp_list) {
+            while (cp_list[sim_count]) {
+                sim_count++;
+            }
+            g_strfreev(cp_list);
+        } else {
+            LOGD("Empty cp name list");
+        }
+
+        if (sim_index >= sim_count) {
+            LOGE("Sim index out of count %d : %d", sim_index, sim_count);
+            throw InvalidValuesException("The index of sim is out of bound");
+        }
+
+        callback->getMessage()->setSimIndex(sim_index);
+    } else {
+        callback->getMessage()->setSimIndex(default_sim);
+    }
+
+    if(!g_idle_add(sendMessageThread, static_cast<void*>(callback))) {
+        LOGE("g_idle_add fails");
+        throw UnknownException("Could not add task");
+    }
+}
+
+static gboolean loadMessageBodyTask(void* data)
+{
+    LOGD("Entered");
+    MessageBodyCallbackData* callback = static_cast<MessageBodyCallbackData*>(data);
+    if(!callback) {
+        LOGE("callback is NULL");
+        return FALSE;
+    }
+
+    try {
+        JSContextRef context = callback->getContext();
+        JSObjectRef jsMessage = JSMessage::makeJSObject(context, callback->getMessage());
+        callback->callSuccessCallback(jsMessage);
+    } catch (...) {
+        LOGE("Couldn't create JSMessage object!");
+        callback->callErrorCallback();
+    }
+
+    return FALSE;
+}
+
+void MessageServiceShortMsg::loadMessageBody(MessageBodyCallbackData *callback)
+{
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    if (m_msg_type != callback->getMessage()->getType()) {
+        LOGE("Incorrect message type");
+        throw Common::TypeMismatchException("Incorrect message type");
+    }
+
+    guint id = g_idle_add(loadMessageBodyTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add fails");
+        throw Common::UnknownException("Could not add task");
+    }
+}
+
+} // Messaging
+} // DeviceAPI
+
diff --git a/src/messaging/old/MessageServiceShortMsg.h b/src/messaging/old/MessageServiceShortMsg.h
new file mode 100755 (executable)
index 0000000..54dd4e1
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
+#define __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
+
+#include "MessageService.h"
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageServiceShortMsg : public MessageService {
+public:
+    MessageServiceShortMsg(int id, MessageType msgType);
+    virtual ~MessageServiceShortMsg();
+
+    void sendMessage(MessageRecipientsCallbackData *callback);
+
+    virtual void loadMessageBody(MessageBodyCallbackData *callback);
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_MESSAGE_SERVICE_SHORT_MSG_H__
diff --git a/src/messaging/old/MessageStorage.cpp b/src/messaging/old/MessageStorage.cpp
new file mode 100644 (file)
index 0000000..10eb8b8
--- /dev/null
@@ -0,0 +1,77 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "MessageStorage.h"
+#include "ChangeListenerContainer.h"
+#include "MessagesChangeCallback.h"
+#include "ConversationsChangeCallback.h"
+#include "FoldersChangeCallback.h"
+#include <Logger.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageStorage::MessageStorage(int id, MessageType msgType):
+        SecurityAccessor(),
+        m_id(id),
+        m_msg_type(msgType)
+{
+    LOGD("Entered");
+}
+
+MessageStorage::~MessageStorage()
+{
+    LOGD("Entered");
+}
+
+int MessageStorage::getMsgServiceId() const {
+    return m_id;
+}
+
+MessageType MessageStorage::getMsgServiceType() const {
+    return m_msg_type;
+}
+
+long MessageStorage::addMessagesChangeListener(
+            std::shared_ptr<MessagesChangeCallback> callback)
+{
+    LOGD("Entered");
+    return ChangeListenerContainer::getInstance().addMessageChangeListener(callback);
+}
+
+long MessageStorage::addConversationsChangeListener(
+            std::shared_ptr<ConversationsChangeCallback> callback)
+{
+    LOGD("Entered");
+    return ChangeListenerContainer::getInstance().addConversationChangeListener(callback);
+}
+
+long MessageStorage::addFoldersChangeListener(
+            std::shared_ptr<FoldersChangeCallback> callback)
+{
+    LOGD("Entered");
+    return ChangeListenerContainer::getInstance().addFolderChangeListener(callback);
+}
+
+void MessageStorage::removeChangeListener(JSContextRef context, long watchId)
+{
+    LOGD("Entered");
+    return ChangeListenerContainer::getInstance().removeChangeListener(context, watchId);
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/MessageStorage.h b/src/messaging/old/MessageStorage.h
new file mode 100644 (file)
index 0000000..82dbc19
--- /dev/null
@@ -0,0 +1,79 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_STORAGE_H
+#define __TIZEN_MESSAGE_STORAGE_H
+
+#include "MessageCallbackUserData.h"
+#include "MessagesCallbackUserData.h"
+#include "FindMsgCallbackUserData.h"
+#include "ConversationCallbackData.h"
+#include "FoldersCallbackData.h"
+#include "MessagingUtil.h"
+#include <memory>
+// headers for ChangeListeners support
+#include "MessagesChangeCallback.h"
+#include "FoldersChangeCallback.h"
+#include "ConversationsChangeCallback.h"
+#include <Security.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessagesChangeCallback;
+
+class MessageStorage : public Common::SecurityAccessor
+{
+public:
+    MessageStorage(int id, MessageType msgType);
+    virtual ~MessageStorage();
+
+    virtual int getMsgServiceId() const;
+    virtual MessageType getMsgServiceType() const;
+
+    virtual void addDraftMessage(MessageCallbackUserData* callback) = 0;
+    virtual void removeMessages(MessagesCallbackUserData* callback) = 0;
+    virtual void updateMessages(MessagesCallbackUserData* callback) = 0;
+    virtual void findMessages(FindMsgCallbackUserData* callback) = 0;
+    virtual void findConversations(ConversationCallbackData* callback) = 0;
+    virtual void removeConversations(ConversationCallbackData* callback) = 0;
+    virtual void findFolders(FoldersCallbackData* callback) = 0;
+
+    // Listeners registration/removal is common for all types of storage
+    // and does not have to be overwritten in derived classes.
+    long addMessagesChangeListener(
+            std::shared_ptr<MessagesChangeCallback> callback);
+    long addConversationsChangeListener(
+            std::shared_ptr<ConversationsChangeCallback> callback);
+    long addFoldersChangeListener(
+            std::shared_ptr<FoldersChangeCallback> callback);
+    void removeChangeListener(JSContextRef context, long watchId);
+
+protected:
+    int m_id;
+    MessageType m_msg_type;
+};
+
+struct MessageStorageHolder {
+    std::shared_ptr<MessageStorage> ptr;
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_MESSAGE_STORAGE_H */
+
diff --git a/src/messaging/old/MessageStorageEmail.cpp b/src/messaging/old/MessageStorageEmail.cpp
new file mode 100644 (file)
index 0000000..c906eb3
--- /dev/null
@@ -0,0 +1,267 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "MessageStorageEmail.h"
+#include "EmailManager.h"
+#include "Message.h"
+
+#include <Logger.h>
+#include <PlatformException.h>
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageStorageEmail::MessageStorageEmail(int id):
+        MessageStorage(id, MessageType::EMAIL) {
+    LOGD("Entered");
+}
+
+MessageStorageEmail::~MessageStorageEmail() {
+    LOGD("Entered");
+}
+
+static gboolean callError(void* data)
+{
+    LOGD("Entered");
+    MessageCallbackUserData* callback =
+           static_cast<MessageCallbackUserData*>(data);
+    if (!callback) {
+       LOGE("Callback is null");
+       return FALSE;
+    }
+    JSContextRef context = callback->getContext();
+    JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+            callback->getErrorName(), callback->getErrorMessage());
+    callback->callErrorCallback(errobj);
+
+    return FALSE;
+}
+
+static gboolean addDraftMessageTask(void* data)
+{
+    LOGD("Entered");
+
+    MessageCallbackUserData *callback = static_cast<MessageCallbackUserData*>(data);
+    EmailManager::getInstance().addDraftMessage(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::addDraftMessage(MessageCallbackUserData* callback) {
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    if (m_msg_type != callback->getMessage()->getType()) {
+       LOGE("Incorrect message type");
+       callback->setError(JSWebAPIErrorFactory::INVALID_VALUES_ERROR,
+               "Incorrect message type");
+       guint id = g_idle_add(callError, static_cast<void*>(callback));
+       if (!id) {
+           LOGE("g_idle_add failed");
+           delete callback;
+           callback = NULL;
+       }
+       return;
+    }
+
+    callback->setAccountId(m_id);
+
+    guint id = g_idle_add(addDraftMessageTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+static gboolean removeMessagesTask(void* data)
+{
+    LOGD("Entered");
+
+    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
+    EmailManager::getInstance().removeMessages(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::removeMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(removeMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+static gboolean updateMessagesTask(void* data)
+{
+    LOGD("Entered");
+
+    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
+    EmailManager::getInstance().updateMessages(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::updateMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+    guint id = g_idle_add(updateMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+static gboolean findMessagesTask(void* data)
+{
+    LOGD("Entered");
+
+    FindMsgCallbackUserData *callback = static_cast<FindMsgCallbackUserData*>(data);
+    EmailManager::getInstance().findMessages(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::findMessages(FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    callback->setAccountId(m_id);
+    callback->setMessageServiceType(m_msg_type);
+    guint id = g_idle_add(findMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+static gboolean findConversationsTask(void* data)
+{
+    LOGD("Entered");
+
+    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
+    EmailManager::getInstance().findConversations(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::findConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    callback->setAccountId(m_id);
+    callback->setMessageServiceType(m_msg_type);
+    guint id = g_idle_add(findConversationsTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+static gboolean removeConversationsTask(void* data)
+{
+    LOGD("Entered");
+
+    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
+    EmailManager::getInstance().removeConversations(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::removeConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+    guint id = g_idle_add(removeConversationsTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+static gboolean findFoldersTask(void* data)
+{
+    LOGD("Entered");
+
+    FoldersCallbackData *callback = static_cast<FoldersCallbackData*>(data);
+    EmailManager::getInstance().findFolders(callback);
+
+    return FALSE;
+}
+
+void MessageStorageEmail::findFolders(FoldersCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw Common::UnknownException("Callback is null");
+    }
+
+    guint id = g_idle_add(findFoldersTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/MessageStorageEmail.h b/src/messaging/old/MessageStorageEmail.h
new file mode 100644 (file)
index 0000000..49f1aac
--- /dev/null
@@ -0,0 +1,45 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_STORAGE_EMAIL_H
+#define __TIZEN_MESSAGE_STORAGE_EMAIL_H
+
+#include "MessageStorage.h"
+#include <JSWebAPIErrorFactory.h>
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageStorageEmail: public MessageStorage {
+public:
+    MessageStorageEmail(int id);
+    virtual ~MessageStorageEmail();
+
+    virtual void addDraftMessage(MessageCallbackUserData* callback);
+    virtual void removeMessages(MessagesCallbackUserData* callback);
+    virtual void updateMessages(MessagesCallbackUserData* callback);
+    virtual void findMessages(FindMsgCallbackUserData* callback);
+    virtual void findConversations(ConversationCallbackData* callback);
+    virtual void removeConversations(ConversationCallbackData* callback);
+    virtual void findFolders(FoldersCallbackData* callback);
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_MESSAGE_STORAGE_EMAIL_H */
+
diff --git a/src/messaging/old/MessageStorageShortMsg.cpp b/src/messaging/old/MessageStorageShortMsg.cpp
new file mode 100755 (executable)
index 0000000..da28f16
--- /dev/null
@@ -0,0 +1,272 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+#include "JSMessageFolder.h"
+#include <JSUtil.h>
+#include "MessageStorageShortMsg.h"
+#include "ShortMsgManager.h"
+#include <Logger.h>
+#include <PlatformException.h>
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageStorageShortMsg::MessageStorageShortMsg(int id, MessageType msgType):
+        MessageStorage(id, msgType) {
+    LOGD("Entered");
+}
+
+MessageStorageShortMsg::~MessageStorageShortMsg() {
+    LOGD("Entered");
+}
+
+static gboolean addDraftMessageTask(void* data) {
+    LOGD("Entered");
+
+    MessageCallbackUserData *callback = static_cast<MessageCallbackUserData*>(data);
+    ShortMsgManager::getInstance().addDraftMessage(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::addDraftMessage(MessageCallbackUserData* callback) {
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    if (m_msg_type != callback->getMessage()->getType()) {
+        LOGE("Incorrect message type");
+        throw TypeMismatchException("Incorrect message type");
+    }
+
+    guint id = g_idle_add(addDraftMessageTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean removeMessagesTask(void* data) {
+    LOGD("Entered");
+
+    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
+    ShortMsgManager::getInstance().removeMessages(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::removeMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(removeMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean updateMessagesTask(void* data) {
+    LOGD("Entered");
+
+    MessagesCallbackUserData *callback = static_cast<MessagesCallbackUserData*>(data);
+    ShortMsgManager::getInstance().updateMessages(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::updateMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(updateMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean findMessagesTask(void* data) {
+    LOGD("Entered");
+
+    FindMsgCallbackUserData *callback = static_cast<FindMsgCallbackUserData*>(data);
+    ShortMsgManager::getInstance().findMessages(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::findMessages(FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(findMessagesTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean findConversationsTask(void* data) {
+    LOGD("Entered");
+
+    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
+    ShortMsgManager::getInstance().findConversations(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::findConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(findConversationsTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean removeConversationsTask(void* data) {
+    LOGD("Entered");
+
+    ConversationCallbackData *callback = static_cast<ConversationCallbackData*>(data);
+    ShortMsgManager::getInstance().removeConversations(callback);
+
+    return false;
+}
+
+void MessageStorageShortMsg::removeConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback) {
+        LOGE("Callback is null");
+        throw UnknownException("Callback is null");
+    }
+
+    callback->setMessageServiceType(m_msg_type);
+
+    guint id = g_idle_add(removeConversationsTask, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        throw UnknownException("g_idle_add failed");
+    }
+}
+
+static gboolean findFoldersCB(void* data)
+{
+    LOGD("Entered");
+
+    FoldersCallbackData *callback = static_cast<FoldersCallbackData*>(data);
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return FALSE;
+    }
+
+    JSObjectRef js_obj = MessagingUtil::vectorToJSObjectArray<FolderPtr,
+                JSMessageFolder>(context, callback->getFolders());
+
+    callback->callSuccessCallback(js_obj);
+
+    delete callback;
+    callback = NULL;
+
+    return FALSE;
+}
+
+
+void MessageStorageShortMsg::findFolders(FoldersCallbackData* callback)
+{
+    LOGD("Entered");
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    std::string content_type = MessagingUtil::messageTypeToString(m_msg_type);
+    std::string empty = "";
+    std::shared_ptr<MessageFolder> folder;
+
+    /* For SMS and MMS, folderId can be one of these values:
+     *
+     *  INBOX = 1,
+     *  OUTBOX = 2,
+     *  DRAFTS = 3,
+     *  SENTBOX = 4
+     */
+
+    for(int i = 1;i < 5;i++)
+    {
+        folder = std::make_shared<MessageFolder>(
+                std::to_string(i),
+                empty,
+                std::to_string(m_id),
+                content_type,
+                MessagingUtil::messageFolderTypeToString((MessageFolderType)i),
+                empty,
+                (MessageFolderType)i,
+                false);
+
+        callback->addFolder(folder);
+    }
+
+    guint id = g_idle_add(findFoldersCB, static_cast<void*>(callback));
+    if (!id) {
+        LOGE("g_idle_add failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/MessageStorageShortMsg.h b/src/messaging/old/MessageStorageShortMsg.h
new file mode 100644 (file)
index 0000000..ac1d77f
--- /dev/null
@@ -0,0 +1,45 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGE_STORAGE_SMS_H
+#define __TIZEN_MESSAGE_STORAGE_SMS_H
+
+#include "MessageStorage.h"
+
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageStorageShortMsg: public MessageStorage {
+public:
+    MessageStorageShortMsg(int id, MessageType msgType);
+    virtual ~MessageStorageShortMsg();
+
+    virtual void addDraftMessage(MessageCallbackUserData* callback);
+    virtual void removeMessages(MessagesCallbackUserData* callback);
+    virtual void updateMessages(MessagesCallbackUserData* callback);
+    virtual void findMessages(FindMsgCallbackUserData* callback);
+    virtual void findConversations(ConversationCallbackData* callback);
+    virtual void removeConversations(ConversationCallbackData* callback);
+    virtual void findFolders(FoldersCallbackData* callback);
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_MESSAGE_STORAGE_SMS_H */
+
diff --git a/src/messaging/old/MessagesCallbackUserData.cpp b/src/messaging/old/MessagesCallbackUserData.cpp
new file mode 100644 (file)
index 0000000..1e436de
--- /dev/null
@@ -0,0 +1,98 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include "MessagesCallbackUserData.h"
+#include "JSMessage.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+
+MessagesCallbackUserData::MessagesCallbackUserData(JSContextRef globalCtx):
+        CallbackUserData(globalCtx),
+        m_is_error(false),
+        m_service_type(MessageType::UNDEFINED)
+{
+}
+
+MessagesCallbackUserData::~MessagesCallbackUserData() {
+}
+
+void MessagesCallbackUserData::addMessage(std::shared_ptr<Message> msg)
+{
+    m_messages.push_back(msg);
+}
+
+std::vector<std::shared_ptr<Message>> MessagesCallbackUserData::getMessages() const
+{
+    return m_messages;
+}
+
+void MessagesCallbackUserData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool MessagesCallbackUserData::isError() const
+{
+    return m_is_error;
+}
+
+std::string MessagesCallbackUserData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string MessagesCallbackUserData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void MessagesCallbackUserData::setMessageServiceType(MessageType m_msg_type)
+{
+    m_service_type = m_msg_type;
+}
+
+MessageType MessagesCallbackUserData::getMessageServiceType() const
+{
+    return m_service_type;
+}
+
+void MessagesCallbackUserData::addMessages(JSContextRef context,
+            const std::vector<JSValueRef>& jsobject_messages)
+{
+    const size_t new_messages_count = jsobject_messages.size();
+    if(0 == new_messages_count) {
+        return;
+    }
+
+    m_messages.reserve(m_messages.size() + new_messages_count);
+    for (auto it = jsobject_messages.begin() ; it != jsobject_messages.end(); ++it) {
+        m_messages.push_back(JSMessage::getPrivateObject(context, *it));
+    }
+}
+
+}//Messaging
+}//DeviceAPI
diff --git a/src/messaging/old/MessagesCallbackUserData.h b/src/messaging/old/MessagesCallbackUserData.h
new file mode 100644 (file)
index 0000000..39b7797
--- /dev/null
@@ -0,0 +1,63 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGES_CALLBACK_USER_DATA_H
+#define __TIZEN_MESSAGES_CALLBACK_USER_DATA_H
+
+#include <CallbackUserData.h>
+#include <memory>
+#include <vector>
+#include <string>
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+
+class MessagesCallbackUserData: public Common::CallbackUserData {
+public:
+    MessagesCallbackUserData(JSContextRef globalCtx);
+    virtual ~MessagesCallbackUserData();
+
+    void addMessages(JSContextRef context,
+            const std::vector<JSValueRef>& jsobject_messages);
+
+    void addMessage(std::shared_ptr<Message> msg);
+    std::vector<std::shared_ptr<Message>> getMessages() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void setMessageServiceType(MessageType m_msg_type);
+    MessageType getMessageServiceType() const;
+
+private:
+    std::vector<std::shared_ptr<Message>> m_messages;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    MessageType m_service_type;
+};
+
+}//Messaging
+}//DeviceAPI
+
+#endif /* __TIZEN_MESSAGES_CALLBACK_USER_DATA_H */
diff --git a/src/messaging/old/MessagesChangeCallback.cpp b/src/messaging/old/MessagesChangeCallback.cpp
new file mode 100644 (file)
index 0000000..b10c6bf
--- /dev/null
@@ -0,0 +1,234 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <PlatformException.h>
+#include <JSUtil.h>
+#include <Logger.h>
+
+#include "MessagesChangeCallback.h"
+#include "JSMessage.h"
+#include "AbstractFilter.h"
+#include "MessagingUtil.h"
+
+using namespace DeviceAPI::Common;
+using namespace DeviceAPI::Tizen;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+
+std::string limitedString(const std::string& src,
+                          const size_t max_len = 40)
+{
+    if(src.length() > max_len) {
+        return src.substr(0,max_len);
+    } else {
+        return src;
+    }
+}
+
+} //Anonymous namespace
+
+const char* MESSAGESADDED = "messagesadded";
+const char* MESSAGESUPDATED = "messagesupdated";
+const char* MESSAGESREMOVED = "messagesremoved";
+
+MessagesChangeCallback::MessagesChangeCallback(JSContextRef global_ctx,
+        JSObjectRef on_added_obj,
+        JSObjectRef on_updated_obj,
+        JSObjectRef on_removed_obj,
+        int service_id,
+        MessageType service_type) :
+        m_callback_data(global_ctx),
+        m_service_id(service_id),
+        m_msg_type(service_type),
+        m_is_act(true)
+{
+    LOGD("Entered");
+
+    m_callback_data.setCallback(MESSAGESADDED, on_added_obj);
+    m_callback_data.setCallback(MESSAGESUPDATED, on_updated_obj);
+    m_callback_data.setCallback(MESSAGESREMOVED, on_removed_obj);
+}
+
+MessagesChangeCallback::~MessagesChangeCallback()
+{
+    LOGD("Entered");
+}
+
+MessagePtrVector MessagesChangeCallback::filterMessages(
+        AbstractFilterPtr filter,
+        const MessagePtrVector& source_messages,
+        const int service_id)
+{
+    LOGD("Entered sourceMessages.size():%d filter:%s", source_messages.size(),
+            (filter ? "PRESENT" : "NULL"));
+
+    if (filter) {
+        MessagePtrVector filtered_messages;
+        MessagePtrVector::const_iterator it = source_messages.begin();
+        MessagePtrVector::const_iterator end_it = source_messages.end();
+
+        for(int i = 0; it != end_it ; ++i, ++it) {
+            const MessagePtr& message = *it;
+            message->setServiceId(service_id);
+
+            const bool matched = filter->isMatching(message.get());
+            if(matched) {
+                filtered_messages.push_back(message);
+            }
+
+            LOGD("[%d] is Message(%p) {", i, message.get());
+            LOGD("[%d] messageId: %d", i, message->getId());
+            LOGD("[%d] message subject: %s", i, message->getSubject().c_str());
+            LOGD("[%d] from: %s", i, message->getFrom().c_str());
+
+            if(message->getBody()) {
+                const std::string& pBody = message->getBody()->getPlainBody();
+                LOGD("[%d] message plainBody: %s", i, limitedString(pBody).c_str());
+            }
+
+            LOGD("[%d] matched filter: %s", i, matched ? "YES" : "NO");
+            LOGD("[%d] }");
+        }
+
+        LOGD("returning matching %d of %d messages", filtered_messages.size(),
+                source_messages.size());
+        return filtered_messages;
+    }
+    else {
+        return source_messages;
+    }
+}
+
+void MessagesChangeCallback::added(const MessagePtrVector& msgs)
+{
+    LOGD("Entered num messages: %d", msgs.size());
+    if (!m_is_act) {
+        return;
+    }
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
+    //cancel callback only if filter did remove all messages
+    //if callback was called with empty msgs list, call it
+    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
+        LOGD("All messages were filtered out, not calling callback");
+        return;
+    }
+    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
+            ctx, filtered_msgs);
+
+    LOGD("Calling:%s with:%d added messages", MESSAGESADDED,
+        filtered_msgs.size());
+    m_callback_data.invokeCallback(MESSAGESADDED, js_obj);
+}
+
+void MessagesChangeCallback::updated(const MessagePtrVector& msgs)
+{
+    LOGD("Entered num messages: %d", msgs.size());
+    if (!m_is_act) {
+        return;
+    }
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
+    //cancel callback only if filter did remove all messages
+    //if callback was called with empty msgs list, call it
+    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
+        LOGD("All messages were filtered out, not calling callback");
+        return;
+    }
+    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
+            ctx, filtered_msgs);
+
+    LOGD("Calling:%s with:%d updated messages", MESSAGESUPDATED,
+        filtered_msgs.size());
+    m_callback_data.invokeCallback(MESSAGESUPDATED, js_obj);
+}
+
+void MessagesChangeCallback::removed(const MessagePtrVector& msgs)
+{
+    LOGD("Enter event: msgs.size() = %d", msgs.size());
+    if (!m_is_act) {
+        return;
+    }
+
+    JSContextRef ctx = m_callback_data.getContext();
+    CHECK_CURRENT_CONTEXT_ALIVE(ctx)
+    MessagePtrVector filtered_msgs = filterMessages(m_filter, msgs, m_service_id);
+    //cancel callback only if filter did remove all messages
+    //if callback was called with empty msgs list, call it
+    if (msgs.size() > 0 && filtered_msgs.size() == 0) {
+        LOGD("All messages were filtered out, not calling callback");
+        return;
+    }
+    JSObjectRef js_obj = JSMessage::messageVectorToJSObjectArray(
+            ctx, filtered_msgs);
+
+    LOGD("Calling:%s with:%d removed messages", MESSAGESREMOVED,
+        filtered_msgs.size());
+    m_callback_data.invokeCallback(MESSAGESREMOVED, js_obj);
+}
+
+void MessagesChangeCallback::setFilter(AbstractFilterPtr filter)
+{
+    m_filter = filter;
+}
+
+AbstractFilterPtr MessagesChangeCallback::getFilter() const
+{
+    return m_filter;
+}
+
+int MessagesChangeCallback::getServiceId() const
+{
+    return m_service_id;
+}
+
+MessageType MessagesChangeCallback::getServiceType() const
+{
+    return m_msg_type;
+}
+
+void MessagesChangeCallback::setActive(bool act) {
+    m_is_act = act;
+}
+
+bool MessagesChangeCallback::isActive() {
+    return m_is_act;
+}
+
+void MessagesChangeCallback::setItems(MessagePtrVector& items)
+{
+    m_items = items;
+}
+MessagePtrVector MessagesChangeCallback::getItems()
+{
+    return m_items;
+}
+
+JSContextRef MessagesChangeCallback::getContext() const
+{
+    return m_callback_data.getContext();
+}
+
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessagesChangeCallback.h b/src/messaging/old/MessagesChangeCallback.h
new file mode 100644 (file)
index 0000000..6f5c571
--- /dev/null
@@ -0,0 +1,80 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
+#define __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
+
+#include <JavaScriptCore/JavaScript.h>
+
+#include <MultiCallbackUserData.h>
+
+#include <AbstractFilter.h>
+
+#include "Message.h"
+#include "MessagingUtil.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+extern const char* MESSAGESADDED;
+extern const char* MESSAGESUPDATED;
+extern const char* MESSAGESREMOVED;
+
+class MessagesChangeCallback {
+public:
+    MessagesChangeCallback(JSContextRef globalCtx,
+            JSObjectRef on_added_obj,
+            JSObjectRef on_updated_obj,
+            JSObjectRef on_removed_obj,
+            int service_id,
+            MessageType service_type);
+    virtual ~MessagesChangeCallback();
+
+    void added(const MessagePtrVector& messages);
+    void updated(const MessagePtrVector& messages);
+    void removed(const MessagePtrVector& messages);
+
+    void setFilter(DeviceAPI::Tizen::AbstractFilterPtr filter);
+    DeviceAPI::Tizen::AbstractFilterPtr getFilter() const;
+
+    int getServiceId() const;
+    MessageType getServiceType() const;
+    static MessagePtrVector filterMessages(
+            DeviceAPI::Tizen::AbstractFilterPtr a_filter,
+            const MessagePtrVector& a_sourceMessages,
+            const int service_id);
+
+    void setActive(bool act);
+    bool isActive();
+
+    void setItems(MessagePtrVector& items);
+    MessagePtrVector getItems();
+    JSContextRef getContext() const;
+private:
+    Common::MultiCallbackUserData m_callback_data;
+    DeviceAPI::Tizen::AbstractFilterPtr m_filter;
+    int m_service_id;
+    MessageType m_msg_type;
+    bool m_is_act;
+    MessagePtrVector m_items;
+};
+
+} // Messaging
+} // DeviceAPI
+
+
+#endif // __TIZEN_MESSAGES_CHANGE_CALLBACK_H__
diff --git a/src/messaging/old/MessagingDatabaseManager.cpp b/src/messaging/old/MessagingDatabaseManager.cpp
new file mode 100755 (executable)
index 0000000..17c1cb1
--- /dev/null
@@ -0,0 +1,872 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessagingDatabaseManager.cpp
+ */
+
+#include <sstream>
+#include <stdio.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include <msg_storage.h>
+#include <email-api.h>
+
+#include <Logger.h>
+
+#include "MessagingDatabaseManager.h"
+#include "MessagingManager.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+using namespace DeviceAPI::Common;
+using namespace DeviceAPI::Tizen;
+
+AttributeInfo::AttributeInfo() :
+        sql_name(),
+        sql_type(UNDEFINED_TYPE),
+        any_type(PrimitiveType_NoType)
+{
+}
+
+AttributeInfo::AttributeInfo(const std::string& in_sql_name,
+        const SQLAttributeType in_sql_type,
+        const Tizen::PrimitiveType in_any_type) :
+        sql_name(in_sql_name),
+        sql_type(in_sql_type),
+        any_type(in_any_type)
+{
+}
+
+AttributeInfo::AttributeInfo(const AttributeInfo& other) :
+        sql_name(other.sql_name),
+        sql_type(other.sql_type),
+        any_type(other.any_type)
+{
+}
+
+AttributeInfo& AttributeInfo::operator=(const AttributeInfo& other)
+{
+    sql_name = other.any_type;
+    sql_type = other.sql_type;
+    any_type = other.any_type;
+    return *this;
+}
+
+MessagingDatabaseManager::MessagingDatabaseManager()
+{
+// Attributes map for short messages ==========================================
+    m_msg_attr_map.insert(std::make_pair("id",
+            AttributeInfo("A.MSG_ID", INTEGER, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("serviceId",
+            AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("folderId",
+            AttributeInfo("A.FOLDER_ID", INTEGER, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("type",
+            AttributeInfo("A.MAIN_TYPE", INTEGER, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("timestamp",
+            AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time)));
+    m_msg_attr_map.insert(std::make_pair("from",
+            AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("to",
+            AttributeInfo("B.ADDRESS_VAL", TEXT, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("body.plainBody",
+            AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("isRead",
+            AttributeInfo("A.READ_STATUS", INTEGER, PrimitiveType_Boolean)));
+    m_msg_attr_map.insert(std::make_pair("hasAttachment",
+            AttributeInfo("A.ATTACHMENT_COUNT", INTEGER, PrimitiveType_Boolean)));
+    m_msg_attr_map.insert(std::make_pair("isHighPriority",
+            AttributeInfo("A.PRIORITY", INTEGER, PrimitiveType_Boolean)));
+    m_msg_attr_map.insert(std::make_pair("subject",
+            AttributeInfo("A.SUBJECT", TEXT, PrimitiveType_String)));
+    m_msg_attr_map.insert(std::make_pair("direction",
+            AttributeInfo("A.MSG_DIRECTION", INTEGER, PrimitiveType_String)));
+
+// Attributes map for emails ==================================================
+    m_email_attr_map.insert(std::make_pair("id",
+            AttributeInfo("mail_id", INTEGER, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("serviceId",
+            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("folderId",
+            AttributeInfo("mailbox_id", INTEGER, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("type",
+            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("timestamp",
+            AttributeInfo("date_time", DATETIME, PrimitiveType_Time)));
+    m_email_attr_map.insert(std::make_pair("from",
+            AttributeInfo("full_address_from", TEXT, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("to",
+            AttributeInfo("full_address_to", TEXT, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("cc",
+            AttributeInfo("full_address_cc", TEXT, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("bcc",
+            AttributeInfo("full_address_bcc", TEXT, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("body.plainBody",
+            AttributeInfo("preview_text", TEXT, PrimitiveType_String)));
+    m_email_attr_map.insert(std::make_pair("isRead",
+            AttributeInfo("flags_seen_field", BOOLEAN, PrimitiveType_Boolean)));
+    m_email_attr_map.insert(std::make_pair("hasAttachment",
+            AttributeInfo("attachment_count", INTEGER, PrimitiveType_Boolean)));
+    m_email_attr_map.insert(std::make_pair("isHighPriority",
+            AttributeInfo("priority", INTEGER, PrimitiveType_Boolean)));
+    m_email_attr_map.insert(std::make_pair("subject",
+            AttributeInfo("subject", TEXT, PrimitiveType_String)));
+
+// Attributes map for short message conversations =============================
+    m_msg_conv_attr_map.insert(std::make_pair("id",
+            AttributeInfo("A.CONV_ID", INTEGER, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("type",
+            AttributeInfo("B.MAIN_TYPE", INTEGER, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("timestamp",
+            AttributeInfo("A.DISPLAY_TIME", DATETIME, PrimitiveType_Time)));
+    m_msg_conv_attr_map.insert(std::make_pair("messageCount",
+            AttributeInfo("(A.SMS_CNT + A.MMS_CNT)", INTEGER, PrimitiveType_ULong)));
+    m_msg_conv_attr_map.insert(std::make_pair("unreadMessages",
+            AttributeInfo("A.UNREAD_CNT", INTEGER, PrimitiveType_ULong)));
+    m_msg_conv_attr_map.insert(std::make_pair("preview",
+            AttributeInfo("A.MSG_TEXT", TEXT, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("from",
+            AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("to",
+            AttributeInfo("C.ADDRESS_VAL", TEXT, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("msgId",
+            AttributeInfo("B.MSG_ID", INTEGER, PrimitiveType_String)));
+    m_msg_conv_attr_map.insert(std::make_pair("direction",
+            AttributeInfo("B.MSG_DIRECTION", INTEGER, PrimitiveType_String)));
+
+// Attributes map for email conversations =====================================
+    m_email_conv_attr_map.insert(std::make_pair("id",
+            AttributeInfo("thread_id", INTEGER, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("serviceId",
+            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("type",
+            AttributeInfo("account_id", INTEGER, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("timestamp",
+            AttributeInfo("date_time", DATETIME, PrimitiveType_Time)));
+    m_email_conv_attr_map.insert(std::make_pair("messageCount",
+            AttributeInfo("thread_item_count", INTEGER, PrimitiveType_ULong)));
+    m_email_conv_attr_map.insert(std::make_pair("unreadMessages",
+            AttributeInfo(std::string("thread_id IN (SELECT thread_id ")
+                    + std::string("FROM mail_tbl WHERE flags_seen_field = 0 ")
+                    + std::string("GROUP BY thread_id HAVING COUNT(thread_id)"),
+                    INTEGER,
+                    PrimitiveType_ULong)));
+    m_email_conv_attr_map.insert(std::make_pair("preview",
+            AttributeInfo("preview_text", TEXT, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("subject",
+            AttributeInfo("subject", TEXT, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("from",
+            AttributeInfo("full_address_from", TEXT, PrimitiveType_String)));
+    m_email_conv_attr_map.insert(std::make_pair("to",
+            AttributeInfo("full_address_to", TEXT, PrimitiveType_String)));
+}
+
+MessagingDatabaseManager::~MessagingDatabaseManager()
+{
+
+}
+
+MessagingDatabaseManager& MessagingDatabaseManager::getInstance()
+{
+    static MessagingDatabaseManager instance;
+    return instance;
+}
+
+__thread sqlite3* sqlHandle = NULL;
+__thread sqlite3_stmt* stmt = NULL;
+
+msg_error_t MessagingDatabaseManager::connect()
+{
+    LOGD("Entered");
+    int err = 0;
+    if (NULL == sqlHandle) {
+        char strDBName[64];
+
+        memset(strDBName, 0x00, sizeof(strDBName));
+        snprintf(strDBName, sizeof(strDBName), "%s", MSG_DB_NAME);
+
+        err = db_util_open(strDBName, &sqlHandle, DB_UTIL_REGISTER_HOOK_METHOD);
+
+        if (SQLITE_OK != err) {
+            LOGE("DB connecting fail [%d]", err);
+            return MSG_ERR_DB_CONNECT;
+        }
+
+        LOGD("DB connecting success: [%d]", sqlHandle);
+    } else {
+        LOGD("DB connection exists: [%d]", sqlHandle);
+    }
+
+    return MSG_SUCCESS;
+}
+
+msg_error_t MessagingDatabaseManager::disconnect()
+{
+    LOGD("Entered");
+    msg_error_t err = 0;
+    if (NULL != sqlHandle) {
+        err = db_util_close(sqlHandle);
+
+        if (SQLITE_OK != err) {
+            LOGE("DB disconnecting fail [%d]", err);
+            return MSG_ERR_DB_DISCONNECT;
+        }
+
+        sqlHandle = NULL;
+        LOGD("DB disconnecting success");
+    }
+
+    return MSG_SUCCESS;
+}
+
+msg_error_t MessagingDatabaseManager::getTable(std::string sqlQuery,
+        char*** results,
+        int* resultsCount)
+{
+    LOGD("Entered");
+    msg_error_t err = 0;
+    *resultsCount = 0;
+
+    freeTable(results);
+    connect();
+
+
+    char* error_msg = NULL;
+    err = sqlite3_get_table(sqlHandle, sqlQuery.c_str(), results,
+            resultsCount, 0, &error_msg);
+
+    if (SQLITE_OK != err) {
+        LOGE("Getting table fail [%d] error_msg:%s querry was:%s", err, error_msg,
+                sqlQuery.c_str());
+        freeTable(results);
+        return MSG_ERR_DB_GETTABLE;
+    }
+
+    LOGD("Getting table success");
+    if (0 == *resultsCount) {
+        LOGD("No results");
+    }
+
+    disconnect();
+    return MSG_SUCCESS;
+}
+
+void MessagingDatabaseManager::freeTable(char*** results)
+{
+    LOGD("Entered");
+    if (*results) {
+        sqlite3_free_table(*results);
+        *results = NULL;
+    }
+}
+
+int MessagingDatabaseManager::cellToInt(char** array, int cellId)
+{
+    LOGD("Entered");
+    if (NULL == array) {
+        LOGD("Array is NULL");
+        return 0;
+    }
+
+    char* tmp = *(array + cellId);
+    if (NULL == tmp) {
+        LOGD("Cell is NULL");
+        return 0;
+    }
+
+    return static_cast<int>(strtol(tmp, (char**) NULL, 10));
+}
+
+std::string MessagingDatabaseManager::getMatchString(Tizen::AnyPtr match_value,
+        const PrimitiveType type) const
+{
+    if(!match_value) {
+        LOGD("Warning: match value is NULL");
+        return std::string();
+    }
+
+    std::ostringstream converter;
+    switch(type) {
+        case PrimitiveType_NoType: {
+            LOGD("Warning: match value is no type");
+            return std::string();
+        }
+        case PrimitiveType_Null: {
+            LOGD("Warning: match value is null");
+            return std::string();
+        }
+        case PrimitiveType_Boolean: {
+            converter << match_value->toBool();
+            return converter.str();
+        }
+        case PrimitiveType_Long: {
+            converter << match_value->toLong();
+            return converter.str();
+        }
+        case PrimitiveType_ULong: {
+            converter << match_value->toULong();
+            return converter.str();
+        }
+        case PrimitiveType_LongLong: {
+            converter << match_value->toLongLong();
+            return converter.str();
+        }
+        case PrimitiveType_ULongLong: {
+            converter << match_value->toULongLong();
+            return converter.str();
+        }
+        case PrimitiveType_Double: {
+            converter << match_value->toDouble();
+            return converter.str();
+        }
+        case PrimitiveType_String: {
+            return match_value->toString();
+        }
+        case PrimitiveType_Time: {
+            converter << match_value->toTimeT();
+            return converter.str();
+        }
+        default: {
+            LOGD("Warning: match value is not specified");
+            return std::string();
+        }
+    }
+}
+
+std::string MessagingDatabaseManager::getAttributeFilterQuery(AbstractFilterPtr filter,
+        AttributeInfoMap& attribute_map, MessageType msgType)
+{
+    LOGD("Entered");
+
+    std::ostringstream sqlQuery;
+    AttributeFilterPtr attr_filter = castToAttributeFilter(filter);
+    if(!attr_filter) {
+        LOGE("passed filter is not valid AttributeFilter!");
+        throw UnknownException("Wrong filter type - not attribute filter");
+    }
+
+    const std::string attribute_name = attr_filter->getAttributeName();
+
+    AttributeInfoMap::iterator it = attribute_map.find(attribute_name);
+    if (it != attribute_map.end()) {
+        sqlQuery << "(" << attribute_map[attribute_name].sql_name << " ";
+    } else {
+        LOGE("The attribute: %s does not exist.", attribute_name.c_str());
+        throw InvalidValuesException("The attribute does not exist.");
+    }
+
+    AnyPtr match_value_any_ptr = attr_filter->getMatchValue();
+    const AttributeInfo& attr_info = it->second;
+    std::string match_value = getMatchString(match_value_any_ptr, attr_info.any_type);
+    const FilterMatchFlag match_flag = attr_filter->getMatchFlag();
+
+    LOGD("match_value_any_ptr:%p any_type:%d attr_name:%s match_value:%s",
+            match_value_any_ptr.get(), attr_info.any_type, attribute_name.c_str(),
+            match_value.c_str());
+
+    if ("serviceId" == attribute_name) {
+
+        int i_matchValue;
+        std::istringstream iss(match_value);
+        iss >> i_matchValue;
+
+        switch(i_matchValue) {
+        case MessageServiceAccountId::SMS_ACCOUNT_ID: {
+            sqlQuery << "= " << MessageType::SMS;
+            break;
+        }
+        case MessageServiceAccountId::MMS_ACCOUNT_ID: {
+            sqlQuery << "= " << MessageType::MMS;
+            break;
+        }
+        default:
+            sqlQuery << "= " << match_value;
+        }
+    }
+    else if ("type" == attribute_name) {
+        if ("messaging.sms" == match_value && MessageType::SMS == msgType) {
+            sqlQuery << "= " << msgType;
+        } else if ("messaging.mms" == match_value && MessageType::MMS == msgType) {
+            sqlQuery << "= " << msgType;
+        } else if ("messaging.email" == match_value && MessageType::EMAIL == msgType) {
+            sqlQuery << "= " << attr_info.sql_name;
+        } else {
+            LOGE("attribute \"type\" matchValue:%s "
+                    "does not match messaging.sms/mms/email\n"
+                    "msgType:%d does not match SMS(%d), MMS(%d) nor EMAIL(%d)!",
+                    match_value.c_str(), msgType, MessageType::SMS, MessageType::MMS,
+                    MessageType::EMAIL);
+            throw UnknownException("The value does not match service type.");
+        }
+    }
+    else if ("isRead" == attribute_name || "hasAttachment" == attribute_name) {
+        if (attr_filter->getMatchValue()->toBool()) {
+            sqlQuery << "> 0";
+        } else {
+            sqlQuery << "= 0";
+        }
+    }
+    else if ("isHighPriority" == attribute_name) {
+        if (attr_filter->getMatchValue()->toBool()) {
+            sqlQuery << "= ";
+        } else {
+            sqlQuery << "<> ";
+        }
+
+        if (MessageType::SMS == msgType || MessageType::MMS == msgType) {
+            sqlQuery << MSG_MESSAGE_PRIORITY_HIGH;
+        } else if (MessageType::EMAIL == msgType) {
+            sqlQuery << EMAIL_MAIL_PRIORITY_HIGH;
+        }
+    }
+    else {
+        // Addresses which are stored in database can have different form than in filters
+        if (MessageType::EMAIL == msgType && ("from" == attribute_name ||
+                "to" == attribute_name || "cc" == attribute_name ||
+                "bcc" == attribute_name)) {
+            std::size_t foundPos;
+            while ((foundPos = match_value.find('<')) != std::string::npos) {
+                match_value.erase(foundPos, 1);
+            }
+
+            while ((foundPos = match_value.find('>')) != std::string::npos) {
+                match_value.erase(foundPos, 1);
+            }
+
+            if (EXACTLY == match_flag) {
+                match_value = "%<" + match_value + ">%";
+            } else if (CONTAINS == match_flag) {
+                match_value = "%<%" + match_value + "%>%";
+            } else if (STARTSWITH == match_flag) {
+                match_value = "%<" + match_value + "%>%";
+            } else if (ENDSWITH == match_flag) {
+                match_value = "%<%" + match_value + ">%";
+            }
+        }
+
+        switch (match_flag) {
+            /*
+            case NONE: {
+                // Determines if the apostrophes have to be added over match value
+                if (TEXT == attribute_map[attribute_name].sql_type) {
+                    sqlQuery << "NOT LIKE '" << match_value << "'";
+                } else {
+                    sqlQuery << "<> " << match_value;
+                }
+                break;
+            }*/
+            case EXACTLY: {
+                // Determines if the apostrophes have to be added over match value
+                if (TEXT == attribute_map[attribute_name].sql_type) {
+                    sqlQuery << "LIKE '" << match_value << "'";
+                } else {
+                    sqlQuery << "= " << match_value;
+                }
+                break;
+            }
+            case CONTAINS: {
+                sqlQuery << "LIKE '%" << match_value << "%'";
+                break;
+            }
+            case STARTSWITH: {
+                sqlQuery << "LIKE '" << match_value << "%'";
+                break;
+            }
+            case ENDSWITH: {
+                sqlQuery << "LIKE '%" << match_value << "'";
+                break;
+            }
+            case EXISTS: {
+                if ("unreadMessages" != attribute_name) {
+                    sqlQuery << "IS NOT NULL";
+                } else {
+                    sqlQuery << "!= 0";
+                }
+                break;
+            }
+            default:
+                throw UnknownException("The match flag is incorrect.");
+        }
+
+        if (MessageType::SMS == msgType || MessageType::MMS == msgType) {
+            if ("from" == attribute_name) {
+                // "From" and "to" attributes require message direction value
+                sqlQuery << " AND " << attribute_map["direction"].sql_name << " = 1";
+            } else if ("to" == attribute_name) {
+                sqlQuery << " AND " << attribute_map["direction"].sql_name << " <> 1";
+            }
+        } else if (MessageType::EMAIL == msgType) {
+            if("unreadMessages" == attribute_name) {
+                sqlQuery << ")";
+            }
+        }
+    }
+    sqlQuery << ") ";
+    return sqlQuery.str();
+}
+
+std::string MessagingDatabaseManager::getAttributeRangeFilterQuery(AbstractFilterPtr filter,
+        AttributeInfoMap& attribute_map, MessageType msg_type)
+{
+    LOGD("Entered");
+
+    std::ostringstream sql_query, converter;
+    std::string initial_value, end_value;
+
+    AttributeRangeFilterPtr attr_range_filter = castToAttributeRangeFilter(filter);
+    if(!attr_range_filter) {
+        LOGE("passed filter is not valid AttributeRangeFilter!");
+        throw UnknownException("Wrong filter type - not attribute range filter");
+    }
+
+    converter << attr_range_filter->getInitialValue()->toTimeT();
+    initial_value = converter.str();
+    converter.str("");
+    converter << attr_range_filter->getEndValue()->toTimeT();
+    end_value = converter.str();
+
+    sql_query << "(" << attribute_map[attr_range_filter->getAttributeName()].sql_name << " ";
+    sql_query << "BETWEEN " << initial_value << " AND " << end_value << ") ";
+    return sql_query.str();
+}
+
+std::string MessagingDatabaseManager::getCompositeFilterQuery(AbstractFilterPtr filter,
+        AttributeInfoMap& attribute_map, MessageType msg_type)
+{
+    LOGD("Entered");
+    std::ostringstream sql_query;
+
+    CompositeFilterPtr comp_filter = castToCompositeFilter(filter);
+    if(!comp_filter) {
+        LOGE("passed filter is not valid CompositeFilter!");
+        throw UnknownException("Wrong filter type - not composite filter");
+    }
+
+    AbstractFilterPtrVector filters_arr = comp_filter->getFilters();
+
+    std::string logical_operator;
+    if (UNION == comp_filter->getType()) {
+        logical_operator = "OR ";
+    } else {
+        logical_operator = "AND ";
+    }
+
+    sql_query << "(";
+    const unsigned int size = filters_arr.size();
+    for (unsigned int i = 0; i < size; ++i) {
+
+        const FilterType filter_type = filters_arr[i]->getFilterType();
+        switch (filter_type) {
+            case ATTRIBUTE_FILTER: {
+                sql_query << getAttributeFilterQuery(filters_arr[i], attribute_map, msg_type);
+                break;
+            }
+            case ATTRIBUTE_RANGE_FILTER: {
+                sql_query << getAttributeRangeFilterQuery(filters_arr[i], attribute_map, msg_type);
+                break;
+            }
+            case COMPOSITE_FILTER: {
+                sql_query << getCompositeFilterQuery(filters_arr[i], attribute_map, msg_type);
+                break;
+            }
+            default:
+                LOGE("Error while querying message - unsupported filter type: %d",
+                        filter_type);
+                throw UnknownException("Error while querying message.");
+        }
+
+        if (i != (size - 1)) {
+            sql_query << logical_operator;
+        }
+    }
+    sql_query << ") ";
+
+    return sql_query.str();
+}
+
+std::string MessagingDatabaseManager::addFilters(AbstractFilterPtr filter,
+        SortModePtr sort_mode, long limit, long offset, AttributeInfoMap& attribute_map,
+        MessageType msg_type)
+{
+    LOGD("Entered");
+    std::ostringstream sql_query;
+
+    // Service type query
+    if (MessageType::SMS == msg_type || MessageType::MMS == msg_type) {
+        if (UNDEFINED != msg_type) {
+            sql_query << attribute_map["type"].sql_name << " = " << msg_type << " AND ";
+        } else {
+            LOGE("The service type is incorrect - msg_type is UNDEFINED");
+            throw UnknownException("The service type is incorrect.");
+        }
+    }
+
+    if(filter) {
+        // Filter query
+        switch (filter->getFilterType()) {
+            case ATTRIBUTE_FILTER: {
+                sql_query << getAttributeFilterQuery(filter, attribute_map, msg_type);
+            } break;
+
+            case ATTRIBUTE_RANGE_FILTER: {
+                sql_query << getAttributeRangeFilterQuery(filter, attribute_map, msg_type);
+            } break;
+
+            case COMPOSITE_FILTER : {
+                sql_query << getCompositeFilterQuery(filter, attribute_map, msg_type);
+            } break;
+
+            default:
+                LOGE("The filter type is incorrect: %d", filter->getFilterType());
+                throw UnknownException("The filter type is incorrect.");
+        }
+    }
+
+    // SortMode query
+    if (sort_mode) {
+        if (attribute_map.find(sort_mode->getAttributeName()) != attribute_map.end()) {
+            sql_query << "ORDER BY "
+                    << attribute_map[sort_mode->getAttributeName()].sql_name << " ";
+        } else {
+            LOGE("The attribute does not exist.");
+            throw UnknownException("The attribute does not exist.");
+        }
+
+        if (ASC == sort_mode->getOrder()) {
+            sql_query << "ASC ";
+        } else {
+            sql_query << "DESC ";
+        }
+    }
+
+    // Limit query
+    if (0 != limit) {
+        sql_query << "LIMIT " << limit << " ";
+    }
+
+    // Offset query
+    if (0 != offset) {
+        if( 0 == limit ) {
+            //Ugly fix proposed by mySQL team:
+            //http://dev.mysql.com/doc/refman/5.0/en/select.html
+            //To retrieve all rows from a certain offset up to the end of the result set,
+            //you can use some large number for the second parameter.
+            //
+            //Reason: to use OFFSET you need to have LIMIT statement
+            //18446744073709551615 is 2^64-1 - max value of big int
+            //However we will use -1 since it will work fine for various int sizes (this
+            //trick have been used in old implementation).
+
+            sql_query << "LIMIT -1 ";
+        }
+        sql_query << "OFFSET " << offset << " ";
+    }
+
+    return sql_query.str();
+}
+
+std::vector<int> MessagingDatabaseManager::findShortMessages(
+        FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+    std::ostringstream sqlQuery;
+    int attributesCount = 1; // It has to be set manually each time when the query is changed
+    int cellId = attributesCount;
+    char** results = NULL;
+    int resultsCount;
+    std::vector<int> messagesIds;
+
+    sqlQuery << "SELECT " << "DISTINCT(" << m_msg_attr_map["id"].sql_name << ") "
+            << "FROM " << MSG_MESSAGE_TABLE_NAME << " A "
+            << "JOIN " << MSG_ADDRESS_TABLE_NAME << " B "
+            << "ON A.CONV_ID = B.CONV_ID " << "WHERE B.ADDRESS_ID <> 0 AND ";
+
+    // Adding filters query
+    AbstractFilterPtr filter = callback->getFilter();
+    SortModePtr sortMode = callback->getSortMode();
+    long limit = callback->getLimit();
+    long offset = callback->getOffset();
+    MessageType msgType = callback->getMessageServiceType();
+
+    sqlQuery << addFilters(filter, sortMode, limit, offset, m_msg_attr_map, msgType);
+    LOGD("%s", sqlQuery.str().c_str());
+
+    // Getting results from database
+    msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount);
+    if (MSG_SUCCESS != err) {
+        freeTable(&results);
+        throw UnknownException("Error while getting data from database.");
+    }
+
+    for (int i = 0; i < resultsCount; ++i) {
+        messagesIds.push_back(cellToInt(results, cellId++));
+        LOGD("id: %d", messagesIds.at(messagesIds.size() - 1));
+    }
+
+    freeTable(&results);
+    return messagesIds;
+}
+
+std::pair<int, email_mail_data_t*> MessagingDatabaseManager::findEmails(
+        FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+    std::ostringstream sqlWhereClause;
+    int resultsCount;
+    email_mail_data_t* results;
+
+    // Adding filters query
+    AbstractFilterPtr filter = callback->getFilter();
+    SortModePtr sortMode = callback->getSortMode();
+    long limit = callback->getLimit();
+    long offset = callback->getOffset();
+    MessageType msgType = callback->getMessageServiceType();
+    int accountId = callback->getAccountId();
+
+    sqlWhereClause << "WHERE "
+            << m_email_attr_map["serviceId"].sql_name << " = " << accountId << " AND "
+            << addFilters(filter, sortMode, limit, offset, m_email_attr_map, msgType);
+    LOGD("%s", sqlWhereClause.str().c_str());
+
+    // Getting results from database
+    msg_error_t err = email_query_mails(const_cast<char*>(sqlWhereClause.str().c_str()),
+                &results, &resultsCount);
+    if (EMAIL_ERROR_NONE != err) {
+        LOGE("Getting mail list fail [%d]", err);
+
+        if (EMAIL_ERROR_MAIL_NOT_FOUND == err) {
+            resultsCount = 0;
+        } else {
+            throw UnknownException("Error while getting data from database.");
+        }
+    }
+
+    return std::make_pair(resultsCount, results);
+}
+
+std::vector<int> MessagingDatabaseManager::findShortMessageConversations(
+        ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+    std::ostringstream sqlQuery;
+    int attributesCount = 1; // It has to be set manually each time when the query is changed
+    int cellId = attributesCount;
+    char** results = NULL;
+    int resultsCount;
+    std::vector<int> conversationsIds;
+
+    sqlQuery << "SELECT " << "DISTINCT(" << m_msg_conv_attr_map["id"].sql_name << ") "
+            << "FROM " << MSG_CONVERSATION_TABLE_NAME << " A "
+            << "JOIN " << MSG_MESSAGE_TABLE_NAME << " B "
+            << "ON A.CONV_ID = B.CONV_ID "
+            << "JOIN " << MSG_ADDRESS_TABLE_NAME << " C "
+            << "ON A.CONV_ID = C.CONV_ID "
+            << "WHERE (A.SMS_CNT > 0 OR A.MMS_CNT > 0) AND ";
+
+    // Adding filters query
+    AbstractFilterPtr filter = callback->getFilter();
+    SortModePtr sortMode = callback->getSortMode();
+    long limit = callback->getLimit();
+    long offset = callback->getOffset();
+    MessageType msgType = callback->getMessageServiceType();
+
+    sqlQuery << addFilters(filter, sortMode, limit, offset, m_msg_conv_attr_map, msgType);
+    LOGD("%s", sqlQuery.str().c_str());
+
+    // Getting results from database
+    msg_error_t err = getTable(sqlQuery.str(), &results, &resultsCount);
+    if (MSG_SUCCESS != err) {
+        freeTable(&results);
+        throw UnknownException("Error while getting data from database.");
+    }
+
+    for (int i = 0; i < resultsCount; ++i) {
+        conversationsIds.push_back(cellToInt(results, cellId++));
+        LOGD("id: %d", conversationsIds.at(conversationsIds.size() - 1));
+    }
+
+    freeTable(&results);
+    return conversationsIds;
+}
+
+std::vector<EmailConversationInfo> MessagingDatabaseManager::findEmailConversations(
+        ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+    std::ostringstream sqlWhereClause;
+    int resultsCount;
+    email_mail_data_t* results;
+    std::map<int, int> conversationsBag;
+    std::vector<EmailConversationInfo> conversationsInfo;
+
+    // Adding filters query
+    AbstractFilterPtr filter = callback->getFilter();
+    SortModePtr sortMode = callback->getSortMode();
+    long limit = callback->getLimit();
+    long offset = callback->getOffset();
+    MessageType msgType = callback->getMessageServiceType();
+    int accountId = callback->getAccountId();
+
+    sqlWhereClause << "WHERE "
+            << m_email_conv_attr_map["serviceId"].sql_name << " = " << accountId << " AND "
+            << addFilters(filter, sortMode, limit, offset, m_email_conv_attr_map, msgType);
+    LOGD("%s", sqlWhereClause.str().c_str());
+
+    // Getting results from database
+    msg_error_t err = email_query_mails(const_cast<char*>(sqlWhereClause.str().c_str()),
+                &results, &resultsCount);
+    if (EMAIL_ERROR_NONE != err) {
+        LOGE("Getting mail list fail [%d]", err);
+
+        if (EMAIL_ERROR_MAIL_NOT_FOUND == err) {
+            resultsCount = 0;
+        } else {
+            throw UnknownException("Error while getting data from database.");
+        }
+    }
+
+    // Assigning found emails to conversation
+    for (int i = 0; i < resultsCount; ++i) {
+        if (conversationsBag.find(results[i].thread_id) == conversationsBag.end()) {
+            EmailConversationInfo info;
+            info.id = results[i].thread_id;
+            conversationsInfo.push_back(info);
+            conversationsBag.insert(std::make_pair(results[i].thread_id, 0));
+        }
+
+        if (!(static_cast<bool>(results[i].flags_seen_field))) {
+            ++conversationsBag[results[i].thread_id];
+        }
+    }
+
+    for (std::vector<EmailConversationInfo>::iterator it = conversationsInfo.begin();
+            it != conversationsInfo.end(); ++it) {
+        (*it).unreadMessages = conversationsBag[(*it).id];
+    }
+
+    email_free_mail_data(&results, resultsCount);
+    return conversationsInfo;
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessagingDatabaseManager.h b/src/messaging/old/MessagingDatabaseManager.h
new file mode 100755 (executable)
index 0000000..6c0286a
--- /dev/null
@@ -0,0 +1,121 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessagingDatabaseManager.h
+ */
+
+#ifndef __TIZEN_MSG_DATABASE_MANAGER_H__
+#define __TIZEN_MSG_DATABASE_MANAGER_H__
+
+#include <iostream>
+#include <map>
+
+#include <msg.h>
+#include <db-util.h>
+#include <AbstractFilter.h>
+
+#include "FindMsgCallbackUserData.h"
+#include "ConversationCallbackData.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+// =================================================================
+#define MSG_DB_NAME                     "/opt/usr/dbspace/.msg_service.db"
+#define MSG_MESSAGE_TABLE_NAME          "MSG_MESSAGE_TABLE"
+#define MSG_FOLDER_TABLE_NAME           "MSG_FOLDER_TABLE"
+#define MSG_ADDRESS_TABLE_NAME          "MSG_ADDRESS_TABLE"
+#define MSG_CONVERSATION_TABLE_NAME     "MSG_CONVERSATION_TABLE"
+#define MSG_SIM_MSG_TABLE_NAME          "MSG_SIM_TABLE"
+#define MSG_FILTER_TABLE_NAME           "MSG_FILTER_TABLE"
+#define MSG_PUSH_MSG_TABLE_NAME         "MSG_PUSH_TABLE"
+#define MSG_CB_MSG_TABLE_NAME           "MSG_CBMSG_TABLE"
+#define MMS_PLUGIN_MESSAGE_TABLE_NAME   "MSG_MMS_MESSAGE_TABLE"
+#define MSG_SYNCML_MSG_TABLE_NAME       "MSG_SYNCML_TABLE"
+#define MSG_SCHEDULED_MSG_TABLE_NAME    "MSG_SCHEDULED_TABLE"
+#define MSG_SMS_SENDOPT_TABLE_NAME      "MSG_SMS_SENDOPT_TABLE"
+// =================================================================
+enum SQLAttributeType {
+    UNDEFINED_TYPE,
+    BOOLEAN,
+    INTEGER,
+    DATETIME,
+    TEXT,
+};
+
+struct AttributeInfo {
+    AttributeInfo();
+    AttributeInfo(const std::string& in_sql_name,
+            const SQLAttributeType in_sql_type,
+            const Tizen::PrimitiveType in_any_type);
+    AttributeInfo(const AttributeInfo& other);
+    AttributeInfo& operator=(const AttributeInfo& other);
+
+    std::string sql_name;
+    SQLAttributeType sql_type;
+    Tizen::PrimitiveType any_type;
+};
+
+typedef std::map<std::string, AttributeInfo> AttributeInfoMap;
+
+struct EmailConversationInfo {
+    int id, unreadMessages;
+};
+// =================================================================
+
+class MessagingDatabaseManager {
+public:
+    static MessagingDatabaseManager& getInstance();
+    std::vector<int> findShortMessages(FindMsgCallbackUserData* callback);
+    std::pair<int, email_mail_data_t*> findEmails(FindMsgCallbackUserData* callback);
+    std::vector<int> findShortMessageConversations(ConversationCallbackData* callback);
+    std::vector<EmailConversationInfo> findEmailConversations(ConversationCallbackData* callback);
+
+private:
+    MessagingDatabaseManager();
+    MessagingDatabaseManager(const MessagingDatabaseManager &);
+    void operator=(const MessagingDatabaseManager &);
+    virtual ~MessagingDatabaseManager();
+
+    msg_error_t connect();
+    msg_error_t disconnect();
+    msg_error_t getTable(std::string query, char*** results, int* resultsCount);
+    void freeTable(char*** array);
+    int cellToInt(char** array, int cellId);
+    std::string getMatchString(Tizen::AnyPtr matchValue,
+            const Tizen::PrimitiveType type) const;
+    std::string getAttributeFilterQuery(Tizen::AbstractFilterPtr filter,
+            AttributeInfoMap& attributeMap, MessageType msgType);
+    std::string getAttributeRangeFilterQuery(Tizen::AbstractFilterPtr filter,
+            AttributeInfoMap& attributeMap, MessageType msgType);
+    std::string getCompositeFilterQuery(Tizen::AbstractFilterPtr filter,
+            AttributeInfoMap& attributeMap, MessageType msgType);
+    std::string addFilters(Tizen::AbstractFilterPtr filter, Tizen::SortModePtr sortMode,
+            long limit, long offset, AttributeInfoMap& attributeMap, MessageType msgType);
+
+    AttributeInfoMap m_msg_attr_map;
+    AttributeInfoMap m_email_attr_map;
+
+    AttributeInfoMap m_msg_conv_attr_map;
+    AttributeInfoMap m_email_conv_attr_map;
+};
+
+} // Messaging
+} // DeviceAPI
+
+#endif // __TIZEN_MSG_DATABASE_MANAGER_H__
diff --git a/src/messaging/old/MessagingManager.cpp b/src/messaging/old/MessagingManager.cpp
new file mode 100755 (executable)
index 0000000..0367248
--- /dev/null
@@ -0,0 +1,343 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+#include <GlobalContextManager.h>
+
+#include <system_info.h>
+
+#include <email-types.h>
+#include <email-api.h>
+
+#include "MessagingManager.h"
+#include "MessagingUtil.h"
+#include "JSMessageService.h"
+#include "MessageService.h"
+#include "MessageServiceShortMsg.h"
+#include "MessageServiceEmail.h"
+#include "ShortMsgManager.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+MessageServiceCallbackData::MessageServiceCallbackData(JSContextRef globalCtx):
+    CallbackUserData(globalCtx),
+    m_msg_type(MessageType::UNDEFINED),
+    m_is_error(false)
+{
+    LOGD("Entered");
+}
+
+MessageServiceCallbackData::~MessageServiceCallbackData()
+{
+    LOGD("Entered");
+}
+
+void MessageServiceCallbackData::setMessageType(MessageType msgType)
+{
+    m_msg_type = msgType;
+}
+
+MessageType MessageServiceCallbackData::getMessageType() const
+{
+    return m_msg_type;
+}
+
+void MessageServiceCallbackData::setMessageServices(
+        const std::vector<MessageService*>& msgServices)
+{
+    m_msg_services = msgServices;
+}
+
+const std::vector<MessageService*>& MessageServiceCallbackData::getMessageServices() const
+{
+    return m_msg_services;
+}
+
+void MessageServiceCallbackData::setError(const std::string& err_name,
+        const std::string& err_message)
+{
+    // keep only first error in chain
+    if (!m_is_error) {
+        m_is_error = true;
+        m_err_name = err_name;
+        m_err_message = err_message;
+    }
+}
+
+bool MessageServiceCallbackData::isError() const
+{
+    return m_is_error;
+}
+
+std::string MessageServiceCallbackData::getErrorName() const
+{
+    return m_err_name;
+}
+
+std::string MessageServiceCallbackData::getErrorMessage() const
+{
+    return m_err_message;
+}
+
+void MessageServiceCallbackData::clearServices()
+{
+    unsigned int count = m_msg_services.size();
+    for (unsigned int i = 0; i < count; ++i) {
+        delete m_msg_services.at(i);
+    }
+    m_msg_services.clear();
+}
+
+
+static gboolean getMsgServicesCompleteCB(void* data)
+{
+    LOGD("Entered");
+
+    MessageServiceCallbackData* callback = static_cast<MessageServiceCallbackData*>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        return false;
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return false;
+    }
+
+    try {
+        if (callback->isError()) {
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        }
+        else {
+            std::vector<MessageService*> msgServices = callback->getMessageServices();
+            unsigned int count = msgServices.size();
+            JSValueRef result = NULL;
+
+            JSObjectRef jsMsgServicesObject[count];
+            for (unsigned int i = 0; i < count; ++i) {
+                jsMsgServicesObject[i] = JSMessageService::createJSObject(context,
+                        msgServices.at(i));
+                if (NULL == jsMsgServicesObject[i]) {
+                    LOGE("Message service object creation failed");
+                    throw Common::UnknownException(
+                            "Message service object creation failed");
+                }
+            }
+            result = JSObjectMakeArray(context, count,
+                    count > 0 ? jsMsgServicesObject : NULL, NULL);
+
+            if (!result) {
+                JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                        JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                        "Could not create JS array object");
+                callback->clearServices();
+                callback->callErrorCallback(errobj);
+            }
+            else {
+                callback->callSuccessCallback(result);
+            }
+        }
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, err);
+        callback->clearServices();
+        callback->callErrorCallback(errobj);
+    }
+    catch (...) {
+        JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                "Cannot retrieve JS message services");
+        callback->clearServices();
+        callback->callErrorCallback(errobj);
+    }
+
+    delete callback;
+    callback = NULL;
+
+    return false;
+}
+
+static void* getMsgServicesThread(void* data)
+{
+    LOGD("Entered");
+
+    MessageServiceCallbackData* callback = static_cast<MessageServiceCallbackData*>(data);
+    if(!callback){
+        LOGE("Callback is null");
+        return NULL;
+    }
+
+    MessageType msgType = callback->getMessageType();
+    std::vector<MessageService*> msgServices;
+    MessageService* messageService = NULL;
+    email_account_t* email_accounts = NULL;
+    int count = 0;
+    bool isSupported = false;
+
+    try {
+        switch (msgType) {
+        case MessageType::SMS:
+            messageService = new(std::nothrow) MessageServiceShortMsg(
+                    MessageServiceAccountId::SMS_ACCOUNT_ID,
+                    MessageType::SMS);
+            if (!messageService) {
+                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                        "MessageService for SMS creation failed");
+            } else {
+                msgServices.push_back(messageService);
+            }
+            callback->setMessageServices(msgServices);
+            break;
+        case MessageType::MMS:
+            messageService = new(std::nothrow) MessageServiceShortMsg(
+                    MessageServiceAccountId::MMS_ACCOUNT_ID,
+                    MessageType::MMS);
+            if (!messageService) {
+                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                        "MessageService for MMS creation failed");
+            } else {
+                msgServices.push_back(messageService);
+            }
+            callback->setMessageServices(msgServices);
+            break;
+        case MessageType::EMAIL:
+            if (email_get_account_list(&email_accounts, &count) != EMAIL_ERROR_NONE) {
+                callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                        "Cannot get email accounts");
+            } else {
+                std::stringstream stream_name;
+                for (int i = 0; i < count; ++i) {
+                    stream_name << "[" << email_accounts[i].account_name << "] "
+                            << email_accounts[i].incoming_server_user_name;
+                    SLOGD("Account[%d/%d] id: %d, name: %s", i, count,
+                            email_accounts[i].account_id, stream_name.str().c_str());
+
+                    messageService = new(std::nothrow) MessageServiceEmail(
+                            email_accounts[i].account_id, stream_name.str());
+                    if (!messageService) {
+                        LOGE("message service[%d] is NULL", i);
+                        unsigned int count_srvcs = msgServices.size();
+                        for (unsigned int j = 0; j < count_srvcs; ++j) {
+                            delete msgServices.at(j);
+                        }
+                        msgServices.clear();
+                        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                                "MessageService for email creation failed");
+                        break;
+                    }
+                    else {
+                        msgServices.push_back(messageService);
+                    }
+
+                    messageService = NULL;
+                    stream_name.str("");
+                }
+                callback->setMessageServices(msgServices);
+            }
+
+            if (email_accounts != NULL) {
+                email_free_account(&email_accounts, count);
+                email_accounts = NULL;
+            }
+            break;
+        default:
+            callback->clearServices();
+            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                    "Invalid message service tag");
+            break;
+        }
+    }
+    catch (...) {
+        unsigned int count_srvcs = msgServices.size();
+        for (unsigned int j = 0; j < count_srvcs; ++j) {
+            delete msgServices.at(j);
+        }
+        msgServices.clear();
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                "Cannot retrieve message services");
+    }
+
+    if (!g_idle_add(getMsgServicesCompleteCB, static_cast<void*>(callback))) {
+        LOGE("g_idle addition failed");
+        callback->clearServices();
+        delete callback;
+        callback = NULL;
+    }
+
+    return NULL;
+}
+
+MessagingManager& MessagingManager::getInstance()
+{
+    LOGD("Entered");
+
+    static MessagingManager instance;
+    return instance;
+}
+
+void MessagingManager::getMessageServices(MessageServiceCallbackData* callback)
+{
+    LOGD("Entered");
+
+    pthread_t thread;
+    if (pthread_create(&thread, NULL, getMsgServicesThread, static_cast<void*>(callback))) {
+        LOGE("Thread creation failed");
+        throw Common::UnknownException("Thread creation failed");
+    }
+    if (pthread_detach(thread)) {
+        LOGE("Thread detachment failed");
+    }
+}
+
+MessagingManager::MessagingManager():
+        SecurityAccessor()
+{
+    LOGD("Entered");
+
+    int ret = msg_open_msg_handle(&m_msg_handle);
+    if (ret != MSG_SUCCESS) {
+        LOGE("Cannot get message handle: %d", ret);
+    }
+    else {
+        ShortMsgManager::getInstance().registerStatusCallback(m_msg_handle);
+    }
+}
+
+MessagingManager::~MessagingManager()
+{
+    LOGD("Entered");
+    int ret = msg_close_msg_handle(&m_msg_handle);
+    if (ret != MSG_SUCCESS) {
+        LOGW("Cannot close message handle: %d", ret);
+    }
+}
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/MessagingManager.h b/src/messaging/old/MessagingManager.h
new file mode 100755 (executable)
index 0000000..8af9399
--- /dev/null
@@ -0,0 +1,77 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_MESSAGING_MANAGER_H__
+#define __TIZEN_MESSAGING_MANAGER_H__
+
+#include <CallbackUserData.h>
+#include <PlatformException.h>
+#include <Security.h>
+
+#include "MessagingUtil.h"
+#include "MessageService.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class MessageServiceCallbackData : public Common::CallbackUserData {
+public:
+    MessageServiceCallbackData(JSContextRef globalCtx);
+    ~MessageServiceCallbackData();
+
+    void setMessageType(MessageType msgType);
+    MessageType getMessageType() const;
+
+    void setMessageServices(const std::vector<MessageService*>& msgServices);
+    const std::vector<MessageService*>& getMessageServices() const;
+
+    void setError(const std::string& err_name,
+            const std::string& err_message);
+    bool isError() const;
+    std::string getErrorName() const;
+    std::string getErrorMessage() const;
+
+    void clearServices();
+
+private:
+    MessageType m_msg_type;
+    bool m_is_error;
+    std::string m_err_name;
+    std::string m_err_message;
+    std::vector<MessageService*> m_msg_services;
+};
+
+class MessagingManager : public Common::SecurityAccessor
+{
+public:
+    static MessagingManager& getInstance();
+
+    void getMessageServices(MessageServiceCallbackData *callback);
+
+private:
+    MessagingManager();
+    MessagingManager(const MessagingManager &);
+    void operator=(const MessagingManager &);
+    virtual ~MessagingManager();
+
+    msg_handle_t m_msg_handle;
+
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_MESSAGING_MANAGER_H__
diff --git a/src/messaging/old/MessagingUtil.cpp b/src/messaging/old/MessagingUtil.cpp
new file mode 100644 (file)
index 0000000..ec733bf
--- /dev/null
@@ -0,0 +1,203 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessagingUtil.cpp
+ */
+
+#include <PlatformException.h>
+#include <string>
+#include "MessagingUtil.h"
+#include <Logger.h>
+#include <fstream>
+#include <streambuf>
+
+using namespace std;
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+namespace {
+const string TYPE_SMS = "messaging.sms";
+const string TYPE_MMS = "messaging.mms";
+const string TYPE_EMAIL = "messaging.email";
+const string SENT = "SENT";
+const string SENDING = "SENDING";
+const string FAILED = "FAILED";
+const string DRAFT = "DRAFT";
+
+const string FOLDER_TYPE_INBOX = "INBOX";
+const string FOLDER_TYPE_OUTBOX = "OUTBOX";
+const string FOLDER_TYPE_DRAFTS = "DRAFTS";
+const string FOLDER_TYPE_SENTBOX = "SENTBOX";
+}
+
+string MessagingUtil::messageFolderTypeToString(MessageFolderType type)
+{
+    switch(type) {
+        case MessageFolderType::MESSAGE_FOLDER_TYPE_INBOX:
+            return FOLDER_TYPE_INBOX;
+        case MessageFolderType::MESSAGE_FOLDER_TYPE_OUTBOX:
+            return FOLDER_TYPE_OUTBOX;
+        case MessageFolderType::MESSAGE_FOLDER_TYPE_DRAFTS:
+            return FOLDER_TYPE_DRAFTS;
+        case MessageFolderType::MESSAGE_FOLDER_TYPE_SENTBOX:
+            return FOLDER_TYPE_SENTBOX;
+        default:
+            return "";
+    }
+}
+
+MessageType MessagingUtil::stringToMessageType(string type)
+{
+    if (TYPE_SMS == type) {
+        return MessageType(SMS);
+    }
+    if (TYPE_MMS == type) {
+        return MessageType(MMS);
+    }
+    if (TYPE_EMAIL == type) {
+        return MessageType(EMAIL);
+    }
+    std::string exceptionMsg = "Not supported type: ";
+    exceptionMsg += type;
+    throw TypeMismatchException(exceptionMsg.c_str());
+}
+
+string MessagingUtil::messageTypeToString(MessageType type)
+{
+    if (type == MessageType(SMS)) {
+        return TYPE_SMS;
+    }
+    if (type == MessageType(MMS)) {
+        return TYPE_MMS;
+    }
+    if (type == MessageType(EMAIL)) {
+        return TYPE_EMAIL;
+    }
+    throw TypeMismatchException("Invalid MessageType");
+}
+
+MessageStatus MessagingUtil::stringToMessageStatus(std::string status)
+{
+    LOGD("Converting string %s to MessageStatus.", status.c_str());
+    if(status == SENT) {
+        return STATUS_SENT;
+    }
+    if(status == SENDING) {
+        return STATUS_SENDING;
+    }
+    if(status == FAILED) {
+        return STATUS_FAILED;
+    }
+    if(status == DRAFT) {
+        return STATUS_DRAFT;
+    }
+    LOGE("Invalid MessageStatus");
+    throw TypeMismatchException("Invalid MessageStatus");
+}
+
+std::string MessagingUtil::messageStatusToString(MessageStatus status) {
+    LOGD("Converting MessageStatus %d to string.", (int)status);
+    switch(status) {
+        case STATUS_SENT:
+            return SENT;
+        case STATUS_SENDING:
+            return SENDING;
+        case STATUS_FAILED:
+            return FAILED;
+        case STATUS_DRAFT:
+            return DRAFT;
+        default:
+        // According to Web API documentation: If the status of the current
+        // message does not correspond to any item from the list, an empty
+        // value is returned.
+            LOGD("Unsupported or undefined MessageStatus");
+            return "";
+    }
+}
+
+std::string MessagingUtil::ltrim(const std::string& input)
+{
+    std::string str = input;
+    std::string::iterator i;
+    for (i = str.begin(); i != str.end(); i++) {
+        if (!isspace(*i)) {
+            break;
+        }
+    }
+    if (i == str.end()) {
+        str.clear();
+    } else {
+        str.erase(str.begin(), i);
+    }
+    return str;
+}
+
+std::string MessagingUtil::extractSingleEmailAddress(const std::string& address)
+{
+    std::size_t found_begin = address.rfind('<');
+    std::size_t found_end = address.rfind('>');
+    // if both '<' and '>' bracket found and '<' is before '>'
+    // then extract email address from the inside
+    if(found_begin != std::string::npos &&
+            found_end != std::string::npos &&
+            found_begin < found_end) {
+        return address.substr(found_begin+1, found_end-found_begin-1);
+    }
+    else {
+        // return unmodified source string
+        return address;
+    }
+}
+
+std::vector<std::string> MessagingUtil::extractEmailAddresses(
+        const std::vector<std::string>& addresses)
+{
+    std::vector<std::string> extractedAddresses;
+    for(auto it = addresses.begin(); it != addresses.end(); ++it) {
+        extractedAddresses.push_back(MessagingUtil::extractSingleEmailAddress(*it));
+    }
+
+    return extractedAddresses;
+}
+
+std::string MessagingUtil::loadFileContentToString(const std::string& file_path)
+{
+    std::ifstream input_file;
+    input_file.open(file_path, std::ios::in);
+
+    if (input_file.is_open()) {
+        std::string outString;
+        input_file.seekg(0, std::ios::end);
+        outString.reserve(input_file.tellg());
+        input_file.seekg(0, std::ios::beg);
+
+        outString.assign((std::istreambuf_iterator<char>(input_file)),
+                std::istreambuf_iterator<char>());
+        input_file.close();
+        return outString;
+    } else {
+        std::stringstream ss_error_msg;
+        ss_error_msg << "Failed to open file: " << file_path;
+        throw Common::IOException(ss_error_msg.str().c_str());
+    }
+}
+
+}
+}
diff --git a/src/messaging/old/MessagingUtil.h b/src/messaging/old/MessagingUtil.h
new file mode 100644 (file)
index 0000000..aeae2c4
--- /dev/null
@@ -0,0 +1,98 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        MessagingUtil.h
+ */
+
+#ifndef __TIZEN_MESSAGING_UTIL_H__
+#define __TIZEN_MESSAGING_UTIL_H__
+#include <string>
+#include <Logger.h>
+#include <PlatformException.h>
+#include "MessageFolder.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+enum MessageType {
+    UNDEFINED = 0,
+    SMS,
+    MMS,
+    EMAIL
+};
+
+enum MessageStatus {
+    STATUS_UNDEFINED = 0,
+    STATUS_DRAFT,
+    STATUS_SENDING,
+    STATUS_SENT,
+    STATUS_LOADED,
+    STATUS_FAILED
+};
+
+class MessagingUtil {
+public:
+    static std::string messageFolderTypeToString(MessageFolderType);
+
+    static MessageType stringToMessageType(std::string);
+    static std::string messageTypeToString(MessageType);
+
+    static MessageStatus stringToMessageStatus(std::string status);
+    static std::string messageStatusToString(MessageStatus status);
+
+    static std::string ltrim(const std::string& input);
+    static std::string extractSingleEmailAddress(const std::string& address);
+    static std::vector<std::string> extractEmailAddresses(
+            const std::vector<std::string>& addresses);
+
+    /**
+    * Throws Common::IOException when file cannot be opened.
+    *
+    * To increase performance invoke this function this way:
+    * std::string result = loadFileContentToString(...);
+    * Reason: no copy constructor will be invoked on return.
+    */
+    static std::string loadFileContentToString(const std::string& file_path);
+
+    /**
+     * Function converts vector of shared_pointers into JSArray
+     */
+    template<class T, class U>
+    static JSObjectRef vectorToJSObjectArray(JSContextRef context,
+            const std::vector<T> & vec)
+    {
+        size_t count = vec.size();
+
+        JSObjectRef array[count];
+        for (size_t i = 0; i < count; ++i) {
+            array[i] = U::makeJSObject(context, vec[i]);
+        }
+        JSObjectRef result = JSObjectMakeArray(context, count,
+                count > 0 ? array : NULL, NULL);
+        if (!result) {
+            LOGW("Failed to create array");
+            throw Common::UnknownException("Failed to create array");
+        }
+        return result;
+    }
+
+};
+
+}
+}
+#endif // __TIZEN_MESSAGING_UTIL_H__
diff --git a/src/messaging/old/ShortMsgManager.cpp b/src/messaging/old/ShortMsgManager.cpp
new file mode 100644 (file)
index 0000000..3d7feb8
--- /dev/null
@@ -0,0 +1,1234 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <JSWebAPIErrorFactory.h>
+#include <JSWebAPIError.h>
+#include <JSUtil.h>
+#include <Logger.h>
+#include <msg.h>
+#include <msg_transport.h>
+#include <msg_storage.h>
+#include <unordered_set>
+#include <GlobalContextManager.h>
+
+#include "ShortMsgManager.h"
+#include "MessagingUtil.h"
+#include "MessageService.h"
+#include "MessageSMS.h"
+#include "MessageMMS.h"
+#include "JSMessage.h"
+#include "JSMessageConversation.h"
+#include "ChangeListenerContainer.h"
+#include "MessagingDatabaseManager.h"
+#include "Message.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+ShortMsgManager& ShortMsgManager::getInstance()
+{
+    LOGD("Entered");
+
+    static ShortMsgManager instance;
+    return instance;
+}
+
+static gboolean sendMessageCompleteCB(void* data)
+{
+    LOGD("Entered callback:%p", data);
+
+    MessageRecipientsCallbackData* callback =
+            static_cast<MessageRecipientsCallbackData*>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        return false;
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return false;
+    }
+
+    try {
+        if (callback->isError()) {
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(),
+                    callback->getErrorMessage());
+
+            LOGD("Calling error callback with error:%s msg:%s",
+                    callback->getErrorName().c_str(),
+                    callback->getErrorMessage().c_str());
+
+            callback->callErrorCallback(errobj);
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
+        }
+        else {
+            std::shared_ptr<Message> message = callback->getMessage();
+
+            LOGD("Calling success callback with: %d recipients", message->getTO().size());
+            callback->callSuccessCallback(
+                    JSUtil::toJSValueRef(context, message->getTO()));
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_SENT);
+        }
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("Error while calling sendMessage callback: %s (%s)",
+                (err.getName()).c_str(),(err.getMessage()).c_str());
+    }
+    catch (...) {
+        LOGE("Unknown error when calling sendMessage callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+
+    return false;
+}
+
+static gboolean addDraftMessageCompleteCB(void *data)
+{
+    LOGD("Enter");
+    auto callback = static_cast<MessageCallbackUserData *>(data);
+    if (!callback) {
+        LOGE("Callback is null");
+        return FALSE;
+    }
+
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return FALSE;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+            callback->getMessage()->setMessageStatus(MessageStatus::STATUS_FAILED);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling addDraftMessage callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling addDraftMessage callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+
+    return FALSE;
+}
+
+
+void ShortMsgManager::addDraftMessagePlatform(std::shared_ptr<Message> message)
+{
+    LOGD("Add new message(%p)", message.get());
+
+    // Save platform msg to get ID
+    msg_struct_t platform_msg
+            = Message::convertPlatformShortMessageToStruct(message.get(), m_msg_handle);
+    if (NULL == platform_msg) {
+        LOGE("Failed to prepare platform message");
+        throw UnknownException("Cannot prepare platform message");
+    }
+
+    msg_struct_t send_opt = msg_create_struct(MSG_STRUCT_SENDOPT);
+    msg_set_bool_value(send_opt, MSG_SEND_OPT_SETTING_BOOL, false);
+    const int msg_id = msg_add_message(m_msg_handle, platform_msg, send_opt);
+    if (msg_id < MSG_SUCCESS) {
+        LOGE("Message(%p): Failed to add draft, error: %d", message.get(), msg_id);
+        msg_release_struct(&send_opt);
+        msg_release_struct(&platform_msg);
+        throw UnknownException("Cannot add message to draft");
+    }
+
+    LOGD("Message(%p): New message ID: %d", message.get(), msg_id);
+    msg_set_int_value(platform_msg, MSG_MESSAGE_ID_INT, msg_id);
+    message->setId(msg_id);
+    message->setMessageStatus(MessageStatus::STATUS_DRAFT);
+
+    msg_struct_t msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO);
+    msg_error_t err = msg_get_conversation(m_msg_handle, msg_id, msg_conv);
+    if (MSG_SUCCESS == err) {
+        int conversationId = 0;
+        msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT, &conversationId);
+        message->setConversationId(conversationId);
+    } else {
+        LOGE("Message(%p): Failed to get conv", message.get());
+    }
+
+    Message* msgInfo = Message::convertPlatformShortMessageToObject(
+            platform_msg);
+
+    const int folderId = msgInfo->getFolderId();
+    message->setFolderId(folderId);
+
+    const time_t timestamp = msgInfo->getTimestamp();
+    message->setTimeStamp(timestamp);
+
+    const std::string from = msgInfo->getFrom();
+    LOGD("From: %s", from.c_str());
+    message->setFrom(from);
+
+    const bool isRead = msgInfo->getIsRead();
+    message->setIsRead(isRead);
+
+    const int inResponseTo = msgInfo->getInResponseTo();
+    message->setInResponseTo(inResponseTo);
+
+    if (msg_release_struct(&platform_msg) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    if (msg_release_struct(&msg_conv) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    if (msg_release_struct(&send_opt) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    delete msgInfo;
+}
+
+void ShortMsgManager::sendMessage(MessageRecipientsCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int msg_id;
+    Message* msgInfo = NULL;
+    msg_struct_t platform_msg = NULL;
+    msg_struct_t send_opt = NULL;
+    msg_struct_t msg_conv = NULL;
+    msg_struct_t req = NULL;
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+
+        std::shared_ptr<Message> message = callback->getMessage();
+        MessageStatus msg_status = message->getMessageStatus();
+        int ret = MSG_ERR_UNKNOWN;
+
+        // if it is draft message just send it
+        // in other case create new platform message
+        // add it to draft and finally send it
+        if (!( message->is_id_set() && MessageStatus::STATUS_DRAFT == msg_status)) {
+            LOGD("Add message to draft");
+            addDraftMessagePlatform(message);
+        }
+
+        msg_id = message->getId();
+        LOGD("Message ID: %d", msg_id);
+
+        platform_msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+        send_opt = msg_create_struct(MSG_STRUCT_SENDOPT);
+        msg_conv = msg_create_struct(MSG_STRUCT_CONV_INFO);
+        ret = msg_get_message(m_msg_handle, msg_id, platform_msg, send_opt);
+        if (MSG_SUCCESS != ret) {
+            LOGE("Failed to get platform message structure: %d", ret);
+            throw UnknownException("Cannot get platform Message structure");
+        }
+
+        // Send message
+        message->setMessageStatus(MessageStatus::STATUS_SENDING);
+        req = msg_create_struct(MSG_STRUCT_REQUEST_INFO);
+        msg_set_struct_handle(req, MSG_REQUEST_MESSAGE_HND, platform_msg);
+
+        int req_id = -1;
+        ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id);
+        if (MSG_SUCCESS != ret) {
+            LOGE("Failed to get send request ID: %d", ret);
+            throw UnknownException("Failed to get send request ID");
+        }
+
+        if (MessageType::MMS == message->getType()) {
+            LOGD("Send MMS message");
+            ret = msg_mms_send_message(m_msg_handle, req);
+        }
+        else if (MessageType::SMS == message->getType()) {
+            LOGD("Send SMS message");
+            ret = msg_sms_send_message(m_msg_handle, req);
+        }
+        else {
+            LOGE("Invalid message type: %d", message->getType());
+            throw TypeMismatchException("Invalid message type");
+        }
+
+        if (ret != MSG_SUCCESS) {
+            LOGE("Failed to send message: %d", ret);
+            throw UnknownException("Failed to send message");
+        }
+
+        ret = msg_get_int_value(req, MSG_REQUEST_REQUESTID_INT, &req_id);
+        if (ret != MSG_SUCCESS) {
+            LOGE("Failed to get message request ID: %d", ret);
+            throw UnknownException("Failed to get send request");
+        }
+        LOGD("req_id: %d", req_id);
+
+        msgInfo = Message::convertPlatformShortMessageToObject(platform_msg);
+
+        int conversationId;
+        ret = msg_get_conversation(m_msg_handle, msg_id, msg_conv);
+        if (MSG_SUCCESS != ret) {
+            LOGE("Failed to get conv");
+        }
+        msg_get_int_value(msg_conv, MSG_CONV_MSG_THREAD_ID_INT,
+                &conversationId);
+        message->setConversationId(conversationId);
+
+        int folderId = msgInfo->getFolderId();
+        message->setFolderId(folderId);
+
+        time_t timestamp = msgInfo->getTimestamp();
+        message->setTimeStamp(timestamp);
+
+        std::string from = msgInfo->getFrom();
+        LOGD("From:%s", from.c_str());
+        message->setFrom(from);
+
+        bool isRead = msgInfo->getIsRead();
+        message->setIsRead(isRead);
+
+        int inResponseTo = msgInfo->getInResponseTo();
+        message->setInResponseTo(inResponseTo);
+
+        m_sendRequests[req_id] = callback;
+        LOGD("Send MSG_SUCCESS");
+    }
+    catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
+            LOGE("g_idle addition failed");
+            delete callback;
+            callback = NULL;
+        }
+    }
+    catch (...) {
+        LOGE("Message send failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message send failed");
+        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
+            LOGE("g_idle addition failed");
+            delete callback;
+            callback = NULL;
+        }
+    }
+
+    if (msg_release_struct(&req) != MSG_SUCCESS) {
+        LOGW("Request structure is already destroyed");
+    }
+    if (msg_release_struct(&platform_msg) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    if (msg_release_struct(&send_opt) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    if (msg_release_struct(&msg_conv) != MSG_SUCCESS) {
+        LOGW("Platform message is already destroyed");
+    }
+    delete msgInfo;
+
+    return;
+}
+
+void ShortMsgManager::sendStatusCallback(msg_struct_t sent_status)
+{
+    int reqId = 0;
+    int status = MSG_NETWORK_NOT_SEND;
+
+    msg_get_int_value(sent_status, MSG_SENT_STATUS_REQUESTID_INT, &reqId);
+    LOGD("Send msg %d", reqId);
+    msg_get_int_value(sent_status, MSG_SENT_STATUS_NETWORK_STATUS_INT, &status);
+    LOGD("Send msg status: %d", status);
+
+    if(MSG_NETWORK_SEND_SUCCESS != status
+        && MSG_NETWORK_SEND_FAIL != status
+        && MSG_NETWORK_SEND_TIMEOUT != status)
+    {
+        LOGD("Not final status, return");
+        return;
+    }
+
+    std::lock_guard<std::mutex> lock(m_mutex);
+    SendReqMap::iterator it = m_sendRequests.find(reqId);
+    if (it != m_sendRequests.end()) {
+        LOGD("Matching request found");
+
+        MessageRecipientsCallbackData* callback = it->second;
+        m_sendRequests.erase(it);
+
+        if (MSG_NETWORK_SEND_FAIL == status
+                || MSG_NETWORK_SEND_TIMEOUT == status) {
+            LOGE("req_id:%d : Failed sending Message(%p) with msg_id:%d msg status is: %s",
+                reqId,
+                callback->getMessage().get(),
+                callback->getMessage()->getId(),
+                (MSG_NETWORK_SEND_FAIL == status ? "FAIL" : "TIMEOUT"));
+
+            callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR,
+                    "Send message failed");
+        }
+
+        if (!g_idle_add(sendMessageCompleteCB, static_cast<void*>(callback))) {
+            LOGE("g_idle addition failed");
+            delete callback;
+            callback = NULL;
+        }
+    }
+    else {
+        LOGE("No matching request found");
+    }
+
+    return;
+}
+
+static void sent_status_cb(msg_handle_t handle,
+        msg_struct_t sent_status,
+        void *data)
+{
+    LOGD("Entered");
+    ShortMsgManager::getInstance().sendStatusCallback(sent_status);
+
+    return;
+}
+
+void ShortMsgManager::callProperEventMessages(EventMessages* event,
+        msg_storage_change_type_t storageChangeType)
+{
+    LOGD("Entered event.items.size()=%d event.removed_conversations.size()=%d"
+            " sChangeType:%d", event->items.size(),
+            event->removed_conversations.size(), storageChangeType);
+
+    EventConversations* eventConv = new EventConversations();
+    eventConv->service_id = event->service_id;
+    eventConv->service_type = event->service_type;
+
+    if(MSG_STORAGE_CHANGE_DELETE == storageChangeType) {
+        eventConv->items = event->removed_conversations;
+    } else {
+        eventConv->items = ShortMsgManager::getConversationsForMessages(
+                event->items, storageChangeType);
+    }
+
+    switch (storageChangeType) {
+        case MSG_STORAGE_CHANGE_INSERT: {
+            ChangeListenerContainer::getInstance().callMessageAdded(event);
+            if (!eventConv->items.empty()) {
+
+                ConversationPtrVector added_conv;
+                ConversationPtrVector updated_conv;
+
+                for(ConversationPtrVector::iterator it = eventConv->items.begin();
+                        it != eventConv->items.end(); it++) {
+                    ConversationPtr cur_conv = *it;
+                    const bool new_conv = (cur_conv->getMessageCount() <= 1);
+                    if(new_conv) {
+                        added_conv.push_back(cur_conv);
+                    } else {
+                        updated_conv.push_back(cur_conv);
+                    }
+
+                    LOGD("%s conversation with id:%d last_msg_id:d",
+                            (new_conv ? "ADDED" : "UPDATED"),
+                            cur_conv->getConversationId(), cur_conv->getLastMessageId());
+                }
+
+                LOGD("num conversations:all=%d added=%d update=%d", eventConv->items.size(),
+                        added_conv.size(), updated_conv.size());
+
+                if(false == added_conv.empty()) {
+                    LOGD("%d new conversations, calling onConversationAdded",
+                            added_conv.size());
+                    eventConv->items = added_conv;
+                    ChangeListenerContainer::getInstance().callConversationAdded(
+                            eventConv);
+                }
+
+                if(false == updated_conv.empty()) {
+                    LOGD("%d updated conversation, calling onConversationUpdated",
+                            updated_conv.size());
+                    eventConv->items = updated_conv;
+                    ChangeListenerContainer::getInstance().callConversationUpdated(
+                            eventConv);
+                }
+
+            }
+        } break;
+        case MSG_STORAGE_CHANGE_DELETE: {
+            ChangeListenerContainer::getInstance().callMessageRemoved(event);
+
+            if(false == eventConv->items.empty()) {
+                LOGD("At least one conversation will be deleted, "
+                     "triggering also onConversationRemoved");
+                ChangeListenerContainer::getInstance().callConversationRemoved(eventConv);
+            }
+        } break;
+        case MSG_STORAGE_CHANGE_UPDATE: {
+            ChangeListenerContainer::getInstance().callMessageUpdated(event);
+            ChangeListenerContainer::getInstance().callConversationUpdated(eventConv);
+        } break;
+        default:
+            LOGW("Unknown storageChangeType: %d", storageChangeType);
+    }
+    delete event;
+    delete eventConv;
+}
+
+void ShortMsgManager::storage_change_cb(msg_handle_t handle,
+        msg_storage_change_type_t storageChangeType,
+        msg_id_list_s *pMsgIdList,
+        void* data)
+{
+    LOGD("Entered handle:%p sChangeType:%d numMsgs:%d", handle, storageChangeType,
+            pMsgIdList->nCount);
+
+    if (MSG_STORAGE_CHANGE_CONTACT == storageChangeType) {
+        LOGD("storageChangeType is MSG_STORAGE_CHANGE_CONTACT, ignoring");
+        return;
+    }
+
+    if (pMsgIdList->nCount < 1) {
+        LOGW("no messages in callback list");
+        return;
+    }
+
+    LOGD("Messages count %d", pMsgIdList->nCount);
+
+    /*
+     * There is possibility that in one callback from msg service will come
+     * SMS and MMS messages in the same list. ChangeListenerContainer requires
+     * that messages in event have common service_id and service_type. So we
+     * create here 2 events: one for SMS and one for MMS. If one of events
+     * has empty message list, we won't trigger it.
+     */
+    EventMessages* eventSMS = NULL;
+    EventMessages* eventMMS = NULL;
+    try {
+        // if allocation below fails than exception is thrown - no NULL check
+        eventSMS = new EventMessages();
+        eventSMS->service_type = MessageType::SMS;
+        eventSMS->service_id = SMS_ACCOUNT_ID;
+        eventMMS = new EventMessages();
+        eventMMS->service_type = MessageType::MMS;
+        eventMMS->service_id = MMS_ACCOUNT_ID;
+
+        if (MSG_STORAGE_CHANGE_DELETE == storageChangeType) {
+
+            ShortMsgManager& msg_manager = ShortMsgManager::getInstance();
+            std::lock_guard<std::mutex> lock(msg_manager.m_mutex);
+
+            std::map<int, MessagePtr>* rem_msgs[2] = {  // Recently removed messages
+                    &msg_manager.m_sms_removed_messages,
+                    &msg_manager.m_mms_removed_messages };
+            std::map<int, int>* rem_convs[2] = { // Recently removed conversations
+                    &msg_manager.m_sms_removed_msg_id_conv_id_map,
+                    &msg_manager.m_mms_removed_msg_id_conv_id_map };
+            EventMessages* dest_event[2] = { // SMS/MMS EventMessage to be propagated
+                    eventSMS,
+                    eventMMS };
+            std::map<int, ConversationPtr>* conv_map[2] = { //Map conversationId - object
+                    &msg_manager.m_sms_removed_conv_id_object_map,
+                    &msg_manager.m_mms_removed_conv_id_object_map };
+
+            for(int event_i = 0; event_i < 2; ++event_i) {
+
+                std::map<int, MessagePtr>& cur_rem_msgs = *(rem_msgs[event_i]);
+                std::map<int, int>& cur_rem_convs = *(rem_convs[event_i]);
+                EventMessages* cur_dest_event = dest_event[event_i];
+                std::map<int, ConversationPtr>& cur_conv_map = *(conv_map[event_i]);
+                std::unordered_set<int> conv_rem_now;
+
+                for (int i = 0; i < pMsgIdList->nCount; ++i) {
+                    const msg_message_id_t& msg_id = pMsgIdList->msgIdList[i];
+                    LOGD("pMsgIdList[%d] = %d", i, msg_id);
+
+                    std::map<int, MessagePtr> ::iterator it = cur_rem_msgs.find(msg_id);
+                    if(it != cur_rem_msgs.end()) {
+                        LOGD("[%d] is %s, Pushing message with id:%d subject:%s", i,
+                                (0 == i) ? "SMS" : "MMS",
+                                it->second->getId(),
+                                it->second->getSubject().c_str());
+                        cur_dest_event->items.push_back(it->second);
+                        cur_rem_msgs.erase(it);
+                    }
+
+                    std::map<int, int>::iterator cit = cur_rem_convs.find(msg_id);
+                    if(cit != cur_rem_convs.end()) {
+                        conv_rem_now.insert(cit->second);
+                        cur_rem_convs.erase(cit);
+                    }
+                }
+
+                for (auto it = conv_rem_now.begin(); it != conv_rem_now.end(); it++) {
+                    const int cur_rem_conv_id = *it;
+
+                    //---------------------------------------------------------------------
+                    // Check if we have removed last message from conversation
+                    //
+                    bool found = false;
+                    for(auto it2 = cur_rem_convs.begin();
+                            it2 != cur_rem_convs.end();
+                            it2++) {
+                        if( cur_rem_conv_id == it2->second) {
+                            found = true;
+                            break;
+                        }
+                    }
+
+                    if(false == found) {
+                        //We have removed last message from conversation
+
+                        std::map<int, ConversationPtr>::iterator conv_it =
+                            cur_conv_map.find(cur_rem_conv_id);
+                        if(conv_it != cur_conv_map.end()) {
+                            LOGD("Pushing removed %s MessageConversation(%p) with id:%d",
+                                    (0 == event_i) ? "SMS" : "MMS",
+                                    conv_it->second.get(), cur_rem_conv_id);
+
+                            cur_dest_event->removed_conversations.push_back(
+                                conv_it->second);
+                            cur_conv_map.erase(conv_it);
+                        } else {
+                            LOGW("Couldn't find ConversationPtr object with id:%d",
+                                    cur_rem_conv_id);
+                        }
+                    }
+                }
+            }
+
+        } else {
+            for (int i = 0; i < pMsgIdList->nCount; ++i) {
+
+                msg_struct_t msg = ShortMsgManager::getInstance().getMessage(
+                        pMsgIdList->msgIdList[i]);
+                if (NULL == msg) {
+                    LOGE("Failed to load short message");
+                    delete eventSMS;
+                    eventSMS = NULL;
+                    delete eventMMS;
+                    eventMMS = NULL;
+                    throw Common::UnknownException("Failed to load short message");
+                }
+                std::shared_ptr<Message> message(
+                        Message::convertPlatformShortMessageToObject(msg));
+                msg_release_struct(&msg);
+                switch (message->getType()) {
+                    case MessageType::SMS:
+                        eventSMS->items.push_back(message);
+                        break;
+                    case MessageType::MMS:
+                        eventMMS->items.push_back(message);
+                        break;
+                    default:
+                        LOGE("Unsupported message type");
+                        delete eventSMS;
+                        eventSMS = NULL;
+                        delete eventMMS;
+                        eventMMS = NULL;
+                        throw Common::UnknownException("Unsupported message type");
+                }
+            }
+        }
+
+        if (!eventSMS->items.empty() || !eventSMS->removed_conversations.empty()) {
+            ShortMsgManager::callProperEventMessages(eventSMS, storageChangeType);
+        } else {
+            LOGD("No SMS messages, not triggering eventSMS");
+            delete eventSMS;
+            eventSMS = NULL;
+        }
+        if (!eventMMS->items.empty() || !eventMMS->removed_conversations.empty()) {
+            ShortMsgManager::callProperEventMessages(eventMMS, storageChangeType);
+        } else {
+            LOGD("No MMS messages, not triggering eventMMS");
+            delete eventMMS;
+            eventMMS = NULL;
+        }
+
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        delete eventSMS;
+        delete eventMMS;
+    } catch (...) {
+        LOGE("Failed to call callback");
+        delete eventSMS;
+        delete eventMMS;
+    }
+}
+
+void ShortMsgManager::registerStatusCallback(msg_handle_t msg_handle)
+{
+    m_msg_handle = msg_handle;
+    // set message sent status callback
+    if (MSG_SUCCESS != msg_reg_sent_status_callback(m_msg_handle,
+            &sent_status_cb, NULL)) {
+        LOGE("sent status callback register error!!!");
+    }
+    if (MSG_SUCCESS != msg_reg_storage_change_callback(m_msg_handle,
+            &storage_change_cb, NULL)) {
+        LOGE("storage change callback register error!");
+    }
+}
+
+void ShortMsgManager::addDraftMessage(MessageCallbackUserData* callback)
+{
+    LOGD("Enter");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::shared_ptr<Message> message = callback->getMessage();
+
+        addDraftMessagePlatform(message);
+
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Message add draft failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
+    }
+
+    // Complete task
+    if (!g_idle_add(addDraftMessageCompleteCB, static_cast<void *>(callback))) {
+        LOGE("g_idle addition failed");
+        delete callback;
+        callback = NULL;
+    }
+}
+
+void ShortMsgManager::removeMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int error;
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
+        MessageType type = callback->getMessageServiceType();
+        for(auto it = messages.begin() ; it != messages.end(); ++it) {
+            if((*it)->getType() != type) {
+                LOGE("Invalid message type: %d", (*it)->getType());
+                throw TypeMismatchException("Error while deleting message");
+            }
+        }
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+
+            const int id = (*it)->getId();
+
+            //Store message object
+            LOGD("Storing removed message (id:%d) in m_removed_messages", id);
+            switch((*it)->getType()) {
+
+                case SMS:  m_sms_removed_messages[id] = (*it); break;
+                case MMS:  m_mms_removed_messages[id] = (*it); break;
+                default:
+                    LOGD("Unknown message type: %d", (*it)->getType());
+                    break;
+            }
+
+            error = msg_delete_message(m_msg_handle, id);
+            if (MSG_SUCCESS != error) {
+                LOGE("Error while deleting message");
+                throw UnknownException("Error while deleting message");
+            }
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages remove failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling removeShortMsg callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling removeShortMsg callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+void ShortMsgManager::updateMessages(MessagesCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    LOGD("messages to update: %d", callback->getMessages().size());
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<std::shared_ptr<Message>> messages = callback->getMessages();
+        MessageType type = callback->getMessageServiceType();
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+            if ((*it)->getType() != type) {
+                LOGE("Invalid message type");
+                throw TypeMismatchException("Error while updating message");
+            }
+        }
+        for (auto it = messages.begin() ; it != messages.end(); ++it) {
+
+            LOGD("updating Message(%p) msg_id:%d", (*it).get(), (*it)->getId());
+
+            msg_struct_t platform_msg
+                    = Message::convertPlatformShortMessageToStruct(it->get(), m_msg_handle);
+            if (NULL == platform_msg) {
+                LOGE("Failed to prepare platform message");
+                throw UnknownException("Cannot prepare platform message");
+            }
+            msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
+            int error = msg_update_message(m_msg_handle, platform_msg, sendOpt);
+            msg_release_struct(&platform_msg);
+            msg_release_struct(&sendOpt);
+            if (error != MSG_SUCCESS) {
+                LOGE("Failed to update message %d", (*it)->getId());
+                throw UnknownException("Error while updating message");
+            }
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages update failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages update failed");
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling updateShortMsg callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling updateShortMsg callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+msg_struct_t ShortMsgManager::getMessage(int msg_id)
+{
+    msg_struct_t sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
+    msg_struct_t msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+    int error = msg_get_message(m_msg_handle, msg_id, msg, sendOpt);
+    if (MSG_SUCCESS != error) {
+        LOGE("Couldn't retrieve message from service, msgId: %d, error:%d", msg_id, error);
+        throw Common::UnknownException("Couldn't retrieve message from service");
+    }
+    msg_release_struct(&sendOpt);
+    return msg;
+}
+
+ConversationPtrVector ShortMsgManager::getConversationsForMessages(
+        MessagePtrVector messages,
+        msg_storage_change_type_t storageChangeType)
+{
+    LOGD("Entered messages.size()=%d storageChangeType=%d", messages.size(),
+            storageChangeType);
+
+    std::unordered_set<int> unique_conv_ids;
+    ConversationPtrVector convs;
+    for (auto it = messages.begin(); it != messages.end(); ++it) {
+
+        MessagePtr msg = (*it);
+        const int conv_id = msg->getConversationId();
+        const int count = unique_conv_ids.count(conv_id);
+        LOGD("Message(%p) msg_id:%d conversationId: %d count:%d", msg.get(),
+                msg->getId(), conv_id, count);
+
+        if (0 == count) {
+            //conversation isn't loaded yet
+            unique_conv_ids.insert(conv_id);
+            ConversationPtr conv = MessageConversation::convertMsgConversationToObject(
+                    conv_id, ShortMsgManager::getInstance().m_msg_handle);
+
+            LOGD("Pushed conv=%p", conv.get());
+            convs.push_back(conv);
+        }
+    }
+    return convs;
+}
+
+void ShortMsgManager::findMessages(FindMsgCallbackUserData* callback)
+{
+    LOGD("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<int> messagesIds =
+                MessagingDatabaseManager::getInstance().findShortMessages(callback);
+        int msgListCount = messagesIds.size();
+        LOGD("Found %d messages", msgListCount);
+
+        msg_struct_t msg;
+        msg_struct_t sendOpt;
+        msg_error_t err;
+        for (int i = 0; i < msgListCount; i++) {
+            msg = msg_create_struct(MSG_STRUCT_MESSAGE_INFO);
+            sendOpt = msg_create_struct(MSG_STRUCT_SENDOPT);
+            err = msg_get_message(m_msg_handle, messagesIds.at(i), msg, sendOpt);
+
+            if (MSG_SUCCESS != err) {
+                LOGE("Failed to get platform message structure: %d", err);
+                throw UnknownException("Cannot get platform Message structure");
+            }
+
+            try {
+                std::shared_ptr<Message> message(
+                    Message::convertPlatformShortMessageToObject(msg));
+                callback->addMessage(message);
+
+                LOGD("Created message with id %d:", messagesIds[i]);
+            }
+            catch(const Common::InvalidValuesException& exception) {
+                //Ignore messages with not supported/unrecognized type
+            }
+
+            msg_release_struct(&sendOpt);
+            msg_release_struct(&msg);
+        }
+
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Message add draft failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback with %d messages:",
+                    callback->getMessages().size());
+            callback->callSuccessCallback(JSMessage::messageVectorToJSObjectArray(context,
+                    callback->getMessages()));
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling findMessages callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Failed to call findMessages callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+void ShortMsgManager::findConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if(!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        std::vector<int> conversationsIds =
+                MessagingDatabaseManager::getInstance().findShortMessageConversations(callback);
+        int convListCount = conversationsIds.size();
+        LOGD("Found %d conversations", convListCount);
+
+        for (int i = 0; i < convListCount; i++) {
+            std::shared_ptr<MessageConversation> conversation =
+                    MessageConversation::convertMsgConversationToObject(
+                            conversationsIds.at(i), m_msg_handle);
+
+            callback->addConversation(conversation);
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Message add draft failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Message add draft failed");
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback(MessagingUtil::vectorToJSObjectArray<
+                    ConversationPtr, JSMessageConversation>(context, callback->getConversations()));
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling findConversations callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Failed to call findConversations callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+void ShortMsgManager::removeConversations(ConversationCallbackData* callback)
+{
+    LOGD("Entered");
+
+    if (!callback){
+        LOGE("Callback is null");
+        return;
+    }
+
+    int error = MSG_SUCCESS;
+    msg_handle_t handle = NULL;
+
+    try {
+        std::lock_guard<std::mutex> lock(m_mutex);
+        ConversationPtrVector conversations = callback->getConversations();
+        const MessageType type = callback->getMessageServiceType();
+
+        error = msg_open_msg_handle(&handle);
+        if (MSG_SUCCESS != error) {
+            LOGE("Open message handle error: %d", error);
+            throw UnknownException("Error while creatng message handle");
+        }
+
+        for(auto it = conversations.begin() ; it != conversations.end(); ++it) {
+            if((*it)->getType() != type) {
+                LOGE("Invalid message type");
+                throw TypeMismatchException("Error while deleting message conversation");
+            }
+        }
+
+        std::map<int, int>* msg_id_conv_id_map = NULL;
+        std::map<int, ConversationPtr>* conv_id_object_map = NULL;
+        if(MessageType::SMS == type) {
+            msg_id_conv_id_map = &m_sms_removed_msg_id_conv_id_map;
+            conv_id_object_map = &m_sms_removed_conv_id_object_map;
+        } else if(MessageType::MMS == type) {
+            msg_id_conv_id_map = &m_mms_removed_msg_id_conv_id_map;
+            conv_id_object_map = &m_mms_removed_conv_id_object_map;
+        } else {
+            LOGE("Invalid message type:%d for ShortMsgManager!", type);
+            throw UnknownException("Invalid message type for ShortMsgManager!");
+        }
+
+        int conv_index = 0;
+        for (auto it = conversations.begin() ; it != conversations.end();
+                    ++it, ++conv_index) {
+
+            ConversationPtr conv = (*it);
+            msg_thread_id_t conv_id = conv->getConversationId();
+
+            LOGD("[%d] MessageConversation(%p) conv_id:%d", conv_index, conv.get(),
+                    conv_id);
+
+            msg_struct_list_s conv_view_list;
+            error = msg_get_conversation_view_list(handle, (msg_thread_id_t)conv_id,
+                    &conv_view_list);
+            if (MSG_SUCCESS == error) {
+                for(int msg_index = 0; msg_index < conv_view_list.nCount; ++msg_index)
+                {
+                    int cur_msg_id = 0;
+                    error = msg_get_int_value(conv_view_list.msg_struct_info[msg_index],
+                            MSG_CONV_MSG_ID_INT, &cur_msg_id);
+
+                    if(MSG_SUCCESS == error && cur_msg_id > 0) {
+                        (*msg_id_conv_id_map)[cur_msg_id] = conv_id;
+                        (*conv_id_object_map)[conv_id] = conv;
+
+                        LOGD("[%d] message[%d] msg_id:%d,"
+                                "saved MessageConversation(%p) with conv_id:%d",
+                                conv_index, msg_index, cur_msg_id, conv.get(), conv_id);
+                    } else {
+                        LOGE("[%d] Couldn't get msg_id, error: %d!", error);
+                    }
+                }
+            } else {
+                LOGE("[%d] Couldn' get conversation view list for conv_id:%d error: %d",
+                        conv_index, conv_id, error);
+            }
+
+            msg_release_list_struct(&conv_view_list);
+
+            error = msg_delete_thread_message_list(handle, (msg_thread_id_t) conv_id,
+                    FALSE);
+            if (MSG_SUCCESS != error) {
+                LOGE("Error while deleting message conversation");
+                throw UnknownException("Error while deleting message conversation");
+            }
+
+        }
+
+    } catch (const BasePlatformException& err) {
+        LOGE("%s (%s)", (err.getName()).c_str(), (err.getMessage()).c_str());
+        callback->setError(err.getName(), err.getMessage());
+    } catch (...) {
+        LOGE("Messages remove failed");
+        callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "Messages remove failed");
+    }
+
+    error = msg_close_msg_handle(&handle);
+    if (MSG_SUCCESS != error) {
+        LOGW("Cannot close message handle: %d", error);
+    }
+
+    //Complete task
+    JSContextRef context = callback->getContext();
+    if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) {
+        LOGE("context was closed");
+        delete callback;
+        callback = NULL;
+        return;
+    }
+
+    try {
+        if (callback->isError()) {
+            LOGD("Calling error callback");
+            JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context,
+                    callback->getErrorName(), callback->getErrorMessage());
+            callback->callErrorCallback(errobj);
+        } else {
+            LOGD("Calling success callback");
+            callback->callSuccessCallback();
+        }
+    } catch (const BasePlatformException& err) {
+        LOGE("Error while calling removeConversations callback: %s (%s)",
+                (err.getName()).c_str(), (err.getMessage()).c_str());
+    } catch (...) {
+        LOGE("Unknown error when calling removeConversations callback.");
+    }
+
+    delete callback;
+    callback = NULL;
+}
+
+ShortMsgManager::ShortMsgManager() : m_msg_handle(NULL)
+{
+    LOGD("Entered");
+}
+
+ShortMsgManager::~ShortMsgManager()
+{
+    LOGD("Entered");
+    LOGD("m_sms_removed_messages.size() = %d",
+            m_sms_removed_messages.size());
+    LOGD("m_mms_removed_messages.size() = %d",
+            m_mms_removed_messages.size());
+    LOGD("m_sms_removed_msg_id_conv_id_map.size() = %d",
+            m_sms_removed_msg_id_conv_id_map.size());
+    LOGD("m_sms_removed_conv_id_object_map.size() = %d",
+            m_sms_removed_conv_id_object_map.size());
+    LOGD("m_mms_removed_msg_id_conv_id_map.size() = %d",
+            m_mms_removed_msg_id_conv_id_map.size());
+    LOGD("m_mms_removed_conv_id_object_map.size() = %d",
+            m_mms_removed_conv_id_object_map.size());
+}
+
+
+} // Messaging
+} // DeviceAPI
diff --git a/src/messaging/old/ShortMsgManager.h b/src/messaging/old/ShortMsgManager.h
new file mode 100755 (executable)
index 0000000..6f17f06
--- /dev/null
@@ -0,0 +1,134 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef __TIZEN_SEND_SHORT_MSG_MANAGER_H__
+#define __TIZEN_SEND_SHORT_MSG_MANAGER_H__
+
+#include <glib.h>
+#include <mutex>
+#include <map>
+
+#include <msg_storage_types.h>
+#include <CallbackUserData.h>
+#include <PlatformException.h>
+#include <msg_types.h>
+
+#include "ChangeListenerContainer.h"
+#include "MessagingUtil.h"
+#include "MessageService.h"
+#include "Message.h"
+#include "MessageConversation.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+class Message;
+class FindMsgCallbackUserData;
+
+class ShortMsgManager {
+public:
+    static ShortMsgManager& getInstance();
+
+    void sendMessage(MessageRecipientsCallbackData* callback);
+    void sendStatusCallback(msg_struct_t sent_status);
+
+    void addDraftMessage(MessageCallbackUserData* callback);
+    void findMessages(FindMsgCallbackUserData* callback);
+    void findConversations(ConversationCallbackData* callback);
+    void removeConversations(ConversationCallbackData* callback);
+
+    void registerStatusCallback(msg_handle_t msg_handle);
+
+    void removeMessages(MessagesCallbackUserData* callback);
+    void updateMessages(MessagesCallbackUserData* callback);
+    msg_struct_t getMessage(int msg_id);
+private:
+    ShortMsgManager();
+    ShortMsgManager(const ShortMsgManager &);
+    void operator=(const ShortMsgManager &);
+    virtual ~ShortMsgManager();
+
+    /**
+     * Listener for msg storage changes. Calls callbacks from ChangeListenerContainer.
+     * @param handle
+     * @param storageChangeType
+     * @param pMsgIdList
+     * @param data
+     */
+    static void storage_change_cb(msg_handle_t handle,
+        msg_storage_change_type_t storageChangeType,
+        msg_id_list_s *pMsgIdList,
+        void* data);
+
+    void addDraftMessagePlatform(std::shared_ptr<Message> message);
+    /**
+     * Returns unique list of conversations for given vector of messages.
+     * storageChangeType is needed to filter conversations returned:
+     * - for MSG_STORAGE_CHANGE_UPDATE all conversations are fetched
+     * - for MSG_STORAGE_CHANGE_INSERT only conversations with 1 message are returned
+     * - for MSG_STORAGE_CHANGE_DELETE  only conversations with 1 message are returned
+     * @param messages
+     * @param storageChangeType
+     * @return
+     */
+    static ConversationPtrVector getConversationsForMessages(
+            MessagePtrVector messages,
+            msg_storage_change_type_t storageChangeType);
+    static void callProperEventMessages(EventMessages* event,
+            msg_storage_change_type_t storageChangeType);
+    typedef std::map<msg_request_id_t, MessageRecipientsCallbackData*> SendReqMap;
+    SendReqMap m_sendRequests;
+    msg_handle_t m_msg_handle;
+
+    /**
+     * Map MessageId - Message object of recently removed SMS messages
+     */
+    std::map<int, MessagePtr> m_sms_removed_messages;
+
+    /**
+     * Map MessageId - Message object of recently removed MMS messages
+     */
+    std::map<int, MessagePtr> m_mms_removed_messages;
+
+
+
+    /**
+     * Map MessageId - ConversationId for SMS messages (only from removed conversation)
+     */
+    std::map<int, int> m_sms_removed_msg_id_conv_id_map;
+
+    /**
+     * Map ConversationId - ConversationPtr object (only removed) for SMS
+     */
+    std::map<int, ConversationPtr> m_sms_removed_conv_id_object_map;
+
+    /**
+     * Map MessageId - ConversationId for MMS messages (only from removed conversation)
+     */
+    std::map<int, int> m_mms_removed_msg_id_conv_id_map;
+
+    /**
+     * Map ConversationId - ConversationPtr object (only removed) for MMS
+     */
+    std::map<int, ConversationPtr> m_mms_removed_conv_id_object_map;
+
+    std::mutex m_mutex;
+};
+
+} // Messaging
+} // DeviceAPI
+#endif // __TIZEN_SEND_SHORT_MSG_MANAGER_H__
diff --git a/src/messaging/old/TestScripts/addConversationsChangeListener_01.js b/src/messaging/old/TestScripts/addConversationsChangeListener_01.js
new file mode 100644 (file)
index 0000000..285c8b7
--- /dev/null
@@ -0,0 +1,121 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        addConversationsChangeListener_01.js
+ */
+
+//
+//
+//  Attribute      | Attribute filter| Attribute range filter
+//                 | supported       | supported
+// ----------------+-----------------+------------------------
+// id              | Yes             | No
+// type            | Yes             | No
+// timestamp       | No              | Yes
+// messageCount    | Yes             | No
+// unreadMessages  | Yes             | No
+// preview         | Yes             | No
+// subject         | No              | No
+// isRead          | No              | No
+// from            | Yes             | No
+// to              | Yes             | No
+// cc              | No              | No
+// bcc             | No              | No
+// lastMessageId   | No              | No
+
+
+var prefferedEmailService = "a.jacak.testmail";
+
+function containCaseInsensitive(string, searchString) {
+    var lcString = string.toLowerCase();
+    var lcSearchString = searchString.toLowerCase();
+    return lcString.indexOf(lcSearchString)>=0;
+}
+
+var currentService = null;
+
+function listConversations(prefix, conversations) {
+
+    for (var i=0; i<conversations.length; i++) {
+        var conversation = conversations[i];
+        console.log(prefix + " CONVERSATION[" + i + "] " +
+                " id: " + conversation.id +
+                " type: " + conversation.type +
+                " timestamp: " + conversation.timestamp +
+                " messageCount: " + conversation.messageCount +
+                " unreadMessages: " + conversation.unreadMessages +
+                " preview: " + conversation.preview +
+                " subject:" + conversation.subject +
+                " isRead: " + conversation.isRead +
+                " from: " + conversation.from +
+                " lastMessageId: " + conversation.lastMessageId);
+    }
+}
+
+var conversationChangeCB = {
+    conversationsupdated: function(conversations) {
+        console.log(conversations.length + " conversation(s) updated");
+        listConversations("conversationsupdated", conversations);
+    },
+    conversationsadded: function(conversations) {
+        console.log(conversations.length + " conversation(s) added");
+        listConversations("conversationsadded", conversations);
+    },
+    conversationsremoved: function(conversations) {
+        console.log(conversations.length + " conversation(s) removed");
+        listConversations("conversationsremoved", conversations);
+    }
+};
+
+function serviceSyncSuccessCB() {
+    console.log("Synced!");
+}
+
+function serviceSyncFailCB() {
+    console.log("Sync failed!");
+}
+
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+
+        var chosenServiceIndex = 0;
+        for(var i = 0; i < services.length; i++) {
+            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
+                chosenServiceIndex = i;
+                console.log("servicesListSuccessCB: " +
+                        "found service which name contains: " +
+                        prefferedEmailService);
+                break;
+            }
+        }
+        currentService = services[chosenServiceIndex];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+
+        var filter = new tizen.AttributeFilter("preview", "CONTAINS", "Home");
+        currentService.messageStorage.addConversationsChangeListener(
+                conversationChangeCB, filter);
+
+        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/src/messaging/old/TestScripts/addFoldersChangeListener_01.js b/src/messaging/old/TestScripts/addFoldersChangeListener_01.js
new file mode 100644 (file)
index 0000000..f669a7e
--- /dev/null
@@ -0,0 +1,112 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// Please send two emails with subject containing "Alaska"
+//  1. subject "Alaska Good" and body containing "hack"
+//  2. subject "Alaska Bad" and body NOT containing "hack"
+//
+// Only 1. should printed in JS console.
+
+/**
+ * @file        addFoldersChangeListener_01.js
+ */
+
+/**
+ *
+ *  Attribute      | Attribute filter| Attribute range filter
+ *                 | supported       | supported
+ * ----------------+-----------------+------------------------
+ *  id             | No              | No
+ *  parentId       | No              | No
+ *  serviceId      | Yes             | No
+ *  contentType    | No              | No
+ *  name           | No              | No
+ *  path           | No              | No
+ *  type           | No              | No
+ *  synchronizable | No              | No
+ */
+
+var prefferedEmailService = "a.jacak.testmail";
+
+function containCaseInsensitive(string, searchString) {
+    var lcString = string.toLowerCase();
+    var lcSearchString = searchString.toLowerCase();
+    return lcString.indexOf(lcSearchString)>=0;
+}
+
+var currentService = null;
+
+function listFolders(prefix, folders) {
+    for (var i=0; i<folders.length; i++) {
+        var folder = folders[i];
+        console.log(prefix + " FOLDER[" + i + "] id: "
+                + folder.id
+                + " name:" + folder.name
+                + " serviceid: " + folder.serviceId);
+    }
+}
+
+var folderChangeCB = {
+    foldersupdated: function(folders) {
+        console.log(folders.length + " folder(s) updated");
+        listFolders("foldersupdated",folders);
+    },
+    foldersadded: function(folders) {
+        console.log(folders.length + " folder(s) added");
+        listFolders("foldersadded",folders);
+    },
+    foldersremoved: function(folders) {
+        console.log(folders.length + " folder(s) removed");
+        listFolders("foldersremoved",folders);
+    }
+ };
+
+function serviceSyncSuccessCB() {
+    console.log("Synced!");
+}
+
+function serviceSyncFailCB() {
+    console.log("Sync failed!");
+}
+
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+        var chosenServiceIndex = 0;
+        for(var i = 0; i < services.length; i++) {
+            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
+                chosenServiceIndex = i;
+                console.log("servicesListSuccessCB: " +
+                        "found service which name contains: " +
+                        prefferedEmailService);
+                break;
+            }
+        }
+        currentService = services[chosenServiceIndex];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+
+        var filter = new tizen.AttributeFilter("serviceId", "EXACTLY", currentService.id);
+
+        currentService.messageStorage.addFoldersChangeListener(folderChangeCB, filter);
+        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
\ No newline at end of file
diff --git a/src/messaging/old/TestScripts/addMessagesChangeListener_01.js b/src/messaging/old/TestScripts/addMessagesChangeListener_01.js
new file mode 100644 (file)
index 0000000..91455e9
--- /dev/null
@@ -0,0 +1,106 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// Please send two emails with subject containing "Alaska"
+//  1. subject "Alaska Good" and body containing "hack"
+//  2. subject "Alaska Bad" and body NOT containing "hack"
+//
+// Only 1. should printed in JS console.
+
+/**
+ * @file        addMessagesChangeListener_01.js
+ */
+
+//https://developer.tizen.org/help/index.jsp?topic=%2Forg.tizen.gettingstarted%2Fhtml%2Ftizen_overview%2Fapplication_filtering.htm
+
+var prefferedEmailService = "a.jacak.testmail";
+
+function containCaseInsensitive(string, searchString) {
+    var lcString = string.toLowerCase();
+    var lcSearchString = searchString.toLowerCase();
+    return lcString.indexOf(lcSearchString)>=0;
+}
+
+var currentService = null;
+
+function listMessages(prefix, messages) {
+    for (var i=0; i<messages.length; i++) {
+        var message = messages[i];
+        console.log(prefix + " MSG[" + i + "] status: "
+                    + message.messageStatus
+                    + " subject:" + message.subject);
+    }
+}
+
+var messageChangeCB = {
+    messagesupdated: function(messages) {
+        console.log(messages.length + " message(s) updated");
+        listMessages("messagesupdated",messages);
+    },
+    messagesadded: function(messages) {
+       console.log("messagesadded: " + messages.length + " message(s) added");
+       listMessages("messagesadded",messages);
+
+    },
+    messagesremoved: function(messages) {
+        console.log(messages.length + " message(s) removed");
+        listMessages("messagesremoved",messages);
+    }
+};
+
+function serviceSyncSuccessCB() {
+    console.log("Synced!");
+}
+
+function serviceSyncFailCB() {
+    console.log("Sync failed!");
+}
+
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+
+        var chosenServiceIndex = 0;
+        for(var i = 0; i < services.length; i++) {
+            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
+                chosenServiceIndex = i;
+                console.log("servicesListSuccessCB: " +
+                        "found service which name contains: " +
+                        prefferedEmailService);
+                break;
+            }
+        }
+        currentService = services[chosenServiceIndex];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+
+        var subjectFilter1 = new tizen.AttributeFilter("subject", "CONTAINS", "Alaska");
+        var subjectFilter2 = new tizen.AttributeFilter("subject", "CONTAINS", "Alabama");
+        var subsfilter = new tizen.CompositeFilter("UNION",
+                [subjectFilter1, subjectFilter2]);
+
+        var pbodyFilter = new tizen.AttributeFilter("body.plainBody", "CONTAINS", "hack");
+        var filter = new tizen.CompositeFilter("INTERSECTION", [subsfilter, pbodyFilter]);
+
+        currentService.messageStorage.addMessagesChangeListener(messageChangeCB, filter);
+        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/src/messaging/old/TestScripts/allChangeListeners_01.js b/src/messaging/old/TestScripts/allChangeListeners_01.js
new file mode 100644 (file)
index 0000000..ff7512f
--- /dev/null
@@ -0,0 +1,172 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+/**
+ * @file        allChangeListeners_01.js
+ */
+
+var prefferedEmailService = "a.jacak.testmail";
+
+function containCaseInsensitive(string, searchString) {
+    var lcString = string.toLowerCase();
+    var lcSearchString = searchString.toLowerCase();
+    return lcString.indexOf(lcSearchString)>=0;
+}
+
+var currentService = null;
+
+//=============================================================================
+// FOLDERS
+//=============================================================================
+function listFolders(prefix, folders) {
+    for (var i=0; i<folders.length; i++) {
+        var folder = folders[i];
+        console.log(prefix + " FOLDER[" + i + "] id: "
+                + folder.id
+                + " name:" + folder.name
+                + " serviceid: " + folder.serviceId);
+    }
+}
+
+var folderChangeCB = {
+    foldersupdated: function(folders) {
+        console.log(folders.length + " folder(s) updated");
+        listFolders("foldersupdated",folders);
+    },
+    foldersadded: function(folders) {
+        console.log(folders.length + " folder(s) added");
+        listFolders("foldersadded",folders);
+    },
+    foldersremoved: function(folders) {
+        console.log(folders.length + " folder(s) removed");
+        listFolders("foldersremoved",folders);
+    }
+ };
+
+
+
+//=============================================================================
+// CONVERSATIONS
+//=============================================================================
+function listConversations(prefix, conversations) {
+
+    for (var i=0; i<conversations.length; i++) {
+        var conversation = conversations[i];
+        console.log(prefix + " CONVERSATION[" + i + "] " +
+                " id: " + conversation.id +
+                " type: " + conversation.type +
+                " timestamp: " + conversation.timestamp +
+                " messageCount: " + conversation.messageCount +
+                " unreadMessages: " + conversation.unreadMessages +
+                " preview: " + conversation.preview +
+                " subject:" + conversation.subject +
+                " isRead: " + conversation.isRead +
+                " from: " + conversation.from +
+                " lastMessageId: " + conversation.lastMessageId);
+    }
+}
+
+var conversationChangeCB = {
+    conversationsupdated: function(conversations) {
+        console.log(conversations.length + " conversation(s) updated");
+        listConversations("conversationsupdated", conversations);
+    },
+    conversationsadded: function(conversations) {
+        console.log(conversations.length + " conversation(s) added");
+        listConversations("conversationsadded", conversations);
+    },
+    conversationsremoved: function(conversations) {
+        console.log(conversations.length + " conversation(s) removed");
+        listConversations("conversationsremoved", conversations);
+    }
+};
+
+//=============================================================================
+// MESSAGES
+//=============================================================================
+function listMessages(prefix, messages) {
+    for (var i=0; i<messages.length; i++) {
+        var message = messages[i];
+        console.log(prefix + " MSG[" + i + "] status: "
+                    + message.messageStatus
+                    + " subject:" + message.subject);
+    }
+}
+
+var messageChangeCB = {
+    messagesupdated: function(messages) {
+        console.log(messages.length + " message(s) updated");
+        listMessages("messagesupdated",messages);
+    },
+    messagesadded: function(messages) {
+       console.log("messagesadded: " + messages.length + " message(s) added");
+       listMessages("messagesadded",messages);
+
+    },
+    messagesremoved: function(messages) {
+        console.log(messages.length + " message(s) removed");
+        listMessages("messagesremoved",messages);
+    }
+};
+
+
+//=============================================================================
+// Sync
+//=============================================================================
+function serviceSyncSuccessCB() {
+    console.log("Synced!");
+}
+
+function serviceSyncFailCB() {
+    console.log("Sync failed!");
+}
+
+//=============================================================================
+// Main
+//=============================================================================
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+
+        var chosenServiceIndex = 0;
+        for(var i = 0; i < services.length; i++) {
+            if(containCaseInsensitive(services[i].name, prefferedEmailService)) {
+                chosenServiceIndex = i;
+                console.log("servicesListSuccessCB: " +
+                        "found service which name contains: " +
+                        prefferedEmailService);
+                break;
+            }
+        }
+        currentService = services[chosenServiceIndex];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+
+        var filter = null;
+
+        currentService.messageStorage.addMessagesChangeListener(messageChangeCB, filter);
+        currentService.messageStorage.addFoldersChangeListener(folderChangeCB, filter);
+        currentService.messageStorage.addConversationsChangeListener(
+                conversationChangeCB, filter);
+
+        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/src/messaging/old/TestScripts/loadMessageAttachment_01.js b/src/messaging/old/TestScripts/loadMessageAttachment_01.js
new file mode 100644 (file)
index 0000000..ed6a18c
--- /dev/null
@@ -0,0 +1,82 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// For simplicity this script is using ONLY first found email message service.
+// If you want to change this please visit servicesListSuccessCB function.
+//
+// It is important to test mailservice which contains at least TWO mails containing
+// attachments.
+//
+
+/**
+ * @file        testLoadMessageAttachment_01.js
+ */
+
+var currentService = null;
+
+function loadMsgAttSuccessCB(attachment) {
+    console.log("loadMsgAttSuccessCB: received attachment:\n"
+            + "        attachmentId: " + attachment.id + "\n"
+            + "        filePath: " + attachment.filePath + "\n"
+            + "        messageId: " + attachment.messageId + "\n"
+            + "        mimeType: " + attachment.mimeType);
+}
+
+function loadMsgAttErrorCB(error) {
+    console.log("loadMsgAttErrorCB: Cannot load message attachment:" + error.message);
+}
+
+function findMessagesSuccessCB(messages) {
+    console.log("messagesFoundCB: found: " + messages.length + " messages");
+
+    for (var msgIndex = 0; msgIndex < messages.length; ++msgIndex) {
+        var message = messages[msgIndex];
+
+        for(var attIndex = 0; attIndex < message.attachments.length; ++attIndex) {
+            var attachment = message.attachments[attIndex];
+
+            console.log("messagesFoundCB: requesting loadMessageAttachment for:\n"
+                    + "        messageId: " + message.id + "\n"
+                    + "        message: " + message.subject + "\n"
+                    + "        attachmentId: " + attachment.id);
+
+            currentService.loadMessageAttachment(attachment, loadMsgAttSuccessCB,
+                         loadMsgAttErrorCB);
+        }
+    }
+}
+
+function findMessagesErrorCB(err) {
+    console.log("servicesListSuccessCB: error:" + err);
+}
+
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+        currentService = services[0];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+        console.log("servicesListSuccessCB: service id is:" + currentService.id);
+        var filter = new tizen.AttributeFilter("hasAttachment", "EXACTLY", true);
+        currentService.messageStorage.findMessages(filter, findMessagesSuccessCB,
+            findMessagesErrorCB);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
diff --git a/src/messaging/old/TestScripts/loadMessageBody_01.js b/src/messaging/old/TestScripts/loadMessageBody_01.js
new file mode 100644 (file)
index 0000000..f15dd89
--- /dev/null
@@ -0,0 +1,104 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// This script registers messagesChangeListener and requests syncing first
+// email message service.
+//
+// If there are new messages it requests loadBody for each message without
+// downloaded body data.
+//
+// Please ensure that there is new email waiting to receive (send new mail before
+// running this test).
+
+/**
+ * @file        testLoadMessageBody_01.js
+ */
+
+var currentService = null;
+
+function loadMBodySuccessCB(message) {
+    console.log("loadMBodySuccessCB: success!");
+    console.log("loadMBodySuccessCB: message subject:" + message.subject);
+
+    if(message.body.plainBody) {
+        console.log("loadMBodySuccessCB: message plainBody:" + message.body.plainBody);
+    } else if(message.body.htmlBody) {
+        console.log("loadMBodySuccessCB: message htmlBody:" + message.body.htmlBody);
+    } else {
+        console.log("loadMBodySuccessCB:"
+            + "ERROR: message do not contain plain nor htmlBody!");
+    }
+}
+function loadMBodyErrorCB(error) {
+    console.log("loadMBodyErrorCB: failes with error:"+error+"!");
+}
+
+var messageChangeCB = {
+    messagesupdated: function(messages) {
+        console.log(messages.length + " message(s) updated");
+    },
+    messagesadded: function(messages) {
+       console.log("messagesadded: " + messages.length + " message(s) added");
+
+        for (var i=0; i<messages.length; i++) {
+            var message = messages[i];
+
+            console.log("messagesadded: MSG[" + i + "] status: "
+                     + message.messageStatus
+                     + " subject:" + message.subject);
+
+            if (message.body.loaded) {
+                console.log("messagesadded: body for message[" + i
+                         + "] is already loaded");
+            } else {
+                console.log("messagesadded: requesting loadMessageBody for message["
+                         + i + "]");
+
+                currentService.loadMessageBody(message, loadMBodySuccessCB,
+                         loadMBodyErrorCB);
+            }
+        }
+    },
+    messagesremoved: function(messages) {
+        console.log(messages.length + " message(s) removed");
+    }
+ };
+
+function serviceSyncSuccessCB() {
+    console.log("Synced!");
+}
+
+function serviceSyncFailCB() {
+    console.log("Sync failed!");
+}
+
+function servicesListSuccessCB(services) {
+    console.log("servicesListSuccessCB: received:" + services.length + " services");
+
+    if(services.length > 0) {
+        currentService = services[0];
+        console.log("servicesListSuccessCB: testing service:" + currentService.name);
+
+        currentService.messageStorage.addMessagesChangeListener(messageChangeCB);
+        currentService.sync(serviceSyncSuccessCB, serviceSyncFailCB, 30);
+    } else {
+        console.log("servicesListSuccessCB: ERROR: could not find any email service!");
+    }
+}
+
+tizen.messaging.getMessageServices("messaging.email", servicesListSuccessCB);
+
diff --git a/src/messaging/old/config.xml b/src/messaging/old/config.xml
new file mode 100755 (executable)
index 0000000..aea0e73
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" ?>
+<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd">
+<plugin-properties>
+    <library-name>libwrt-plugins-tizen-messaging.so</library-name>
+    <feature-install-uri>messaging.install.uri</feature-install-uri>
+
+    <api-feature>
+        <name>http://tizen.org/privilege/messaging.read</name>
+        <device-capability>messaging.read</device-capability>
+    </api-feature>
+
+    <api-feature>
+        <name>http://tizen.org/privilege/messaging.send</name>
+        <device-capability>messaging.send</device-capability>
+    </api-feature>
+
+     <api-feature>
+        <name>http://tizen.org/privilege/messaging.write</name>
+        <device-capability>messaging.write</device-capability>
+    </api-feature>
+
+</plugin-properties>
diff --git a/src/messaging/old/plugin_config.cpp b/src/messaging/old/plugin_config.cpp
new file mode 100755 (executable)
index 0000000..ecc4fc9
--- /dev/null
@@ -0,0 +1,302 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <map>
+#include <utility>
+#include <Commons/FunctionDefinition.h>
+#include <Commons/FunctionDeclaration.h>
+#include <Commons/Exception.h>
+#include "plugin_config.h"
+
+#define MESSAGING_FEATURE_API_READ "http://tizen.org/privilege/messaging.read"
+#define MESSAGING_FEATURE_API_SEND "http://tizen.org/privilege/messaging.send"    // before sendMessage move to write privilege start
+#define MESSAGING_FEATURE_API_WRITE "http://tizen.org/privilege/messaging.write"
+
+#define MESSAGING_DEVICE_CAP_READ "messaging.read"
+#define MESSAGING_DEVICE_CAP_SEND "messaging.send"    // before sendMessage move to write privilege start
+#define MESSAGING_DEVICE_CAP_WRITE "messaging.write"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+using namespace WrtDeviceApis::Commons;
+
+static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions();
+static WrtDeviceApis::Commons::FunctionMapping MessagingFunctions = createMessagingFunctions();
+
+#pragma GCC visibility push(default)
+
+DEFINE_FUNCTION_GETTER(Messaging, MessagingFunctions);
+
+#pragma GCC visibility pop
+
+static WrtDeviceApis::Commons::FunctionMapping createMessagingFunctions()
+{
+     /**
+     * Device capabilities
+     */
+
+    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_READ, MESSAGING_DEVICE_CAP_READ);
+    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_SEND, MESSAGING_DEVICE_CAP_SEND);
+    ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MESSAGING_WRITE, MESSAGING_DEVICE_CAP_WRITE);
+
+    ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST);
+
+    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_READ);
+    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_READ, DEVICE_CAP_MESSAGING_READ);
+
+    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_SEND);
+    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_SEND, DEVICE_CAP_MESSAGING_SEND);
+
+    ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MESSAGING_WRITE);
+    ACE_ADD_DEVICE_CAP(DEVICE_LIST_MESSAGING_WRITE, DEVICE_CAP_MESSAGING_WRITE);
+
+    /**
+    * API features
+    */
+    ACE_CREATE_FEATURE(FEATURE_MESSAGING_READ, MESSAGING_FEATURE_API_READ);
+    ACE_CREATE_FEATURE(FEATURE_MESSAGING_SEND, MESSAGING_FEATURE_API_SEND);
+    ACE_CREATE_FEATURE(FEATURE_MESSAGING_WRITE, MESSAGING_FEATURE_API_WRITE);
+
+    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE);
+
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_READ);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_SEND);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE, FEATURE_MESSAGING_WRITE);
+
+    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_READ);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_READ, FEATURE_MESSAGING_READ);
+
+    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_SEND);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND, FEATURE_MESSAGING_SEND);
+
+    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_WRITE);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_WRITE, FEATURE_MESSAGING_WRITE);
+
+// before sendMessage move to write privilege start
+    ACE_CREATE_FEATURE_LIST(MESSAGING_FEATURES_MESSAGING_SEND_WRITE);
+
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND_WRITE, FEATURE_MESSAGING_SEND);
+    ACE_ADD_API_FEATURE(MESSAGING_FEATURES_MESSAGING_SEND_WRITE, FEATURE_MESSAGING_WRITE);
+// before sendMessage move to write privilege end
+
+    /**
+     * Functions
+     */
+
+     FunctionMapping MessagingMapping;
+
+    //get Message Service
+    AceFunction getMessagingServiceFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
+            MESSAGING_FEATURES_MESSAGING_READ_SEND_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert(std::make_pair(
+            MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE,
+            getMessagingServiceFunc));
+
+      /**  Read  **/
+    AceFunction stopSyncFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_STOP_SYNC,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_STOP_SYNC,
+            stopSyncFunc));
+
+    AceFunction findMessagesFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_FIND_MESSAGES,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_FIND_MESSAGES,
+            findMessagesFunc));
+
+    AceFunction findConversationsFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_FIND_CONVERSATIONS,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_FIND_CONVERSATIONS,
+            findConversationsFunc));
+
+    AceFunction findFoldersFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_FIND_FOLDERS,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_FIND_FOLDERS,
+            findFoldersFunc));
+
+    AceFunction addMessagesChangeListenerFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER,
+            addMessagesChangeListenerFunc));
+
+    AceFunction addConversationsChangeListenerFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER,
+            addConversationsChangeListenerFunc));
+
+    AceFunction addFoldersChangeListenerFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER,
+            addFoldersChangeListenerFunc));
+
+    AceFunction removeChangeListenerFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER,
+            MESSAGING_FEATURES_MESSAGING_READ,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER,
+            removeChangeListenerFunc));
+
+    /**  Send  **/
+
+    // before sendMessage move to write privilege start
+    AceFunction sendMessageFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_SEND_MESSAGE,
+            MESSAGING_FEATURES_MESSAGING_SEND_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_SEND_MESSAGE,
+            sendMessageFunc));
+// before sendMessage move to write privilege end
+      /**  Write  **/
+    AceFunction loadMessageBodyFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY,
+            loadMessageBodyFunc));
+
+    AceFunction loadMessageAttachmentFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT,
+            loadMessageAttachmentFunc));
+
+    AceFunction syncFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_SYNC,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_SYNC,
+            syncFunc));
+
+    AceFunction syncFolderFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_SYNC_FOLDER,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_SYNC_FOLDER,
+            syncFolderFunc));
+
+    AceFunction addDraftMessageFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE,
+            addDraftMessageFunc));
+
+    AceFunction removeMessagesFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_REMOVE_MESSAGES,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_REMOVE_MESSAGES,
+            removeMessagesFunc));
+
+    AceFunction removeConversationsFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS,
+            removeConversationsFunc));
+
+    AceFunction updateMessagesFunc = ACE_CREATE_FUNCTION(
+            FUNCTION_GET_MGR_SERVICE,
+            MESSAGING_FUNCTION_API_UPDATE_MESSAGES,
+            MESSAGING_FEATURES_MESSAGING_WRITE,
+            EMPTY_DEVICE_LIST);
+
+    MessagingMapping.insert( std::make_pair(
+            MESSAGING_FUNCTION_API_UPDATE_MESSAGES,
+            updateMessagesFunc));
+
+    return MessagingMapping;
+}
+
+}
+}
+
+#undef MESSAGING_FEATURE_API
+#undef MESSAGING_FEATURE_API_READ
+#undef MESSAGING_FEATURE_API_SEND // before sendMessage move to write privilege start
+#undef MESSAGING_FEATURE_API_WRITE
+#undef MESSAGING_DEVICE_CAP_READ
+#undef MESSAGING_DEVICE_CAP_SEND // before sendMessage move to write privilege start
+#undef MESSAGING_DEVICE_CAP_WRITE
+
diff --git a/src/messaging/old/plugin_config.h b/src/messaging/old/plugin_config.h
new file mode 100755 (executable)
index 0000000..c00107a
--- /dev/null
@@ -0,0 +1,39 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef _MESSAGING_PLUGIN_CONFIG_H_
+#define _MESSAGING_PLUGIN_CONFIG_H_
+
+#include <Commons/FunctionDeclaration.h>
+#include <Security.h>
+#include "plugin_config_impl.h"
+
+namespace DeviceAPI {
+namespace Messaging {
+
+DECLARE_FUNCTION_GETTER(Messaging);
+
+#define MESSAGING_CHECK_ACCESS(functionName)   \
+    aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >(        \
+    getMessagingFunctionData,                                              \
+    functionName)
+
+}
+}
+
+#endif //MESSAGING_PLUGIN_CONFIG_H_
+
diff --git a/src/messaging/old/plugin_config_impl.h b/src/messaging/old/plugin_config_impl.h
new file mode 100755 (executable)
index 0000000..9ade59b
--- /dev/null
@@ -0,0 +1,46 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#ifndef _MESSAGING_PLUGIN_CONFIG_IMPL_H_
+#define _MESSAGING_PLUGIN_CONFIG_IMPL_H_
+
+#define TIZEN_MESSAGING_MESSAGING_MANAGER_CLASS "messaging"
+#define TIZEN_MESSAGING_MESSAGE_INTERFACE "Message"
+#define TIZEN_MESSAGING_MESSAGE_ATTACHMENT_INTERFACE "MessageAttachment"
+
+// functions
+#define MESSAGING_FUNCTION_API_GET_MESSAGE_SERVICE "getMessageServices"
+#define MESSAGING_FUNCTION_API_SEND_MESSAGE "sendMessage"
+#define MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY "loadMessageBody"
+#define MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT "loadMessageAttachment"
+#define MESSAGING_FUNCTION_API_SYNC "sync"
+#define MESSAGING_FUNCTION_API_SYNC_FOLDER "syncFolder"
+#define MESSAGING_FUNCTION_API_STOP_SYNC "stopSync"
+#define MESSAGING_FUNCTION_API_ADD_DRAFT_MESSAGE "addDraftMessage"
+#define MESSAGING_FUNCTION_API_FIND_MESSAGES "findMessages"
+#define MESSAGING_FUNCTION_API_REMOVE_MESSAGES "removeMessages"
+#define MESSAGING_FUNCTION_API_UPDATE_MESSAGES "updateMessages"
+#define MESSAGING_FUNCTION_API_FIND_CONVERSATIONS "findConversations"
+#define MESSAGING_FUNCTION_API_REMOVE_CONVERSATIONS "removeConversations"
+#define MESSAGING_FUNCTION_API_FIND_FOLDERS "findFolders"
+#define MESSAGING_FUNCTION_API_ADD_MESSAGES_CHANGE_LISTNER "addMessagesChangeListener"
+#define MESSAGING_FUNCTION_API_ADD_CONVERSATIONS_CHANGE_LISTNER "addConversationsChangeListener"
+#define MESSAGING_FUNCTION_API_ADD_FOLDERS_CHANGE_LISTNER "addFoldersChangeListener"
+#define MESSAGING_FUNCTION_API_REMOVE_CHANGE_LISTENER "removeChangeListener"
+
+#endif //MESSAGING_PLUGIN_CONFIG_IMPL_H_
+
diff --git a/src/messaging/old/plugin_initializer.cpp b/src/messaging/old/plugin_initializer.cpp
new file mode 100644 (file)
index 0000000..e613aa7
--- /dev/null
@@ -0,0 +1,133 @@
+//
+// Tizen Web Device API
+// Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+#include <Commons/plugin_initializer_def.h>
+#include <Commons/WrtAccess/WrtAccess.h>
+
+#include <GlobalContextManager.h>
+#include <Logger.h>
+#include <Security.h>
+#include <TimeTracer.h>
+
+#include "JSMessageAttachment.h"
+#include "JSMessage.h"
+#include "JSMessagingManager.h"
+#include "MessagingManager.h"
+
+#include "plugin_config.h"
+
+using namespace WrtDeviceApis;
+using namespace WrtDeviceApis::Commons;
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Messaging {
+
+AceSecurityStatus messagingAceCheckAccessFunction(const char* functionName)
+{
+    return MESSAGING_CHECK_ACCESS(functionName);
+}
+
+DEFINE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor);
+
+DEFINE_SECURITY_ACCESSOR_SETTER(AceCheckerMessagingSetter, MessagingManager, gSecurityAccessor);
+
+class_definition_options_t MessagingOptions =
+{
+    JS_CLASS,
+    CREATE_INSTANCE,
+    ALWAYS_NOTICE,
+    USE_OVERLAYED, //ignored
+    AceCheckerMessagingSetter,
+    NULL,
+    NULL
+};
+
+class_definition_options_t MessagingInterfaceOptions = {
+    JS_INTERFACE,
+    CREATE_INSTANCE,
+    NONE_NOTICE,
+    USE_OVERLAYED, //ignored
+    NULL, // JSWidget::acquireGlobalContext,
+    NULL,
+    NULL
+};
+
+void on_widget_start_callback(int widgetId) {
+    LOGD("[Tizen\\MessagingManager] on_widget_start_callback (%d)", widgetId);
+    TIME_TRACER_INIT();
+    try {
+        WrtAccessSingleton::Instance().initialize(widgetId);
+    } catch (...) {
+        LOGE("WrtAccess initialization failed");
+    }
+    INITAILIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor, messagingAceCheckAccessFunction);
+}
+
+void on_widget_stop_callback(int widgetId) {
+    LOGD("[Tizen\\MessagingManager] on_widget_stop_callback (%d)", widgetId);
+    std::string name = "MessagingManager";
+    TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE, const_cast<char*>(name.c_str()));
+    TIME_TRACER_RELEASE();
+    try {
+        WrtAccessSingleton::Instance().deinitialize(widgetId);
+    } catch (...) {
+        LOGE("WrtAccess deinitialization failed");
+    }
+    FINALIZE_GLOBAL_SECURITY_ACCESSOR(gSecurityAccessor);
+}
+
+void on_frame_load_callback(const void * context)
+{
+    LOGD("[Tizen\\MessagingManager] on_frame_load_callback (%p)", context);
+    DeviceAPI::Common::GlobalContextManager::getInstance()->
+            addGlobalContext(static_cast<JSContextRef>(context));
+}
+
+void on_frame_unload_callback(const void * context)
+{
+    LOGD("[Tizen\\MessagingManager] on_frame_unload_callback (%p)", context);
+    DeviceAPI::Common::GlobalContextManager::getInstance()->
+            removeGlobalContext(static_cast<JSContextRef>(context));
+}
+
+
+PLUGIN_ON_WIDGET_START(on_widget_start_callback)
+PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback)
+
+PLUGIN_ON_FRAME_LOAD(on_frame_load_callback)
+PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback)
+
+PLUGIN_CLASS_MAP_BEGIN
+PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN,
+        TIZEN_MESSAGING_MESSAGING_MANAGER_CLASS,
+        (js_class_template_getter)DeviceAPI::Messaging::JSMessagingManager::getClassRef,
+        &MessagingOptions)
+PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN,
+        TIZEN_MESSAGING_MESSAGE_INTERFACE,
+        (js_class_template_getter)DeviceAPI::Messaging::JSMessage::getClassRef,
+        (js_class_constructor_cb_t)DeviceAPI::Messaging::JSMessage::constructor,
+        &MessagingInterfaceOptions)
+PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN,
+        TIZEN_MESSAGING_MESSAGE_ATTACHMENT_INTERFACE,
+        (js_class_template_getter)DeviceAPI::Messaging::JSMessageAttachment::getClassRef,
+        (js_class_constructor_cb_t)DeviceAPI::Messaging::JSMessageAttachment::constructor,
+        &MessagingInterfaceOptions)
+PLUGIN_CLASS_MAP_END
+
+} // Messaging
+} // DeviceAPI