Пример #1
0
int json_handle_set_parameter_value(char *line)
{
	json_object *js_obj;
	char *param_name, *fault_code, *status, *cfg_load;


	js_obj = json_tokener_parse(line);
	if (js_obj == NULL || is_error(js_obj) || json_object_get_type(js_obj) != json_type_object)
		return -1;

	if (status = json_common_get_string(js_obj, "status")) {
		cfg_load = json_common_get_string(js_obj, "config_load");
		if (cfg_load && atoi(cfg_load))
			cwmp->end_session |= ENDS_RELOAD_CONFIG;
		external_set_param_val_resp_status(status);
	}
	else {
		param_name = json_common_get_string(js_obj, "parameter");
		fault_code = json_common_get_string(js_obj, "fault_code");
		external_add_list_paramameter(param_name, NULL, NULL, fault_code);
	}
	json_object_put(js_obj);
	return 0;
}
Пример #2
0
pa_bool_t pa_format_info_get_prop_string(pa_format_info *f, const char *key, char **v) {
    const char *str = NULL;
    json_object *o;

    pa_assert(f);
    pa_assert(key);
    pa_assert(v);

    str = pa_proplist_gets(f->plist, key), FALSE;
    if (!str)
        return FALSE;

    o = json_tokener_parse(str);
    pa_return_val_if_fail(!is_error(o), FALSE);
    if (json_object_get_type(o) != json_type_string) {
        json_object_put(o);
        return FALSE;
    }

    *v = pa_xstrdup(json_object_get_string(o));
    json_object_put(o);

    return TRUE;
}
Пример #3
0
/**
 * 項
 *
 * @param[in] calc calcinfo構造体
 * @return 値
 */
static dbl
term(calcinfo *calc)
{
    dbl x = 0.0, y = 0.0; /* 値 */

    dbglog("start");

    if (is_error(calc))
        return EX_ERROR;

    x = factor(calc);
    dbglog(calc->fmt, x);

    while (true) {
        if (calc->ch == '*') {
            readch(calc);
            x *= factor(calc);
        } else if (calc->ch == '/') {
            readch(calc);
            y = factor(calc);
            if (y == 0) { /* ゼロ除算エラー */
                set_errorcode(calc, E_DIVBYZERO);
                return EX_ERROR;
            }
            x /= y;
        } else if (calc->ch == '^') {
            readch(calc);
            y = factor(calc);
            x = get_pow(calc, x, y);
        } else {
            break;
        }
    }
    dbglog(calc->fmt, x);
    return x;
}
ApplicationDescription* ApplicationDescription::fromJsonString(const char* jsonStr)
{
    ApplicationDescription* appDesc = new ApplicationDescription();

    struct json_object* root=0;

    root = json_tokener_parse( jsonStr );
    if( !root || is_error( root ) )
    {
        fprintf( stderr, "ApplicationDescription::fromJsonString: Failed to parse string into a JSON string.\n" );
        return 0;
    }

    bool success = true;

    success &= extractFromJson(root, "id", appDesc->m_id);
    success &= extractFromJson(root, "category", appDesc->m_category);
    success &= extractFromJson(root, "main", appDesc->m_entryPoint);
    success &= extractFromJson(root, "version", appDesc->m_version);
    success &= extractFromJson(root, "splashicon", appDesc->m_splashIconName);
    success &= extractFromJson(root, "splashBackground", appDesc->m_splashBackgroundName);
    success &= extractFromJson(root, "miniicon", appDesc->m_miniIconName);
    success &= extractFromJson(root, "folderPath", appDesc->m_folderPath);
    success &= extractFromJson(root, "attributes", appDesc->m_attributes);
    success &= extractFromJson(root, "vendor", appDesc->m_vendorName);
    success &= extractFromJson(root, "vendorUrl", appDesc->m_vendorUrl);
    success &= extractFromJson(root, "appmenu", appDesc->m_appmenuName);

    success &= extractFromJson(root, "noWindow", appDesc->m_isHeadLess);
    success &= extractFromJson(root, "transparent", appDesc->m_hasTransparentWindows);
    success &= extractFromJson(root, "removable", appDesc->m_isRemovable);
    success &= extractFromJson(root, "userHideable", appDesc->m_isUserHideable);
    success &= extractFromJson(root, "visible", appDesc->m_isVisible);
    success &= extractFromJson(root, "launchinnewgroup", appDesc->m_launchInNewGroup);
    success &= extractFromJson(root, "requestedWindowOrientation", appDesc->m_requestedWindowOrientation);
    success &= extractFromJson(root, "tapToShareSupported", appDesc->m_tapToShareSupported);


    int temp;
    success &= extractFromJson(root, "hardwareFeaturesNeeded", temp);
    appDesc->m_hardwareFeaturesNeeded = (uint32_t)temp;

    success &= extractFromJson(root, "type", temp);
    appDesc->m_type = (Type)temp;

    success &= extractFromJson(root, "size", temp);
    appDesc->m_appSize = temp;

    success &= extractFromJson(root, "runtimeMemoryRequired", temp);
    appDesc->m_runtimeMemoryRequired = (unsigned int)temp;

    if( root && !is_error(root) )json_object_put(root);

    if(!success) {
        fprintf(stderr,"ApplicationDescription::fromJsonString : error decodeing app description JSON string.\n" );
        delete appDesc;
        return 0;
    }

    return appDesc;
}
Пример #5
0
static bool test_hairpin(l4_protocol l4_proto, skb_creator create_skb_fn)
{
	struct sk_buff *skb_in = NULL;
	struct sk_buff *skb_out = NULL;
	struct sk_buff *skb_tmp = NULL;
	struct bib_entry *static_bib = NULL;
	struct bib_entry *dynamic_bib = NULL;
	struct session_entry *static_session = NULL;
	struct session_entry *dynamic_session = NULL;
	struct tuple tuple6;
	bool success = true;

	static_bib = bib_create_str(SERVER_ADDR6, SERVER_PORT6,
			NAT64_POOL4, SERVER_PORT6,
			l4_proto);
	dynamic_bib = bib_create_str(CLIENT_ADDR, CLIENT_PORT,
			NAT64_POOL4, DYNAMIC_BIB_IPV4_PORT,
			l4_proto);
	static_session = session_create_str(
			SERVER_ADDR6, SERVER_PORT6,
			SERVER_HAIRPIN_ADDR, DYNAMIC_BIB_IPV4_PORT,
			NAT64_POOL4, SERVER_PORT6,
			NAT64_POOL4, DYNAMIC_BIB_IPV4_PORT,
			l4_proto);
	dynamic_session = session_create_str(CLIENT_ADDR, CLIENT_PORT,
			SERVER_HAIRPIN_ADDR, SERVER_PORT6,
			NAT64_POOL4, DYNAMIC_BIB_IPV4_PORT,
			NAT64_POOL4, SERVER_PORT6,
			l4_proto);

	if (!static_bib || !dynamic_bib || !static_session || !dynamic_session)
		goto fail;

	/* Send the request. */
	if (is_error(init_ipv6_tuple(&tuple6,
			CLIENT_ADDR, CLIENT_PORT,
			SERVER_HAIRPIN_ADDR, SERVER_PORT6,
			l4_proto)))
		goto fail;
	if (is_error(create_skb_fn(&tuple6, &skb_in, 40, 32)))
		goto fail;

	success &= send(skb_in);
	success &= BIB_ASSERT(l4_proto, static_bib, dynamic_bib);
	success &= SESSION_ASSERT(l4_proto, static_session, dynamic_session);

	skb_out = skb_tmp = get_sent_skb();
	success &= assert_not_null(skb_out, "Request packet");
	if (!success)
		goto fail;

	do {
		success &= assert_equals_ipv6_str(SERVER_HAIRPIN_ADDR, &ipv6_hdr(skb_tmp)->saddr, "out src");
		success &= assert_equals_ipv6_str(SERVER_ADDR6, &ipv6_hdr(skb_tmp)->daddr, "out dst");
		skb_tmp = skb_tmp->next;
	} while (skb_tmp);
	switch (l4_proto) {
	case L4PROTO_UDP:
		success &= assert_equals_u16(DYNAMIC_BIB_IPV4_PORT,
				be16_to_cpu(udp_hdr(skb_out)->source),
				"out's src port");
		success &= assert_equals_u16(SERVER_PORT6,
				be16_to_cpu(udp_hdr(skb_out)->dest),
				"out's dst port");
		break;
	case L4PROTO_TCP:
		success &= assert_equals_u16(DYNAMIC_BIB_IPV4_PORT,
				be16_to_cpu(tcp_hdr(skb_out)->source),
				"out's src port");
		success &= assert_equals_u16(SERVER_PORT6,
				be16_to_cpu(tcp_hdr(skb_out)->dest),
				"out's dst port");
		break;
	case L4PROTO_ICMP:
	case L4PROTO_OTHER:
		log_err("Test is not designed for protocol %d.", l4_proto);
		success = false;
		break;
	}

	if (!success)
		goto fail;

	kfree_skb(skb_out);

	/* Send the response. */
	if (is_error(init_ipv6_tuple(&tuple6,
			SERVER_ADDR6, SERVER_PORT6,
			SERVER_HAIRPIN_ADDR, DYNAMIC_BIB_IPV4_PORT,
			l4_proto)))
		goto fail;
	if (is_error(create_skb_fn(&tuple6, &skb_in, 100, 32)))
		goto fail;

	success &= send(skb_in);
	/* The module should have reused the entries, so the database shouldn't have changed. */
	success &= BIB_ASSERT(l4_proto, static_bib, dynamic_bib);
	success &= SESSION_ASSERT(l4_proto, static_session, dynamic_session);

	skb_out = skb_tmp = get_sent_skb();
	success &= assert_not_null(skb_out, "Response packet");
	if (!success)
		goto fail;

	do {
		success &= assert_equals_ipv6_str(SERVER_HAIRPIN_ADDR, &ipv6_hdr(skb_out)->saddr, "out src");
		success &= assert_equals_ipv6_str(CLIENT_ADDR, &ipv6_hdr(skb_out)->daddr, "out dst");
		skb_tmp = skb_tmp->next;
	} while (skb_tmp);
	switch (l4_proto) {
	case L4PROTO_UDP:
		success &= assert_equals_u16(SERVER_PORT6,
				be16_to_cpu(udp_hdr(skb_out)->source),
				"out's src port");
		success &= assert_equals_u16(CLIENT_PORT,
				be16_to_cpu(udp_hdr(skb_out)->dest),
				"out's dst port");
		break;
	case L4PROTO_TCP:
		success &= assert_equals_u16(SERVER_PORT6,
				be16_to_cpu(tcp_hdr(skb_out)->source),
				"out's src port");
		success &= assert_equals_u16(CLIENT_PORT,
				be16_to_cpu(tcp_hdr(skb_out)->dest),
				"out's dst port");
		break;
	case L4PROTO_ICMP:
	case L4PROTO_OTHER:
		log_err("Test is not designed for protocol %d.", l4_proto);
		success = false;
		break;
	}

	kfree_skb(skb_out);
	session_return(dynamic_session);
	session_return(static_session);
	bib_kfree(dynamic_bib);
	bib_kfree(static_bib);
	return success;

fail:
	kfree_skb(skb_out);
	if (dynamic_session)
		session_return(dynamic_session);
	if (static_session)
		session_return(static_session);
	if (dynamic_bib)
		bib_kfree(dynamic_bib);
	if (static_bib)
		bib_kfree(static_bib);

	return false;
}
Пример #6
0
void system_call_print(int argc, char *argv[]) {

    print_debug("Here- Syscall!!\n");

    pid_t child_pid;

    if ((child_pid = fork()) == 0) {
        print_debug("Child: Entering\n");

        if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) == -1) {
            perror("ptrace in Child");
        }

        print_debug("Child: After ptrace\n");

        if (raise(SIGSTOP) != 0) {
            perror("raise stop signal in child");
        }

        print_debug("Child: After STOP\n");

        if (execvp(argv[1], argv + 1) == -1) {
            perror("Exec error");
        }
    }
    else {
        int stat;

        print_debug("Parent: Entering...\n");

        if (waitpid(child_pid, &stat, 0) == -1) {
            perror("Waiting for SIGSTOP");
        }
        else if (WIFSTOPPED(stat) == 0) {
            fprintf(stderr, "Error: Strange signal in child\n");
        }

        print_debug("Parent: After waitpid...\n");

        // set options PTRACE_O_TRACESYSGOOD to distinguish ptrace trap from normal
        // trap
        ptrace(PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACESYSGOOD);


        while (1) {
            print_debug("Parent: In loop\n");

            ptrace(PTRACE_SYSCALL, child_pid, NULL, NULL);

            print_debug("Signal...\n");

            // tracee enters ptrace stop
            if (waitpid(child_pid, &stat, WUNTRACED) == -1)
                perror("Waiting for signal");

            if (WIFEXITED(stat)) {
                print_debug("Done...\n");
                break;
            }

            if (!WIFSTOPPED(stat) || !((WSTOPSIG(stat) & 0x80))) {
                continue;
            }

            int syscall_num, return_val;

            syscall_num = ptrace(PTRACE_PEEKUSER, child_pid, sizeof(long) * ORIG_EAX);

            struct user_regs_struct regists;
            ptrace(PTRACE_GETREGS, child_pid, NULL, &regists);

            ptrace(PTRACE_SYSCALL, child_pid, NULL, NULL);

            print_debug("Signal...\n");

            // tracee enters ptrace stop
            if (waitpid(child_pid, &stat, WUNTRACED) == -1)
                perror("Waiting for signal");

            if (WIFEXITED(stat)) {
                print_debug("Done...\n");
                break;
            }

            if (!WIFSTOPPED(stat) || !(WSTOPSIG(stat) & 0x80)) {
                continue;
            }

            return_val = ptrace(PTRACE_PEEKUSER, child_pid, sizeof(long) * EAX);

            printf("%s (", syscall_entries[syscall_num].sys_name);

            int i;

            for (i=0; i < syscall_entries[syscall_num].nargs; i++) {
                switch (i) {
                case 0:
                    printf("%llu", regists.rdi);
                    break;
                case 1:
                    printf("%llu", regists.rsi);
                    break;
                case 2:
                    printf("%llu", regists.rdx);
                    break;
                case 3:
                    printf("%llu", regists.r10);
                    break;
                case 4:
                    printf("%llu", regists.r8);
                    break;
                case 5:
                    printf("%llu", regists.r9);
                    break;
                }

                if (i != syscall_entries[syscall_num].nargs - 1)
                    printf(", ");
                else
                    printf(")");
            }

            if (return_val >= 0 || !is_error(return_val)) {
                printf("  = %d\n", return_val);
            }
            else {
                printf("  = -1 (%s)\n", strerror(return_val * -1));
            }


        }

    }

}
void LocalePrefsHandler::readLocaleFile()
{
	// Read the locale file
	char* jsonStr = Utils::readFile(s_custLocaleFile);
	if (!jsonStr)
		jsonStr = Utils::readFile(s_defaultLocaleFile);
	if (!jsonStr) {
        //luna_critical(s_logChannel, "Failed to load locale files: [%s] nor [%s]", s_custLocaleFile,s_defaultLocaleFile);
        qCritical() << "Failed to load locale files: [" << s_custLocaleFile << "] nor [" << s_defaultLocaleFile << "]";
		return;
	}

	json_object* root = 0;
	json_object* label = 0;
	array_list* localeArray = 0;

	root = json_tokener_parse(jsonStr);
	if (!root || is_error(root)) {
        //luna_critical(s_logChannel, "Failed to parse locale file contents into json");
        qCritical() << "Failed to parse locale file contents into json";
		goto Done;
	}

	label = json_object_object_get(root, "locale");
	if (!label || is_error(label)) {
        //luna_critical(s_logChannel, "Failed to get locale entry from locale file");
        qCritical() << "Failed to get locale entry from locale file";
		goto Done;
	}

	localeArray = json_object_get_array(label);
	if (!localeArray) {
        //luna_critical(s_logChannel, "Failed to get locale array from locale file");
        qCritical() << "Failed to get locale array from locale file";
		goto Done;
	}

	for (int i = 0; i < array_list_length(localeArray); i++) {
		json_object* obj = (json_object*) array_list_get_idx(localeArray, i);

		LocaleEntry localeEntry;
		array_list* countryArray = 0;
		
		label = json_object_object_get(obj, "languageName");
		if (!label || is_error(label))
			continue;

		localeEntry.language.first = json_object_get_string(label);

		label = json_object_object_get(obj, "languageCode");
		if (!label || is_error(label))
			continue;

		localeEntry.language.second = json_object_get_string(label);

		label = json_object_object_get(obj, "countries");
		if (!label || is_error(label))
			continue;

		countryArray = json_object_get_array(label);
		for (int j = 0; j < array_list_length(countryArray); j++) {
			json_object* countryObj = (json_object*) array_list_get_idx(countryArray, j);
			NameCodePair country;

			label = json_object_object_get(countryObj, "countryName");
			if (!label || is_error(label))
				continue;

			country.first = json_object_get_string(label);

			label = json_object_object_get(countryObj, "countryCode");
			if (!label || is_error(label))
				continue;

			country.second = json_object_get_string(label);

			localeEntry.countries.push_back(country);
		}

		m_localeEntryList.push_back(localeEntry);		
	}

Done:

	if (root && !is_error(root))
		json_object_put(root);

	delete [] jsonStr;
}
Пример #8
0
static int pa_format_info_prop_compatible(const char *one, const char *two) {
    json_object *o1 = NULL, *o2 = NULL;
    int i, ret = 0;

    o1 = json_tokener_parse(one);
    if (is_error(o1))
        goto out;

    o2 = json_tokener_parse(two);
    if (is_error(o2))
        goto out;

    /* We don't deal with both values being non-fixed - just because there is no immediate need (FIXME) */
    pa_return_val_if_fail(pa_json_is_fixed_type(o1) || pa_json_is_fixed_type(o2), false);

    if (pa_json_is_fixed_type(o1) && pa_json_is_fixed_type(o2)) {
        ret = pa_json_value_equal(o1, o2);
        goto out;
    }

    if (pa_json_is_fixed_type(o1)) {
        json_object *tmp = o2;
        o2 = o1;
        o1 = tmp;
    }

    /* o2 is now a fixed type, and o1 is not */

    if (json_object_get_type(o1) == json_type_array) {
        for (i = 0; i < json_object_array_length(o1); i++) {
            if (pa_json_value_equal(json_object_array_get_idx(o1, i), o2)) {
                ret = 1;
                break;
            }
        }
    } else if (json_object_get_type(o1) == json_type_object) {
        /* o1 should be a range type */
        int min, max, v;
        json_object *o_min = NULL, *o_max = NULL;

        if (json_object_get_type(o2) != json_type_int) {
            /* We don't support non-integer ranges */
            goto out;
        }

        o_min = json_object_object_get(o1, PA_JSON_MIN_KEY);
        if (!o_min || json_object_get_type(o_min) != json_type_int)
            goto out;

        o_max = json_object_object_get(o1, PA_JSON_MAX_KEY);
        if (!o_max || json_object_get_type(o_max) != json_type_int)
            goto out;

        v = json_object_get_int(o2);
        min = json_object_get_int(o_min);
        max = json_object_get_int(o_max);

        ret = v >= min && v <= max;
    } else {
        pa_log_warn("Got a format type that we don't support");
    }

out:
    if (o1)
        json_object_put(o1);
    if (o2)
        json_object_put(o2);

    return ret;
}
Пример #9
0
/**
* @brief Remove an alarm by id.
*
* {"alarmId":1}
*
* Response:
*
* {"returnValue":true}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmRemove(LSHandle *sh, LSMessage *message, void *ctx)
{
	LSError lserror;
	LSErrorInit(&lserror);

	bool found = false;
	bool retVal;

	const char *payload = LSMessageGetPayload(message);
	struct json_object *object = json_tokener_parse(payload);

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("alarmRemove() : %s", LSMessageGetPayload(message));

	int alarmId =
	    json_object_get_int(json_object_object_get(object, "alarmId"));

	GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms);

	while (!g_sequence_iter_is_end(iter))
	{
		_Alarm *alarm = (_Alarm *)g_sequence_get(iter);
		GSequenceIter *next = g_sequence_iter_next(iter);

		if (alarm && alarm->id == alarmId)
		{
			char *timeout_key = g_strdup_printf("%s-%d", alarm->key, alarm->id);
			_timeout_clear("com.palm.sleep", timeout_key,
			               false /*public_bus*/);
			g_free(timeout_key);

			g_sequence_remove(iter);
			found = true;
		}

		iter = next;
	}

	const char *response;

	if (found)
	{
		alarm_write_db();
		response = "{\"returnValue\":true}";
	}
	else
	{
		response = "{\"returnValue\":false}";
	}

	retVal = LSMessageReply(sh, message, response, &lserror);

	if (!retVal)
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	return true;
}
Пример #10
0
/**
* @brief Query for set of alarms identified by 'serviceName' & 'key'.
*
* {"serviceName":"com.palm.X", "key":"calendarAlarm"}
*
* Response:
*
* {"alarms":
*   [{"alarmId":1,"key":"calendarAlarm"},
*    {"alarmId":2,"key":"calendarAlarm"},
*   ]}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmQuery(LSHandle *sh, LSMessage *message, void *ctx)
{
	bool retVal;
	const char *serviceName, *key;
	struct json_object *object;
	GString *alarm_str = NULL;
	GString *buf = NULL;

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));
	key = json_object_get_string(
	          json_object_object_get(object, "key"));

	if (!serviceName || !key)
	{
		goto invalid_format;
	}

	alarm_str = g_string_sized_new(512);

	if (!alarm_str)
	{
		goto cleanup;
	}

	bool first = true;
	GSequenceIter *iter = g_sequence_get_begin_iter(gAlarmQueue->alarms);

	while (!g_sequence_iter_is_end(iter))
	{
		_Alarm *alarm = (_Alarm *)g_sequence_get(iter);
		GSequenceIter *next = g_sequence_iter_next(iter);

		if (alarm && alarm->serviceName && alarm->key &&
		        (strcmp(alarm->serviceName, serviceName) == 0) &&
		        (strcmp(alarm->key, key) == 0))
		{
			g_string_append_printf(alarm_str,
			                       "%s{\"alarmId\":%d,\"key\":\"%s\"}",
			                       first ? "" : "\n,",
			                       alarm->id, alarm->key);
			first = false;
		}

		iter = next;
	}

	buf = g_string_sized_new(512);
	g_string_append_printf(buf, "{\"alarms\": [%s]}", alarm_str->str);

	LSError lserror;
	LSErrorInit(&lserror);
	retVal = LSMessageReply(sh, message, buf->str, &lserror);

	if (!retVal)
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	goto cleanup;

invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"alarmQuery parameters are missing.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (alarm_str)
	{
		g_string_free(alarm_str, TRUE);
	}

	if (buf)
	{
		g_string_free(buf, TRUE);
	}

	if (!is_error(object))
	{
		json_object_put(object);
	}

	return true;
}
Пример #11
0
/**
* @brief Set a calendar event.
*
* luna://com.palm.sleep/time/alarmAddCalendar
*
* Message:
* Set alarm to expire at a fixed calendar time in UTC. Response will be sent
* as a call to "luna://com.palm.X/alarm".
*
* {"key":"calendarAlarm", "serviceName":"com.palm.X",
*  "date":"01-02-2009", "time":"13:40:03"}
*
* Subscribing indicates that you want the alarm message as a response to
* the current call.
*
* {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X",
*  "date":"01-02-2009", "time":"13:40:03"}
*
* Response:
*
* Alarm is sucessfully registered for calendar date
* {"alarmId":1}
*
* Subscribe case:
* {"alarmId":1,"subscribed":true}
* {"alarmId":1,"fired":true}
*
* Alarm failed to be registered:
*
* {"returnValue":false, ...}
* {"returnValue":false,"serivceName":"com.palm.sleep",
*  "errorText":"com.palm.sleep is not running"}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmAddCalendar(LSHandle *sh, LSMessage *message, void *ctx)
{
	int alarm_id;
	struct json_object *object;
	const char *key, *serviceName, *applicationName, *cal_date, *cal_time;
	struct tm gm_time;
	bool subscribe;
	bool retVal = false;
	gchar **cal_date_str;

	time_t alarm_time = 0;

	LSError lserror;
	LSErrorInit(&lserror);

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("alarmAddCalendar() : %s", LSMessageGetPayload(message));

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));

	applicationName = LSMessageGetApplicationID(message);

	key = json_object_get_string(json_object_object_get(object, "key"));

	cal_date = json_object_get_string(
	               json_object_object_get(object, "date"));
	cal_time = json_object_get_string(
	               json_object_object_get(object, "time"));


	if (!cal_date || !cal_time)
	{
		goto invalid_format;
	}

	int hour, min, sec;
	int month, day, year;

	if (!ConvertJsonTime(cal_time, &hour, &min, &sec))
	{
		goto invalid_format;
	}

	cal_date_str = g_strsplit(cal_date, "-", 3);

	if ((NULL == cal_date_str[0]) || (NULL == cal_date_str[1]) ||
	        (NULL == cal_date_str[2]))
	{
		goto invalid_format;
	}

	month = atoi(cal_date_str[0]);
	day = atoi(cal_date_str[1]);
	year = atoi(cal_date_str[2]);
	g_strfreev(cal_date_str);

	if (hour < 0 || hour > 24 || min < 0 || min > 59 ||
	        sec < 0 || sec > 59 ||
	        month < 1 || month > 12 || day < 1 || day > 31 || year < 0)
	{
		goto invalid_format;
	}

	SLEEPDLOG_DEBUG("alarmAddCalendar() : (%s %s %s) at %s %s", serviceName,
	                applicationName, key, cal_date, cal_time);

	struct json_object *subscribe_json =
	    json_object_object_get(object, "subscribe");

	subscribe = json_object_get_boolean(subscribe_json);

	memset(&gm_time, 0, sizeof(struct tm));

	gm_time.tm_hour = hour;
	gm_time.tm_min = min;
	gm_time.tm_sec = sec;
	gm_time.tm_mon = month - 1; // month-of-year [0-11]
	gm_time.tm_mday = day;      // day-of-month [1-31]
	gm_time.tm_year = year - 1900;

	/* timegm converts time(GMT) -> seconds since epoch */
	alarm_time = timegm(&gm_time);

	if (alarm_time < 0)
	{
		goto invalid_format;
	}

	retVal = alarm_queue_new(key, true, alarm_time,
	                         serviceName, applicationName, subscribe, message, &alarm_id);

	if (!retVal)
	{
		goto error;
	}

	/*****************
	 * Use new timeout API
	 */
	{
		char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id);
		_AlarmTimeout timeout;
		_timeout_create(&timeout, "com.palm.sleep", timeout_key,
		                "luna://com.palm.sleep/time/internalAlarmFired",
		                "{}",
		                false /*public bus*/,
		                true /*wakeup*/,
		                "" /*activity_id*/,
		                0 /*activity_duration_ms*/,
		                true /*calendar*/,
		                alarm_time);

		retVal = _timeout_set(&timeout);

		g_free(timeout_key);

		if (!retVal)
		{
			goto error;
		}
	}
	/*****************/

	/* Send alarm id of sucessful alarm add. */
	GString *reply = g_string_sized_new(512);
	g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id);

	if (subscribe_json)
	{
		g_string_append_printf(reply, ",\"subscribed\":%s",
		                       subscribe ? "true" : "false");
	}

	g_string_append_printf(reply, "}");

	retVal = LSMessageReply(sh, message, reply->str, &lserror);

	g_string_free(reply, TRUE);

	goto cleanup;
error:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Unknown error\"}", &lserror);
	goto cleanup;
invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Invalid format for alarm time.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	if (!retVal && LSErrorIsSet(&lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	return true;
}
Пример #12
0
/**
* @brief  Set alarm to fire in a fixed time in the future.
*
* luna://com.palm.sleep/time/alarmAdd
*
* Set alarm to expire in T+5hrs. Response will be sent
* as a call to "luna://com.palm.X/alarm".
*
* {"key":"calendarAlarm", "serviceName":"com.palm.X",
*  "relative_time":"05:00:00"}
*
* Subscribing indicates that you want the alarm message as a response to
* the current call.
*
* {"subscribe":true, "key":"calendarAlarm", "serviceName":"com.palm.X",
*  "relative_time":"05:00:00"}
*
* Alarm is sucessfully registered.
* {"alarmId":1}
*
* Alarm failed to be registered:
*
* {"returnValue":false, ...}
* {"returnValue":false,"serivceName":"com.palm.sleep",
*  "errorText":"com.palm.sleep is not running"}
*
* @param  sh
* @param  message
* @param  ctx
*
* @retval
*/
static bool
alarmAdd(LSHandle *sh, LSMessage *message, void *ctx)
{
	time_t alarm_time = 0;
	int rel_hour, rel_min, rel_sec;

	const char *key, *serviceName, *applicationName, *rel_time;
	bool subscribe;

	struct json_object *object;

	int alarm_id;
	bool retVal = false;

	LSError lserror;
	LSErrorInit(&lserror);
	time_t rtctime = 0;

	object = json_tokener_parse(LSMessageGetPayload(message));

	if (is_error(object))
	{
		goto malformed_json;
	}

	SLEEPDLOG_DEBUG("%s", LSMessageGetPayload(message));

	serviceName = json_object_get_string(
	                  json_object_object_get(object, "serviceName"));

	applicationName = LSMessageGetApplicationID(message);

	key = json_object_get_string(json_object_object_get(object, "key"));

	rel_time = json_object_get_string(
	               json_object_object_get(object, "relative_time"));

	if (!rel_time)
	{
		goto invalid_format;
	}

	if (!ConvertJsonTime(rel_time, &rel_hour, &rel_min, &rel_sec) ||
	        (rel_hour < 0 || rel_hour > 24 || rel_min < 0 || rel_min > 59 || rel_sec < 0 ||
	         rel_sec > 59))
	{
		goto invalid_format;
	}

	nyx_system_query_rtc_time(GetNyxSystemDevice(), &rtctime);

	SLEEPDLOG_DEBUG("alarmAdd(): (%s %s %s) in %s (rtc %ld)", serviceName,
	                applicationName, key, rel_time, rtctime);
	struct json_object *subscribe_json =
	    json_object_object_get(object, "subscribe");

	subscribe = json_object_get_boolean(subscribe_json);


	alarm_time = reference_time();
	alarm_time += rel_sec;
	alarm_time += rel_min * 60;
	alarm_time += rel_hour * 60 * 60;

	retVal = alarm_queue_new(key, false, alarm_time,
	                         serviceName, applicationName, subscribe, message, &alarm_id);

	if (!retVal)
	{
		goto error;
	}

	/*****************
	 * Use new timeout API
	 */
	{
		char *timeout_key = g_strdup_printf("%s-%d", key, alarm_id);
		_AlarmTimeout timeout;
		_timeout_create(&timeout, "com.palm.sleep", timeout_key,
		                "luna://com.palm.sleep/time/internalAlarmFired",
		                "{}",
		                false /*public bus*/,
		                true /*wakeup*/,
		                "" /*activity_id*/,
		                0 /*activity_duration_ms*/,
		                false /*calendar*/,
		                alarm_time);

		retVal = _timeout_set(&timeout);

		g_free(timeout_key);

		if (!retVal)
		{
			goto error;
		}
	}
	/*****************/

	/* Send alarm id of sucessful alarm add. */
	GString *reply = g_string_sized_new(512);
	g_string_append_printf(reply, "{\"alarmId\":%d", alarm_id);

	if (subscribe_json)
	{
		g_string_append_printf(reply, ",\"subscribed\":%s",
		                       subscribe ? "true" : "false");
	}

	g_string_append_printf(reply, "}");

	retVal = LSMessageReply(sh, message, reply->str, &lserror);

	g_string_free(reply, TRUE);
	goto cleanup;
error:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Unknown error\"}", &lserror);
	goto cleanup;
invalid_format:
	retVal = LSMessageReply(sh, message, "{\"returnValue\":false,"
	                        "\"errorText\":\"Invalid format for alarm time.\"}", &lserror);
	goto cleanup;
malformed_json:
	LSMessageReplyErrorBadJSON(sh, message);
	goto cleanup;
cleanup:

	if (!is_error(object))
	{
		json_object_put(object);
	}

	if (!retVal && LSErrorIsSet(&lserror))
	{
		LSErrorPrint(&lserror, stderr);
		LSErrorFree(&lserror);
	}

	return true;
}
Пример #13
0
static bool 
serviceResponse(LSHandle *sh, LSMessage *reply, void *ctx)
{
    LSError lserror;
    LSErrorInit(&lserror);
    LSMessageToken token;

    const char *payload;
    bool free_payload = false;

    token = LSMessageGetResponseToken(reply);
    payload = LSMessageGetPayload(reply);

    //g_message("%s Handling: %ld, %s", __FUNCTION__, token, payload);
    
    if (line_number) {
      printf("%2d: ", current_line_number++);
    }
    
    if (query_list != NULL) {
      // Use set of queries to transform original object into reduced form that
      // only contains queried selections -- then pass that through normal formatting.
      struct json_object *original = json_tokener_parse(payload);
      struct json_object *new_object = json_object_new_object();
      GList * query = query_list;
      if ( original && !is_error(original) ) {
        while (query) {
          char * query_text = (char*)query->data;
          struct json_object * result = apply_query(original, query_text);
          json_object_object_add(new_object, query_text, result);
          query = query->next;
        }
        payload = strdup(json_object_get_string(new_object));
        free_payload = true;
        json_object_put(new_object);
      }
    }
    
    if (format_response) {
      struct json_object *object = json_tokener_parse(payload);
      if ( !object || is_error(object) ) {
        // fall back to plain print
        printf("%s\n", payload);
      } else {
        pretty_print(object, 0, line_number ? 4 /* expected characters in line numbers */ : 0);
        printf("\n");
        json_object_put(object);
      }
    } else {
      printf("%s\n", payload);
    }
    
    if (free_payload)
      free((void*)payload);
    
    fflush(stdout);

    if (--count == 0)
    {
        bool retVal = LSCallCancel (sh, token, &lserror);
        if (!retVal)
        {
            LSErrorPrint (&lserror, stderr);
            LSErrorFree (&lserror);
        }
        g_timeout_add (300, goodbye, ctx);
        return true;
    }

    return true;
}
Пример #14
0
//------------------------------------------------------------------------------
// Name:
// Desc:
//------------------------------------------------------------------------------
IDebugEvent::Message PlatformEvent::error_description() const {
	Q_ASSERT(is_error());

	auto fault_address = static_cast<edb::address_t>(-1);
	if(event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
		fault_address = (edb::address_t)(event.u.Exception.ExceptionRecord.ExceptionInformation[1]);
	}

	switch(code()) {
	case EXCEPTION_ACCESS_VIOLATION:
		return Message(
			tr("Illegal Access Fault"),
			tr(
				"<p>The debugged application encountered a segmentation fault.<br />The address <strong>0x%1</strong> could not be accessed.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>").arg(edb::v1::format_pointer(fault_address))
			);
	case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
		return Message(
			tr("Array Bounds Error"),
			tr(
				"<p>The debugged application tried to access an out of bounds array element.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>").arg(edb::v1::format_pointer(fault_address))
			);
	case EXCEPTION_DATATYPE_MISALIGNMENT:
		return Message(
			tr("Bus Error"),
			tr(
				"<p>The debugged application tried to read or write data that is misaligned.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_DENORMAL_OPERAND:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);

	case EXCEPTION_FLT_DIVIDE_BY_ZERO:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The debugged application tried to divide a floating-point value by a floating-point divisor of zero.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_INEXACT_RESULT:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The result of a floating-point operation cannot be represented exactly as a decimal fraction.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_INVALID_OPERATION:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The application attempted an invalid floating point operation.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_OVERFLOW:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_STACK_CHECK:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The stack overflowed or underflowed as the result of a floating-point operation.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_FLT_UNDERFLOW:
		return Message(
			tr("Floating Point Exception"),
			tr(
				"<p>The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_ILLEGAL_INSTRUCTION:
		return Message(
			tr("Illegal Instruction Fault"),
			tr(
				"<p>The debugged application attempted to execute an illegal instruction.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_IN_PAGE_ERROR:
		return Message(
			tr("Page Error"),
			tr(
				"<p>The debugged application tried to access a page that was not present, and the system was unable to load the page.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_INT_DIVIDE_BY_ZERO:
		return Message(
			tr("Divide By Zero"),
			tr(
				"<p>The debugged application tried to divide an integer value by an integer divisor of zero.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_INT_OVERFLOW:
		return Message(
			tr("Integer Overflow"),
			tr(
				"<p>The result of an integer operation caused a carry out of the most significant bit of the result.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_INVALID_DISPOSITION:
		return Message(
			tr("Invalid Disposition"),
			tr(
				"<p>An exception handler returned an invalid disposition to the exception dispatcher.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_NONCONTINUABLE_EXCEPTION:
		return Message(
			tr("Non-Continuable Exception"),
			tr(
				"<p>The debugged application tried to continue execution after a non-continuable exception occurred.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_PRIV_INSTRUCTION:
		return Message(
			tr("Privileged Instruction"),
			tr(
				"<p>The debugged application tried to execute an instruction whose operation is not allowed in the current machine mode.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	case EXCEPTION_STACK_OVERFLOW:
		return Message(
			tr("Stack Overflow"),
			tr(
				"<p>The debugged application has exhausted its stack.</p>"
				"<p>If you would like to pass this exception to the application press Shift+[F7/F8/F9]</p>")
			);
	default:
		return Message();
	}
}
Пример #15
0
Value * evaluate(Environment *env, Value *expr) {

    EvaluationContext *ctx;
    Value *temp, *result;

    Value *operator;
    Value *operand_val, *operand_cons;
    Value *operands, *operands_end, *nil_value;
    int num_operands;

    /* Set up a new evaluation context and record our local variables, so that
     * the garbage-collector can see any temporary values we use.
     */
    ctx = push_new_evalctx(env, expr);
    evalctx_register(&temp);
    evalctx_register(&result);
    evalctx_register(&operator);
    evalctx_register(&operand_val);
    evalctx_register(&operand_cons);
    evalctx_register(&operands);
    evalctx_register(&operands_end);
    evalctx_register(&nil_value);

#ifdef VERBOSE_EVAL
    printf("\nEvaluating expression:  ");
    print_value(stdout, expr);
    printf("\n");
#endif

    /* If this is a special form, evaluate it.  Otherwise, this function will
     * simply pass the input through to the result.
     */
    result = eval_special_form(env, expr);
    if (result != expr)
        goto Done;    /* It was a special form. */

    /*
     * If the input is an atom, we need to resolve it to a value, using the
     * current environment.
     */

    if (is_atom(expr)) {
        /* Treat the atom as a name - resolve it to a value. */
        result = resolve_binding(env, expr->string_val);
        if (result == NULL) {
            result = make_error("couldn't resolve name \"%s\" to a value!",
                expr->string_val);
        }

        goto Done;
    }

    /*
     * If the input isn't an atom and isn't a cons-pair, then assume it's a
     * value that doesn't need evaluating, and just return it.
     */

    if (!is_cons_pair(expr)) {
        result = expr;
        goto Done;
    }

    /*
     * Evaluate operator into a lambda expression.
     */

    temp = get_car(expr);

    operator = evaluate(env, temp);
    if (is_error(operator)) {
        result = operator;
        goto Done;
    }
    if (!is_lambda(operator)) {
        result = make_error("operator is not a valid lambda expression");
        goto Done;
    }

#ifdef VERBOSE_EVAL
    printf("Operator:  ");
    print_value(stdout, operator);
    printf("\n");
#endif

    /*
     * Evaluate each operand into a value, and build a list up of the values.
     */

#ifdef VERBOSE_EVAL
    printf("Starting evaluation of operands.\n");
#endif

    num_operands = 0;
    operands_end = NULL;
    operands = nil_value = make_nil();

    temp = get_cdr(expr);
    while (is_cons_pair(temp)) {
        Value *raw_operand;

        num_operands++;

        /* This is the raw unevaluated value. */
        raw_operand = get_car(temp);

        /* Evaluate the raw input into a value. */

        operand_val = evaluate(env, raw_operand);
        if (is_error(operand_val)) {
            result = operand_val;
            goto Done;
        }

        operand_cons = make_cons(operand_val, nil_value);
        if (operands_end != NULL)
            set_cdr(operands_end, operand_cons);
        else
            operands = operand_cons;

        operands_end = operand_cons;

        temp = get_cdr(temp);
    }

    /*
     * Apply the operator to the operands, to generate a result.
     */

    if (operator->lambda_val->native_impl) {
        /* Native lambdas don't need an environment created for them.  Rather,
         * we just pass the list of arguments to the native function, and it
         * processes the arguments as needed.
         */
        result = operator->lambda_val->func(num_operands, operands);
    }
    else {
        /* These don't need registered on the explicit stack.  (I hope.) */
        Environment *child_env;
        Value *body_iter;

        /* It's an interpreted lambda.  Create a child environment, then
         * populate it with values based on the lambda's argument-specification
         * and the input operands.
         */
        child_env = make_environment(operator->lambda_val->parent_env);
        temp = bind_arguments(child_env, operator->lambda_val, operands);
        if (is_error(temp)) {
            result = temp;
            goto Done;
        }

        /* Evaluate each expression in the lambda, using the child environment.
         * The result of the last expression is the result of the lambda.
         */
        body_iter = operator->lambda_val->body;
        do {
            result = evaluate(child_env, get_car(body_iter));
            body_iter = get_cdr(body_iter);
        }
        while (!is_nil(body_iter));
    }

Done:

#ifdef VERBOSE_EVAL
    printf("Result:  ");
    print_value(stdout, result);
    printf("\n\n");
#endif

    /* Record the result and then perform garbage-collection. */
    pop_evalctx(result);
    collect_garbage();

    return result;
}
Пример #16
0
 bool good() const {
     return !is_error();
 }
Пример #17
0
pa_prop_type_t pa_format_info_get_prop_type(pa_format_info *f, const char *key) {
    const char *str;
    json_object *o, *o1;
    pa_prop_type_t type;

    pa_assert(f);
    pa_assert(key);

    str = pa_proplist_gets(f->plist, key);
    if (!str)
        return PA_PROP_TYPE_INVALID;

    o = json_tokener_parse(str);
    if (is_error(o))
        return PA_PROP_TYPE_INVALID;

    switch (json_object_get_type(o)) {
        case json_type_int:
            type = PA_PROP_TYPE_INT;
            break;

        case json_type_string:
            type = PA_PROP_TYPE_STRING;
            break;

        case json_type_array:
            if (json_object_array_length(o) == 0) {
                /* Unlikely, but let's account for this anyway. We need at
                 * least one element to figure out the array type. */
                type = PA_PROP_TYPE_INVALID;
                break;
            }

            o1 = json_object_array_get_idx(o, 1);

            if (json_object_get_type(o1) == json_type_int)
                type = PA_PROP_TYPE_INT_ARRAY;
            else if (json_object_get_type(o1) == json_type_string)
                type = PA_PROP_TYPE_STRING_ARRAY;
            else
                type = PA_PROP_TYPE_INVALID;

            json_object_put(o1);
            break;

        case json_type_object:
            /* We actually know at this point that it's a int range, but let's
             * confirm. */
            o1 = json_object_object_get(o, PA_JSON_MIN_KEY);
            if (!o1) {
                type = PA_PROP_TYPE_INVALID;
                break;
            }
            json_object_put(o1);

            o1 = json_object_object_get(o, PA_JSON_MAX_KEY);
            if (!o1) {
                type = PA_PROP_TYPE_INVALID;
                break;
            }
            json_object_put(o1);

            type = PA_PROP_TYPE_INT_RANGE;
            break;

        default:
            type = PA_PROP_TYPE_INVALID;
            break;
    }

    json_object_put(o);
    return type;
}
Пример #18
0
void Preferences::init()
{
	m_locale = s_defaultLocale;
	m_localeRegion = s_defaultLocaleRegion;
	m_phoneRegion = s_defaultPhoneRegion;

	// We open the preferences database and read the locale setting.
	// avoid waiting for the system-service to come up
	// and we waiting synchronously to get the locale value

	sqlite3* prefsDb = 0;
	sqlite3_stmt* statement = 0;
	const char* tail = 0;
	json_object* label = 0;
	json_object* json = 0;
	json_object* subobj = 0;
	std::string localeCountryCode;
	
	int ret = sqlite3_open(s_prefsDbPath, &prefsDb);
	if (ret) {
		luna_critical(s_logChannel, "Failed to open preferences db");
		goto Done;
	}

	// immediately read lock timeout
	ret = sqlite3_prepare(prefsDb, "SELECT * FROM Preferences WHERE KEY='lockTimeout'",
						  -1, &statement, &tail);

	if (ret) {
		luna_critical(s_logChannel, "Failed to prepare query");
		goto Done;
	}

	ret = sqlite3_step(statement);
	if (ret == SQLITE_ROW) {

		m_lockTimeout = static_cast<uint32_t>( sqlite3_column_int(statement, 1) );
	}
	else {
		setLockTimeout(m_lockTimeout);
	}

	sqlite3_finalize(statement);

	// immediately read locale
	ret = sqlite3_prepare(prefsDb, "SELECT * FROM Preferences WHERE KEY='locale'",
						  -1, &statement, &tail);
	if (ret) {
		luna_critical(s_logChannel, "Failed to prepare query");
		goto Done;
	}

	ret = sqlite3_step(statement);
	if (ret == SQLITE_ROW) {

		std::string languageCode, countryCode;

		const char* val = (const char*) sqlite3_column_text(statement, 1);
		if (!val)
			goto Done;

		label = 0;		
		json = json_tokener_parse(val);
		if (!json || is_error(json))
			goto Done;

		label = json_object_object_get(json, "languageCode");
		if (!label || is_error(label))
			goto Done;
		languageCode = json_object_get_string(label);

		label = json_object_object_get(json, "countryCode");
		if (!label || is_error(label))
			goto Done;
		countryCode = json_object_get_string(label);

		localeCountryCode = countryCode;

		m_locale = languageCode + "_" + countryCode;

		subobj = json_object_object_get(json, "phoneRegion");

		if (subobj && !is_error(subobj)){
			label = json_object_object_get(subobj, "countryCode");

			if (label && !is_error(label)){
				m_phoneRegion = json_object_get_string(label);
			}
		}

		json_object_put(json);
		json = 0;
	}

	sqlite3_finalize(statement);
	
	// immediately read regon
	ret = sqlite3_prepare(prefsDb, "SELECT * FROM Preferences WHERE KEY='region'",
						  -1, &statement, &tail);
	if (ret) {
		luna_critical(s_logChannel, "Failed to prepare query");
		goto Done;
	}

	ret = sqlite3_step(statement);
	if (ret == SQLITE_ROW) {

		const char* val = (const char*) sqlite3_column_text(statement, 1);
		if (!val)
			goto Done;

		label = 0;		
		json = json_tokener_parse(val);
		if (!json || is_error(json))
			goto Done;

		label = json_object_object_get(json, "countryCode");
		if (!label || is_error(label))
			goto Done;
		m_localeRegion = json_object_get_string(label);

		json_object_put(json);
		json = 0;
	}
	
Done:

	QLocale myLocale (m_locale.c_str());
	g_message ("%s: setting locale country %d language %d", __PRETTY_FUNCTION__,
			myLocale.country(), myLocale.language());
	QLocale::setDefault (myLocale);

	// locale region defaults to locale country code
	if (m_localeRegion.empty())
		m_localeRegion = localeCountryCode;

	if (m_phoneRegion.empty())
		m_phoneRegion = m_localeRegion;

	if (json && !is_error(json))
		json_object_put(json);

	if (statement)
		sqlite3_finalize(statement);

	if (prefsDb)
		sqlite3_close(prefsDb);    
}
Пример #19
0
void WebAppBase::attach(WebPage* page)
{
	WebAppManager::instance()->reportAppLaunched(page->appId(),
												 page->processId());
	
	if (m_page) {
		detach();
	}

	m_page = page;
	m_page->setClient(this);

	m_appId = page->appId();
	m_processId = page->processId();

	createActivity();

	ApplicationDescription* appDesc = getAppDescription();
	if (appDesc == NULL || appDesc->id().empty() || appDesc->attributes().empty()) {
	    return;
	}

	struct json_object* root = json_tokener_parse(appDesc->attributes().c_str());

	if (!root || is_error(root))
	{
	    fprintf(stderr, "Failed to parse '%s' into a JSON string.\n",
	            appDesc->attributes().c_str());
	    return;
	}

	// parse out optional http proxy host and port app attributes
    char* httpProxyHost = NULL;
    int   httpProxyPort = 0;

    struct json_object* label = json_object_object_get(root, "proxyhost");
	if (label && !is_error(label)) {
	    httpProxyHost = json_object_get_string(label);
	}

	label = json_object_object_get(root, "proxyport");
	if (label && !is_error(label)) {
	    httpProxyPort = json_object_get_int(label);
	}

	if (httpProxyHost != NULL && httpProxyPort != 0 && m_page->webkitPage()) {
	    m_page->webkitPage()->enableHttpProxy(httpProxyHost, httpProxyPort);
	}

	// parse out optional data connection interface type attributes
    char* interfaceName = NULL;

    label = json_object_object_get(root, "forceInterface");
	if (label && !is_error(label)) {
		interfaceName = json_object_get_string(label);
	}

	if (interfaceName != NULL && m_page->webkitPage()) {
		if (0 == strcmp(interfaceName, wanIdentifierString)) {
			m_page->webkitPage()->forceNetworkInterface(Settings::LunaSettings()->wanInterfaceName.c_str());  // use cellular
		} else if (0 == strcmp(interfaceName, wifiIdentifierString)) {
			m_page->webkitPage()->forceNetworkInterface(Settings::LunaSettings()->wifiInterfaceName.c_str()); // use wifi
		} else {
			m_page->webkitPage()->forceNetworkInterface(NULL); // use any
		}
	}

	if (root && !is_error(root)) {
        json_object_put(root);
    }
}
Пример #20
0
bool Preferences::serverConnectCallback(LSHandle *sh, LSMessage *message, void *ctx)
{
	if (!message)
		return true;

	const char* payload = LSMessageGetPayload(message);
	if (!payload)
		return true;
	
	json_object* label = 0;
	json_object* json = 0;
	bool connected = false;
	Preferences * prefObjPtr;
	
	label = 0;		
	json = json_tokener_parse(payload);
	if (!json || is_error(json))
		goto Done;

	label = json_object_object_get(json, "connected");
	if (!label || is_error(label))
		goto Done;
	connected = json_object_get_boolean(label);

	prefObjPtr = (Preferences *)ctx;
	
	if (connected) {

		// We are connected to the systemservice. call and get the preference values
		
		bool ret = false;
		LSError error;
		LSErrorInit(&error);
		
		ret = LSCall(Preferences::instance()->m_lsHandle,
					 "palm://com.palm.systemservice/getPreferences", "{\"subscribe\":true, \"keys\": [ \"locale\" ]}",
					 getPreferencesCallback, prefObjPtr, NULL, &error);
		if (!ret) {
			luna_critical(s_logChannel, "Failed in calling palm://com.palm.systemservice/getPreferences: %s",
						  error.message);
			LSErrorFree(&error);
		}

		ret = LSCall(Preferences::instance()->m_lsHandle,
					 "palm://com.palm.systemservice/getPreferences",
					 "{\"subscribe\":true, \"keys\": [ \"ringtone\",\
													   \"alerttone\", \
													   \"notificationtone\", \
													   \"region\", \
													   \"timeFormat\", \
													   \"wallpaper\" , \
													   \"dockwallpaper\" , \
													   \"systemSounds\" , \
													   \"showAlertsWhenLocked\", \
													   \"BlinkNotifications\", \
													   \"imeEnabled\", \
													   \"imeType\", \
													   \"sysUiNoHomeButtonMode\", \
													   \"sysUiEnableNextPrevGestures\", \
													   \"airplaneMode\", \
													   \"hideWANAlert\", \
													   \"roamingIndicator\", \
													   \"dualRSSI\", \
													   \"lockTimeout\",\
													   \"rotationLock\",\
													   \"muteSound\",\
													   \"" PALM_VIRTUAL_KEYBOARD_PREFS "\",\
													   \"" PALM_VIRTUAL_KEYBOARD_SETTINGS "\",\
					 	 	 	 	 	 	 	 	   \"enableVoiceCommand\",\
													   \"enableALS\" ]}",
					 getPreferencesCallback, prefObjPtr, NULL, &error);
		if (!ret) {
			g_critical("%s: Failed in calling palm://com.palm.systemservice/getPreferences: %s",
					   __PRETTY_FUNCTION__, error.message);
			LSErrorFree(&error);
		}
	}
Пример #21
0
/**
 * 計算結果
 *
 * @param[in] calc calcinfo構造体
 * @param[in] expr 式
 * @return 新たに領域確保された結果文字列ポインタ
 * @retval NULL エラー
 * @attention destroy_answerを必ず呼ぶこと.
 */
uchar *
create_answer(calcinfo *calc, const uchar *expr)
{
    dbl val = 0.0;     /* 値 */
    size_t length = 0; /* 文字数 */
    int retval = 0;    /* 戻り値 */
    uint start = 0;    /* タイマ開始 */

    dbglog("start");

    calc->ptr = (uchar *)expr; /* 走査用ポインタ */
    dbglog("ptr=%p", calc->ptr);

    /* フォーマット設定 */
    retval = snprintf(calc->fmt, sizeof(calc->fmt),
                      "%s%ld%s", "%.", digit, "g");
    if (retval < 0) {
        outlog("snprintf");
        return NULL;
    }
    dbglog("fmt=%s", calc->fmt);

    readch(calc);

    if (g_tflag)
        start_timer(&start);

    val = expression(calc);
    dbglog(calc->fmt, val);
    dbglog("ptr=%p, ch=%c", calc->ptr, calc->ch);

    check_validate(calc, val);
    if (calc->ch != '\0') /* エラー */
        set_errorcode(calc, E_SYNTAX);

    if (g_tflag) {
        uint calc_time = stop_timer(&start);
        print_timer(calc_time);
    }

    if (is_error(calc)) { /* エラー */
        calc->answer = get_errormsg(calc);
        clear_error(calc);
        if (!calc->answer)
            return NULL;
        dbglog("answer=%p, length=%zu", calc->answer, length);
    } else {
        /* 文字数取得 */
        retval = get_strlen(val, calc->fmt);
        if (retval <= 0) { /* エラー */
            outlog("get_strlen=%d", retval);
            return NULL;
        }
        dbglog("get_strlen=%d, INT_MAX=%d", retval, INT_MAX);
        length = (size_t)retval + 1; /* 文字数 + 1 */

        /* メモリ確保 */
        calc->answer = (uchar *)malloc(length * sizeof(uchar));
        if (!calc->answer) {
            outlog("malloc: length=%zu", length);
            return NULL;
        }
        (void)memset(calc->answer, 0, length * sizeof(uchar));

        /* 値を文字列に変換 */
        retval = snprintf((char *)calc->answer, length, calc->fmt, val);
        if (retval < 0) {
            outlog("snprintf: answer=%p, length=%zu", calc->answer, length);
            return NULL;
        }
        dbglog(calc->fmt, val);
        dbglog("answer=%s, length=%zu", calc->answer, length);
    }
    return calc->answer;
}
Пример #22
0
bool Preferences::getPreferencesCallback(LSHandle *sh, LSMessage *message, void *ctx)
{
	if (!message)
		return true;
	
	const char* payload = LSMessageGetPayload(message);
	if (!payload)
		return true;

	json_object* label = 0;
	json_object* root_label = 0;
	json_object* json = 0;
	json_object* value = 0;
	json_object* subobject = 0;

	const char* languageCode = 0;
	const char* countryCode = 0;
	const char* phoneRegion = 0;
	std::string newLocale;
	std::string newLocaleRegion;
	std::string newPhoneRegion;

	const char* imeType = 0;

	Preferences * prefObjPtr = (Preferences *)ctx;
	label = 0;		
	json = json_tokener_parse(payload);
	if (!json || is_error(json))
		goto Done;
		
	g_message("Preferences::getPreferencesCallback(): toString -> [%s]\n", payload);
	
	label = json_object_object_get(json, "imeEnabled");
	if (label && !is_error(label)) {

		if (prefObjPtr)
			prefObjPtr->m_imeEnabled = json_object_get_boolean(label);
	}

	label = json_object_object_get(json, "imeType");
	if (label && !is_error(label)) {

        imeType = json_object_get_string(label);

		if (prefObjPtr)
        {
            if (!strcmp (imeType, "pinyin"))
            {
    			prefObjPtr->m_pinyinEnabled = true;
    			prefObjPtr->m_hwrEnabled = false;
            }
            else if (!strcmp (imeType, "hwr"))
            {
    			prefObjPtr->m_pinyinEnabled = false;
    			prefObjPtr->m_hwrEnabled = true;
            }
            else // Unknown!
            {
    			prefObjPtr->m_pinyinEnabled = false;
    			prefObjPtr->m_hwrEnabled = false;
            }
        }
	}

	value = json_object_object_get(json, "locale");
	if ((value) && (!is_error(value))) {
		
		label = json_object_object_get(value, "languageCode");
		if ((label) && (!is_error(label))) {
			languageCode = json_object_get_string(label);
		}

		label = json_object_object_get(value, "countryCode");
		if ((label) && (!is_error(label))) {
			countryCode = json_object_get_string(label);
		}

		subobject = json_object_object_get(value, "phoneRegion");
		if ((subobject) && (!is_error(subobject))) {
			label = json_object_object_get(subobject, "countryCode");
			if ((label) && (!is_error(label))) {
				newPhoneRegion = json_object_get_string(label);
			}
		}

		newLocale = languageCode;
		newLocale += "_";
		newLocale += countryCode;

		if ((newLocale != prefObjPtr->m_locale && newLocale != "_") ||
			(!newPhoneRegion.empty() && newPhoneRegion != prefObjPtr->m_phoneRegion )) {

			prefObjPtr->m_mutex.lock();
			if (newLocale != "_") {
				prefObjPtr->m_locale = newLocale;
			}
			if (!newPhoneRegion.empty()){
				prefObjPtr->m_phoneRegion =  newPhoneRegion;
			}
			prefObjPtr->m_mutex.unlock();

			// Don't shutdown sysmgr for locale changes in minimal mode
			if (Settings::LunaSettings()->uiType != Settings::UI_MINIMAL) {

				VirtualKeyboardPreferences::instance().localeChanged();

				g_warning("locale changed: %s (%s). shutting down sysmgr",
						  newLocale.empty() ? "" : newLocale.c_str(),
						  prefObjPtr->m_locale.empty() ? "" : prefObjPtr->m_locale.c_str());

				// Locale has changed. SysMgr needs to be restarted
				exit(0);
			}
			else
			{   // first use: set the default keyboard layout based on the new locale
				VirtualKeyboardPreferences::instance().applyFirstUseSettings();

				// reload localization strings to get updated translations of non-cached strings
				Localization::instance()->loadLocalizedStrings();
			}
		}
	}

	value = json_object_object_get(json, "region");
	if (value && !is_error(value)) {

		label = json_object_object_get(value, "countryCode");
		if (label && !is_error(label))
			newLocaleRegion = json_object_get_string(label);

		if (!newLocaleRegion.empty() && newLocaleRegion != prefObjPtr->m_localeRegion) {

			// Don't shutdown sysmgr for locale changes in minimal mode
			if (Settings::LunaSettings()->uiType != Settings::UI_MINIMAL) {
						
				g_warning("region changed: %s (%s). shutting down sysmgr",
										  newLocaleRegion.empty() ? "" : newLocaleRegion.c_str(),
										  prefObjPtr->m_localeRegion.empty() ? "" : prefObjPtr->m_localeRegion.c_str());

				prefObjPtr->m_mutex.lock();
				prefObjPtr->m_localeRegion = newLocaleRegion;
				prefObjPtr->m_mutex.unlock();


			
				// Region has changed. SysMgr needs to be restarted
				exit(0);
			}
		}
	}
	
	root_label = json_object_object_get(json, "ringtone");
	if ((root_label) && (!is_error(root_label))) {
		
		label = json_object_object_get(root_label,"fullPath");
		if ((label) && (!is_error(label))) {
			if (prefObjPtr)
				prefObjPtr->m_currentRingtoneFile = json_object_get_string(label);
		}
	}
	
	root_label = json_object_object_get(json, "alerttone");
	if ((root_label) && (!is_error(root_label))) {

		label = json_object_object_get(root_label,"fullPath");
		if ((label) && (!is_error(label))) {
			if (prefObjPtr)
				prefObjPtr->m_currentAlerttoneFile = json_object_get_string(label);
		}
	}

	root_label = json_object_object_get(json, "notificationtone");
	if ((root_label) && (!is_error(root_label))) {

		label = json_object_object_get(root_label,"fullPath");
		if ((label) && (!is_error(label))) {
			if (prefObjPtr)
				prefObjPtr->m_currentNotificationtoneFile = json_object_get_string(label);
		}
	}
		
	label = json_object_object_get(json, "timeFormat");
	if (label && !is_error(label)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
			prefObjPtr->m_currentTimeFormat = json_object_get_string(label);
			Q_EMIT prefObjPtr->signalTimeFormatChanged(prefObjPtr->m_currentTimeFormat.c_str());
		}
	}

	label = json_object_object_get(json, "wallpaper");
	if (label && !is_error(label)) {

		label = json_object_object_get(label, "wallpaperFile");
		if (label && !is_error(label)) {
			if (prefObjPtr)
				Q_EMIT prefObjPtr->signalWallPaperChanged(json_object_get_string(label));
		}
	}

	label = json_object_object_get(json, "dockwallpaper");
	if (label && !is_error(label)) {

		label = json_object_object_get(label, "wallpaperFile");
		if (label && !is_error(label)) {
			if (prefObjPtr)
				Q_EMIT prefObjPtr->signalDockModeWallPaperChanged(json_object_get_string(label));
		}
	}

	label = json_object_object_get(json, "showAlertsWhenLocked");
	if (label && !is_error(label)) {
		
		if (prefObjPtr)
			prefObjPtr->m_showAlertsWhenLocked = json_object_get_boolean(label);
	}

	label = json_object_object_get(json, "BlinkNotifications");
	if (label && !is_error(label)) {
		
		if (prefObjPtr)
			prefObjPtr->m_ledThrobberEnabled = json_object_get_boolean(label);
	}

	label = json_object_object_get(json, "systemSounds");
	if (label && !is_error(label)) {

		if (prefObjPtr)
			prefObjPtr->m_playFeedbackSounds = json_object_get_boolean(label);
	}

	label = json_object_object_get(json, "sysUiNoHomeButtonMode");
	if (label && !is_error(label)) {

		if (prefObjPtr)
			prefObjPtr->m_sysUiNoHomeButtonMode = json_object_get_boolean(label);
	}

	label = json_object_object_get(json, "sysUiEnableNextPrevGestures");
	if (label && !is_error(label)) {

		if (prefObjPtr) {
			prefObjPtr->m_sysUiEnableNextPrevGestures = json_object_get_boolean(label);
#if defined(TARGET_DEVICE)
			setAdvancedGestures(prefObjPtr->m_sysUiEnableNextPrevGestures ? 1 : 0);
#endif
		}
	}

	label = json_object_object_get(json, "lockTimeout");
	if (label && !is_error(label) && json_object_is_type(label, json_type_int)) {

		if (prefObjPtr) {
			prefObjPtr->m_lockTimeout = json_object_get_int(label);
			Q_EMIT prefObjPtr->signalSetLockTimeout(prefObjPtr->m_lockTimeout);
		}
	}

	label = json_object_object_get(json, "dualRSSI");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			prefObjPtr->m_dualRSSI = json_object_get_boolean(label);
			if(prefObjPtr->m_dualRSSI) {
				prefObjPtr->m_show3GForEvdo = true;
				Q_EMIT prefObjPtr->signalDualRssiEnabled();
			}
		}
	}

	label = json_object_object_get(json, "hideWANAlert");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			prefObjPtr->m_hideWANAlert = json_object_get_boolean(label);
		}
	}

	label = json_object_object_get(json, "roamingIndicator");
	if (label && !is_error(label)) {
		if (prefObjPtr) {
			prefObjPtr->m_roamingIndicator = json_object_get_string(label);
			Q_EMIT prefObjPtr->signalRoamingIndicatorChanged();
			if(prefObjPtr->m_roamingIndicator == "triangle") {
				prefObjPtr->m_show3GForEvdo = true;
			}
		}
	}

	label = json_object_object_get(json, "airplaneMode");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
			prefObjPtr->m_airplaneMode = json_object_get_boolean(label);
			Q_EMIT prefObjPtr->signalAirplaneModeChanged(prefObjPtr->m_airplaneMode);
		}
	}

	label = json_object_object_get(json, "wifiRadio");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
			prefObjPtr->m_wifiOn = json_object_get_boolean(label);
		}
	}

	label = json_object_object_get(json, "bluetoothRadio");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
			prefObjPtr->m_bluetoothOn = json_object_get_boolean(label);
		}
	}

	label = json_object_object_get(json, "rotationLock");
	if (label && !is_error(label) && json_object_is_type(label, json_type_int)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
            prefObjPtr->m_rotationLock = (OrientationEvent::Orientation)json_object_get_int(label);
			Q_EMIT prefObjPtr->signalRotationLockChanged(prefObjPtr->m_rotationLock);
		}
	}

	label = json_object_object_get(json, "muteSound");
	if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
		if (prefObjPtr) {
			MutexLocker locker(&prefObjPtr->m_mutex);
			prefObjPtr->m_muteOn = json_object_get_boolean(label);
			Q_EMIT prefObjPtr->signalMuteSoundChanged(prefObjPtr->m_muteOn);
		}
	}

	label = json_object_object_get(json, PALM_VIRTUAL_KEYBOARD_SETTINGS);
	if ((label) && (!is_error(label)))
		VirtualKeyboardPreferences::instance().virtualKeyboardSettingsChanged(json_object_get_string(label));

	label = json_object_object_get(json, PALM_VIRTUAL_KEYBOARD_PREFS);
	if ((label) && (!is_error(label)))
		VirtualKeyboardPreferences::instance().virtualKeyboardPreferencesChanged(json_object_get_string(label));

	label = json_object_object_get(json, "enableVoiceCommand");
	if (label && !is_error(label)) {

		if (prefObjPtr)
		{
			prefObjPtr->m_enableVoiceDial = json_object_get_boolean(label);
			Q_EMIT prefObjPtr->signalVoiceDialSettingChanged(prefObjPtr->m_enableVoiceDial);
		}
	}


	label = json_object_object_get(json, "enableALS");
	if (label && !is_error(label)) {
		if (prefObjPtr) 
		{
			prefObjPtr->m_enableALS = json_object_get_boolean(label);
			Q_EMIT prefObjPtr->signalAlsEnabled (prefObjPtr->m_enableALS);
		}
	}
Done:

	if (json && !is_error(json))
		json_object_put(json);

	return true;
}
void LocalePrefsHandler::readRegionFile() 
{
	// Read the locale file
	char* jsonStr = Utils::readFile(s_custRegionFile);
	if (!jsonStr)
		jsonStr = Utils::readFile(s_defaultRegionFile);
	if (!jsonStr) {
        //luna_critical(s_logChannel, "Failed to load region files: [%s] nor [%s]", s_custRegionFile,s_defaultRegionFile);
        qCritical() << "Failed to load region files: [" << s_custRegionFile << "] nor [" << s_defaultRegionFile << "]";
		return;
	}

	json_object* root = 0;
	json_object* label = 0;
	array_list* regionArray = 0;

	root = json_tokener_parse(jsonStr);
	if (!root || is_error(root)) {
        //luna_critical(s_logChannel, "Failed to parse region file contents into json");
        qCritical() << "Failed to parse region file contents into json";
		goto Done;
	}

	label = json_object_object_get(root, "region");
	if (!label || is_error(label)) {
        //luna_critical(s_logChannel, "Failed to get region entry from region file");
        qCritical() << "Failed to get region entry from region file";
		goto Done;
	}

	regionArray = json_object_get_array(label);
	if (!regionArray) {
        //luna_critical(s_logChannel, "Failed to get region array from region file");
        qCritical() << "Failed to get region array from region file";
		goto Done;
	}

	for (int i = 0; i < array_list_length(regionArray); i++) {
		json_object* obj = (json_object*) array_list_get_idx(regionArray, i);

		RegionEntry regionEntry;

		label = json_object_object_get(obj, "countryName");
		if (!label || is_error(label))
			continue;

		regionEntry.region[1] = std::string(json_object_get_string(label));
		
		label = json_object_object_get(obj, "shortCountryName");
		if (!label || is_error(label))
			regionEntry.region[0] = regionEntry.region[1];
		else
			regionEntry.region[0] = std::string(json_object_get_string(label));
		
		label = json_object_object_get(obj, "countryCode");
		if (!label || is_error(label))
			continue;

		regionEntry.region[2] = std::string(json_object_get_string(label));

		m_regionEntryList.push_back(regionEntry);		
	}

	Done:

	if (root && !is_error(root))
		json_object_put(root);

	delete [] jsonStr;
}
Пример #24
0
static int query_bfile(sqlite3* db) {
	int rc, rc2;
	sqlite3_stmt *pStmt, *pBfileStmt;
	char *photo;
	off_t offset;
	int row, id, bHdl, len, i;
	const char *sql_bfile_open =
		"SELECT id, BFILE_OPEN(photo) FROM test_bfile;";
	const char *sql_bfile_read = "SELECT BFILE_READ(?, ?, ?);";
	const char *sql_bfile_close = "SELECT BFILE_CLOSE(?);";
	const int amount = 80;

	pStmt = NULL;
	printf("\nRUNNING: query id, photo\n");

	/* BFILE_OPEN */
	rc = sqlite3_prepare(db, sql_bfile_open, -1, &pStmt, 0);
	if (rc != SQLITE_OK) {
		printf("BFILE_OPEN: prepare error\n");
		return -1;
	}

	row = 0;
	while (SQLITE_ROW == (rc = sqlite3_step(pStmt))) {
		printf("-------------row%d------------\n", ++row);

		id = sqlite3_column_int(pStmt, 0);
		bHdl = sqlite3_column_int(pStmt, 1);

		printf("id:\n%d\nphoto:\n", id);

		if ((void*)bHdl == NULL) {
			printf("NULL\n");
			continue;
		}

		offset = 0;

		/* BFILE_READ */
		rc2 = sqlite3_prepare(db, sql_bfile_read, -1, &pBfileStmt, 0);
		cleanup_if_error(rc2, cleanup_read);

		while (1) {
			rc2 = sqlite3_bind_int(pBfileStmt, 1, bHdl);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_bind_int(pBfileStmt, 2, amount);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_bind_int(pBfileStmt, 3, offset);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_step(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			if (rc2 == SQLITE_ROW) {
				photo = 
					(char*)sqlite3_column_blob(pBfileStmt, 0);
				len = sqlite3_column_bytes(pBfileStmt, 0);

				/* EOF */
				if (len == 0)
					break;

				for(i=0; i<len; i++)
					putchar(photo[i]);
			}

			rc2 = sqlite3_reset(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			rc2 = sqlite3_clear_bindings(pBfileStmt);
			cleanup_if_error(rc2, cleanup_read);

			offset += amount;
		}

cleanup_read:		
		if (pBfileStmt != NULL) {
			sqlite3_finalize(pBfileStmt);
			pBfileStmt = NULL;
		}

		/* BFILE_CLOSE */
		rc2 = sqlite3_prepare(db, sql_bfile_close, -1, &pBfileStmt, 0);
		cleanup_if_error(rc2, cleanup_close);

		rc2 = sqlite3_bind_int(pBfileStmt, 1, bHdl);
		cleanup_if_error(rc2, cleanup_close);

		rc2 = sqlite3_step(pBfileStmt);

cleanup_close:
		if (pBfileStmt != NULL) {
			sqlite3_finalize(pBfileStmt);
			pBfileStmt = NULL;
		}
	}

	if (pStmt != NULL) {
		sqlite3_finalize(pStmt);
		pStmt = NULL;
	}

	if (!is_error(rc) && is_error(rc2))
		rc = rc2;

	rc = !is_error(rc) ? 0 : -1;
	return rc;
}
Пример #25
0
bool is_bound(object *expression, object *env) {
    return is_variable(expression) ? !is_error(lookup_variable_value(expression, env)) : false;
}
Пример #26
0
void CHttpServer::parse_openstack_data(void *arg,
		                               struct evhttp_request *req, 
		                               struct evkeyvalq params, 
									   char *post_data)
{

	CHttpServer *pthis = (CHttpServer *)arg;

	struct json_object *fst_obj = NULL, *snd_obj = NULL, *trd_obj = NULL;
	fst_obj = json_tokener_parse(post_data);	
	if (is_error(fst_obj)){
		logerr("parse json cloud data fail!!! data:(%s)", post_data);
		//printf("error parsing json:%s", json_tokener_errors[-(unsigned long)fst_obj]);
        	return;
	}
   
	char tm_buf[64];
	char g_timestamp[32]={0};
	host_data_st host_data;
	vm_data_st vm_data;
	memset((void*)&host_data, 0, sizeof(host_data));
	memset((void*)&vm_data, 0, sizeof(vm_data));

   	if (json_object_get_type(fst_obj) == json_type_array) {
		for (int i=0 ; i<json_object_array_length(fst_obj) ; i++ ){
                        snd_obj = json_object_array_get_idx(fst_obj, i );
			if (NULL == snd_obj) {
				logerr("parse cloud data get snd_obj == NULL!\n");
				json_object_put(fst_obj);
				return;
			}
			json_object_object_foreach(snd_obj, key, val) {
				if (json_object_get_type(val) == json_type_array) {
					for (int j=0; j<json_object_array_length(val); j++) {
						trd_obj = json_object_array_get_idx(val, j);
						if (NULL == trd_obj) {
							logerr("parse cloud data get trd_obj == NULL!\n");
							json_object_put(fst_obj);
							json_object_put(snd_obj);
							return;
						}
						json_object_object_foreach(trd_obj, key, val) {
							
                            /* padding vm data info */
                            if (NULL == val) {
					        logerr("json parse data as NULL!!!");
						 	json_object_put(fst_obj);
						 	json_object_put(snd_obj);
						 	json_object_put(trd_obj);
						 	return;
						 }
						 strcpy(vm_data.iaas_code, host_data.iaas_code);
						 strcpy(vm_data.iaas_host_id, host_data.iaas_host_id);
						 strcpy(vm_data.timestamp, host_data.timestamp);
						 if (strcmp(key, VM_ID)==0)
						 	strcpy(vm_data.iaas_vm_id, json_object_get_string(val));
							else if (strcmp(key, VM_CPU)==0)
								vm_data.cpu_use_rate = json_object_get_double(val);
							else if (strcmp(key, VM_MEM)==0)
								vm_data.memory_use_rate = json_object_get_double(val);
							else if (strcmp(key, VM_IO)==0)
								vm_data.io_use_rate = json_object_get_double(val);
						}
						
						/* 打印虚拟机运行数据日志 */                    
						bzero(&tm_buf, 0);                  
						get_time_str(vm_data.timestamp, tm_buf);
								                                        
					    //pthread_mutex_lock(&pthis->m_mutex);
						logvm("%s %s %s %s %f %f %f",       
							tm_buf,                     
							vm_data.iaas_code,              
							vm_data.iaas_host_id,       								                                vm_data.iaas_vm_id,										                                    vm_data.cpu_use_rate,									                                    vm_data.memory_use_rate,
  							vm_data.io_use_rate);
						//pthread_mutex_unlock(&pthis->m_mutex);
					}
				} else { 
					/* padding host data info */
					if (NULL == val) {
						logerr("json parse host data as NULL!!!");
						json_object_put(fst_obj);
						json_object_put(snd_obj);
						json_object_put(trd_obj);
						return;
					}
					time_t tt = get_time_utc(json_object_get_string(val),
							"%Y-%m-%d %H:%M:%S");
					sprintf(g_timestamp, "%ld", tt);
					if (strcmp(key, IAAS_CODE)==0)
						strcpy(host_data.iaas_code, json_object_get_string(val));
					else if (strcmp(key, HOST_ID)==0)
						strcpy(host_data.iaas_host_id, json_object_get_string(val));
					else if (strcmp(key, TIMESTAMP)==0)
						strcpy(host_data.timestamp, g_timestamp);
					else if (strcmp(key, PM_CPU)==0)
						host_data.cpu_use_rate = json_object_get_double(val);
					else if (strcmp(key, PM_MEM)==0)
						host_data.memory_use_rate = json_object_get_double(val);
					else if (strcmp(key, PM_IO)==0)
						host_data.io_use_rate = json_object_get_double(val);
				}
			}
			
			/* 打印物理主机运行数据 */
			bzero(&tm_buf, 0);
			get_time_str(host_data.timestamp, tm_buf);

			//pthread_mutex_lock(&pthis->m_mutex);  
			loghost("%s %s %s %f %f %f",          
					tm_buf,                       
					host_data.iaas_code,              
				    host_data.iaas_host_id,           
					host_data.cpu_use_rate,           									                        host_data.memory_use_rate,        
					host_data.io_use_rate);           
			//pthread_mutex_unlock(&pthis->m_mutex);
		}

	}
void ApplicationDescription::updateSysmgrBuiltinWithLocalization()
{
    /*
     * Needed due to localization assumptions about app locations.
     * Localization for sysmgr builtins will be in the sysmgr localization dir, and some of it will be wrong (like icon location)
     * So this is intended to scan and update the fields that can be localized
     * Whenever the fields allowed in the special sysmgr builtin appinfo.json change (i.e. the schema of the file), this
     * function should be revisited and checked and updated if necessary
     *
     * This will not change the default launchpoint, so it has be called before that gets created
     */

    if (m_type != Type_SysmgrBuiltin)
        return;			//not a valid app descriptor to call this fn on

    // Do we have a locale setting
    std::string locale = Preferences::instance()->locale();

    // Look for the language/region specific appinfo.json

    if (locale.empty())
        return;			//nothing to do

    //sysmgr always seems to have lang_region style directories, so this is all that need to be checked
    std::string filePath = Settings::LunaSettings()->lunaSystemLocalePath
                           + std::string("/") + locale + std::string("/sysapps/") + m_id;

    char * jsonStr = readFile(filePath.c_str());
    if (!jsonStr || !g_utf8_validate(jsonStr, -1, NULL))
        return;		// probably no file there

    struct json_object* root=0;
    struct json_object* label=0;

    //the only 2 that are localizable in the special builtin appinfo.json
    root = json_tokener_parse( jsonStr );
    if( !root || is_error( root ) )
    {
        g_warning("%s: Failed to parse '%s' into a JSON string", __FUNCTION__, filePath.c_str() );
        delete [] jsonStr;
        return;
    }

    // TITLE
    label = json_object_object_get(root, "title");
    if( label && !is_error(label) )
    {
        m_title = json_object_get_string(label);
    }
    else
    {
        g_warning("%s: App %s does not have a localized title",__FUNCTION__, filePath.c_str() );
    }

    //CATEGORY
    label = json_object_object_get(root, "category");
    if( label && !is_error(label) )
    {
        m_category = json_object_get_string(label);

    }
    else
    {
        g_warning("%s: App %s does not have a localized category",__FUNCTION__, filePath.c_str() );
    }

    json_object_put(root);
    delete [] jsonStr;

}
Пример #28
0
/**
 * @brief This parses configuration file such as (default.conf) and returns the instance of expr::ConfData class.
 */
expr::ConfData* expr::ConfigManager::parse_conf_json(std::string json_conf)
{
    json_object* jobj = NULL;
    json_object* confjobj = NULL;
    json_object* subjobj = NULL;

    char* payload = NULL;
    payload = g_strdup(json_conf.c_str());

    jobj = json_tokener_parse(payload);

    if((jobj == NULL) || is_error(jobj))
    {
        return NULL;
    }

    bool parsed = true;
    expr::error_type e_type = expr::CONFIG;
    expr::error_code e_code = expr::CONFIG_PARSE;

    if(!json_object_object_get_ex(jobj, "conf", &confjobj))
    {
        std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
        error_input_param->set_error_desc("cannot find conf");
        expr::ErrorMessagePool::getInstance()->add(error_input_param);

        parsed = false;
    }
    else
    {
        if(!json_object_object_get_ex(confjobj, "log_port", &subjobj))
        {
        }
        else
        {
            int port = json_object_get_int(subjobj);
            expr::ConfData::getInstance()->set_log_port(port);
        }

        if(!json_object_object_get_ex(confjobj, "control_port", &subjobj))
        {
        }
        else
        {
            int port = json_object_get_int(subjobj);
            expr::ConfData::getInstance()->set_ctl_port(port);
        }

        if(!json_object_object_get_ex(confjobj, "log_priority", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find log_priority");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            std::string priority(json_object_get_string(subjobj));
            expr::PRIORITY level = this->get_priority(priority);

            if(level == NOT_DEFINED)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("invalid Priority");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }
            else
            {
                expr::ConfData::getInstance()->set_log_priority(level);
            }
        }

        if(!json_object_object_get_ex(confjobj, "export_period", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find export_period");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            expr::ConfData::getInstance()->set_export_period(json_object_get_int(subjobj));
        }

        if(!json_object_object_get_ex(confjobj, "max_log_buffer_size", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find max_log_buffer_size");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            expr::ConfData::getInstance()->set_max_log_buffer_size(json_object_get_int(subjobj));
        }

        if(!json_object_object_get_ex(confjobj, "mapping", &subjobj))
        {
            std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
            error_input_param->set_error_desc("cannot find mapping");
            expr::ErrorMessagePool::getInstance()->add(error_input_param);
            parsed = false;
        }
        else
        {
            struct array_list* arr_obj;
            struct lh_entry* entry;

            arr_obj = json_object_get_array(subjobj);

            if(arr_obj == NULL)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("mapping list error");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }

            int arr_size = array_list_length(arr_obj);
            
            if(arr_size < 1)
            {
                std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                error_input_param->set_error_desc("please set mapping table");
                expr::ErrorMessagePool::getInstance()->add(error_input_param);
                parsed = false;
            }

            json_object* arr_item = NULL;
            int arr_index;
            std::string key;
            std::string value;

            std::string ps_log_id;
            std::string log_d_id;
            std::string log_F_path;

            for(arr_index = 0; arr_index < arr_size; arr_index++)
            {
                arr_item = static_cast<json_object*>(array_list_get_idx(arr_obj, arr_index));
                entry = json_object_get_object(static_cast<struct json_object*>(arr_item))->head;

                ps_log_id.clear();
                log_d_id.clear();
                log_F_path.clear();

                while(entry)
                {
                    key.assign(static_cast<const char*>(entry->k));
                    value.assign(json_object_get_string((struct json_object*)entry->v));

                    if(key.compare("process_log_id") == 0)
                    {
                        ps_log_id = value;
                    }
                    else if(key.compare("log_file_id") == 0)
                    {
                        log_d_id = value;
                    }
                    else if(key.compare("log_file_path") == 0)
                    {
                        log_F_path = value;
                    }
                    else
                    {
                        std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                        error_input_param->set_error_desc("Invalid key: " + key);
                        expr::ErrorMessagePool::getInstance()->add(error_input_param);
                        parsed = false;
                    }

                    entry = entry->next;
                } //while

                if(ps_log_id.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("process_log_id key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;
                }

                if(log_d_id.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("log_file_id key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;

                }

                if(log_F_path.empty())
                {
                    std::shared_ptr<expr::ErrorMessage> error_input_param = std::make_shared<expr::ErrorMessage>(e_type, e_code);
                    error_input_param->set_error_desc("log_file_path key is NOT found at array[" + std::to_string(arr_index) + "]");
                    expr::ErrorMessagePool::getInstance()->add(error_input_param);
                    parsed = false;
                }

                if( (ps_log_id.empty() == false) && (log_d_id.empty() == false) && (log_F_path.empty() == false) )
                {
                    expr::ConfData::getInstance()->add_to_table(ps_log_id, log_d_id, log_F_path);
                }
            } //for
        }
    }

    if(jobj)
    {
        json_object_put(jobj);
    }
    
    if(payload)
    {
        g_free(payload);
        payload = NULL;
    }

    expr::ConfData::getInstance()->set_parsed(parsed);
    return expr::ConfData::getInstance();
}
ApplicationDescription* ApplicationDescription::fromFile(const std::string& filePath, const std::string& folderPath)
{
    bool success = false;
    ApplicationDescription* appDesc = 0;
    char* jsonStr = 0;
    const gchar* palmAppDirPrefix = "/usr/palm/applications/";
    std::vector<MimeRegInfo> extractedMimeTypes;
    std::string launchParams;

    std::string builtinEntrypt;
    std::string builtinArgs;

    jsonStr = readFile(filePath.c_str());
    if (!jsonStr || !g_utf8_validate(jsonStr, -1, NULL))
    {
        return 0;
    }

    struct json_object* root=0;
    struct json_object* label=0;

    std::string title, icon, dirPath;
    gchar* dirPathCStr;

    dirPathCStr = g_path_get_dirname(filePath.c_str());
    dirPath = dirPathCStr;
    dirPath += "/";
    g_free(dirPathCStr);

    root = json_tokener_parse( jsonStr );
    if( !root || is_error( root ) )
    {
        g_warning("%s: Failed to parse '%s' into a JSON string", __FUNCTION__, filePath.c_str() );
        goto Done;
    }

    appDesc = new ApplicationDescription();

    appDesc->m_folderPath = folderPath;

    // ID: mandatory
    label = json_object_object_get(root, "id");
    if( label && !is_error(label) )
    {
        appDesc->m_id = json_object_get_string(label);
    }
    else
    {
        g_warning("%s: App %s does not have an ID", __FUNCTION__, filePath.c_str() );
        goto Done;
    }


    // MAIN: optional
    label = json_object_object_get(root, "main");
    if( label && !is_error(label) )
    {
        appDesc->m_entryPoint = json_object_get_string(label);
    }
    else
    {
        appDesc->m_entryPoint = "index.html";
    }

    if (!strstr(appDesc->m_entryPoint.c_str(), "://"))
        appDesc->m_entryPoint = std::string("file://") + dirPath + appDesc->m_entryPoint;


    // TITLE: mandatory
    label = json_object_object_get(root, "title");
    if( label && !is_error(label) )
    {
        appDesc->m_title = json_object_get_string(label);
    }
    else
    {
        g_warning("%s: App %s does not have a title",__FUNCTION__, filePath.c_str() );
        goto Done;
    }

    // SHORT NAME: optional
    label = json_object_object_get(root,"appmenu");
    if ( label && !is_error(label))
    {
        appDesc->m_appmenuName = json_object_get_string(label);
    }
    else
        appDesc->m_appmenuName = appDesc->m_title;

    // KEYWORDS: optional
    label = json_object_object_get(root,"keywords");
    if ( label && !is_error(label)) {
        appDesc->m_keywords.addKeywords(label);
    }

    //MIME HANDLING REGISTRATIONS: optional
    label = json_object_object_get(root,"mimeTypes");
    if ( label && !is_error(label)) {
        if (utilExtractMimeTypes(label,extractedMimeTypes)) {
            //found some!
            for (std::vector<MimeRegInfo>::iterator it = extractedMimeTypes.begin();
                    it != extractedMimeTypes.end();
                    ++it)
            {
                if ((*it).mimeType.size()) {
                    // ADD BY MIME TYPE.  The extension that is appropriate for this mimeType will be automatically filled in into "extension" if successful
                    if (MimeSystem::instance()->addResourceHandler((*it).extension,(*it).mimeType,!((*it).stream),appDesc->id(),NULL,false) > 0)
                        appDesc->m_mimeTypes.push_back(ResourceHandler((*it).extension,(*it).mimeType,appDesc->id(),(*it).stream));			//success adding to mime system, so add it to this app descriptor for bookeeping purposes
                }
                else if ((*it).extension.size()) {
                    // ADD BY EXTENSION... count on the extension->mime mapping to already exist, or this will fail
                    if (MimeSystem::instance()->addResourceHandler((*it).extension,!((*it).stream),appDesc->id(),NULL,false) > 0) {
                        //get the mime type
                        MimeSystem::instance()->getMimeTypeByExtension((*it).extension,(*it).mimeType);
                        appDesc->m_mimeTypes.push_back(ResourceHandler((*it).extension,(*it).mimeType,appDesc->id(),(*it).stream));
                    }
                }
                else if ((*it).scheme.size()) {			//TODO: fix this so it's more robust; it should check if the way the appinfo file specified the scheme is in fact a valid "scheme form" regexp and if not, make it one
                    // ADD REDIRECT: THIS IS A SCHEME or "COMMAND" FORM.... (e.g. "tel://")
                    (*it).scheme = std::string("^")+(*it).scheme+std::string(":");
                    if (MimeSystem::instance()->addRedirectHandler((*it).scheme,appDesc->id(),NULL,true,false) > 0) {
                        appDesc->m_redirectTypes.push_back(RedirectHandler((*it).scheme,appDesc->id(),true));
                    }
                }
                else if ((*it).urlPattern.size()) {
                    // ADD REDIRECT: THIS IS A PURE REDIRECT FORM... (e.g. "^[^:]+://www.youtube.com/watch\\?v="
                    if (MimeSystem::instance()->addRedirectHandler((*it).urlPattern,appDesc->id(),NULL,false,false) > 0) {
                        appDesc->m_redirectTypes.push_back(RedirectHandler((*it).urlPattern,appDesc->id(),false));
                    }
                }
            }
        }
    }

    // ICON: we have a default if this is not present.
    label = json_object_object_get(root, "icon");
    if( label && !is_error(label) )
    {
        icon = dirPath + json_object_get_string(label);
    }
    else
        icon = dirPath + "icon.png";

    // Optional parameters
    success = true;

    // Type: optional (defaults to Type_Web)
    label = json_object_object_get(root, "type");
    if (label && !is_error(label) && json_object_is_type(label, json_type_string)) {
        if (strncmp(json_object_get_string(label), "game", 4) == 0)
            appDesc->m_type = Type_Native;
        else if (strncmp(json_object_get_string(label), "pdk", 3) == 0)
            appDesc->m_type = Type_PDK;
        else if (strncmp(json_object_get_string(label), "qt", 2) == 0)
            appDesc->m_type = Type_Qt;
        else if (strncmp(json_object_get_string(label), "sysmgrbuiltin" , 13 ) == 0)
            appDesc->m_type = Type_SysmgrBuiltin;
        else
            appDesc->m_type = Type_Web;
    }

    // SPLASH ICON: optional (Used for loading/splash screen for cards)
    label = json_object_object_get(root, "splashicon");
    if (label && !is_error(label)) {
        appDesc->m_splashIconName = dirPath + json_object_get_string(label);
    }
    // SPLASH BACKGROUND: optional (Used for loading/splash screen for cards)
    label = json_object_object_get(root, "splashBackground");
    if (label && !is_error(label) && json_object_is_type(label, json_type_string)) {
        appDesc->m_splashBackgroundName = dirPath + json_object_get_string(label);
    }
    else {
        label = json_object_object_get(root, "splashbackground");
        if (label && !is_error(label) && json_object_is_type(label, json_type_string)) {
            appDesc->m_splashBackgroundName = dirPath + json_object_get_string(label);
        }
    }

    // MINI ICON: optional (Used for notification banner area)
    label = json_object_object_get(root, "miniicon");
    if( label && !is_error(label) )
    {
        appDesc->m_miniIconName = json_object_get_string(label);
    }
    else
        appDesc->m_miniIconName = "miniicon.png";

    appDesc->m_miniIconName = dirPath + appDesc->m_miniIconName;

    // LAUNCH IN NEW GROUP: optional (Used to prevent app from launching in current card stack)
    label = json_object_object_get(root, "launchinnewgroup");
    if( label && !is_error(label) )
    {
        appDesc->m_launchInNewGroup = json_object_get_boolean(label);
    }
    else
        appDesc->m_launchInNewGroup = false;

    // CATEGORY: optional
    label = json_object_object_get(root, "category");
    if( label && !is_error(label) )
    {
        appDesc->m_category = json_object_get_string(label);
    }

    // VENDOR: optional
    label = json_object_object_get(root, "vendor");
    if( label && !is_error(label) )
    {
        appDesc->m_vendorName = json_object_get_string(label);
    }
    else if (g_str_has_prefix(dirPath.c_str(), palmAppDirPrefix)) {
        appDesc->m_vendorName = "Palm, Inc.";
    }

    // VENDOR URL: optional
    label = json_object_object_get(root, "vendorurl");
    if( label && !is_error(label) )
    {
        appDesc->m_vendorUrl = json_object_get_string(label);
    }

    // SIZE: optional
    label = json_object_object_get(root, "appsize");
    if( label && !is_error(label) )
    {
        appDesc->m_appSize = (unsigned int) json_object_get_int(label);
    }

    // RUNTIME MEMORY REQUIRED: optional
    label = json_object_object_get(root, "requiredMemory");
    if( label && !is_error(label) )
    {
        appDesc->m_runtimeMemoryRequired = (unsigned int) json_object_get_int(label);
        //json_object_put( label );
    }

    // HEADLESS: optional
    label = json_object_object_get(root, "noWindow");
    if( label && !is_error(label) )
    {
        appDesc->m_isHeadLess = (strcasecmp( json_object_get_string(label), "true") == 0);
    }

    //VISIBLE: optional* by default the launch icons are visible...set to false in the json and they won't show in the
    //launcher screen
    label = json_object_object_get(root, "visible");
    if( label && !is_error(label) )
    {
        if (json_object_is_type(label,json_type_string))
            appDesc->m_isVisible = (strcasecmp( json_object_get_string(label), "true") == 0);
        else
            appDesc->m_isVisible = json_object_get_boolean(label);
    }

    // TRANSPARENT: optional
    label = json_object_object_get(root, "transparent");
    if( label && !is_error(label) )
    {
        appDesc->m_hasTransparentWindows = (strcasecmp( json_object_get_string(label), "true") == 0);
    }

    // VERSION: optional?
    label = json_object_object_get(root, "version");
    if (label && !is_error(label)) {
        appDesc->m_version = json_object_get_string(label);
    }

    // additional attributes, like http proxy
    label = json_object_object_get(root, "attributes");
    if (label && !is_error(label)) {
        appDesc->m_attributes = json_object_get_string(label);
    }

    // REMOVABLE: optional
    label = json_object_object_get(root, "removable");
    if (label && !is_error(label) && json_object_is_type(label, json_type_boolean)) {
        // Any appinfo.json can set removable to true. But if you want to set removable to false you better be a trusted palm application
        // NOTE: we should always be able to trust the removable flag set in the appinfo
        appDesc->m_isRemovable = json_object_get_boolean(label);
        g_debug("%s: App %s is %s because of appinfo.json",__FUNCTION__, appDesc->m_id.c_str(), appDesc->m_isRemovable ? "removable" : "non-removable");
    }
    else {
        // apps in ROM are never removable
        appDesc->m_isRemovable = !(folderPath.find("/usr") == 0);
        g_debug("%s: App %s is %s by default",__FUNCTION__, appDesc->m_id.c_str(), appDesc->m_isRemovable ? "removable" : "non-removable");
    }

    // DOCK ENABLED: optional (defines if this app can provide a Dock mode stage)
    label = json_object_object_get(root, "exhibitionMode");
    if (!label || is_error (label)) // maintaining backward compatibility
        label = json_object_object_get(root, "dockMode");

    if (label && !is_error(label) && json_object_is_type(label, json_type_boolean))
    {
        appDesc->m_dockMode = json_object_get_boolean(label);
        if(appDesc->m_dockMode) {
            // read the optional Dock mode parameters
            struct json_object *dockOptions=0, *dockLabel=0;

            // DOCK Mode options: (optional)
            dockOptions = json_object_object_get(root, "exhibitionModeOptions");
            if (!dockOptions || is_error (dockOptions)) // maintaining backward compatibility
                dockOptions = json_object_object_get(root, "dockModeOptions");

            if (dockOptions && !is_error(dockOptions)) {
                dockLabel = json_object_object_get(dockOptions, "title");
                if (dockLabel && !is_error(dockLabel) && json_object_is_type(dockLabel, json_type_string)) {
                    appDesc->m_dockModeTitle = json_object_get_string(dockLabel);
                }
                else {
                    appDesc->m_dockModeTitle = appDesc->m_appmenuName;
                }
            }
            else {
                appDesc->m_dockModeTitle = appDesc->m_appmenuName;
            }
        }
    }

    // Hardware features needed: optional
    label = json_object_object_get(root, "hardwareFeaturesNeeded");
    if (label && !is_error(label) && json_object_is_type(label, json_type_array)) {

        for (int i = 0; i < json_object_array_length(label); i++) {

            struct json_object* entry = json_object_array_get_idx(label, i);
            if (!entry  || is_error(entry))
                continue;

            if (!json_object_is_type(entry, json_type_string))
                continue;

            const char* str = json_object_get_string(entry);

            if (strncasecmp(str, "wifi", 4) == 0)
                appDesc->m_hardwareFeaturesNeeded |= HardwareFeaturesNeeded_Wifi;
            else if (strncasecmp(str, "bluetooth", 9) == 0)
                appDesc->m_hardwareFeaturesNeeded |= HardwareFeaturesNeeded_Bluetooth;
            else if (strncasecmp(str, "compass", 7) == 0)
                appDesc->m_hardwareFeaturesNeeded |= HardwareFeaturesNeeded_Compass;
            else if (strncasecmp(str, "accelerometer", 13) == 0)
                appDesc->m_hardwareFeaturesNeeded |= HardwareFeaturesNeeded_Accelerometer;
        }
    }

    //Universal Search JSON objct: optional
    label = json_object_object_get(root, "universalSearch");
    if(label && !is_error(label)) {
        appDesc->m_universalSearchJsonStr = json_object_to_json_string(label);
    }

    // Services JSON array: optional
    label = json_object_object_get(root, "services");
    if (label && !is_error(label))
        appDesc->m_servicesJsonStr = json_object_to_json_string(label);

    // Accounts JSON array: optional
    label = json_object_object_get(root, "accounts");
    if (label && !is_error(label))
        appDesc->m_accountsJsonStr = json_object_to_json_string(label);

    // Launch params: optional
    label = json_object_object_get(root, "params");
    if (label && !is_error(label)) {
        if (appDesc->m_type == Type_Qt)
            launchParams = json_object_get_string(label);
        else
            launchParams = json_object_to_json_string(label);
    }

    // Tap to Share Supported: optional
    label = json_object_object_get(root, "tapToShareSupported");
    if (label && !is_error(label)) {
        appDesc->m_tapToShareSupported = json_object_get_boolean(label);
    }

    // Requested Window Orientation: optional
    label = json_object_object_get(root, "requestedWindowOrientation");
    if( label && !is_error(label) && json_object_is_type(label, json_type_string))
    {
        appDesc->m_requestedWindowOrientation = json_object_get_string(label);
    }


    //check to see if it's a sysmgr-builtin
    if (appDesc->m_type == Type_SysmgrBuiltin)
    {
        //must have an entrypoint
        label = json_object_object_get(root,"entrypoint");
        if ((!label) || is_error(label))
        {
            g_warning("%s: App %s of type SysmgrBuiltin doesn't name an entrypoint",__FUNCTION__,appDesc->m_id.c_str());
            success = false;
            goto Done;
        }
        builtinEntrypt = json_object_get_string(label);
        label = json_object_object_get(root,"args");
        if (label && !is_error(label))
            builtinArgs = json_object_get_string(label);
        else
            builtinArgs = "";

        //update fields that can be localized   ...won't be done automatically because of sysmgr builtins being in a special location
        appDesc->updateSysmgrBuiltinWithLocalization();

        //try and create a launch helper
        if (appDesc->initSysmgrBuiltIn(ApplicationManager::instance(),builtinEntrypt,builtinArgs) == false)
        {
            //failed...something was specified wrong
            g_warning("%s: App %s cannot be formed into a sysmgrbuiltin: entry = [%s] , args = [%s]",
                      __FUNCTION__,appDesc->m_id.c_str(),builtinEntrypt.c_str(),builtinArgs.c_str());
            success = false;
            goto Done;
        }
    }
Done:

    if( root && !is_error(root) )json_object_put(root);

    delete [] jsonStr;

    if (!success) {
        delete appDesc;
        return 0;
    }

    // Default launchpoint (with empty params)
    LaunchPoint * defaultLp = new LaunchPoint(appDesc,
            appDesc->m_id,
            appDesc->m_id + "_default",
            appDesc->m_title, appDesc->m_appmenuName, icon, launchParams,appDesc->m_isRemovable);
    defaultLp->setAsDefault();
    appDesc->m_launchPoints.push_back(defaultLp);

    return appDesc;
}
Пример #30
0
int main(int argc, char **argv)
{
	struct json_object *json;
	struct array_list *tests;
	struct lh_entry *entry;
	char *key;
	struct json_object *val;
	int i;
	context ctx;

	if (argc != 2) {
		printf("Usage: %s <filename>\n", argv[0]);
		return 1;
	}

	json = json_object_from_file(argv[1]);
	assert(!is_error(json));

	assert(strcmp((char *) ((json_object_get_object(json)->head)->k),
			"tests") == 0);

	/* Get array of tests */
	tests = json_object_get_array((struct json_object *)
			(json_object_get_object(json)->head)->v);

	for (i = 0; i < array_list_length(tests); i++) {
		/* Get test */
		struct json_object *test =
			(struct json_object *) array_list_get_idx(tests, i);

		ctx.last_start_tag = NULL;
		ctx.content_model = NULL;
		ctx.process_cdata = false;

		/* Extract settings */
		for (entry = json_object_get_object(test)->head; entry;
				entry = entry->next) {
			key = (char *) entry->k;
			val = (struct json_object *) entry->v;

			if (strcmp(key, "description") == 0) {
				printf("Test: %s\n",
					json_object_get_string(val));
			} else if (strcmp(key, "input") == 0) {
				ctx.input = (const uint8_t *)
					json_object_get_string(val);
				ctx.input_len =	json_object_get_string_len(val);
			} else if (strcmp(key, "output") == 0) {
				ctx.output = json_object_get_array(val);
				ctx.output_index = 0;
				ctx.char_off = 0;
			} else if (strcmp(key, "lastStartTag") == 0) {
				ctx.last_start_tag = (const char *)
						json_object_get_string(val);
			} else if (strcmp(key, "contentModelFlags") == 0) {
				ctx.content_model =
						json_object_get_array(val);
			} else if (strcmp(key, "processCDATA") == 0) {
				ctx.process_cdata =
					json_object_get_boolean(val);
			}
		}

		/* And run the test */
		run_test(&ctx);
	}

	json_object_put(json);

	printf("PASS\n");

	return 0;
}