Ejemplo n.º 1
0
std::shared_ptr<json_object>& ResourceCache::loadAsset(const std::string& name) {
    std::shared_ptr<json_object> object;

    if (this->assetCache.find(name) == this->assetCache.end()) {
        Logger::getInstance().log(Logger::LOG_INFO, "Asset `%s' not in cache, trying to load", name.c_str());

        std::string fullPath(this->buildPath(name).c_str());
        auto entitySource = this->loadSource(fullPath.c_str());
        if (entitySource == nullptr) {
            Logger::getInstance().log(Logger::LOG_ERROR, "Failed to open `%s'", fullPath.c_str());
            return this->assetCache["nullptr"];
        }

        json_tokener_error parseError;
        object = std::shared_ptr<json_object>(
                json_tokener_parse_verbose(entitySource.get(), &parseError), json_object_put);
        if (object == nullptr) {
            Logger::getInstance().log(Logger::LOG_ERROR, "Failed to parse `%s': %s",
                    fullPath.c_str(), json_tokener_error_desc(parseError));
            return this->assetCache["nullptr"];
        }

        this->assetCache.insert(std::make_pair(name, object));
    } else {
        Logger::getInstance().log(Logger::LOG_INFO, "Asset `%s' picked from cache", name.c_str());
    }

    return this->assetCache.at(name);
}
Ejemplo n.º 2
0
json_object * rocsmq_get_message_json(p_rocsmq_message mesg) {
	enum json_tokener_error error;
	json_object * obj = json_tokener_parse_verbose(mesg->tail, &error);
	int i;
	if (error != json_tokener_success) {
		log_message(ERROR,"Json Parse: %s", json_tokener_error_desc(error));
		return 0;
	}
	return obj; 
}
Ejemplo n.º 3
0
static void test_verbose_parse()
{
	json_object *new_obj;
	enum json_tokener_error error = json_tokener_success;

	new_obj = json_tokener_parse_verbose("{ foo }", &error);
	assert (error == json_tokener_error_parse_object_key_name);
	assert (new_obj == NULL);

	new_obj = json_tokener_parse("{ foo }");
	assert (new_obj == NULL);

	new_obj = json_tokener_parse("foo");
	assert (new_obj == NULL);
	new_obj = json_tokener_parse_verbose("foo", &error);
	assert (new_obj == NULL);

	/* b/c the string starts with 'f' parsing return a boolean error */
	assert (error == json_tokener_error_parse_boolean);

	printf("json_tokener_parse_versbose() OK\n");
}
Ejemplo n.º 4
0
/** Couchbase callback for get (read) operations
 *
 * @param instance Couchbase connection instance.
 * @param cookie   Couchbase cookie for returning information from callbacks.
 * @param error    Couchbase error object.
 * @param resp     Couchbase get operation response object.
 */
void couchbase_get_callback(lcb_t instance, const void *cookie, lcb_error_t error, const lcb_get_resp_t *resp) {
	cookie_u cu;                            /* union of const and non const pointers */
	cu.cdata = cookie;                      /* set const union member to cookie passed from couchbase */
	cookie_t *c = (cookie_t *) cu.data;     /* set our cookie struct using non-const member */
	const char *bytes = resp->v.v0.bytes;   /* the payload of this chunk */
	lcb_size_t nbytes = resp->v.v0.nbytes;  /* length of this data chunk */

	/* check error */
	switch (error) {
	case LCB_SUCCESS:
		/* check for valid bytes */
		if (bytes && nbytes > 1) {
			/* debug */
			DEBUG("rlm_couchbase: (get_callback) got %zu bytes", nbytes);
			/* build json object */
			c->jobj = json_tokener_parse_verbose(bytes, &c->jerr);
			/* switch on current error status */
			switch (c->jerr) {
			case json_tokener_continue:
				/* do nothing */
				break;
			case json_tokener_success:
				/* do nothing */
				break;
			default:
				/* log error */
				ERROR("rlm_couchbase: (get_callback) JSON Tokener error: %s", json_tokener_error_desc(c->jerr));
				break;
			}
		}
		break;

	case LCB_KEY_ENOENT:
		/* ignored */
		DEBUG("rlm_couchbase: (get_callback) key does not exist");
		break;

	default:
		/* log error */
		ERROR("rlm_couchbase: (get_callback) %s (0x%x)", lcb_strerror(instance, error), error);
		break;
	}
}
Ejemplo n.º 5
0
ss_conf_t* ss_conf_file_parse(char* conf_path) {
    int is_ok = 1;
    int rv;
    char* conf_buffer            = NULL;
    json_object* json_underlying = NULL;
    json_object* items           = NULL;
    json_object* item            = NULL;
    json_error_t json_error      = json_tokener_success;

    conf_buffer                  = ss_conf_file_read(conf_path);
    if (conf_buffer == NULL) {
        fprintf(stderr, "conf file read error\n");
        is_ok = 0;
        goto error_out;
    }

    json_underlying = json_tokener_parse_verbose(conf_buffer, &json_error);
    if (json_underlying == NULL) {
        is_ok = 0;
        fprintf(stderr, "json parse error: %s\n", json_tokener_error_desc(json_error));
        is_ok = 0;
        goto error_out;
    }

    ss_conf = je_calloc(1, sizeof(ss_conf_t));
    if (ss_conf == NULL) {
        fprintf(stderr, "could not allocate sdn_sensor configuration\n");
        is_ok = 0;
        goto error_out;
    }

    ss_conf->json = json_object_get(json_underlying);
    is_ok         = json_object_is_type(ss_conf->json, json_type_object);
    if (!is_ok) {
        is_ok = 0;
        fprintf(stderr, "json configuration root is not object\n");
        is_ok = 0;
        goto error_out;
    }

    //const char* content = json_object_to_json_string_ext(ss_conf->json, JSON_C_TO_STRING_PRETTY);
    //fprintf(stderr, "json configuration:\n%s\n", content);

    TAILQ_INIT(&ss_conf->re_chain.re_list);
    TAILQ_INIT(&ss_conf->pcap_chain.pcap_list);
    TAILQ_INIT(&ss_conf->dns_chain.dns_list);
    TAILQ_INIT(&ss_conf->ioc_chain.ioc_list);

    items = ss_json_object_get(ss_conf->json, "network");
    if (items == NULL) {
        fprintf(stderr, "could not load network configuration\n");
        is_ok = 0;
        goto error_out;
    }
    if (!json_object_is_type(items, json_type_object)) {
        fprintf(stderr, "network configuration is not object\n");
        is_ok = 0;
        goto error_out;
    }

    rv = ss_conf_network_parse(items);
    if (rv) {
        fprintf(stderr, "could not parse network configuration\n");
        is_ok = 0;
        goto error_out;
    }

    items = ss_json_object_get(ss_conf->json, "dpdk");
    if (items == NULL) {
        fprintf(stderr, "could not load dpdk configuration\n");
        is_ok = 0;
        goto error_out;
    }
    if (!json_object_is_type(items, json_type_object)) {
        fprintf(stderr, "dpdk configuration is not object\n");
        is_ok = 0;
        goto error_out;
    }

    rv = ss_conf_dpdk_parse(items);
    if (rv) {
        fprintf(stderr, "could not parse dpdk configuration\n");
        is_ok = 0;
        goto error_out;
    }

    items = ss_json_object_get(ss_conf->json, "re_chain");
    if (items) {
        is_ok = json_object_is_type(items, json_type_array);
        if (!is_ok) {
            fprintf(stderr, "re_chain is not an array\n");
            goto error_out;
        }
        int length = json_object_array_length(items);
        for (int i = 0; i < length; ++i) {
            item = json_object_array_get_idx(items, i);
            ss_re_entry_t* entry = ss_re_entry_create(item);
            /*
            if (entry == NULL) {
                fprintf(stderr, "could not create re_chain entry\n");
                if (entry) je_free(entry);
                is_ok = 0; goto error_out;
            }
            */
            if (entry == NULL) {
                fprintf(stderr, "could not create re_chain entry %d\n", i);
                ss_re_entry_destroy(entry);
                is_ok = 0;
                goto error_out;
            }
            ss_re_chain_add(entry);
        }
    }

    items = ss_json_object_get(ss_conf->json, "pcap_chain");
    if (items) {
        is_ok = json_object_is_type(items, json_type_array);
        if (!is_ok) {
            fprintf(stderr, "pcap_chain is not an array\n");
            goto error_out;
        }
        int length = json_object_array_length(items);
        for (int i = 0; i < length; ++i) {
            item = json_object_array_get_idx(items, i);
            ss_pcap_entry_t* entry = ss_pcap_entry_create(item);
            if (entry == NULL) {
                fprintf(stderr, "could not create pcap_chain entry %d\n", i);
                ss_pcap_entry_destroy(entry);
                is_ok = 0;
                goto error_out;
            }
            ss_pcap_chain_add(entry);
        }
    }

    items = ss_json_object_get(ss_conf->json, "dns_chain");
    if (items) {
        is_ok = json_object_is_type(items, json_type_array);
        if (!is_ok) {
            fprintf(stderr, "dns_chain is not an array\n");
            goto error_out;
        }
        int length = json_object_array_length(items);
        for (int i = 0; i < length; ++i) {
            item = json_object_array_get_idx(items, i);
            ss_dns_entry_t* entry = ss_dns_entry_create(item);
            if (entry == NULL) {
                fprintf(stderr, "could not create dns_chain entry %d\n", i);
                ss_dns_entry_destroy(entry);
                is_ok = 0;
                goto error_out;
            }
            ss_dns_chain_add(entry);
        }
    }

    items = ss_json_object_get(ss_conf->json, "cidr_table");
    if (items) {
        is_ok = json_object_is_type(items, json_type_array);
        if (!is_ok) {
            fprintf(stderr, "cidr_table is not an array\n");
            goto error_out;
        }
        int length = json_object_array_length(items);
        for (int i = 0; i < length; ++i) {
            item = json_object_array_get_idx(items, i);
            ss_cidr_entry_t* entry = ss_cidr_entry_create(item);
            /*
            if (entry == NULL) {
                fprintf(stderr, "could not create cidr_table entry %d\n", i);
                ss_cidr_entry_destroy(entry);
                is_ok = 0; goto error_out;
            }
            */
            ss_cidr_table_add(&ss_conf->cidr_table, entry);
        }
    }

    // XXX: do more stuff
error_out:
    if (conf_buffer)        {
        je_free(conf_buffer);
        conf_buffer = NULL;
    }
    if (!is_ok && ss_conf)  {
        ss_conf_destroy();
        ss_conf     = NULL;
    }

    return ss_conf;
}
Ejemplo n.º 6
0
Archivo: mq.cpp Proyecto: karlp/mqblynk
void BlynkMQTT::on_message(const struct mosquitto_message* message)
{
	const char *payloads = (const char *)message->payload;
	bool matches;
	mosqpp::topic_matches_sub("mqblynk/command/#", message->topic, &matches);
	if (matches) {
		if (strstr(payloads, "quit")) {
			printf("exiting on quit request\n");
			this->_should_run = false;
		} else {
			printf("command unrecognised!: %s\n", payloads);
		}
		return;
	}
	
	enum json_tokener_error js_tok_error;
	struct json_object *js = json_tokener_parse_verbose((const char*)message->payload, &js_tok_error);

	if (js_tok_error != json_tokener_success) {
		printf("Invalid json, reason: %s, actual data: %s\n", json_tokener_error_desc(js_tok_error), (const char*)message->payload);
		return;
	}
	
	for (auto map : this->_conf.outputs) {
		bool matches;
		int rc = mosqpp::topic_matches_sub(map->topic, message->topic, &matches);
		if (rc != MOSQ_ERR_SUCCESS) {
			printf("invalid params is code error, out of memory we can't handle: %d\n", rc);
			break;
		}
		if (matches) {
			map->blynk = &this->_blynk;
			jp_match(map->_jp->path, js, mq_blynk_js_cb, &map);
			


//			if (strcmp(map.magic, "int") == 0) {
//				int x = atoi((const char*) message->payload);
//				printf("blynking int %d -> %d\n", map.pin, x);
//				this->_blynk.virtualWrite(map.pin, x);
//			} else if (strcmp(map.magic, "str") == 0) {
//				const char *x = (const char *) message->payload;
//				printf("blynking str %d -> %s\n", map.pin, x);
//				this->_blynk.virtualWrite(map.pin, x);
//			} else if (strcmp(map.magic, "lcd") == 0) {
//				const char *x = (const char *) message->payload;
//				printf("blynking lcd %d -> %s\n", map.pin, x);
//				char mem[64] = "";
//				BlynkParam cmd(mem, 0, sizeof(mem));
//				cmd.add("p");
//				cmd.add(0);
//				cmd.add(0);
//				cmd.add(x);
//				this->_blynk.virtualWrite(map.pin, cmd);
//			} else {
//				printf("unknown magic mapping: %s\n", map.magic);
//			}
		}
	}
	json_object_put(js);
}
Ejemplo n.º 7
0
  json_object_put(new_obj);

  new_obj = json_tokener_parse("{ \"foo\": \"bar\", \"baz\": null, \"bool0\": true }");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  new_obj = json_tokener_parse("{ \"foo\": [null, \"foo\"] }");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  new_obj = json_tokener_parse("{ \"abc\": 12, \"foo\": \"bar\", \"bool0\": false, \"bool1\": true, \"arr\": [ 1, 2, 3, null, 5 ] }");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  json_object_put(new_obj);

  enum json_tokener_error error = json_tokener_success;
  new_obj = json_tokener_parse_verbose("{ foo }", &error);
  assert (error == json_tokener_error_parse_object_key_name);
  assert (new_obj == NULL);

  new_obj = json_tokener_parse("{ foo }");
  assert (new_obj == NULL);
  
  // if(is_error(new_obj)) printf("got error as expected\n");

  new_obj = json_tokener_parse("foo");
  assert (new_obj == NULL);
  new_obj = json_tokener_parse_verbose("foo", &error);
  assert (new_obj == NULL);
  assert (error == json_tokener_error_parse_boolean);

  new_obj = json_tokener_parse("{ \"foo");
Ejemplo n.º 8
0
bool settings_read(void)
{
  bool rv;
  bool bind_defaults;
  bool nonexistent_ok;

  rv             = true;
  bind_defaults  = true;
  nonexistent_ok = false;
  
  /* Read and delete the old versions first if it exists. */
  settings_read_v1();

  if(settings_read_v2())
    {
      bind_defaults = false;
      nonexistent_ok = true; // If we managed to read the old .lua file, then failing to read the new .json file should not cause any error messages.
    }


  /* Read the new version if it exists. */
  char * json;
  int    json_size;

  snprintf(filename, sizeof filename, "%s", get_save_filename("settings.json"));
  if(read_file(filename, &json, &json_size) == true)
    {
      enum json_tokener_error e;
      struct json_object * obj;

      obj = json_tokener_parse_verbose(json, &e);
      if(obj != NULL)
        {
          bool ok;
          struct json_object_iterator it;
          struct json_object_iterator itEnd;
          int active_questline;

          ok    = true;
          it    = json_object_iter_begin(obj);
          itEnd = json_object_iter_end(obj);

          active_questline = globals.active_questline;

          while(ok == true && !json_object_iter_equal(&it, &itEnd))
            {
              const char *         name;
              struct json_object * value;
              enum json_type       type;
              bool                 dummy_boolean;
              
              name  = json_object_iter_peek_name(&it);
              value = json_object_iter_peek_value(&it);
              type = json_object_get_type(value);

              struct
              {
                const char *   name;
                enum json_type type;
                bool (*callback)(struct json_object * value, void * value_ptr);
                void *         value_ptr;
              } stuff[] =
                  {
                    { "Fullscreen",                 json_type_boolean, cb_bool,                 &globals.fullscreen                   },
                    { "OpenGL",                     json_type_boolean, cb_bool,                 &globals.opengl                       },
                    { "OpenGL_POT",                 json_type_boolean, cb_opengl_pot,           NULL                                  },               
                    { "OpenGL_compressed_textures", json_type_boolean, cb_bool,                 &globals.opengl_compressed_textures   },
                    { "SFX",                        json_type_boolean, cb_bool,                 &globals.use_sfx                      },
                    { "Music",                      json_type_boolean, cb_bool,                 &globals.use_music                    },
                    { "SFX_max_channels",           json_type_int,     cb_int,                  &globals.max_channels                 },
                    { "Sound_volume",               json_type_int,     cb_sound_volume,         NULL                                  },
                    { "Joysticks",                  json_type_boolean, cb_bool,                 &globals.use_joysticks                },
                    { "CaveSelection",              json_type_string,  cb_cave_selection,       NULL                                  },
                    { "CaveSelectionLevel",         json_type_int,     cb_cave_selection_level, NULL                                  },
                    { "ShowFPS",                    json_type_boolean, cb_bool,                 &globals.fps_counter_active           },
                    { "GameMode",                   json_type_string,  cb_game_mode,            NULL                                  },
                    { "ActiveQuestline",            json_type_int,     cb_int,                  &active_questline                     },
                    { "TitleMidarea",               json_type_string,  cb_title_midarea,        NULL                                  },
                    { "IronGirlMode",               json_type_boolean, cb_bool,                 &globals.iron_girl_mode               },
                    { "Locale",                     json_type_string,  cb_locale,               NULL                                  },
                    { "MapTilting",                 json_type_boolean, cb_bool,                 &globals.map_tilting                  },
                    { "SmoothClassicMode",          json_type_boolean, cb_bool,                 &globals.smooth_classic_mode          },
                    { "Bindings",                   json_type_array,   cb_bindings,             NULL                                  },
                    { "Themes",                     json_type_array,   cb_themes,               NULL                                  },
                    { "WriteSettings",              json_type_boolean, cb_bool,                 &globals.write_settings               },
                    { "TestsCompleted",             json_type_boolean, cb_bool,                 &dummy_boolean                        }, // Ignored.
                    { NULL,                         json_type_int,     NULL,                    NULL                                  }
                  };
              
              int ind;

              ind = -1;
              for(int i = 0; ind == -1 && stuff[i].name != NULL; i++)
                if(!strcmp(stuff[i].name, name))
                  ind = i;

              if(ind >= 0)
                {
                  if(stuff[ind].type == type)
                    {
                      ok = stuff[ind].callback(value, stuff[ind].value_ptr);

                      /* Don't bind the default keybindings if we were able to read them from the settings.json. */
                      if(ok == true && !strcmp(name, "Bindings"))
                        bind_defaults = false;
                    }
                  else
                    {
                      fprintf(stderr, "%s: Incorrect value type %s for '%s', expected %s.\n", filename, json_type_to_name(type), name, json_type_to_name(stuff[ind].type));
                      ok = false;
                    }
                }
              else
                {
                  fprintf(stderr, "%s: Failed to parse: unknown variable '%s'.\n", filename, name);
                  ok = false;
                }

              json_object_iter_next(&it);
            }

          if(ok == true)
            globals.active_questline = active_questline;
          else
            rv = false;
        }
      else
        {
          fprintf(stderr, "%s: Failed to parse: %d: %s\n", filename, (int) e, json_tokener_error_desc(e));
        }
      free(json);
    }
  else
    {
      if(nonexistent_ok == false)
        fprintf(stderr, "%s: Failed to read '%s'.\n", __FUNCTION__, filename);
    }


  if(bind_defaults)
    ui_bindings_default(true);

  if(globals.iron_girl_mode)
    theme_set(THEME_TRAIT, "iron-girl");
  
  return rv;
}
Ejemplo n.º 9
0
VerifyResult verify_assertion_local(request_rec *r, const char *assertion)
{
  char *pair;
  char *last = NULL;
  VerifyResult res = apr_pcalloc(r->pool, sizeof(struct _VerifyResult));
  char *assertion_string = apr_pstrdup(r->pool, assertion);

  char *delim = ".";
  const char *assertions[16];

  int i = 0;

  /* XXX: Need to make sure we don't overrun assertions[] */
  for (pair = apr_strtok(assertion_string, delim, &last);
       pair; pair = apr_strtok(NULL, delim, &last)) {
    assertions[i++] = pair;
  }

  ap_log_rerror(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, 0, r,
                ERRTAG
                "Local Assertion Verification enabled but not implemented yet");

  int assertion_count = i;

  json_object *json_assertions[16];
  enum json_tokener_error jerr;

  for (i = 0; i < assertion_count; i++) {
    assertions[i] = base64url_decode(r->pool, assertions[i]);
    json_assertions[i] = json_tokener_parse_verbose(assertions[i], &jerr);
    if (json_tokener_success != jerr) {
      ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                    ERRTAG "json parse error %s",
                    json_tokener_error_desc(jerr));
      ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                    ERRTAG "Raw Pair %d is %s", i, assertions[i]);
    }
    else {
      ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                    ERRTAG "JSON is %s",
                    json_object_to_json_string(json_assertions[i]));
    }
  }

  json_object *principal =
    json_object_object_get(json_assertions[1], "principal");
  json_object *issuer = json_object_object_get(json_assertions[1], "iss");
  json_object *expiry = json_object_object_get(json_assertions[3], "exp");
  json_object *audience = json_object_object_get(json_assertions[3], "aud");
  json_object *email = NULL;

  /* Not fully implemented yet */
  res->errorResponse = "Local verification enabled but not implemented yet";

  if (principal && json_object_is_type(principal, json_type_object)) {
    email = json_object_object_get(principal, "email");
    if (email && json_object_is_type(email, json_type_string)) {
      res->verifiedEmail = json_object_get_string(email);
    }
  }
  if (issuer && json_object_is_type(issuer, json_type_string)) {
    res->identityIssuer = json_object_get_string(issuer);
  }
  if (audience && json_object_is_type(audience, json_type_string)) {
    const char *audience_str = json_object_get_string(audience);
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                  ERRTAG "Audience is %s", audience_str);
  }

  if (expiry && json_object_is_type(expiry, json_type_int)) {
    int64_t expiry_time = json_object_get_int64(expiry);
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r,
                  ERRTAG "Expiry is %" APR_INT64_T_FMT, expiry_time);
  }

  /* Fake success */
  if (email && issuer) {
    res->errorResponse = NULL;
  }

  return res;
}
Ejemplo n.º 10
0
Archivo: main.c Proyecto: jsvana/alfred
int main(int argc, char *argv[]) {
	printf("Content-type: text/plain\n\n");
	char *data = alfred_read_file(stdin);
	enum json_tokener_error err;

	json_object *json = json_tokener_parse_verbose(data, &err);
	
	// Shouldn't need this var any more
	g_free(data);

	// Parse error
	if (err != json_tokener_success) {
		alfred_error_static(ALFRED_ERROR_MALFORMED_COMMAND);
		return 0;
	}

	char *method = alfred_json_get_string(json, "method");
	char *alfred = alfred_json_get_string(json, "alfred");
	char *key = alfred_json_get_string(json, "key");
	json_object *params = json_object_object_get(json, "params");

	if (!method || !alfred || !key || !params) {
		alfred_error_static(ALFRED_ERROR_MALFORMED_COMMAND);
		g_free(method);
		g_free(alfred);
		g_free(key);
		if (params) {
			json_object_put(params);
		}

		return 0;
	}

	alfred_auth_set_key(key);

	alfred_sql_init();

	gchar **info = g_strsplit(method, ".", 2);

	if (info && info[0] && info[1]) {
		if (strcmp(info[0], "Alfred") == 0) {
			alfred_module_alfred(info[1], params);
		} else if (strcmp(info[0], "Location") == 0) {
			alfred_module_location(info[1], params);
		} else if (strcmp(info[0], "Net") == 0) {
			alfred_module_net(info[1], params);
		} else if (strcmp(info[0], "Password") == 0) {
			alfred_module_password(info[1], params);
		} else if (strcmp(info[0], "XBMC") == 0) {
			alfred_module_xbmc(info[1], params);
		} else if (!alfred_authed()) {
			alfred_error_static(ALFRED_ERROR_NOT_AUTHENTICATED);
		} else {
			alfred_error_static(ALFRED_ERROR_UNKNOWN_COMMAND);
		}
	} else if (!alfred_authed()) {
		alfred_error_static(ALFRED_ERROR_NOT_AUTHENTICATED);
	} else {
		alfred_error_static(ALFRED_ERROR_UNKNOWN_COMMAND);
	}

	alfred_sql_shutdown();

	// For good measure
	alfred_auth_forget_key();
	
	g_strfreev(info);
	g_free(method);
	g_free(alfred);
	g_free(key);

	json_object_put(json);

	return 0;
}
Ejemplo n.º 11
0
int main(int argc, char *argv[]) {
    CURL *ch;                                               /* curl handle */
    CURLcode rcode;                                         /* curl result code */

    json_object *json;                                      /* json post body */
    enum json_tokener_error jerr = json_tokener_success;    /* json parse error */

    struct curl_fetch_st curl_fetch;                        /* curl fetch struct */
    struct curl_fetch_st *cf = &curl_fetch;                 /* pointer to fetch struct */
    struct curl_slist *headers = NULL;                      /* http headers to send with request */

    /* url to test site */
    char *url = "http://energybill.ir/api/remote";

    /* init curl handle */
    if ((ch = curl_easy_init()) == NULL) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to create curl handle in fetch_session");
        /* return error */
        return 1;
    }

    /* set content type */
    headers = curl_slist_append(headers, "Accept: application/json");
    headers = curl_slist_append(headers, "Content-Type: application/json");

    /* create json object for post */
    json = json_object_new_object();

    /* build post data */
    //linux one: curl -H "Accept:application/json" -H "Content-Type: application/json" -X POST -d '{"SerialNumber":"61600010","AccumulatedEnergy":0.0,"AccumulatedVolume":0.0,"TariffEnergy":0.0,"FlowSensorVolume":0.0,"Power":0.0,"Aux1":0,"Aux2":0,"MeterTime":null,"OnTime":0,"ErrorTime":0,"LowTemp":0.0,"HighTemp":0.0,"ErrorCode":0}'  http://energybill.ir/api/remote
    //curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d
    //           curl -H "Accept:application/json" -H "Content-Type: application/json" -X POST -d '{"SerialNumber":"61600010","AccumulatedEnergy":10.6,"AccumulatedVolume":15.42,"TariffEnergy":0.0,"FlowSensorVolume":0.0,"Power":0.0,"Aux1":0,"Aux2":0,"MeterTime":null,"OnTime":0,"ErrorTime":0,"LowTemp":0.0,"HighTemp":0.0,"ErrorCode":0}'  http://energybill.ir/api/remote
    FILE *fptr;
    fptr=fopen("Room_Temperature.txt","r");
    char buffer[5];
    fgets (buffer,5,fptr);
    printf ("TT%s",buffer);

    FILE *fptrh;
    fptrh=fopen("Room_Humidity.txt","r");
    char bufferh[5];
    fgets (bufferh,5,fptrh);
    printf ("HH%s",bufferh);


    json_object_object_add(json, "SerialNumber", json_object_new_string("51600004"));
    json_object_object_add(json, "AccumulatedEnergy", json_object_new_int(0));
    json_object_object_add(json, "AccumulatedVolume", json_object_new_int(0));
    json_object_object_add(json, "TariffEnergy", json_object_new_int(0));
    json_object_object_add(json, "FlowSensorVolume", json_object_new_int(atoi(bufferh)));
    json_object_object_add(json, "Power", json_object_new_int(0));
    json_object_object_add(json, "Aux1", json_object_new_int(0));
    json_object_object_add(json, "Aux2", json_object_new_int(0));
    //json_object_object_add(json, "MeterTime", json_object_new_int((int32_t)));
    json_object_object_add(json, "OnTime", json_object_new_int(0));
    json_object_object_add(json, "ErrorTime", json_object_new_int(0));
    json_object_object_add(json, "LowTemp", json_object_new_double(atoi(bufferh)));
    json_object_object_add(json, "HighTemp", json_object_new_double(atof(buffer)));
    json_object_object_add(json, "ErrorCode", json_object_new_int(0));



    /* set curl options */
    curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(ch, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(ch, CURLOPT_POSTFIELDS, json_object_to_json_string(json));

    /* fetch page and capture return code */
    rcode = curl_fetch_url(ch, url, cf);

    /* cleanup curl handle */
    curl_easy_cleanup(ch);

    /* free headers */
    curl_slist_free_all(headers);

    /* free json object */
    json_object_put(json);

    /* check return code */
    if (rcode != CURLE_OK || cf->size < 1) {
        /* log error */
        fprintf(stderr, "ERROR: Failed to fetch url (%s) - curl said: %s \n",
            url, curl_easy_strerror(rcode));
        /* return error */
        return 2;
    }

    /* check payload */
    if (cf->payload != NULL) {
        /* print result */
        printf("CURL Returned: \n%s\n", cf->payload);
        /* parse return */
        json = json_tokener_parse_verbose(cf->payload, &jerr);
        /* free payload */
        free(cf->payload);
    } else {
        /* error */
        fprintf(stderr, "ERROR: Failed to populate payload");
        /* free payload */
        free(cf->payload);
        /* return */
        return 3;
    }

    /* check error */
    if (jerr != json_tokener_success) {
        /* error */
        fprintf(stderr, "ERROR: Failed to parse json string\n");
        /* free json object */
        json_object_put(json);
        /* return */
        return 4;
    }

    /* debugging */
    printf("Parsed JSON: %s\n", json_object_to_json_string(json));

    /* exit */
    return 0;
}