MojErr
TestCategoryHandler::WhereMatchTest(MojServiceMessage *msg, MojObject &payload)
{
	ACTIVITY_SERVICEMETHOD_BEGIN();

	MojObject response;
	bool found = payload.get(_T("response"), response);
	if (!found) {
		throw std::runtime_error("Please provide a \"response\" and a "
			"\"where\" clause to test against it");
	}

	MojObject where;
	found = payload.get(_T("where"), where);
	if (!found) {
		throw std::runtime_error("Please provide a \"where\" clause to test "
			"the response against");
	}

	MojoNewWhereMatcher matcher(where);
	bool matched = matcher.Match(response);

	MojObject reply;
	MojErr err = reply.putBool(_T("matched"), matched);
	MojErrCheck(err);

	err = msg->reply(reply);
	MojErrCheck(err);

	ACTIVITY_SERVICEMETHOD_END(msg);

	return MojErrNone;
}
예제 #2
0
MojErr MojService::dispatchReply(MojServiceMessage* msg)
{
	MojAssert(msg);
	MojAssertMutexUnlocked(m_mutex);
	MojLogTrace(s_log);

	// parse payload
	MojObjectBuilder builder;
	MojObject payload;
	MojErr err = MojErrNone;
	MojInt64 errCode = MojErrNone;
	errCode = err = msg->payload(builder);
	MojErrCatchAll(err);
	if (errCode == MojErrNone)
		payload = builder.object();

	// get errCode
	bool retVal = false;
	if (payload.get(MojServiceMessage::ReturnValueKey, retVal) && !retVal) {
		if (!payload.get(MojServiceMessage::ErrorCodeKey, errCode))
			errCode = MojErrUnknown;
	}
	// find request
	MojRefCountedPtr<MojServiceRequest> req;
	err = getRequest(msg, req);
	MojErrCheck(err);

	// do the dispatch
	err = dispatchReplyImpl(req.get(), msg, payload, (MojErr) errCode);
	MojErrCatchAll(err);

	return MojErrNone;
}
예제 #3
0
MojErr MojDbServiceHandler::handleStats(MojServiceMessage* msg, MojObject& payload, MojDbReq& req)
{
	MojAssert(msg);
	MojLogTrace(s_log);


	MojString forKind;

	bool verify = false;
	payload.get(MojDbServiceDefs::VerifyKey, verify);

	MojString *pKind = NULL;
	bool found = false;
	MojErr err = payload.get(MojDbServiceDefs::KindKey, forKind, found);
	MojErrCheck(err);
	if (found)
		pKind = &forKind;
	

	MojObject results;
	err = m_db.stats(results, req, verify, pKind);
	MojErrCheck(err);

	MojObjectVisitor& writer = msg->writer();
	err = writer.beginObject();
	MojErrCheck(err);
	err = writer.boolProp(MojServiceMessage::ReturnValueKey, true);
	MojErrCheck(err);
	err = writer.objectProp(MojDbServiceDefs::ResultsKey, results);
	MojErrCheck(err);
	err = writer.endObject();
	MojErrCheck(err);

	return MojErrNone;
}
예제 #4
0
void MojoWhereMatcher::ValidateClause(const MojObject& clause) const
{
	MojLogTrace(s_log);
	MojLogInfo(s_log, _T("Validating where clause \"%s\""),
		MojoObjectJson(clause).c_str());

	if (!clause.contains(_T("prop"))) {
		throw std::runtime_error("Each where clause must contain a property "
			"to operate on");
	}

	MojObject prop;
	clause.get(_T("prop"), prop);
	ValidateKey(prop);

	if (!clause.contains(_T("op"))) {
		throw std::runtime_error("Each where clause must contain a test "
			"operation to perform");
	}

	MojObject op;
	clause.get(_T("op"), op);
	ValidateOp(op);

	if (!clause.contains(_T("val"))) {
		throw std::runtime_error("Each where clause must contain a value to "
			"test against");
	}
}
예제 #5
0
MojErr MojDbPropExtractor::fromObjectImpl(const MojObject& obj, const MojDbPropExtractor& defaultConfig, const MojChar* locale)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);

	// super
	MojErr err = MojDbExtractor::fromObject(obj, locale);
	MojErrCheck(err);

	// default value
	m_default = defaultConfig.m_default;
	MojObject defaultVal;
	if (obj.get(DefaultKey, defaultVal)) {
		MojObject::Type type = defaultVal.type();
		MojDbKey key;
		if (type == MojObject::TypeArray) {
			// if the value is an array, act on its elements rather than the array object itself
			MojObject::ConstArrayIterator end = defaultVal.arrayEnd();
			for (MojObject::ConstArrayIterator j = defaultVal.arrayBegin(); j != end; ++j) {
				err = key.assign(*j);
				MojErrCheck(err);
				err = m_default.put(key);
				MojErrCheck(err);
			}
		} else {
			err = key.assign(defaultVal);
			MojErrCheck(err);
			err = m_default.put(key);
			MojErrCheck(err);
		}
	}

	// tokenizer
	m_tokenizer = defaultConfig.m_tokenizer;
	MojString tokenize;
	bool found = false;
	err = obj.get(TokenizeKey, tokenize, found);
	MojErrCheck(err);
	if (found) {
		if (tokenize == AllKey || tokenize == DefaultKey) {
			m_tokenizer.reset(new MojDbTextTokenizer);
			MojAllocCheck(m_tokenizer.get());
			err = m_tokenizer->init(locale);
			MojErrCheck(err);
		} else {
			MojErrThrow(MojErrDbInvalidTokenization);
		}
	}

	// collator
	if (m_collation == MojDbCollationInvalid)
		m_collation = defaultConfig.m_collation;
	err = updateLocale(locale);
	MojErrCheck(err);

	// set prop
	err = prop(m_name);
	MojErrCheck(err);

	return MojErrNone;
}
/*
 * inviteBuddy: tell libpurple to add the buddy
 * add buddy to buddyStatus and contact DB kinds
 *
 * imcommand:
 * {
   "params" : {
      "group"            : {"type"        : "string",
                            "optional"    : true,
                            "description" : "The name of the group to put the buddy in."},
      "message"          : {"type"        : "string",
                            "optional"    : true,
                            "description" : "If the IM transport supports custom invite messages."}
     }
 * }
 *
 */
LibpurpleAdapter::SendResult SendOneCommandHandler::inviteBuddy(const MojObject imCmd) {

	bool found = false;

	// params
	MojObject params;
	MojString group;
	found = imCmd.get(MOJDB_PARAMS, params);
	IMServiceHandler::logMojObjectJsonString(_T("command params: %s"),params);
	if (found) {
		params.get(XPORT_GROUP, group, found);
	}

	MojLogInfo (IMServiceApp::s_log, "sending addBuddy command to transport. id: %s, serviceName: %s, username: %s, buddyUsername: %s, groupName: %s",
			m_currentCmdDbId.data(), m_serviceName.data(), m_username.data(), m_buddyName.data(), group.data());

	// Note, libpurple does not return errors on send - adapter only checks that the parameters are valid and that the user is logged in
	// otherwise assume success...
	LibpurpleAdapter::SendResult retVal = LibpurpleAdapter::addBuddy(m_serviceName.data(), m_username.data(), m_buddyName.data(), group.data());

	// Note: if the remote user rejects our invite, buddy gets deleted on the server but we do not get notified, so the contact will remain, but the buddy list gets re-synced on the next login

	if (LibpurpleAdapter::SENT == retVal) {
		// add to buddyStatus and contacts list. They will get removed later if the invite is rejected
		addBuddyToDb();
	}
	return retVal;
}
/*
 * blockBuddy command: Send the blockBuddy command off to libPurple
 * remove buddy from buddyStatus and contact DB kinds
 * imcommand
 * {
   "params" : {
     "block"           : {"type"        : "boolean",
                          "description" : "whether to block or unblock the buddy."}
     }
 * }
 */
LibpurpleAdapter::SendResult SendOneCommandHandler::blockBuddy(const MojObject imCmd) {

	bool found = false;

	// params
	MojObject params;
	found = imCmd.get(MOJDB_PARAMS, params);
	IMServiceHandler::logMojObjectJsonString(_T("command params: %s"),params);
	bool block = true;
	found = params.get(XPORT_BLOCK, block);

	MojLogInfo (IMServiceApp::s_log, "sending blockBuddy command to transport. id: %s, serviceName: %s, username: %s, buddyUsername: %s, block: %d",
			m_currentCmdDbId.data(), m_serviceName.data(), m_username.data(), m_buddyName.data(), block);


	// Note, libpurple does not return errors on send - adapter only checks that the parameters are valid and that the user is logged in
	// otherwise assume success...
	LibpurpleAdapter::SendResult retVal = LibpurpleAdapter::blockBuddy(m_serviceName.data(), m_username.data(), m_buddyName.data(), block);

	if (LibpurpleAdapter::SENT == retVal) {

		// if the buddy was blocked, remove from buddyStatus and contacts list, otherwise add it
		if (block)
			removeBuddyFromDb();
		// Note: we don't actually have UI to unblock a buddy as of 6/28/2010 so this is not used...
		else addBuddyToDb();
	}

	return retVal;
}
예제 #8
0
void MojoWhereMatcher::ValidateClause(const MojObject& clause) const
{
	LOG_AM_TRACE("Entering function %s", __FUNCTION__);
	LOG_AM_DEBUG("Validating where clause \"%s\"",
		MojoObjectJson(clause).c_str());

	if (!clause.contains(_T("prop"))) {
		throw std::runtime_error("Each where clause must contain a property "
			"to operate on");
	}

	MojObject prop;
	clause.get(_T("prop"), prop);
	ValidateKey(prop);

	if (!clause.contains(_T("op"))) {
		throw std::runtime_error("Each where clause must contain a test "
			"operation to perform");
	}

	MojObject op;
	clause.get(_T("op"), op);
	ValidateOp(op);

	if (!clause.contains(_T("val"))) {
		throw std::runtime_error("Each where clause must contain a value to "
			"test against");
	}
}
MojoNewWhereMatcher::MatchResult MojoNewWhereMatcher::CheckClause(
	const MojObject& clause, const MojObject& response, MatchMode mode) const
{
	LOG_AM_TRACE("Entering function %s", __FUNCTION__);

	if (clause.type() == MojObject::TypeArray) {
		return CheckClauses(clause, response, mode);
	} else if (clause.type() != MojObject::TypeObject) {
		throw std::runtime_error("Clauses must be either an object or array "
			"of objects");
	}

	LOG_AM_DEBUG("Checking clause '%s' against response '%s' (%s)",
		MojoObjectJson(clause).c_str(), MojoObjectJson(response).c_str(),
		(mode == AndMode) ? "and" : "or");

	if (clause.contains(_T("and"))) {
		MojObject andClause;
		clause.get(_T("and"), andClause);

		return CheckClause(andClause, response, AndMode);
	} else if (clause.contains(_T("or"))) {
		MojObject orClause;
		clause.get(_T("or"), orClause);

		return CheckClause(orClause, response, OrMode);
	}

	MojObject prop;
	bool found = clause.get(_T("prop"), prop);
	if (!found) {
		throw std::runtime_error("Clauses must contain \"and\", \"or\", "
			"or a comparison to make");
	}

	MojObject op;
	found = clause.get(_T("op"), op);
	if (!found) {
		throw std::runtime_error("Clauses must specify a comparison operation "
			"to perform");
	}

	MojObject val;
	found = clause.get(_T("val"), val);
	if (!found) {
		throw std::runtime_error("Clauses must specify a value to compare "
			"against");
	}

	MatchResult result = CheckProperty(prop, response, op, val, mode);

	LOG_AM_DEBUG("Where Trigger: Clause %s %s",
		MojoObjectJson(clause).c_str(), (result == Matched) ? "matched" :
	    "did not match");

	return result;
}
예제 #10
0
/*
 * networkStatusQuery
 *
 * {
 *    "extended" : {
 *    ...
 *        "state" : "noservice" | "limited" | "service"
 *    ...
 *    }
 * }
 *
 */
void TelephonyProxy::NetworkStatusUpdate(MojServiceMessage *msg,
	const MojObject& response, MojErr err)
{
	LOG_TRACE("Entering function %s", __FUNCTION__);
	LOG_DEBUG("Network status update message: %s",
		MojoObjectJson(response).c_str());

	if (err != MojErrNone) {
		if (MojoCall::IsPermanentFailure(msg, response, err)) {
			LOG_WARNING(MSGID_TIL_NWSTATUS_QUERY_ERR,0,
				"TIL experienced an uncorrectable failure : %s", MojoObjectJson(response).c_str());
			m_networkStatusQuery.reset();
		} else {
			LOG_WARNING(MSGID_TIL_NWSTATUS_QUERY_RETRY, 0,
				"Subscription to TIL failed, retrying - %s", MojoObjectJson(response).c_str() );
			m_networkStatusQuery->Call();
		}
		return;
	}

	MojObject extended;

	bool found;
	found = response.get(_T("extended"), extended);
	if (!found) {
		/* Way to have 2 different formats for the same thing!  First
		 * response names the property "extended".  All subsequent ones
		 * name it "eventNetwork". */
		found = response.get(_T("eventNetwork"), extended);
	}

	if (found) {
		MojString status;
		MojErr err2;

		err2 = extended.get(_T("state"), status, found);
		if (err2) {
			LOG_WARNING(MSGID_TIL_NWSTATE_ERR, 1 ,
				PMLOGKFV("NWSTATE","%d",err2),
				"Error attempting to retrieve network state");
		} else if (found) {
			if (status == "service") {
			    m_haveTelephonyService = true;
			} else {
			    m_haveTelephonyService = false;
			}
			UpdateTelephonyState();
		} else {
			LOG_WARNING(MSGID_TIL_NO_NWSTATE, 0 ,
				"Network status update message did not include network state: %s", MojoObjectJson(response).c_str());
		}
	}
}
예제 #11
0
MojErr MojLogEngine::configure(const MojObject& conf, const MojChar* name)
{
	MojAssert(name);

	MojErr err = MojErrNone;
	MojLogger::Level defaultLevel = MojLogger::LevelDefault;
	MojAutoPtr<MojLogAppender> appender;
	LevelMap levels;

	// validate entire configuration before we apply any changes
	MojObject logConf;
	if (conf.get(LogKey, logConf)) {
		// appender
		MojObject obj;
		if (logConf.get(AppenderKey, obj)) {
			err = createAppender(obj, name, appender);
			MojErrCheck(err);
		}
		// levels
		if (logConf.get(LevelsKey, obj)) {
			// configure loggers
			MojString str;
			for (MojObject::ConstIterator i = obj.begin(); i != obj.end(); ++i) {
				MojLogger::Level level = MojLogger::LevelNone;
				err = i.value().stringValue(str);
				MojErrCheck(err);
				err = MojLogger::levelFromString(str, level);
				MojErrCheck(err);
				if (i.key() == DefaultKey) {
					defaultLevel = level;
				} else {
					err = levels.put(i.key(), level);
					MojErrCheck(err);
				}
			}
		}
	}

	// apply changes
	MojThreadGuard guard(m_mutex);
	// update name
	err = m_name.assign(name);
	MojErrCheck(err);
	// update appender
	updateAppender(appender);
	// update levels
	m_levels = levels;
	m_defaultLogger.level(defaultLevel);
	updateLoggers();

	return MojErrNone;
}
예제 #12
0
bool MojoWhereMatcher::GetObjectValue(const MojObject& key,
	const MojObject& response, MojObject& value) const
{
	if (key.type() == MojObject::TypeString) {
		MojString keyStr;
		MojErr err = key.stringValue(keyStr);
		if (err) {
			throw std::runtime_error("Error attempting to retrieve key name "
				"getting object value");
		}

		if (response.contains(keyStr)) {
			return response.get(keyStr, value);
		} else {
			return false;
		}
	} else if (key.type() == MojObject::TypeArray) {
		MojObject cur = response;
		for (MojObject::ConstArrayIterator iter = key.arrayBegin();
			iter != key.arrayEnd(); ++iter) {
			const MojObject& keyObj = *iter; 

			if (keyObj.type() != MojObject::TypeString) {
				throw std::runtime_error("Non-string found in property "
					"specifiction array");
			}

			MojString keyStr;
			MojErr err = keyObj.stringValue(keyStr);
			if (err) {
				throw std::runtime_error("Failed to access lookup key");
			}

			if (cur.contains(keyStr)) {
				MojObject tmp;
				if (!cur.get(keyStr, tmp)) {
					return false;
				} else {
					cur = tmp;
				}
			} else {
				return false;
			}
		}

		value = cur;
		return true;
	} else {
		throw std::runtime_error("Property specification must be the "
			"property name or array of property names");
	}
}
예제 #13
0
MojErr MojDbServiceHandler::handleMerge(MojServiceMessage* msg, MojObject& payload, MojDbReq& req)
{
	MojAssert(msg);
	MojLogTrace(s_log);

	MojErr err = MojErrNone;
	MojUInt32 count = 0;
	MojObject obj;
	

	if (payload.get(MojDbServiceDefs::ObjectsKey, obj)) {
		if (payload.contains(MojDbServiceDefs::QueryKey))
			MojErrThrowMsg(MojErrInvalidArg, _T("db: cannot have both an objects param and a query param"));
		MojObject::ArrayIterator begin;
		bool ignoreM = false;
		payload.get(MojDbServiceDefs::IgnoreMissingKey, ignoreM);
		MojUInt32 mflags = MojDb::FlagNone;
		if (ignoreM)
			mflags = mflags | MojDb::FlagIgnoreMissing;
		err = obj.arrayBegin(begin);
		MojErrCheck(err);
		MojObject::ConstArrayIterator end = obj.arrayEnd();
		err = m_db.merge(begin, end, mflags, req);
		MojErrCheck(err);
		err = formatPut(msg, begin, end); // TO DO: we need to drop non-existing objects
		MojErrCheck(err);
	}
	else if (payload.get(MojDbServiceDefs::QueryKey, obj)) {
		MojObject props;
		err = payload.getRequired(MojDbServiceDefs::PropsKey, props);
		MojErrCheck(err);
		bool ignoreM = false;
		if (payload.get(MojDbServiceDefs::IgnoreMissingKey, ignoreM))
			MojErrThrowMsg(MojErrInvalidArg, _T("db: ignoreMissing - invalid option for merge query"));

		MojDbQuery query;
		err = query.fromObject(obj);
		MojErrCheck(err);
		MojUInt32 queryCount = 0;
		err = m_db.merge(query, props, queryCount, MojDb::FlagNone, req);
		MojErrCheck(err);
		count += queryCount;
		err = formatCount(msg, count);
		MojErrCheck(err);
	}
	else {
		MojErrThrowMsg(MojErrInvalidArg, _T("db: either objects or query param required for merge"));
	}

	return MojErrNone;
}
예제 #14
0
MojErr PopBusDispatcher::ValidateAccount(MojServiceMessage* msg, MojObject& payload)
{
	// cancel shut down if it is in shut down state
	CancelShutdown();

	MojLogTrace(s_log);

	boost::shared_ptr<PopAccount> account(new PopAccount());

	try {
		MojObject accountId;
		if(payload.get("accountId", accountId)) {
			MojRefCountedPtr<FirstUseValidator> firstUseValidator(new FirstUseValidator(*this, m_dbInterface, accountId, msg, payload));
			firstUseValidator->Validate();
		} else {
			// NOT First Use
			boost::shared_ptr<PopAccount> account(new PopAccount());
			GetAccountFromPayload(account, payload);
			ValidatePopAccount(account, msg, payload);
		}
	} catch (const std::exception& e) {
		MojErrThrowMsg(MojErrInternal, "%s", e.what());
	}

	return MojErrNone;
}
MojErr OnEnabledHandler::getAccountConfigResult(MojObject& payload, MojErr err)
{
    MojLogTrace(IMServiceApp::s_log);

    if (err != MojErrNone) {
        MojString error;
        MojErrToString(err, error);
        MojLogCritical(IMServiceApp::s_log, "getAccountConfig failed: error %d - %s", err, error.data());
    }
    else
    {
        MojObject results;
        payload.get("results", results);

        if (!results.empty())
        {
            m_config = *results.arrayBegin();
        }
    }

	if (m_enable) {
		err = accountEnabled();
	} else {
		err = accountDisabled();
	}

	return err;
}
예제 #16
0
bool MojoCompareMatcher::Match(const MojObject& response)
{
	MojLogTrace(s_log);

	if (response.contains(m_key)) {
		MojObject value;
		MojString valueString;
		response.get(m_key, value);
		value.stringValue(valueString);
		if (value != m_value) {
			MojString oldValueString;
			m_value.stringValue(oldValueString);

			MojLogInfo(s_log, _T("Compare Matcher: Comparison key \"%s\" "
				"value changed from \"%s\" to \"%s\".  Firing."), m_key.data(),
				oldValueString.data(), valueString.data());

			return true;
		} else {
			MojLogInfo(s_log, _T("Compare Matcher: Comparison key \"%s\" "
				"value \"%s\" unchanged."), m_key.data(), valueString.data());
		}
	} else {
		MojLogInfo(s_log, _T("Compare Matcher: Comparison key (%s) not "
			"present."), m_key.data());
	}

	return false;
}
예제 #17
0
void ImapAccountAdapter::ParseLoginConfig(const MojObject& config, ImapLoginSettings& login)
{
	MojErr err;

	// Optional username; overrides account username if available
	bool hasServerUsername = false;
	MojString serverUsername;
	err = config.get(ImapAccountAdapter::USERNAME, serverUsername, hasServerUsername);
	ErrorToException(err);
	if(hasServerUsername) {
		login.SetUsername(serverUsername.data());
	}

	MojString hostname;
	err = config.getRequired(ImapAccountAdapter::HOSTNAME, hostname);
	ErrorToException(err);
	login.SetHostname(hostname.data());

	int port;
	err = config.getRequired(ImapAccountAdapter::PORT, port);
	ErrorToException(err);
	login.SetPort(port);

	MojString encryptionStr;
	err = config.getRequired(ImapAccountAdapter::ENCRYPTION, encryptionStr);
	ErrorToException(err);
	login.SetEncryption(GetEncryptionType(encryptionStr));
}
예제 #18
0
bool MojoCompareMatcher::Match(const MojObject& response)
{
	LOG_AM_TRACE("Entering function %s", __FUNCTION__);

	if (response.contains(m_key)) {
		MojObject value;
		MojString valueString;
		response.get(m_key, value);
		value.stringValue(valueString);
		if (value != m_value) {
			MojString oldValueString;
			m_value.stringValue(oldValueString);

			LOG_AM_DEBUG("Compare Matcher: Comparison key \"%s\" value changed from \"%s\" to \"%s\".  Firing.", 
				m_key.data(),
				oldValueString.data(), valueString.data());

			return true;
		} else {
			LOG_AM_DEBUG("Compare Matcher: Comparison key \"%s\" value \"%s\" unchanged.",
				m_key.data(), valueString.data());
		}
	} else {
		LOG_AM_DEBUG("Compare Matcher: Comparison key (%s) not present.",
			m_key.data());
	}

	return false;
}
예제 #19
0
MojErr
DevelCategoryHandler::Evict(MojServiceMessage *msg, MojObject &payload)
{
	ACTIVITY_SERVICEMETHOD_BEGIN();

	LOG_AM_TRACE("Entering function %s", __FUNCTION__);
	LOG_AM_DEBUG("Evict: %s", MojoObjectJson(payload).c_str());

	MojErr err = MojErrNone;

	bool evictAll = false;

	payload.get(_T("evictAll"), evictAll);

	if (evictAll) {
		LOG_AM_DEBUG("EVICTING ALL ACTIVITIES FROM BACKGROUND QUEUE");
		m_am->EvictAllBackgroundActivities();
	} else {
		boost::shared_ptr<Activity> act;

		err = LookupActivity(msg, payload, act);
		MojErrCheck(err);

		LOG_AM_DEBUG(" EVICTING [Activity %llu] FROM BACKGROUND QUEUE",act->GetId());

		m_am->EvictBackgroundActivity(act);
	}

	err = msg->replySuccess();
	MojErrCheck(err);

	ACTIVITY_SERVICEMETHOD_END(msg);

	return MojErrNone;
}
예제 #20
0
MojoNewWhereMatcher::MatchResult MojoNewWhereMatcher::CheckProperty(
	const MojObject& keyArray, MojObject::ConstArrayIterator keyIter,
	const MojObject& response, const MojObject& op, const MojObject& val,
	MatchMode mode) const
{
	MojObject onion = response;
	for (; keyIter != keyArray.arrayEnd(); ++keyIter) {
		if (onion.type() == MojObject::TypeArray) {
			return CheckProperty(keyArray, keyIter, onion, onion.arrayBegin(),
				op, val, mode);
		} else if (onion.type() == MojObject::TypeObject) {
			MojString keyStr;
			MojErr err = (*keyIter).stringValue(keyStr);
			if (err) {
				throw std::runtime_error("Failed to convert property lookup "
					"key to string");
			}

			MojObject next;
			if (!onion.get(keyStr.data(), next)) {
				return NoProperty;
			}

			onion = next;
		} else {
			return NoProperty;
		}
	}

	return CheckMatch(onion, op, val);

}
예제 #21
0
MojoNewWhereMatcher::MatchResult MojoNewWhereMatcher::CheckProperty(
	const MojObject& key, const MojObject& response, const MojObject& op,
	const MojObject& val, MatchMode mode) const
{
	if (key.type() == MojObject::TypeString) {
		MojString keyStr;
		MojErr err = key.stringValue(keyStr);
		if (err) {
			throw std::runtime_error("Failed to convert property lookup key "
				"to string");
		}

		MojObject propVal;
		bool found = response.get(keyStr.data(), propVal);
		if (!found) {
			return NoProperty;
		}

		return CheckMatch(propVal, op, val);

	} else if (key.type() == MojObject::TypeArray) {
		return CheckProperty(key, key.arrayBegin(), response, op, val, mode);
	} else {
		throw std::runtime_error("Key specified was neither a string or "
			"array of strings");
	}
}
예제 #22
0
MojErr MojDbKindState::id(const MojChar* name, const MojChar* objKey, MojDbReq& req, MojObject& idOut, bool& createdOut)
{
	MojAssert(name && objKey);
	MojAssertMutexLocked(m_lock);

	createdOut = false;

	// reload object each time because last update may have been rolled back
	MojObject obj;
	MojRefCountedPtr<MojDbStorageItem> item;
	MojErr err = readIds(objKey, req, obj, item);
	MojErrCheck(err);

	if (!obj.get(name, idOut)) {
		// get next id from seq
		MojDbStorageSeq* seq = m_kindEngine->indexSeq();
		MojAssert(seq);
		MojInt64 id = 0;
		MojErr err = seq->get(id);
		MojErrCheck(err);
		// update copy of id map and write it out
		err = obj.put(name, id);
		MojErrCheck(err);
		err = writeIds(objKey, obj, req, item);
		MojErrCheck(err);
		// update retval
		idOut = id;
		createdOut = true;
	}
	return MojErrNone;
}
예제 #23
0
MojErr MojLunaService::dispatchReplyImpl(MojServiceRequest* req, MojServiceMessage *msg, MojObject& payload, MojErr errCode)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);
	MojAssert(req);
	MojAssertMutexUnlocked(m_mutex);

	// don't automatically cancel a subscription if the payload has "subscribed":true
	bool subscribed = false;
	payload.get(_T("subscribed"), subscribed);

	// remove if there are more responses coming. due to the vagaries of the luna-service protocol,
	// we never really know for sure, but this is a good guess.
	bool remove = (req->numReplies() + 1 >= req->numRepliesExpected()) || (errCode != MojErrNone && !subscribed);
	MojErr err = req->dispatchReply(msg, payload, errCode);
	MojErrCatchAll(err) {
		remove = true;
	}
	if (remove) {
		if (req->numRepliesExpected() == 1) {
			bool found = false;
			err = removeRequest(req, found);
			MojErrCheck(err);
		} else {
			err = cancel(req);
			MojErrCheck(err);
		}
	}
	return MojErrNone;
}
MojErr
DevelCategoryHandler::PriorityControl(MojServiceMessage *msg, MojObject& payload)
{
	ACTIVITY_SERVICEMETHOD_BEGIN();

	MojLogTrace(s_log);
	MojLogInfo(s_log, _T("PriorityControl: %s"),
		MojoObjectJson(payload).c_str());

	MojErr err;

	bool enabled = false;
	bool found = payload.get(_T("enabled"), enabled);
	if (!found) {
		err = msg->replyError(MojErrInvalidArg, _T("Must specify "
			"\"enabled\":true or \"enabled\":false"));
		MojErrCheck(err);
		return MojErrNone;
	}

	if (enabled) {
		m_resourceManager->Enable();
	} else {
		m_resourceManager->Disable();
	}

	err = msg->replySuccess();
	MojErrCheck(err);

	ACTIVITY_SERVICEMETHOD_END(msg);

	return MojErrNone;
}
예제 #25
0
MojErr DeleteAccountCommand::GetAccountInfoResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		ResponseToException(response, err);

		MojObject result;
		err = response.getRequired("result", result);
		ErrorToException(err);

		MojString templateId;
		bool hasTemplateId = false;
		err = result.get(ImapAccountAdapter::TEMPLATEID, templateId, hasTemplateId);
		ErrorToException(err);

		if(hasTemplateId) {
			if(templateId == "com.palm.yahoo") { // FIXME use constant
				m_isYahoo = true;
			}
		}

		DeleteAccount();
	} CATCH_AS_FAILURE

	return MojErrNone;
}
예제 #26
0
EmailAddressPtr EmailAdapter::ParseAddress(const MojObject& addressObj)
{
	MojErr err;
	
	MojString addr;
	err = addressObj.getRequired(Address::ADDR, addr);
	ErrorToException(err);
	
	MojString name;
	bool hasName;
	err = addressObj.get(Address::NAME, name, hasName);
	ErrorToException(err);
	
	// WORKAROUND: some parts of the system expect a displayable name, even if only the
	// address is available. If the name is equal to the address, assume there wasn't
	// actually a real name available.
	if(name == addr) {
		hasName = false;
	}

	if(hasName)
		return boost::make_shared<EmailAddress>( std::string(name), std::string(addr) );
	else
		return boost::make_shared<EmailAddress>( std::string(addr) );
}
예제 #27
0
MojErr AccountFinderCommand::GetPasswordResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		// check the result first
		ErrorToException(err);

		MojObject credentials;
		// Credentials object can be missing if the POP account is restored from
		// backup.  Checking for its existence before using it will prevent exception
		// to be thrown.
		bool exists = response.get("credentials", credentials);
		if (exists) {
			MojString password;
			err = credentials.getRequired("password", password);
			ErrorToException(err);

			m_account->SetPassword(password.data());
		} else {
			MojLogInfo(m_log, "The credentials of POP account '%s' are missing", AsJsonString(m_accountId).c_str());
		}

		// get the transport object
		GetPopAccount();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
예제 #28
0
MojErr MojObjectTest::emptyTest(MojObject& obj)
{
    MojObject obj2;
    MojString str1;
    MojString str2;

    bool found = false;

    MojTestAssert(obj.size() == 0);
    MojTestAssert(obj.empty());
    MojTestAssert(obj.boolValue() == false);
    MojTestAssert(obj.intValue() == 0);
    MojTestAssert(obj.decimalValue() == MojDecimal());

    MojTestAssert(obj.begin() == obj.end());
    MojTestAssert(!obj.contains(_T("hello")));
    MojTestAssert(!obj.get(_T("hi"), obj2));
    MojErr err = obj.del(_T("hello"), found);
    MojTestErrCheck(err);

    obj2.assign(obj);
    MojTestAssert(obj2.type() == obj.type());
    MojTestAssert(obj2 == obj);
    MojTestAssert(!(obj2 != obj));

    err = obj.stringValue(str1);
    MojTestErrCheck(err);
    err = obj2.stringValue(str2);
    MojTestErrCheck(err);
    MojTestAssert(str1 == str2);

    return MojErrNone;
}
/*
 * Result of query for buddy with given username and serviceName
 *
 * If the buddy is found, we can send no matter what. If buddy is not found, we need to check if this service allows sending IM messages
 * to non buddies (gtalk does not allow this, aol does)
 */
MojErr SendOneMessageHandler::findBuddyResult(MojObject& result, MojErr findErr)
{

	if (findErr) {

		MojString error;
		MojErrToString(findErr, error);
		MojLogError(IMServiceApp::s_log, _T("findBuddyResult: error %d - %s"), findErr, error.data());
		// not much we can do here...
		failMessage(ERROR_SEND_GENERIC_ERROR);

	} else {

		// log the results
		MojString mojStringJson;
		result.toJson(mojStringJson);
		MojLogDebug(IMServiceApp::s_log, _T("findBuddyResult result: %s"), mojStringJson.data());

		// "results" in result
		MojObject results;
		result.get(_T("results"), results);

		// check to see if array is empty - there should really always be 0 or 1 item here
		if (!results.empty()){

			// buddy is on the list - send to the transport
			MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - user is on buddy list. No need to check account template."));
			sendToTransport();
		}
		else {
			MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - no buddy found. Need to check account template if this is allowed"));

			// check palm://com.palm.service.accounts/listAccountTemplates {"capability":"MESSAGING"} to get a list of account templates that support messaging.
			// If the account template includes "chatWithNonBuddies":false, it should fail to send.
			MojLogInfo(IMServiceApp::s_log, "Issuing listAccountTemplates request to com.palm.service.accounts");

			// parameters: {“capability”:”MESSAGING”}
			MojObject params;
			params.putString("capability", "MESSAGING");

			// Get a request object from the service
			MojRefCountedPtr<MojServiceRequest> req;
			MojErr err = m_service->createRequest(req);

			if (!err) {
				err = req->send(m_listAccountSlot, "com.palm.service.accounts", "listAccountTemplates", params);
			}

			if (err) {
				MojString error;
				MojErrToString(err, error);
				MojLogError(IMServiceApp::s_log, _T("findBuddyResult failed to send request to accounts: error %d - %s"), err, error.data());
				// not much we can do here...don't leave message still pending
				failMessage(ERROR_SEND_GENERIC_ERROR);
			}
		}
	}

	return MojErrNone;
}
예제 #30
0
MojErr MojDbQuery::addClauses(WhereMap& map, const MojObject& array)
{
	MojObject clause;
	MojSize i = 0;
	while (array.at(i++, clause)) {
		MojString prop;
		MojErr err = clause.getRequired(PropKey, prop);
		MojErrCheck(err);
		MojString opStr;
		err = clause.getRequired(OpKey, opStr);
		MojErrCheck(err);
		CompOp op = OpNone;
		err = stringToOp(opStr, op);
		MojErrCheck(err);
		MojObject val;
		err = clause.getRequired(ValKey, val);
		MojErrCheck(err);
		MojDbCollationStrength coll = MojDbCollationInvalid;
		MojString collateStr;
		bool found = false;
		err = clause.get(CollateKey, collateStr, found);
		MojErrCheck(err);
		if (found) {
			err = MojDbUtils::collationFromString(collateStr, coll);
			MojErrCheck(err);
		}
		err = addClause(map, prop, op, val, coll);
		MojErrCheck(err);
	}
	return MojErrNone;
}