Example #1
0
	void Client::sendChat(std::string str)
	{
        if((_state != ConnectionState::connected) || (_socket == NULL)){
            if(_chatlistener != NULL)
			{
				_chatlistener->onSendChatDone(ResultCode::connection_error);
			}
            return;
        }
		if(str.length() >= 512)
		{
			if(_chatlistener != NULL)
				_chatlistener->onSendChatDone(ResultCode::bad_request);

			return;
		}

		std::string payload;
		int len;

		cJSON *payloadJSON;
		payloadJSON = cJSON_CreateObject();
		cJSON_AddStringToObject(payloadJSON, "chat" ,str.c_str());
		char *cRet = cJSON_PrintUnformatted(payloadJSON);
		payload = cRet;

		byte * req = buildWarpRequest(RequestType::chat, payload, len);

		char *data = new char[len];
		for(int i=0; i< len; ++i)
		{
			data[i] = req[i];
		}

		_socket->sockSend(data, len);

		delete[] data;
		delete[] req;
		cJSON_Delete(payloadJSON);
		free(cRet);
	}
static bool getacc_allmanacc(data_getacc_reply *data_reply) {
	int count = 0;
	cJSON *root;
	relater_inf *p = protodata->relaterlist.head;

	root = cJSON_CreateArray();

	while (p != NULL) {
		if (p->right == RELATER_AUTHORITY_MAN) {
			cJSON *user = cJSON_CreateObject();
			cJSON_AddStringToObject(user, GETACC_INFO_ACCOUNT, p->username);
			cJSON_AddNumberToObject(user, GETACC_INFO_RIGHT, p->right);
			cJSON_AddItemToArray(root, user);
			count++;
		}
		p = p->next;
	}
	data_reply->json_info = root;
	data_reply->ret = count;
	return true;
}
Example #3
0
/***************************************************************************
  Function:       package_json_callback 
  Description:    发到5017端口的callback数据格式
  Input:          
                  
  Output:      输出封装好的callback数据的地址   
  Return:       
  Others:         
****************************************************************************/
char *package_json_callback(int type,char *pic_name,int num)
{
    cJSON *root,*fmt;
    char *out;	
    //Our "Video" datatype: 
    root=cJSON_CreateObject();
	cJSON_AddNumberToObject(root,"msgtype",0);
	cJSON_AddNumberToObject(root,"mainid",2);
	cJSON_AddNumberToObject(root,"subid",6);
	cJSON_AddNumberToObject(root,"status",type );
	cJSON_AddNumberToObject(root,"pic_count",num);
	if(type == 0)
	{
		
		cJSON_AddStringToObject(root,"pic_name",pic_name);

	}
    out=cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    return out; 
}
Example #4
0
/*
 * Special properties. This values can modified with the web interface.
 * I.e. angle of kinect, nmbr of areas, position of areas, minimal blob size.
 */
cJSON* PrintSettings::loadDefaults()
{
	cJSON* root = cJSON_CreateObject();	
	cJSON_AddStringToObject(root, "kind", "printSettings");

	cJSON* html = cJSON_CreateArray();	
	cJSON_AddItemToArray(html, jsonIntField("firstLayer",1,1,10000,100) );
	cJSON_AddItemToArray(html, jsonIntField("lastLayer",10000,1,10000,100) );
	cJSON_AddItemToArray(html, jsonDoubleField("normalLayerExposure",12,1,100,10) );
	cJSON_AddItemToArray(html, jsonIntField("nbrAttachLayers",3,1,100,10) );
	cJSON_AddItemToArray(html, jsonDoubleField("attachLayerExposure",60,1,300,10) );

	cJSON_AddItemToObject(root, "html", html);

	/* Point information for repoke 
	cJSON* areas = cJSON_CreateArray();	
	cJSON_AddItemToArray(areas, jsonArea(1,320.0,240.0,100.0) );
	cJSON_AddItemToObject(root, "areas", areas);
	*/
	return root;
}
Example #5
0
int createServerUserLogin(int sock,int serverid,int isSuccess,char* username){
	server_header_2_t* header = createServerHeader(serverid,COMMAND_OTHER_MESSAGE,MESSAGE_TYPE_USER_LOGIN);
	cJSON* json = cJSON_CreateObject();
	cJSON_AddNumberToObject(json,"result",isSuccess);
	cJSON_AddStringToObject(json,"username",username);	
	//cJSON_AddStringToObject(json,"userid","userid");
	char* str = cJSON_Print(json);	
	int total = sizeof(server_header_2_t)+sizeof(uint16_t)+strlen(str);
	void* bufs = malloc(total);
	void* buf = bufs;
	header->total = total;
	memcpy(buf,header,sizeof(server_header_2_t));
	buf += sizeof(server_header_2_t);
	*(uint16_t*)buf = htons(strlen(str));
	buf += sizeof(uint16_t);
	memcpy(buf,str,strlen(str));
	int ret =send(sock,bufs,total,0);
	free(bufs);
	cJSON_Delete(json);
	//free(str);
	return ret;	
}
Example #6
0
int createClientUserGetFriends(int sock,int clienttype,char* username){
	client_header_2_t* header = createClientHeader(COMMAND_OTHER_MESSAGE,MESSAGE_TYPE_USER_GET_FRIEND,clienttype);	
	cJSON* json = cJSON_CreateObject();
	cJSON_AddStringToObject(json,"username",username);		
	char* str = cJSON_Print(json);	
	int total = sizeof(client_header_2_t)+sizeof(uint16_t)+strlen(str);
	void* bufs = malloc(total);
	void* buf = bufs;
	header->total = total;
	memcpy(buf,header,sizeof(client_header_2_t));	
	buf += sizeof(client_header_2_t);
	*(uint16_t*)buf = htons(strlen(str));	
	buf += sizeof(uint16_t);
	memcpy(buf,str,strlen(str));
	dump_data(bufs,total);
	int ret =send(sock,bufs,total,0);
	printf("%d\n",ret);
	free(bufs);	
//	free(str);
	cJSON_Delete(json);	
	return ret;	
}
Example #7
0
/* Do a printf to stderr or log file as appropriate, then exit. */
void
iperf_errexit(struct iperf_test *test, const char *format, ...)
{
    va_list argp;
    char str[1000];

    va_start(argp, format);
    vsnprintf(str, sizeof(str), format, argp);
    if (test != NULL && test->json_output && test->json_top != NULL) {
	cJSON_AddStringToObject(test->json_top, "error", str);
	iperf_json_finish(test);
    } else
	if (test && test->outfile) {
	    fprintf(test->outfile, "iperf3: %s\n", str);
	}
	else {
	    fprintf(stderr, "iperf3: %s\n", str);
	}
    va_end(argp);
    iperf_delete_pidfile(test);
    exit(1);
}
Example #8
0
cJSON *socket_end_serialize(struct socket_end_st *se) {
	cJSON *result, *pipelines;
	char keybuf[SHAREDKEY_BYTESIZE*4], byte[8];
	int i;

	result = cJSON_CreateObject();
	pipelines = cJSON_CreateArray();

	cJSON_AddNumberToObject(result, "id", se->id);
	keybuf[0]=0;
	for (i=0;i<SHAREDKEY_BYTESIZE;++i) {
		snprintf(byte, 8, "%.2x ", se->shared_key[i]);
		strcat(keybuf, byte);
	}
	cJSON_AddStringToObject(result, "SharedKey", keybuf);
	cJSON_AddNumberToObject(result, "SendBuffer", streambuf_nr_bytes(se->send_buffer));
	for (i=se->pipeline_1; i!=-1; i=se->pipeline_end[i]->next_id) {
		cJSON_AddItemToArray(pipelines, pipeline_end_serialize(se->pipeline_end[i]));
	}
	cJSON_AddItemToObject(result, "Pipelines", pipelines);
	return result;
}
Example #9
0
Eina_Bool
azy_content_serialize_request_json(Azy_Content *content)
{
   Eina_List *l;
   Eina_Value *v;
   cJSON *object, *params;
   char *msg;

   if ((!content) || (content->buffer))
     return EINA_FALSE;

   object = cJSON_CreateObject();
   cJSON_AddStringToObject(object, "method", content->method);

   if (content->params)
     {
        params = cJSON_CreateArray();
        EINA_LIST_FOREACH(content->params, l, v)
          cJSON_AddItemToArray(params, azy_value_serialize_json(v));

        cJSON_AddItemToObject(object, "params", params);
     }
   cJSON_AddNumberToObject(object, "id", content->id);

   if (eina_log_domain_level_check(azy_log_dom, EINA_LOG_LEVEL_DBG))
     msg = cJSON_Print(object);
   else
     msg = cJSON_PrintUnformatted(object);

   if(!msg) goto free_object;
   azy_content_buffer_set_(content, (unsigned char *)msg, strlen(msg));

   cJSON_Delete(object);
   return EINA_TRUE;

free_object:
   cJSON_Delete(object);
   return EINA_FALSE;
}
Example #10
0
int CRedWoodDataParse::AddSensorDataToJson(cJSON* sensorJson, cJSON* descJson)
{
    if (sensorJson == NULL)
        return -1;

    cJSON* jsonSon        = NULL;
    cJSON* jsonGrandChild = NULL;
    jsonSon = sensorJson->child;

    while (jsonSon) {
        jsonGrandChild = jsonSon->child;

        if (jsonGrandChild) {
            //get grandchild value
            switch (jsonGrandChild->type) {
            case cJSON_Number:
                cJSON_AddNumberToObject(descJson, 
                    jsonSon->string, jsonGrandChild->valuedouble);
                break;

            case cJSON_String:
                cJSON_AddStringToObject(descJson, 
                    jsonSon->string, jsonGrandChild->valuestring);
                break;

            default:
                break;
            }
        }
        else {
            cJSON_AddNullToObject(descJson, jsonSon->string);
        }

        jsonSon = jsonSon->next;
    }

    return 0;
}
Example #11
0
// Print JSON header to gzout
static void bubble_caller_print_header(gzFile gzout, const char* out_path,
                                       BubbleCallingPrefs prefs,
                                       cJSON **hdrs, size_t nhdrs,
                                       const dBGraph *db_graph)
{
  size_t i;

  // Construct cJSON
  cJSON *json = cJSON_CreateObject();

  cJSON_AddStringToObject(json, "file_format", "CtxBubbles");
  cJSON_AddNumberToObject(json, "format_version", BUBBLE_FORMAT_VERSION);

  // Add standard cortex headers
  json_hdr_make_std(json, out_path, hdrs, nhdrs, db_graph);

  // Add parameters used in bubble calling to the header
  json_hdr_augment_cmd(json, "bubbles", "max_flank_kmers",  cJSON_CreateInt(prefs.max_flank_len));
  json_hdr_augment_cmd(json, "bubbles", "max_allele_kmers", cJSON_CreateInt(prefs.max_allele_len));
  cJSON *haploids = cJSON_CreateArray();
  for(i = 0; i < prefs.num_haploid; i++)
    cJSON_AddItemToArray(haploids, cJSON_CreateInt(prefs.haploid_cols[i]));
  json_hdr_augment_cmd(json, "bubbles", "haploid_colours", haploids);

  // Write header to file
  json_hdr_gzprint(json, gzout);

  // Print comments about the format
  gzputs(gzout, "\n");
  gzputs(gzout, "# This file was generated with McCortex\n");
  gzputs(gzout, "#   written by Isaac Turner <*****@*****.**>\n");
  gzputs(gzout, "#   url: "CORTEX_URL"\n");
  gzputs(gzout, "# \n");
  gzputs(gzout, "# Comment lines begin with a # and are ignored, but must come after the header\n");
  gzputs(gzout, "\n");

  cJSON_Delete(json);
}
Example #12
0
static void _set_cjson_field(E_KRType type, char *name, U_KRValue *value, cJSON *json) 
{ 
    switch(type) 
    { 
        case KR_TYPE_INT: 
            cJSON_AddNumberToObject(json, name, value->i);
            break;
        case KR_TYPE_LONG: 
            cJSON_AddNumberToObject(json, name, value->l);
            break;
        case KR_TYPE_DOUBLE: 
            cJSON_AddNumberToObject(json, name, value->d);
            break;
        case KR_TYPE_POINTER:
            cJSON_AddNumberToObject(json, name, (long )(value->p));
            break;
        case KR_TYPE_STRING: 
            cJSON_AddStringToObject(json, name, value->s?value->s:" ");
            break;
        default: 
            return; 
    } 
} 
Example #13
0
void four_moveGreedy(char* charOut) {
	{
		cJSON* objectOut = cJSON_CreateObject();
		cJSON* objectIn = NULL;
		
		{
			cJSON_AddStringToObject(objectOut, "strFunction", "four_moveGreedy");
		}
		
		{
			zeromq_send(objectOut);
			
			objectIn = zeromq_recv();
		}
		
		{
			strcpy(charOut, cJSON_GetObjectItem(objectIn, "strOut")->valuestring);
		}
		
		cJSON_Delete(objectOut);
		cJSON_Delete(objectIn);
	}
}
Example #14
0
int Parser_PackScrrenshotError(char * errorStr, char **outputStr)
{
	char * out = NULL;
	int outLen = 0;
	cJSON *pSUSICommDataItem = NULL;
	if(errorStr == NULL || outputStr == NULL) return outLen;

	pSUSICommDataItem = cJSON_CreateObject();
	if(pSUSICommDataItem)
	{
		cJSON_AddStringToObject(pSUSICommDataItem, SCREENSHOT_ERROR_REP, errorStr);
	}

	out = cJSON_PrintUnformatted(pSUSICommDataItem);
	outLen = strlen(out) + 1;
	*outputStr = (char *)(malloc(outLen));
	memset(*outputStr, 0, outLen);
	strcpy(*outputStr, out);
	cJSON_Delete(pSUSICommDataItem);	
	printf("%s\n",out);	
	free(out);
	return outLen;
}
Example #15
0
OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining)
{
    OCStackResult ret = OC_STACK_ERROR;
    cJSON *json;
    cJSON *body;

    char *jsonStr;
    uint16_t jsonLen;

    OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
    json = cJSON_CreateObject();

    cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());

    OCCapability* pointerCapa = action->head;
    while (pointerCapa)
    {
        cJSON_AddStringToObject(body, pointerCapa->capability, pointerCapa->status);
        pointerCapa = pointerCapa->next;
    }

    jsonStr = cJSON_PrintUnformatted(json);

    jsonLen = strlen(jsonStr);
    if (jsonLen < *remaining)
    {
        strcat((char*) bufferPtr, jsonStr);
        *remaining -= jsonLen;
        bufferPtr += jsonLen;
        ret = OC_STACK_OK;
    }

    cJSON_Delete(json);
    free(jsonStr);

    return ret;
}
Example #16
0
    void
    OutofcoreOctreeBaseMetadata::serializeMetadataToDisk ()
    {
      if (LOD_num_points_.empty ())
        return;

      // Create JSON object
      boost::shared_ptr<cJSON> idx (cJSON_CreateObject (), cJSON_Delete);
  
      cJSON* name = cJSON_CreateString (tree_name_.c_str ());
      cJSON* version = cJSON_CreateNumber ( __PCL_OUTOFCORE_VERSION__ );
      cJSON* pointtype = cJSON_CreateString (point_type_.c_str ());
      cJSON* lod = cJSON_CreateNumber (static_cast<double> (levels_of_depth_));

      // cJSON does not allow 64 bit ints.  Have to put the points in a double to
      // use this api, will allow counts up to 2^52 points to be stored correctly
      //or split into LSB MSB?
      std::vector<double> lodPoints_db;
      lodPoints_db.insert (lodPoints_db.begin (), LOD_num_points_.begin (), LOD_num_points_.end ());

      cJSON* numpts = cJSON_CreateDoubleArray ( &(lodPoints_db.front ()), static_cast<int>(lodPoints_db.size ()));

      cJSON_AddItemToObject (idx.get (), "name", name);
      cJSON_AddItemToObject (idx.get (), "version", version);
      cJSON_AddItemToObject (idx.get (), "pointtype", pointtype);
      cJSON_AddItemToObject (idx.get (), "lod", lod);
      cJSON_AddItemToObject (idx.get (), "numpts", numpts);
      cJSON_AddStringToObject(idx.get(), "coord_system", coordinate_system_.c_str());

      char* idx_txt = cJSON_Print (idx.get ());

      std::ofstream f (metadata_filename_.string ().c_str (), std::ios::out | std::ios::trunc);
      f << idx_txt;
      f.close ();

      free (idx_txt);
    }
Example #17
0
bool boosted_trees::write_boosted_trees_base_info_to_file(const ml_string &path) const {
  
  cJSON *json_boosted = cJSON_CreateObject();
  if(!json_boosted) {
    log_error("couldn't create json object from boosted trees\n");
    return(false);
  }

  cJSON_AddStringToObject(json_boosted, "object", "boosted_trees");
  cJSON_AddNumberToObject(json_boosted, "type", (double)type_);
  cJSON_AddNumberToObject(json_boosted, "index_of_feature_to_predict", index_of_feature_to_predict_);
  cJSON_AddNumberToObject(json_boosted, "number_of_trees", number_of_trees_);
  cJSON_AddNumberToObject(json_boosted, "learning_rate", learning_rate_);
  cJSON_AddNumberToObject(json_boosted, "seed", seed_);
  cJSON_AddNumberToObject(json_boosted, "max_tree_depth", max_tree_depth_);
  cJSON_AddNumberToObject(json_boosted, "subsample", subsample_);
  cJSON_AddNumberToObject(json_boosted, "min_leaf_instances", min_leaf_instances_);
  cJSON_AddNumberToObject(json_boosted, "features_to_consider_per_node", features_to_consider_per_node_);

  bool status = write_model_json_to_file(path, json_boosted);
  cJSON_Delete(json_boosted);
  
  return(status);
}
Example #18
0
void passthroughCanMessage(Listener* listener, int id, uint64_t data) {
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, ID_FIELD_NAME, id);

    char encodedData[67];
    union {
        uint64_t whole;
        uint8_t bytes[8];
    } combined;
    combined.whole = data;

    sprintf(encodedData, "0x%02x%02x%02x%02x%02x%02x%02x%02x",
            combined.bytes[0],
            combined.bytes[1],
            combined.bytes[2],
            combined.bytes[3],
            combined.bytes[4],
            combined.bytes[5],
            combined.bytes[6],
            combined.bytes[7]);
    cJSON_AddStringToObject(root, DATA_FIELD_NAME, encodedData);

    sendJSON(root, listener);
}
Example #19
0
	void Client::getLiveUserInfo(std::string user)
	{
        if((_state != ConnectionState::connected) || (_socket == NULL)){
            if(_zonelistener != NULL)
			{
				liveuser _user;
				_user.result = ResultCode::connection_error;
				_zonelistener->onGetLiveUserInfoDone(_user);
			}
            return;
        }
		int byteLen;
		byte *req;

		std::string payload;
		cJSON *payloadJSON;
		payloadJSON = cJSON_CreateObject();
		cJSON_AddStringToObject(payloadJSON, "name",user.c_str());
		char *cRet = cJSON_PrintUnformatted(payloadJSON);
		payload = cRet;

		req = buildWarpRequest(RequestType::get_user_info, payload, byteLen);

		char *data = new char[byteLen];
		for(int i=0; i< byteLen; ++i)
		{
			data[i] = req[i];
		}

		_socket->sockSend(data, byteLen);

		delete[] data;
		delete[] req;
		cJSON_Delete(payloadJSON);
		free(cRet);
	}
Example #20
0
/***************************************************************************
  Function:       package_json_callback 
  Description:    ����5017�˿ڵ�callback���ݸ�ʽ
  Input:          
                  
  Output:      �����װ�õ�callback���ݵĵ�ַ   
  Return:       
  Others:         
****************************************************************************/
char *package_json_callback(char *ipc_status_list)
{
    cJSON *root,*fmt;
    char *out;	
    //Our "Video" datatype: 
    root=cJSON_CreateObject();
	cJSON_AddNumberToObject(root,"msgtype",0);
	cJSON_AddNumberToObject(root,"mainid",2);
	cJSON_AddNumberToObject(root,"subid",4);
	//cJSON_AddNumberToObject(root,"status",type );
	//if(type == 0)
	//{
		cJSON_AddStringToObject(root,"ipc_status_list", ipc_status_list);	
	//}
    //out=cJSON_Print(root);
    out=cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    //cJSON_Delete(fmt);
    //printf("%s\n",out);	
    //free(out);
    // Print to text, Delete the cJSON, print it, release the string. 

    return out; 
}
Example #21
0
static cJSON * cJSON_CreateEventLogInfo(PEVENTLOGINFO pEventLogInfo)
{
	cJSON *pEventLogInfoItem = NULL;
	if(!pEventLogInfo) return pEventLogInfoItem;
	pEventLogInfoItem = cJSON_CreateObject();

	if(pEventLogInfo->eventGroup)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_GROUP, pEventLogInfo->eventGroup);
	}
	if(pEventLogInfo->eventType)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_TYPE, pEventLogInfo->eventType);
	}
	if(pEventLogInfo->eventTimestamp)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_TIMESTAMP, pEventLogInfo->eventTimestamp);
	}
	cJSON_AddNumberToObject(pEventLogInfoItem, SWM_EVENT_LOG_ID, pEventLogInfo->eventID);
	if(pEventLogInfo->eventSource)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_SOURCE, pEventLogInfo->eventSource);
	}
	if(pEventLogInfo->eventUser)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_USER, pEventLogInfo->eventUser);
	}
	if(pEventLogInfo->eventComputer)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_COMPUTER, pEventLogInfo->eventComputer);
	}
	if(pEventLogInfo->eventDescription)
	{
		cJSON_AddStringToObject(pEventLogInfoItem, SWM_EVENT_LOG_DESCRIPTION, pEventLogInfo->eventDescription);
	}
	return pEventLogInfoItem;
}
Example #22
0
char *status_json_string(int no_cache, int periodical)
{
	char *out = NULL;
	int pe;
	
	/* if we have a very recent status JSON available, return it instead. */
	if (!no_cache) {
		if ((pe = pthread_mutex_lock(&status_json_mt))) {
			hlog(LOG_ERR, "status_json_string(): could not lock status_json_mt: %s", strerror(pe));
			return NULL;
		}
		if (status_json_cached && (status_json_cache_t == tick || status_json_cache_t == tick - 1)) {
			out = hstrdup(status_json_cached);
			if ((pe = pthread_mutex_unlock(&status_json_mt))) {
				hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
				hfree(out);
				return NULL;
			}
			return out;
		}
		if ((pe = pthread_mutex_unlock(&status_json_mt))) {
			hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
			return NULL;
		}
	}
	
	/* Ok, go and build the JSON tree */
	cJSON *root = cJSON_CreateObject();
	if (http_status_options)
		cJSON_AddStringToObject(root, "status_options", http_status_options);
	status_check_motd(root);
	
	cJSON *server = cJSON_CreateObject();
	cJSON_AddStringToObject(server, "server_id", serverid);
	cJSON_AddStringToObject(server, "admin", myadmin);
	cJSON_AddStringToObject(server, "email", myemail);
	cJSON_AddStringToObject(server, "software", PROGNAME);
	cJSON_AddStringToObject(server, "software_version", version_build);
	cJSON_AddStringToObject(server, "software_build_time", verstr_build_time);
	cJSON_AddStringToObject(server, "software_build_user", verstr_build_user);
	cJSON_AddStringToObject(server, "software_build_features", verstr_features);
	cJSON_AddNumberToObject(server, "uptime", tick - startup_tick);
	cJSON_AddNumberToObject(server, "tick_now", tick);
	cJSON_AddNumberToObject(server, "time_now", now);
	cJSON_AddNumberToObject(server, "time_started", startup_time);
	status_uname(server);
	cJSON_AddItemToObject(root, "server", server);
	
	cJSON *memory = cJSON_CreateObject();
#ifndef _FOR_VALGRIND_
	struct cellstatus_t cellst;
	historydb_cell_stats(&cellst), 
	cJSON_AddNumberToObject(memory, "historydb_cells_used", historydb_cellgauge);
	cJSON_AddNumberToObject(memory, "historydb_cells_free", cellst.freecount);
	cJSON_AddNumberToObject(memory, "historydb_used_bytes", historydb_cellgauge*cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "historydb_allocated_bytes", (long)cellst.blocks * (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "historydb_block_size", (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "historydb_blocks", (long)cellst.blocks);
	cJSON_AddNumberToObject(memory, "historydb_blocks_max", (long)cellst.blocks_max);
	cJSON_AddNumberToObject(memory, "historydb_cell_size", cellst.cellsize);
	cJSON_AddNumberToObject(memory, "historydb_cell_size_aligned", cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "historydb_cell_align", cellst.alignment);
	
	dupecheck_cell_stats(&cellst), 
	cJSON_AddNumberToObject(memory, "dupecheck_cells_used", dupecheck_cellgauge);
	cJSON_AddNumberToObject(memory, "dupecheck_cells_free", cellst.freecount);
	cJSON_AddNumberToObject(memory, "dupecheck_used_bytes", dupecheck_cellgauge*cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "dupecheck_allocated_bytes", (long)cellst.blocks * (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "dupecheck_block_size", (long)cellst.block_size);
	cJSON_AddNumberToObject(memory, "dupecheck_blocks", (long)cellst.blocks);
	cJSON_AddNumberToObject(memory, "dupecheck_blocks_max", (long)cellst.blocks_max);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_size", cellst.cellsize);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_size_aligned", cellst.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "dupecheck_cell_align", cellst.alignment);
	
	struct cellstatus_t cellst_filter, cellst_filter_wx, cellst_filter_entrycall;
	filter_cell_stats(&cellst_filter, &cellst_filter_entrycall, &cellst_filter_wx),
	cJSON_AddNumberToObject(memory, "filter_cells_used", filter_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_cells_free", cellst_filter.freecount);
	cJSON_AddNumberToObject(memory, "filter_used_bytes", filter_cellgauge*cellst_filter.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_allocated_bytes", (long)cellst_filter.blocks * (long)cellst_filter.block_size);
	cJSON_AddNumberToObject(memory, "filter_block_size", (long)cellst_filter.block_size);
	cJSON_AddNumberToObject(memory, "filter_blocks", (long)cellst_filter.blocks);
	cJSON_AddNumberToObject(memory, "filter_blocks_max", (long)cellst_filter.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_cell_size", cellst_filter.cellsize);
	cJSON_AddNumberToObject(memory, "filter_cell_size_aligned", cellst_filter.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_cell_align", cellst_filter.alignment);
	
	cJSON_AddNumberToObject(memory, "filter_wx_cells_used", filter_wx_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_wx_cells_free", cellst_filter_wx.freecount);
	cJSON_AddNumberToObject(memory, "filter_wx_used_bytes", filter_wx_cellgauge*cellst_filter_wx.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_wx_allocated_bytes", (long)cellst_filter_wx.blocks * (long)cellst_filter_wx.block_size);
	cJSON_AddNumberToObject(memory, "filter_wx_block_size", (long)cellst_filter_wx.block_size);
	cJSON_AddNumberToObject(memory, "filter_wx_blocks", (long)cellst_filter_wx.blocks);
	cJSON_AddNumberToObject(memory, "filter_wx_blocks_max", (long)cellst_filter_wx.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_size", cellst_filter_wx.cellsize);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_size_aligned", cellst_filter_wx.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_wx_cell_align", cellst_filter_wx.alignment);
	
	cJSON_AddNumberToObject(memory, "filter_entrycall_cells_used", filter_entrycall_cellgauge);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cells_free", cellst_filter_entrycall.freecount);
	cJSON_AddNumberToObject(memory, "filter_entrycall_used_bytes", filter_entrycall_cellgauge*cellst_filter_entrycall.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_entrycall_allocated_bytes", (long)cellst_filter_entrycall.blocks * (long)cellst_filter_entrycall.block_size);
	cJSON_AddNumberToObject(memory, "filter_entrycall_block_size", (long)cellst_filter_entrycall.block_size);
	cJSON_AddNumberToObject(memory, "filter_entrycall_blocks", (long)cellst_filter_entrycall.blocks);
	cJSON_AddNumberToObject(memory, "filter_entrycall_blocks_max", (long)cellst_filter_entrycall.blocks_max);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_size", cellst_filter_entrycall.cellsize);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_size_aligned", cellst_filter_entrycall.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "filter_entrycall_cell_align", cellst_filter_entrycall.alignment);
	
	struct cellstatus_t cellst_pbuf_small, cellst_pbuf_medium, cellst_pbuf_large;
	incoming_cell_stats(&cellst_pbuf_small, &cellst_pbuf_medium, &cellst_pbuf_large);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_used", cellst_pbuf_small.cellcount - cellst_pbuf_small.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_free", cellst_pbuf_small.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_small_cells_alloc", cellst_pbuf_small.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_small_used_bytes", (cellst_pbuf_small.cellcount - cellst_pbuf_small.freecount)*cellst_pbuf_small.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_small_allocated_bytes", (long)cellst_pbuf_small.blocks * (long)cellst_pbuf_small.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_small_block_size", (long)cellst_pbuf_small.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_small_blocks", (long)cellst_pbuf_small.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_small_blocks_max", (long)cellst_pbuf_small.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_size", cellst_pbuf_small.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_size_aligned", cellst_pbuf_small.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_small_cell_align", cellst_pbuf_small.alignment);
	
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_used", cellst_pbuf_medium.cellcount - cellst_pbuf_medium.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_free", cellst_pbuf_medium.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cells_alloc", cellst_pbuf_medium.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_medium_used_bytes", (cellst_pbuf_medium.cellcount - cellst_pbuf_medium.freecount)*cellst_pbuf_medium.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_medium_allocated_bytes", (long)cellst_pbuf_medium.blocks * (long)cellst_pbuf_medium.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_medium_block_size", (long)cellst_pbuf_medium.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_medium_blocks", (long)cellst_pbuf_medium.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_medium_blocks_max", (long)cellst_pbuf_medium.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_size", cellst_pbuf_medium.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_size_aligned", cellst_pbuf_medium.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_medium_cell_align", cellst_pbuf_medium.alignment);
	
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_used", cellst_pbuf_large.cellcount - cellst_pbuf_large.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_free", cellst_pbuf_large.freecount);
	cJSON_AddNumberToObject(memory, "pbuf_large_cells_alloc", cellst_pbuf_large.cellcount);
	cJSON_AddNumberToObject(memory, "pbuf_large_used_bytes", (cellst_pbuf_large.cellcount - cellst_pbuf_large.freecount)*cellst_pbuf_large.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_large_allocated_bytes", (long)cellst_pbuf_large.blocks * (long)cellst_pbuf_large.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_large_block_size", (long)cellst_pbuf_large.block_size);
	cJSON_AddNumberToObject(memory, "pbuf_large_blocks", (long)cellst_pbuf_large.blocks);
	cJSON_AddNumberToObject(memory, "pbuf_large_blocks_max", (long)cellst_pbuf_large.blocks_max);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_size", cellst_pbuf_large.cellsize);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_size_aligned", cellst_pbuf_large.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "pbuf_large_cell_align", cellst_pbuf_large.alignment);
	
	struct cellstatus_t cellst_client_heard;
	client_heard_cell_stats(&cellst_client_heard);
	cJSON_AddNumberToObject(memory, "client_heard_cells_used", cellst_client_heard.cellcount - cellst_client_heard.freecount);
	cJSON_AddNumberToObject(memory, "client_heard_cells_free", cellst_client_heard.freecount);
	cJSON_AddNumberToObject(memory, "client_heard_cells_alloc", cellst_client_heard.cellcount);
	cJSON_AddNumberToObject(memory, "client_heard_used_bytes", (cellst_client_heard.cellcount - cellst_client_heard.freecount)*cellst_client_heard.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "client_heard_allocated_bytes", (long)cellst_client_heard.blocks * (long)cellst_client_heard.block_size);
	cJSON_AddNumberToObject(memory, "client_heard_block_size", (long)cellst_client_heard.block_size);
	cJSON_AddNumberToObject(memory, "client_heard_blocks", (long)cellst_client_heard.blocks);
	cJSON_AddNumberToObject(memory, "client_heard_blocks_max", (long)cellst_client_heard.blocks_max);
	cJSON_AddNumberToObject(memory, "client_heard_cell_size", cellst_client_heard.cellsize);
	cJSON_AddNumberToObject(memory, "client_heard_cell_size_aligned", cellst_client_heard.cellsize_aligned);
	cJSON_AddNumberToObject(memory, "client_heard_cell_align", cellst_client_heard.alignment);
#endif
	
	cJSON_AddItemToObject(root, "memory", memory);
	
	cJSON *historydb = cJSON_CreateObject();
	cJSON_AddNumberToObject(historydb, "inserts", historydb_inserts);
	cJSON_AddNumberToObject(historydb, "lookups", historydb_lookups);
	cJSON_AddNumberToObject(historydb, "hashmatches", historydb_hashmatches);
	cJSON_AddNumberToObject(historydb, "keymatches", historydb_keymatches);
	cJSON_AddNumberToObject(historydb, "noposcount", historydb_noposcount);
	cJSON_AddNumberToObject(historydb, "cleaned", historydb_cleanup_cleaned);
	cJSON_AddItemToObject(root, "historydb", historydb);
	
	cJSON *dupecheck = cJSON_CreateObject();
	cJSON_AddNumberToObject(dupecheck, "dupes_dropped", dupecheck_dupecount);
	cJSON_AddNumberToObject(dupecheck, "uniques_out", dupecheck_outcount);
	cJSON_AddItemToObject(root, "dupecheck", dupecheck);
	
	cJSON *dupe_vars = cJSON_CreateObject();
	cJSON_AddNumberToObject(dupe_vars, "exact", dupecheck_dupetypes[0]);
	cJSON_AddNumberToObject(dupe_vars, "space_trim", dupecheck_dupetypes[DTYPE_SPACE_TRIM]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_strip", dupecheck_dupetypes[DTYPE_STRIP_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_clear", dupecheck_dupetypes[DTYPE_CLEAR_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "8bit_spaced", dupecheck_dupetypes[DTYPE_SPACED_8BIT]);
	cJSON_AddNumberToObject(dupe_vars, "low_strip", dupecheck_dupetypes[DTYPE_LOWDATA_STRIP]);
	cJSON_AddNumberToObject(dupe_vars, "low_spaced", dupecheck_dupetypes[DTYPE_LOWDATA_SPACED]);
	cJSON_AddNumberToObject(dupe_vars, "del_strip", dupecheck_dupetypes[DTYPE_DEL_STRIP]);
	cJSON_AddNumberToObject(dupe_vars, "del_spaced", dupecheck_dupetypes[DTYPE_DEL_SPACED]);
	cJSON_AddItemToObject(dupecheck, "variations", dupe_vars);
	
	cJSON *json_totals = cJSON_CreateObject();
	cJSON *json_listeners = cJSON_CreateArray();
	accept_listener_status(json_listeners, json_totals);
	cJSON_AddItemToObject(root, "totals", json_totals);
	cJSON_AddItemToObject(root, "listeners", json_listeners);
	
	cJSON *json_clients = cJSON_CreateArray();
	cJSON *json_uplinks = cJSON_CreateArray();
	cJSON *json_peers = cJSON_CreateArray();
	cJSON *json_workers = cJSON_CreateArray();
	worker_client_list(json_workers, json_clients, json_uplinks, json_peers, json_totals, memory);
	cJSON_AddItemToObject(root, "workers", json_workers);
	cJSON_AddItemToObject(root, "uplinks", json_uplinks);
	cJSON_AddItemToObject(root, "peers", json_peers);
	cJSON_AddItemToObject(root, "clients", json_clients);
	
	/* if this is a periodical per-minute dump, collect historical data */
	if (periodical) {
		cJSON *ct, *cv;
		struct cdata_list_t *cl;
		for (cl = cdata_list; (cl); cl = cl->next) {
			ct = cJSON_GetObjectItem(root, cl->tree);
			if (!ct)
				continue;
				
			cv = cJSON_GetObjectItem(ct, cl->name);
			
			/* cJSON's cv->valueint is just an integer, which will overflow
			 * too quickly. So, let's take the more expensive valuedouble.
			 */
			if (cl->gauge)
				cdata_gauge_sample(cl->cd, (cv) ? cv->valuedouble : -1);
			else
				cdata_counter_sample(cl->cd, (cv) ? cv->valuedouble : -1);
		}
	}
	
	cJSON_AddNumberToObject(json_totals, "tcp_bytes_rx_rate", cdata_get_last_value("totals.tcp_bytes_rx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "tcp_bytes_tx_rate", cdata_get_last_value("totals.tcp_bytes_tx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "udp_bytes_rx_rate", cdata_get_last_value("totals.udp_bytes_rx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "udp_bytes_tx_rate", cdata_get_last_value("totals.udp_bytes_tx") / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "bytes_rx_rate", (cdata_get_last_value("totals.tcp_bytes_rx") + cdata_get_last_value("totals.udp_bytes_rx")) / CDATA_INTERVAL);
	cJSON_AddNumberToObject(json_totals, "bytes_tx_rate", (cdata_get_last_value("totals.tcp_bytes_tx") + cdata_get_last_value("totals.udp_bytes_tx")) / CDATA_INTERVAL);
	
	cJSON *json_rx_errs = cJSON_CreateStringArray(inerr_labels, INERR_BUCKETS);
	cJSON_AddItemToObject(root, "rx_errs", json_rx_errs);
	
	cJSON_AddItemToObject(root, "alarms", status_error_json());
	
	/* the tree is built, print it out to a malloc'ed string */
	out = cJSON_Print(root);
	cJSON_Delete(root);
	
	/* cache it */
	if ((pe = pthread_mutex_lock(&status_json_mt))) {
		hlog(LOG_ERR, "status_json_string(): could not lock status_json_mt: %s", strerror(pe));
                                return NULL;
	}
	if (status_json_cached)
		hfree(status_json_cached);
		
	status_json_cached = hstrdup(out);
	status_json_cache_t = tick;
	
	if ((pe = pthread_mutex_unlock(&status_json_mt))) {
		hlog(LOG_ERR, "status_json_string(): could not unlock status_json_mt: %s", strerror(pe));
		return NULL;
	}
	
	return out;
}
Example #23
0
int main(int args,char *argv[]){
    const int smallOutputNumber=-1;
    int i,j;
    cJSON *root;
    int num_chromosome;
    int req_type=1;
    char buffer[30];
    char req_gene[20]={0};
    cJSON *msg;
    char req_kind[50]="E.coli K12-DH10B";

    pi=0;
    ini=0;
    req_restrict.rfc10=0;
    req_restrict.rfc12=0;
    req_restrict.rfc12a=0;
    req_restrict.rfc21=0;
    req_restrict.rfc23=0;
    req_restrict.rfc25=0;

    char *req_str=argv_default;
    if(args==2) req_str=argv[1];

    cJSON *request=cJSON_Parse(req_str);
    if(check_req(request)){
        onError("illegal args");
        return 0;
    }

    i=1;
    j=1;

    cJSON *cJSON_temp;
    cJSON_temp=cJSON_GetObjectItem(request,"type");
    if(cJSON_temp) req_type=cJSON_temp->valueint;
    char req_pam[PAM_LEN+1];
    int req_pam_len;
    strcpy(req_pam,cJSON_GetObjectItem(request,"pam")->valuestring);
    req_pam_len=(int)strlen(req_pam);
    char req_specie[30];
    struct return_struct rs;
    int ptts_num;
    int len[NUM_CHROMOSOME];
    strcpy(req_specie,cJSON_GetObjectItem(request,"specie")->valuestring);
    if(strcmp(req_specie,"SARS")==0){
        rs=info_readin(PTT_SARS,ptts,str,wai,NULL);
    }else if(strcmp(req_specie,"E.coli")==0){
        cJSON_temp=cJSON_GetObjectItem(request,"kind");
        if(cJSON_temp) strcpy(req_kind,cJSON_temp->valuestring);
        rs=info_readin(PTT_ECOLI,ptts,str,wai,req_kind);
    }else if(strcmp(req_specie,"Saccharomycetes")==0){
        rs=info_readin(PTT_SACCHAROMYCETES,ptts,str,wai,NULL);
    }else{
        onError("no specie");
        return 0;
    }
    ptts_num=rs.ptts_num;
    num_chromosome=rs.num_chromosome;
    for(i=1;i<=num_chromosome;i++) len[i]=rs.len[i];

    double req_r1=0.65;
    cJSON_temp=cJSON_GetObjectItem(request,"gene");
    if(cJSON_temp){
        req_r1=cJSON_GetObjectItem(request,"r1")->valuedouble;
    }

    cJSON_temp=cJSON_GetObjectItem(request,"gene");
    int req_id,req_gene_start,req_gene_end;
    if(cJSON_temp){
        strcpy(req_gene,cJSON_temp->valuestring);
        for(int i=0;i<ptts_num;i++){
            if(strcmp(req_gene,ptts[i].gene)==0){
                req_id=ptts[i].chromosome;
                req_gene_start=ptts[i].s;
                req_gene_end=ptts[i].t;
                break;
            }
        }
    }else{
        char req_location[20];
        strcpy(req_location,cJSON_GetObjectItem(request,"location")->valuestring);
        sscanf(req_location,"%d:%d..%d",&req_id,&req_gene_start,&req_gene_end);
    }

    char req_rfc[10];
    strcpy(req_rfc,cJSON_GetObjectItem(request,"rfc")->valuestring);
    req_restrict.rfc10=req_rfc[0]-48;
    req_restrict.rfc12=req_rfc[1]-48;
    req_restrict.rfc12a=req_rfc[2]-48;
    req_restrict.rfc21=req_rfc[3]-48;
    req_restrict.rfc23=req_rfc[4]-48;
    req_restrict.rfc25=req_rfc[5]-48;

    generate_filename(buffer,req_specie,req_kind,req_pam,req_type);
    dc_init(buffer);
    /*
    This part above is for read in JSON-style request.
    The result stored in req_specie, req_pam, req_gene_start, req_gene_end, rfc and so on.
    At the same time, it reads in ptt file for specie,
    and also open files.
    */

    for(int id=1;id<=num_chromosome;id++){
        for(i=LEN;i<len[id]-req_pam_len;i++){       // All possible gRNAs, +direction
            if(check_pam(str[id]+i,req_pam)){
                psb_site[pi].index=i;
                psb_site[pi].strand='+';
                psb_site[pi].chromosome=id;
                for(j=0;j<req_pam_len;j++) psb_site[pi].pam[j]=(str[id]+i)[j];
                psb_site[pi].pam[j]=0;
                for(j=0;j<LEN;j++) psb_site[pi].nt[j]=(str[id]+i-LEN)[j];
                psb_site[pi].nt[j]=0;
                pi++;
            }
        }
        char req_pam_rev[PAM_LEN];
        int last=-1;
        dna_rev(req_pam_rev,req_pam,req_pam_len);
        for(i=0;i<len[id]-LEN-req_pam_len;i++){     // All possible gRNAs, -direction
            if(check_pam(str[id]+i,req_pam_rev)){
                psb_site[pi].index=i+req_pam_len-1;
                psb_site[pi].strand='-';
                psb_site[pi].chromosome=id;
                if(req_pam_len!=last){
                    last=req_pam_len;
                }
                for(j=0;j<req_pam_len;j++) psb_site[pi].pam[j]=dna_rev_char((str[id]+i)[req_pam_len-1-j]);
                psb_site[pi].pam[j]=0;
                for(j=0;j<LEN;j++) psb_site[pi].nt[j]=dna_rev_char((str[id]+i+req_pam_len)[LEN-j-1]);
                psb_site[pi].nt[j]=0;
                pi++;
            }
        }
    }

    for(i=0;i<pi;i++){
        fflush(stdout);
        if(psb_site[i].chromosome!=req_id) continue;
        if(psb_site[i].strand=='+'){
            if(psb_site[i].index<req_gene_start || psb_site[i].index+req_pam_len-1>req_gene_end) continue;
            for(j=psb_site[i].index-LEN;j<psb_site[i].index+req_pam_len-1;j++){
                if(wai[req_id][j]!=1) break;
            }
            if(j<psb_site[i].index+req_pam_len-1) j=0;
            else j=1;
        }else{
            if(psb_site[i].index-req_pam_len+1<req_gene_start || psb_site[i].index>req_gene_end) continue;
            for(j=psb_site[i].index-req_pam_len+1;j<psb_site[i].index+LEN;j++){
                if(wai[req_id][j]!=1) break;
            }
            if(j<psb_site[i].index+LEN) j=0;
            else j=1;
        }
        if(j){
            score(i,&ini,req_type,req_r1);
        }
    }

    dc_save();

    sort(in_site,in_site+ini,cmp_in_site);  // Sort & Output

    root=cJSON_CreateObject();
    cJSON_AddNumberToObject(root,"status",0);

    msg=cJSON_CreateObject();
    cJSON_AddStringToObject(msg,"specie",req_specie);
    cJSON_AddStringToObject(msg,"kind",req_kind);
    cJSON_AddStringToObject(msg,"gene",req_gene);
    sprintf(buffer,"%d:%d..%d",req_id,req_gene_start,req_gene_end);
    cJSON_AddStringToObject(msg,"location",buffer);
    cJSON_AddItemToObject(root,"message",msg);

    vector<cJSON*> list;
    list.clear();
    for(i=0;i<ini && i!=smallOutputNumber;i++){
        cJSON *ans=cJSON_CreateObject();
        sprintf(buffer,"#%d",i+1);
        cJSON_AddStringToObject(ans,"key",buffer);
        sprintf(buffer,"%s%s",in_site[i].nt,in_site[i].pam);
        cJSON_AddStringToObject(ans,"grna",buffer);
        sprintf(buffer,"%d:%d",in_site[i].chromosome,in_site[i].index);
        cJSON_AddStringToObject(ans,"position",buffer);
        char xs[2];
        xs[0]=in_site[i].strand;
        xs[1]=0;
        cJSON_AddStringToObject(ans,"strand",xs);
        cJSON_AddNumberToObject(ans,"total_score",(int)in_site[i].score);
        cJSON_AddNumberToObject(ans,"Sspe",(int)(req_r1*in_site[i].Sspe_nor));
        cJSON_AddNumberToObject(ans,"Seff",(int)((1.0-req_r1)*in_site[i].Seff_nor));
        cJSON_AddNumberToObject(ans,"count",in_site[i].count);
        cJSON_AddItemToObject(ans,"offtarget",in_site[i].otj);

        list.push_back(ans);
    }

    cJSON_AddItemToObject(root,"result",Create_array_of_anything(&(list[0]),list.size()));

    printf("%s\n",NomoreSpace(argv[0]=cJSON_Print(root)));

    free(argv[0]);
    return 0;
}
void App42Service::populateMetaHeaderParams(std::map<string, string>& metaHeaderParamsMap)
{
    if (pageMaxRecords!=-1)
    {
        std::stringstream ss;
        ss << pageMaxRecords;
        metaHeaderParamsMap[PAGE_MAX_RECORDS] = ss.str();
    }
    
    if (pageOffset!=-1)
    {
        std::stringstream ss;
        ss << pageOffset;
        metaHeaderParamsMap[PAGE_OFFSET] = ss.str();
    }
    if (adminKey.length()>0)
    {
        metaHeaderParamsMap["adminKey"] = adminKey;
    }
    setApp42ACLHeader(metaHeaderParamsMap);
    
    if((geoTag.c_str()!=NULL) && geoTag.length())
    {
        metaHeaderParamsMap[GEO_TAG] = geoTag;
    }
    
    if ((event.c_str()!=NULL) && event.length())
    {
        metaHeaderParamsMap[EVENT] = event;
    }
    
    string loggedInUser = App42API::getLoggedInUser();
    if ((loggedInUser.c_str()!=NULL) && loggedInUser.length())
    {
        metaHeaderParamsMap["loggedInUser"] = loggedInUser;
    }
    
    string installationID = App42API::getInstallId();
    if ((installationID.c_str()!=NULL) && installationID.length())
    {
        metaHeaderParamsMap["deviceId"] = installationID;
    }
    
    if ((query.c_str()!=NULL) && query.length())
    {
        metaHeaderParamsMap["metaQuery"] = query;
    }
    
    if ((jsonObject.c_str()!=NULL) && jsonObject.length())
    {
        metaHeaderParamsMap["jsonObject"] = jsonObject;
    }
    
    if ((dbName.c_str()!=NULL) && dbName.length() && (collectionName.c_str()!=NULL) && collectionName.length())
    {
        cJSON *obj = cJSON_CreateObject();
        cJSON_AddStringToObject(obj, "dbName", dbName.c_str());
        cJSON_AddStringToObject(obj, "collectionName", collectionName.c_str());
        metaHeaderParamsMap["dbCredentials"] = cJSON_PrintUnformatted(obj);
    }
    
    std::map<string,string>::iterator it;
    
    for(it=otherMetaHearders.begin(); it!=otherMetaHearders.end(); ++it)
    {
        metaHeaderParamsMap[it->first] = it->second;
    }
    
    if (sessionId.length()>0)
    {
        metaHeaderParamsMap["sessionId"] = sessionId;
    }
    else
    {
        string _sessionId = App42API::getUserSessionId();
        if (_sessionId.length())
        {
            metaHeaderParamsMap["sessionId"] = _sessionId;
        }
    }
    
    if (fbAccessToken.length()>0)
    {
        metaHeaderParamsMap["fbAccessToken"] = fbAccessToken;
    }
    else
    {
        string accessToken = App42API::getFbAccesToken();
        if (accessToken.length())
        {
            metaHeaderParamsMap["fbAccessToken"] = accessToken;
        }
    }
    
    printf("metaHeaderParamsMap: ");
    //Printing Headers
    Util::printMap(metaHeaderParamsMap);
    
}
Example #25
0
std::string outputJsonEntityFile(const std::string &name, const aiMatrix4x4 &matrix, const std::string &mesh, const std::string &material, const std::string &occlusionName)
{
	float deg;
	aiVector3D s, p, a;
	aiQuaternion r;
	matrix.Decompose(s, r, p);
	convertToAxisAngle(r, a, deg);

	cJSON *root = cJSON_CreateObject();
	cJSON *entity = cJSON_CreateObject();
	cJSON_AddItemToObject(root, "entity", entity);
	cJSON_AddStringToObject(entity, "name", name.c_str());

	cJSON *transform = cJSON_CreateObject();
	cJSON_AddItemToObject(entity, "transform", transform);

	cJSON *position = cJSON_CreateArray();
	cJSON_AddNumberToArray(position, p.x);
	cJSON_AddNumberToArray(position, p.y);
	cJSON_AddNumberToArray(position, p.z);
	cJSON_AddItemToObject(transform, "position", position);

	cJSON *orientation = cJSON_CreateArray();
	cJSON *axis = cJSON_CreateArray();
	cJSON_AddNumberToArray(axis, a.x);
	cJSON_AddNumberToArray(axis, a.y);
	cJSON_AddNumberToArray(axis, a.z);

	cJSON_AddNumberToArray(orientation, deg);
	cJSON_AddItemToArray(orientation, axis);
	cJSON_AddItemToObject(transform, "orientation", orientation);

	cJSON *scale = cJSON_CreateArray();
	cJSON_AddNumberToArray(scale, s.x);
	cJSON_AddNumberToArray(scale, s.y);
	cJSON_AddNumberToArray(scale, s.z);
	cJSON_AddItemToObject(transform, "scale", scale);

	cJSON *components = cJSON_CreateObject();
	cJSON_AddItemToObject(entity, "components", components);

	cJSON *renderable = cJSON_CreateObject();
	cJSON_AddItemToObject(components, "renderable", renderable);
	cJSON_AddStringToObject(renderable, "mesh", mesh.c_str());
	cJSON_AddStringToObject(renderable, "material", (material + ".material").c_str());

	cJSON *physics = cJSON_CreateObject();
	cJSON_AddItemToObject(components, "physics", physics);
	cJSON_AddStringToObject(physics, "type", "static");

	if(!occlusionName.empty())
	{
		cJSON *occlusion = cJSON_CreateObject();
		cJSON_AddItemToObject(components, "occlusion", occlusion);
		cJSON_AddStringToObject(occlusion, "source", occlusionName.c_str());
	}

	std::string filename = outdir + "/Entities/" + name + ".entity";
	writeJsonToFile(root, filename);
	return filename;
}
Example #26
0
static cJSON* build_event(const char *name, const char* json_string){
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "content", json_string);
    cJSON_AddStringToObject(root, "name", name);
    cJSON_AddStringToObject(root, "type", "custom");
    cJSON_AddStringToObject(root, "app_bundle_id", "embed_system");
    cJSON_AddStringToObject(root, "sdk_version", SDK_VERSION);

    if (info.app_name[0] != '\0') {
        cJSON_AddStringToObject(root, "app_name", info.app_name);
    }

    if (info.app_version[0] != '\0') {
        cJSON_AddStringToObject(root, "app_version", info.app_version);
    }

    if (info.device_model[0] != '\0') {
        cJSON_AddStringToObject(root, "device_model", info.device_model);
    }

    if (info.manufacturer[0] != '\0') {
        cJSON_AddStringToObject(root, "manufacturer", info.manufacturer);
    }

    if (info.device_id[0] != '\0') {
        cJSON_AddStringToObject(root, "device_id", info.device_id);
    }

    if (info.os_platform[0] != '\0') {
        cJSON_AddStringToObject(root, "os_platform", info.os_platform);
    }

    if (info.os_version[0] != '\0') {
        cJSON_AddStringToObject(root, "os_version", info.os_version);
    }

    if (info.sdk_id[0] != '\0') {
        cJSON_AddStringToObject(root, "sdk_id", info.sdk_id);
    }

    if (info.tag[0] != '\0') {
        cJSON_AddStringToObject(root, "tag", info.tag);
    }

    return root;
}
Example #27
0
/* Create a bunch of objects as demonstration. */
void create_objects()
{
    cJSON *root, *fmt, *img, *thm, *fld; char *out; int i;	/* declare a few. */
                                                            /* Our "days of the week" array: */
    const char *strings[7] = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
    /* Our matrix: */
    int numbers[3][3] = { { 0,-1,0 },{ 1,0,0 },{ 0,0,1 } };
    /* Our "gallery" item: */
    int ids[4] = { 116,943,234,38793 };
    /* Our array of "records": */
    struct record fields[2] = {
        { "zip",37.7668,-1.223959e+2,"","SAN FRANCISCO","CA","94107","US" },
        { "zip",37.371991,-1.22026e+2,"","SUNNYVALE","CA","94085","US" } };

    /* Here we construct some JSON standards, from the JSON site. */

    /* Our "Video" datatype: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "name", cJSON_CreateString("Jack (\"Bee\") Nimble"));
    cJSON_AddItemToObject(root, "format", fmt = cJSON_CreateObject());
    cJSON_AddStringToObject(fmt, "type", "rect");
    cJSON_AddNumberToObject(fmt, "width", 1920);
    cJSON_AddNumberToObject(fmt, "height", 1080);
    cJSON_AddFalseToObject(fmt, "interlace");
    cJSON_AddNumberToObject(fmt, "frame rate", 24);

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);	/* Print to text, Delete the cJSON, print it, release the string. */

                                                                                        /* Our "days of the week" array: */
    root = cJSON_CreateStringArray(strings, 7);

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

    /* Our matrix: */
    root = cJSON_CreateArray();
    for (i = 0; i<3; i++) cJSON_AddItemToArray(root, cJSON_CreateIntArray(numbers[i], 3));

    /*	cJSON_ReplaceItemInArray(root,1,cJSON_CreateString("Replacement")); */

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);


    /* Our "gallery" item: */
    root = cJSON_CreateObject();
    cJSON_AddItemToObject(root, "Image", img = cJSON_CreateObject());
    cJSON_AddNumberToObject(img, "Width", 800);
    cJSON_AddNumberToObject(img, "Height", 600);
    cJSON_AddStringToObject(img, "Title", "View from 15th Floor");
    cJSON_AddItemToObject(img, "Thumbnail", thm = cJSON_CreateObject());
    cJSON_AddStringToObject(thm, "Url", "http:/*www.example.com/image/481989943");
    cJSON_AddNumberToObject(thm, "Height", 125);
    cJSON_AddStringToObject(thm, "Width", "100");
    cJSON_AddItemToObject(img, "IDs", cJSON_CreateIntArray(ids, 4));

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

    /* Our array of "records": */

    root = cJSON_CreateArray();
    for (i = 0; i<2; i++)
    {
        cJSON_AddItemToArray(root, fld = cJSON_CreateObject());
        cJSON_AddStringToObject(fld, "precision", fields[i].precision);
        cJSON_AddNumberToObject(fld, "Latitude", fields[i].lat);
        cJSON_AddNumberToObject(fld, "Longitude", fields[i].lon);
        cJSON_AddStringToObject(fld, "Address", fields[i].address);
        cJSON_AddStringToObject(fld, "City", fields[i].city);
        cJSON_AddStringToObject(fld, "State", fields[i].state);
        cJSON_AddStringToObject(fld, "Zip", fields[i].zip);
        cJSON_AddStringToObject(fld, "Country", fields[i].country);
    }

    /*	cJSON_ReplaceItemInObject(cJSON_GetArrayItem(root,1),"City",cJSON_CreateIntArray(ids,4)); */

    out = cJSON_Print(root);	cJSON_Delete(root);	printf("%s\n", out);	free(out);

}
Example #28
0
void thread_ssid_msgio(void)
{
	int ret = pthread_detach(pthread_self());
	Debug("pthread_self():%lu, ret[%d]", pthread_self(), ret);
	char mac[32] = {0};
	char ssid[14] = {"FotileAP_"};
	int retssid = 0;
	while (1) 
	{
		fd_set rset, wset;
		FD_ZERO(&rset);
		//FD_ZERO(&wset);
		int i, maxfd, rcvfd;
		maxfd = set_get_max(&ssid_fdset);
		for(i=0;i<set_get_elem_num(&ssid_fdset);i++)
		{
			FD_SET(set_at(&ssid_fdset, i),&rset);
		}
		//FD_SET(socket_fd,&wset);
		struct timeval tval;
		tval.tv_sec = 0;
		tval.tv_usec = 10000;
		if(select(maxfd+1, &rset, NULL, NULL,&tval) > 0)
		{
			int i;
			for(i=0;i<set_get_elem_num(&ssid_fdset);i++)
			{
				if(FD_ISSET(set_at(&ssid_fdset, i), &rset))
				{
					rcvfd = set_at(&ssid_fdset, i);
					break;
				}
			}
			
			char szRcv[MAX_MESSAGE_LEN] = {0};
			int len = 0;
			int lens =0;
			unsigned char mac_arr[6] = {0};		//not use

			if (retssid == 0){
				retssid = get_eth0_mac(mac, mac_arr, 32);
				ssid[9] = mac[12];
				ssid[10] = mac[13];
				ssid[11] = mac[15];
				ssid[12] = mac[16];
				Debug("first time get ssid!");
			}else{

			}
			int ret = recv(rcvfd, szRcv, MAX_MESSAGE_LEN, 0);
			//Info("ret[%d]%s", ret, szRcv);
			if (ret > 0) 
			{
				cJSON *root1 = cJSON_Parse(szRcv);
				cJSON *root2 = cJSON_CreateObject();
				if(strcmp(cJSON_GetObjectItem(root1,"type")->valuestring,"reqssid") == 0)
				{
					cJSON_AddItemToObject(root2, "type", cJSON_CreateString("reqssid"));
					cJSON_AddNumberToObject(root2, "seq", cJSON_GetObjectItem(root1,"seq")->valueint);
					if(retssid > 0)
					{
						cJSON_AddNumberToObject(root2, "respcode", 0);
						cJSON_AddStringToObject(root2, "respmsg", ssid);
					}
					else
					{
						cJSON_AddNumberToObject(root2, "respcode", -1);
						cJSON_AddStringToObject(root2,"respmsg",  "error:get ssid failed!");
					}
					char *out = cJSON_Print(root2);
					//Info("out[%s]", out);
					lens = strlen(out);
					send(rcvfd, out , lens ,0);
					//Info("%s",rendered);
					cJSON_Delete(root1);
					cJSON_Delete(root2);
					free(out);
				}else{
					Warn("param error!");
				}
			} 
			else
			{
				//Warn("[fd:%d]rcv error! close socket", rcvfd);
				set_erase(rcvfd, &ssid_fdset);
				close(rcvfd);
			}
		}
	}
}
Example #29
0
void web_factory_desribe(struct evhttp_request *req, void *arg) {
	std::map<std::string, moProperty*>::iterator it;
	cJSON *root, *mod, *properties, *io, *array;
	moDataStream *ds;
	moModule *module;
	struct evkeyvalq headers;
	const char *uri;

	uri = evhttp_request_uri(req);
	evhttp_parse_query(uri, &headers);

	if ( evhttp_find_header(&headers, "name") == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "missing name");
	}

	module = moFactory::getInstance()->create(evhttp_find_header(&headers, "name"));
	if ( module == NULL ) {
		evhttp_clear_headers(&headers);
		return web_error(req, "invalid name");
	}

	root = cJSON_CreateObject();
	cJSON_AddNumberToObject(root, "success", 1);
	cJSON_AddStringToObject(root, "message", "ok");
	cJSON_AddItemToObject(root, "describe", mod=cJSON_CreateObject());

	cJSON_AddStringToObject(mod, "name", module->getName().c_str());
	cJSON_AddStringToObject(mod, "description", module->getDescription().c_str());
	cJSON_AddStringToObject(mod, "author", module->getAuthor().c_str());
	cJSON_AddNumberToObject(mod, "running", module->isStarted() ? 1 : 0);
	cJSON_AddItemToObject(mod, "properties", properties=cJSON_CreateObject());

	for ( it = module->getProperties().begin(); it != module->getProperties().end(); it++ ) {
		cJSON_AddStringToObject(properties, it->first.c_str(),
				it->second->asString().c_str());
	}

	if ( module->getInputCount() ) {
		cJSON_AddItemToObject(mod, "inputs", array=cJSON_CreateArray());
		for ( int i = 0; i < module->getInputCount(); i++ ) {
			ds = module->getInput(i);
			cJSON_AddItemToArray(array, io=cJSON_CreateObject());
			cJSON_AddNumberToObject(io, "index", i);
			cJSON_AddStringToObject(io, "name", module->getInputInfos(i)->getName().c_str());
			cJSON_AddStringToObject(io, "type", module->getInputInfos(i)->getType().c_str());
		}
	}

	if ( module->getOutputCount() ) {
		cJSON_AddItemToObject(mod, "outputs", array=cJSON_CreateArray());
		for ( int i = 0; i < module->getOutputCount(); i++ ) {
			ds = module->getOutput(i);
			cJSON_AddItemToArray(array, io=cJSON_CreateObject());
			cJSON_AddNumberToObject(io, "index", i);
			cJSON_AddStringToObject(io, "name", module->getOutputInfos(i)->getName().c_str());
			cJSON_AddStringToObject(io, "type", module->getOutputInfos(i)->getType().c_str());
		}
	}

	delete module;

	evhttp_clear_headers(&headers);
	web_json(req, root);
}
Example #30
0
void web_pipeline_status(struct evhttp_request *req, void *arg) {
	std::map<std::string, moProperty*>::iterator it;
	char buffer[64];
	cJSON *root, *data, *modules, *mod, *properties, *io, *observers, *array, *property;
	moDataStream *ds;

	root = cJSON_CreateObject();
	cJSON_AddNumberToObject(root, "success", 1);
	cJSON_AddStringToObject(root, "message", "ok");
	cJSON_AddItemToObject(root, "status", data=cJSON_CreateObject());
	cJSON_AddNumberToObject(data, "size", pipeline->size());
	cJSON_AddNumberToObject(data, "running", pipeline->isStarted() ? 1 : 0);
	cJSON_AddItemToObject(data, "modules", modules=cJSON_CreateObject());

	for ( unsigned int i = 0; i < pipeline->size(); i++ ) {
		moModule *module = pipeline->getModule(i);
		assert( module != NULL );

		cJSON_AddItemToObject(modules,
			module->property("id").asString().c_str(),
			mod=cJSON_CreateObject());

		cJSON_AddStringToObject(mod, "name", module->getName().c_str());
		cJSON_AddStringToObject(mod, "description", module->getDescription().c_str());
		cJSON_AddStringToObject(mod, "author", module->getAuthor().c_str());
		cJSON_AddNumberToObject(mod, "running", module->isStarted() ? 1 : 0);
		cJSON_AddItemToObject(mod, "properties", properties=cJSON_CreateObject());

		for ( it = module->getProperties().begin(); it != module->getProperties().end(); it++ ) {
			cJSON_AddStringToObject(properties, it->first.c_str(),
					it->second->asString().c_str());
		}

		cJSON_AddItemToObject(mod, "propertiesInfos", properties=cJSON_CreateObject());

		for ( it = module->getProperties().begin(); it != module->getProperties().end(); it++ ) {
			moProperty *p = it->second;
			cJSON_AddItemToObject(properties, it->first.c_str(), property=cJSON_CreateObject());
			cJSON_AddStringToObject(property, "type", moProperty::getPropertyTypeName(p->getType()).c_str());
			cJSON_AddNumberToObject(property, "readonly", p->isReadOnly() ? 1 : 0);
			if ( p->haveMax() )
				cJSON_AddNumberToObject(property, "max", p->getMax());
			if ( p->haveMin() )
				cJSON_AddNumberToObject(property, "min", p->getMin());
			if ( p->haveChoices() )
				cJSON_AddStringToObject(property, "choices", p->getChoices().c_str());
		}

		if ( module->getInputCount() ) {
			cJSON_AddItemToObject(mod, "inputs", array=cJSON_CreateArray());
			for ( int i = 0; i < module->getInputCount(); i++ ) {
				ds = module->getInput(i);
				cJSON_AddItemToArray(array, io=cJSON_CreateObject());
				cJSON_AddNumberToObject(io, "index", i);
				cJSON_AddStringToObject(io, "name", module->getInputInfos(i)->getName().c_str());
				cJSON_AddStringToObject(io, "type", module->getInputInfos(i)->getType().c_str());
				cJSON_AddNumberToObject(io, "used", ds == NULL ? 0 : 1);
			}
		}

		if ( module->getOutputCount() ) {
			cJSON_AddItemToObject(mod, "outputs", array=cJSON_CreateArray());
			for ( int i = 0; i < module->getOutputCount(); i++ ) {
				ds = module->getOutput(i);
				cJSON_AddItemToArray(array, io=cJSON_CreateObject());
				cJSON_AddNumberToObject(io, "index", i);
				cJSON_AddStringToObject(io, "name", module->getOutputInfos(i)->getName().c_str());
				cJSON_AddStringToObject(io, "type", module->getOutputInfos(i)->getType().c_str());
				cJSON_AddNumberToObject(io, "used", ds == NULL ? 0 : 1);
				cJSON_AddItemToObject(io, "observers", observers=cJSON_CreateObject());
				if ( ds != NULL ) {
					for ( unsigned int j = 0; j < ds->getObserverCount(); j++ ) {
						snprintf(buffer, sizeof(buffer), "%d", j);
						cJSON_AddStringToObject(observers, buffer,
							ds->getObserver(j)->property("id").asString().c_str());
					}
				}
			}
		}
	}

	web_json(req, root);
}