Ejemplo n.º 1
0
  void Mistress::opLoad()
  {
    beginOperation( Operation_Load );

    void* buffer;
    uint16_t length;

    DEBUG( "Loading graphs from flash" );
    mMemory.readSector( Memory::Sector_Graphs, buffer, length );
    if ( length > 0 )
    {
      JsonValue value;
      JsonAllocator allocator;
      JsonParseStatus status = jsonParse( (char*)buffer, &value, allocator );
      SPARK_ASSERT( status == JSON_PARSE_OK );
      mGraphs.fromJSON( value );
      free( buffer );
    }

    DEBUG( "Loading vibrators from flash" );
    mMemory.readSector( Memory::Sector_Vibrators, buffer, length );
    if ( length > 0 )
    {
      JsonValue value;
      JsonAllocator allocator;
      JsonParseStatus status = jsonParse( (char*)buffer, &value, allocator );
      SPARK_ASSERT( status == JSON_PARSE_OK );
      mVibrators.fromJSON( value );
      free( buffer );
    }

    endOperation( Operation_Load );
  }
Ejemplo n.º 2
0
void mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] )
{
  char action[1024]; if(!nr) mexErrMsgTxt("Inputs expected.");
  mxGetString(pr[0],action,1024); nr--; pr++;
  char *endptr; JsonValue val; JsonAllocator allocator;
  if( nl>1 ) mexErrMsgTxt("One output expected.");
  
  if(!strcmp(action,"convert")) {
    if( nr!=1 ) mexErrMsgTxt("One input expected.");
    if( mxGetClassID(pr[0])==mxCHAR_CLASS ) {
      // object = mexFunction( string )
      char *str = mxArrayToStringRobust(pr[0]);
      int status = jsonParse(str, &endptr, &val, allocator);
      if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
      pl[0] = json(val); mxFree(str);
    } else {
      // string = mexFunction( object )
      ostrm S; S << std::setprecision(12); json(S,pr[0]);
      pl[0]=mxCreateStringRobust(S.str().c_str());
    }
    
  } else if(!strcmp(action,"split")) {
    // strings = mexFunction( string, k )
    if( nr!=2 ) mexErrMsgTxt("Two input expected.");
    char *str = mxArrayToStringRobust(pr[0]);
    int status = jsonParse(str, &endptr, &val, allocator);
    if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
    if( val.getTag()!=JSON_ARRAY ) mexErrMsgTxt("Array expected");
    siz i=0, t=0, n=length(val), k=(siz) mxGetScalar(pr[1]);
    k=(k>n)?n:(k<1)?1:k; k=ceil(n/ceil(double(n)/k));
    pl[0]=mxCreateCellMatrix(1,k); ostrm S; S<<std::setprecision(12);
    for(auto o:val) {
      if(!t) { S.str(std::string()); S << "["; t=ceil(double(n)/k); }
      json(S,&o->value); t--; if(!o->next) t=0; S << (t ? "," : "]");
      if(!t) mxSetCell(pl[0],i++,mxCreateStringRobust(S.str().c_str()));
    }
    
  } else if(!strcmp(action,"merge")) {
    // string = mexFunction( strings )
    if( nr!=1 ) mexErrMsgTxt("One input expected.");
    if(!mxIsCell(pr[0])) mexErrMsgTxt("Cell array expected.");
    siz n = mxGetNumberOfElements(pr[0]);
    ostrm S; S << std::setprecision(12); S << "[";
    for( siz i=0; i<n; i++ ) {
      char *str = mxArrayToStringRobust(mxGetCell(pr[0],i));
      int status = jsonParse(str, &endptr, &val, allocator);
      if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
      if( val.getTag()!=JSON_ARRAY ) mexErrMsgTxt("Array expected");
      for(auto j:val) json(S,&j->value) << (j->next ? "," : "");
      mxFree(str); if(i<n-1) S<<",";
    }
    S << "]"; pl[0]=mxCreateStringRobust(S.str().c_str());
    
  } else mexErrMsgTxt("Invalid action.");
}
Ejemplo n.º 3
0
/**
	@brief Translate a JSON array into an array of osrfMessages.
	@param string The JSON string to be translated.
	@param msgs Pointer to an array of pointers to osrfMessage, to receive the results.
	@param count How many slots are available in the @a msgs array.
	@return The number of osrfMessages created.

	The JSON string is expected to be a JSON array, with each element encoding an osrfMessage.

	If there are too many messages in the JSON array to fit into the pointer array, we
	silently ignore the excess.
*/
int osrf_message_deserialize(const char* string, osrfMessage* msgs[], int count) {

	if(!string || !msgs || count <= 0) return 0;
	int numparsed = 0;

	// Parse the JSON
	jsonObject* json = jsonParse(string);

	if(!json) {
		osrfLogWarning( OSRF_LOG_MARK,
			"osrf_message_deserialize() unable to parse data: \n%s\n", string);
		return 0;
	}

	// Traverse the JSON_ARRAY, turning each element into an osrfMessage
	int x;
	for( x = 0; x < json->size && x < count; x++ ) {

		const jsonObject* message = jsonObjectGetIndex( json, x );

		if( message && message->type != JSON_NULL &&
			message->classname && !strcmp(message->classname, "osrfMessage" )) {
			msgs[numparsed++] = deserialize_one_message( message );
		}
	}

	jsonObjectFree( json );
	return numparsed;
}
Ejemplo n.º 4
0
void cartJsonExecute(struct cartJson *cj)
/* Get commands from cgi, print Content-type, execute commands, print results as JSON. */
{
cartJsonPushErrHandlers();
puts("Content-Type:text/javascript\n");

// Initialize response JSON object:
jsonWriteObjectStart(cj->jw, NULL);
// Always send back hgsid:
jsonWriteString(cj->jw, cartSessionVarName(), cartSessionId(cj->cart));

char *commandJson = cgiOptionalString(CARTJSON_COMMAND);
if (commandJson)
    {
    struct jsonElement *commandObj = jsonParse(commandJson);
    struct hash *commandHash = jsonObjectVal(commandObj, "commandObj");
    // change* commands need to go first!  Really we need an ordered map type here...
    // for now, just make a list and sort to put change commands at the front.
    struct slPair *commandList = NULL, *cmd;
    struct hashCookie cookie = hashFirst(commandHash);
    struct hashEl *hel;
    while ((hel = hashNext(&cookie)) != NULL)
        slAddHead(&commandList, slPairNew(hel->name, hel->val));
    slSort(&commandList, commandCmp);
    for (cmd = commandList;  cmd != NULL;  cmd = cmd->next)
	doOneCommand(cj, cmd->name, (struct jsonElement *)cmd->val);
    }

cartJsonPrintWarnings(cj->jw);
jsonWriteObjectEnd(cj->jw);
puts(cj->jw->dy->string);
cartJsonPopErrHandlers();
}
Ejemplo n.º 5
0
void fileSystemPerformance(STORAGE::Filesystem* fs, std::string filename, std::string should) {
	const int iterations = 100000;
	char* herp = new char[1024 * 1024];
	char* endptr = nullptr;

	JsonAllocator allocator;


	std::cout << "Parsing: " << should << std::endl;
	auto start = std::chrono::high_resolution_clock::now();
	for (int i = 0; i < iterations; ++i) {
		File file = fs->select(filename);
		STORAGE::IO::Reader reader = fs->getReader(file);
		std::string msg = reader.readString();

		memcpy(herp, msg.c_str(), msg.length() + 1);
		JsonValue value;

		int status = jsonParse(herp, &endptr, &value, allocator);
		if (status != JSON_OK) {
			std::cout << "Failure?" << std::endl;
		}
		allocator.deallocate();
	}
	delete herp;
	auto end = std::chrono::high_resolution_clock::now();

	std::cout << iterations / (0.0000000001 + std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()) << " iterations per millisecond" << std::endl;
}
Ejemplo n.º 6
0
/**
	@brief Populate the _result_content membersof an osrfMessage from a JSON string.
	@param msg Pointer to the osrfMessage to be populated.
	@param json_string A JSON string encoding a result.

	Used for a RESULT message to return the results of a remote procedure call.
*/
void osrf_message_set_result_content( osrfMessage* msg, const char* json_string ) {
	if( msg == NULL || json_string == NULL) return;
	if( msg->_result_content )
		jsonObjectFree( msg->_result_content );

	msg->_result_content = jsonParse(json_string);
}
Ejemplo n.º 7
0
void rsyncEdwExpDataType(char *url, char *userId, char *password, char *outTab)
/* rsyncEdwExpDataType - Get experiment and data types from ENCODED via json.. */
{
char *jsonText = NULL;
if (jsonIn)
    readInGulp(jsonIn, &jsonText, NULL);
else
    jsonText = getJsonViaHttps(url, userId, password);
if (jsonOut)
    writeGulp(jsonOut, jsonText, strlen(jsonText));
struct jsonElement *jsonRoot = jsonParse(jsonText);
char *expListName = "@graph";
struct jsonElement *jsonExpList = jsonMustFindNamedField(jsonRoot, "", expListName);
verbose(1, "Got @graph %p\n", jsonExpList);
struct slRef *ref, *refList = jsonListVal(jsonExpList, expListName);
verbose(1, "Got %d experiments\n", slCount(refList));
FILE *f = mustOpen(outTab, "w");
int realExpCount = 0;
for (ref = refList; ref != NULL; ref = ref->next)
    {
    struct jsonElement *el = ref->val;
    char *acc = jsonStringField(el, "accession");
    char *dataType = jsonStringField(el, "assay_term_name");
    if (dataType != NULL)
        {
	fprintf(f, "%s\t%s\t%s\t%s\t%s\n", acc, dataType,
	    jsonOptionalStringField(el, "lab.title", ""),
	    jsonOptionalStringField(el, "biosample_term_name", ""),
	    jsonOptionalStringField(el, "award.rfa", ""));
	++realExpCount;
	}
    }
verbose(1, "Got %d experiments with dataType\n", realExpCount);
carefulClose(&f);
}
Ejemplo n.º 8
0
static int test_json_query( const char* json_query ) {

	jsonObject* hash = jsonParse( json_query );
	if( !hash ) {
		fprintf( stderr, "Invalid JSON\n" );
		return -1;
	}

	int flags = 0;

	if ( obj_is_true( jsonObjectGetKeyConst( hash, "distinct" )))
		flags |= SELECT_DISTINCT;

	if ( obj_is_true( jsonObjectGetKeyConst( hash, "no_i18n" )))
		flags |= DISABLE_I18N;

	char* sql_query = buildQuery( NULL, hash, flags );

	if ( !sql_query ) {
		fprintf( stderr, "Invalid query\n" );
		return -1;
	}
	else
		printf( "%s\n", sql_query );

	free( sql_query );
	jsonObjectFree( hash );
	return 0;
}
/************************************************************************************************************
 * The JsonList for the findElement Function to test are as shown below,                                    *
 *                                                                                                          *
 *  {                                                                                                       *
 *    "NAME1":"JS",                                                                                         *
 *    "AGE"  :{ "NAME2":"STEVEN",                                                                           *
 *              "NAME4":"YEN"}                                                                              *
 *  }                                                                                                       *
 *                                                                                                          *
 * -Test to find the 'Key'="AGE" in recur=0.                                                                *
 * -Test to find the 'Key'="NAME3" in recur=1.                                                              *
 *                                                                                                          *                                                                                                         *
 ************************************************************************************************************/
void test_Finding_Element_if_Key_not_Found_in_the_Recursion_JSON_List_Should_Throw_Error()
{
  printf("JSON list Finding Element test No.3\n");
  JsonObject *jsonObj;
  Token *jsonTok;
  ListElement *findKey;
  Token *findVal;
  ErrorObject *err;

  TOKEN_DECLARE;

  getToken_ExpectAndReturn(openBrace0);    //"{"
  getToken_ExpectAndReturn(NAME1);         //"NAME1"
  getToken_ExpectAndReturn(colon0);        //":"
  getToken_ExpectAndReturn(JS);            //"JS"
  getToken_ExpectAndReturn(coma0);          //","
  getToken_ExpectAndReturn(AGE);           //"AGE"
  getToken_ExpectAndReturn(colon1);        //":"
  getToken_ExpectAndReturn(openBrace1);    //"{"
  getToken_ExpectAndReturn(NAME2);         //"NAME2"
  getToken_ExpectAndReturn(colon2);        //":"
  getToken_ExpectAndReturn(STEVEN);        //"STEVEN"
  getToken_ExpectAndReturn(coma1);          //","
  getToken_ExpectAndReturn(NAME4);         //"NAME4"
  getToken_ExpectAndReturn(colon3);        //":"
  getToken_ExpectAndReturn(YEN);           //"YEN"
  getToken_ExpectAndReturn(closeBrace0);   //"}"
  getToken_ExpectAndReturn(closeBrace1);   //"}"
  getToken_ExpectAndReturn(dollarSign);

  jsonObj=createJsonObject();

  Try{
    jsonTok=jsonParse(jsonObj);
  }Catch(err){
    TEST_FAIL_JSON("unexpected error occurred =>'%s'",err->errorMsg);
    free(err);
  }

  TEST_ASSERT_EQUAL(END,jsonObj->state);

  Try{
    findKey=(ListElement *)(keyFind(((JsonToken *)jsonTok)->list, "AGE", strCompare));
    findKey=(ListElement *)(keyFind(((JsonToken *)(((OperatorToken *)(findKey->value))->token[1]))->list, "NAME3", strCompare));
    TEST_FAIL_MESSAGE("Expecting ERR_KEY_NOT_FOUND but none thrown.");
  }Catch(err){
    TEST_ASSERT_EQUAL_STRING("ERROR[14]:Key not Found.Finding 'Key'=>'NAME3'.",err->errorMsg);
    TEST_ASSERT_EQUAL(ERR_KEY_NOT_FOUND,err->errorCode);
    free(err);
  }

  free(jsonObj);
  free(jsonTok);
  free(err);
  free(findKey);
  free(findVal);

  TOKEN_FREE;
  printf("\n\n");
}
Ejemplo n.º 10
0
static void add_cb(evhtp_request_t* req, void* a) {
    if (req->method != htp_method_POST) {
        evhtp_send_reply(req, EVHTP_RES_METHNALLOWED);
        return;
    }

    size_t len;
    auto buf = extract_body(req, &len);
    if (!buf) {
        evhtp_send_reply(req, EVHTP_RES_500);
        return;
    }

    char* endptr;
    JsonValue value;
    JsonAllocator allocator;
    int status = jsonParse(buf, &endptr, &value, allocator);
    if (status != JSON_OK) {
        evhtp_send_reply(req, EVHTP_RES_500);
        return;
    }

    evbuffer_add(req->buffer_out, "OK:", 3);
    // TODO: how to retrieve id?
    // evbuffer_add(req->buffer_out, id.c_str(), id.size());
    evhtp_send_reply(req, EVHTP_RES_OK);
}
Ejemplo n.º 11
0
PJsonObject jsonObject(const char *jsonString){
    PJsonObject object=createNewItem();
    string_start=jsonString;
    object_start=object;
    jsonParse(object,jsonString);
    return object;
}
Ejemplo n.º 12
0
/* ****************************************************************************
*
* jsonTreat - 
*/
std::string jsonTreat(const char* content, ConnectionInfo* ciP, ParseData* parseDataP, RequestType request, std::string payloadWord, JsonRequest** reqPP)
{
  std::string   res   = "OK";
  JsonRequest*  reqP  = jsonRequestGet(request, ciP->method);

  LM_T(LmtParse, ("Treating a JSON request: '%s'", content));

  ciP->parseDataP = parseDataP;

  if (reqP == NULL)
  {
    std::string errorReply = restErrorReplyGet(ciP, ciP->outFormat, "", requestType(request), SccBadRequest,
                                               std::string("Sorry, no request treating object found for RequestType '") + requestType(request) + "'");

    LM_RE(errorReply, ("Sorry, no request treating object found for RequestType %d (%s)", request, requestType(request)));
  }

  if (reqPP != NULL)
    *reqPP = reqP;

  LM_T(LmtParse, ("Treating '%s' request", reqP->keyword.c_str()));

  reqP->init(parseDataP);

  try
  {
    res = jsonParse(ciP, content, reqP->keyword, reqP->parseVector, parseDataP);
    if (ciP->inCompoundValue == true)
      orion::compoundValueEnd(ciP, parseDataP);
    if ((lmTraceIsSet(LmtCompoundValueShow)) && (ciP->compoundValueP != NULL))
      ciP->compoundValueP->shortShow("after parse: ");
  }
  catch (std::exception &e)
  {
    std::string errorReply  = restErrorReplyGet(ciP, ciP->outFormat, "", reqP->keyword, SccBadRequest, std::string("JSON Parse Error: ") + e.what());
    LM_E(("JSON Parse Error: '%s'", e.what()));
    LM_RE(errorReply, (res.c_str()));
  }

  if (res != "OK")
  {
    LM_E(("JSON parse error: %s", res.c_str()));
    ciP->httpStatusCode = SccBadRequest;

    std::string answer = restErrorReplyGet(ciP, ciP->outFormat, "", payloadWord, ciP->httpStatusCode, res);
    return answer; 
  }

  reqP->present(parseDataP);

  LM_T(LmtParseCheck, ("Calling check for JSON parsed tree (%s)", ciP->payloadWord));
  res = reqP->check(parseDataP, ciP);
  reqP->present(parseDataP);

  return res;
}
Ejemplo n.º 13
0
/************************************************************************************************************
 * The JsonList for the findElement Function to test are as shown below,                                    *
 *                                                                                                          *
 *  {                                                                                                       *
 *    "NAME1":"JS",                                                                                         *
 *    "AGE"  :{ "NAME2":"STEVEN",                                                                           *
 *              "NAME3":"YEN"}                                                                              *
 *  }                                                                                                       *
 *                                                                                                          *
 * -Test to find the 'Key'="AGE" in recur=0.                                                                *
 * -Test to find the 'Key'="NAME3" in recur=1.                                                              *
 * -Test to get the 'Value' for the 'Key' found in recur=1.                                                 *
 *                                                                                                          *                                                                                                         *
 ************************************************************************************************************/
void test_Finding_Element_in_Recursion_JSON_List()
{
  printf("JSON list Finding Element test No.4\n");
  JsonObject *jsonObj;
  Token *jsonTok;
  ListElement *findKey;
  Token *findVal;
  ErrorObject *err;

  TOKEN_DECLARE;

  getToken_ExpectAndReturn(openBrace0);    //"{"
  getToken_ExpectAndReturn(NAME1);         //"NAME1"
  getToken_ExpectAndReturn(colon0);        //":"
  getToken_ExpectAndReturn(JS);            //"JS"
  getToken_ExpectAndReturn(coma0);          //","
  getToken_ExpectAndReturn(AGE);           //"AGE"
  getToken_ExpectAndReturn(colon1);        //":"
  getToken_ExpectAndReturn(openBrace1);    //"{"
  getToken_ExpectAndReturn(NAME2);         //"NAME2"
  getToken_ExpectAndReturn(colon2);        //":"
  getToken_ExpectAndReturn(STEVEN);        //"STEVEN"
  getToken_ExpectAndReturn(coma1);          //","
  getToken_ExpectAndReturn(NAME3);         //"NAME3"
  getToken_ExpectAndReturn(colon3);        //":"
  getToken_ExpectAndReturn(YEN);           //"YEN"
  getToken_ExpectAndReturn(closeBrace0);   //"}"
  getToken_ExpectAndReturn(closeBrace1);   //"}"
  getToken_ExpectAndReturn(dollarSign);

  jsonObj=createJsonObject();

  Try{
    jsonTok=jsonParse(jsonObj);
    TEST_ASSERT_EQUAL(END,jsonObj->state);
    findKey=(ListElement *)(keyFind(((JsonToken *)jsonTok)->list, "AGE", strCompare));
    findKey=(ListElement *)(keyFind(((JsonToken *)(((OperatorToken *)(findKey->value))->token[1]))->list, "NAME3", strCompare));
    findVal=(Token *)(getElementValue(findKey));
    TEST_ASSERT_NOT_NULL(findVal);
  }Catch(err){
    TEST_FAIL_JSON("unexpected error occurred =>'%s'",err->errorMsg);
    free(err);
  }

  TEST_ASSERT_EQUAL_STRING(((StringToken *)(YEN))->name,((StringToken *)(findVal))->name);

  free(jsonObj);
  free(jsonTok);
  free(err);
  free(findKey);
  free(findVal);

  TOKEN_FREE;
  printf("\n\n");
}
Ejemplo n.º 14
0
 int vibratorCommandFwd( String argument )
 {
   JsonValue value;
   JsonAllocator allocator;
   // Proudly casting away the constness; string will be ruined by jsonParse
   JsonParseStatus status = jsonParse( (char*)argument.c_str(),
     &value, allocator );
   if ( status != JSON_PARSE_OK )
     return CmdRet_BadJSON;
   return Mistress::mSelf->onVibratorCommand( value );
 }
 virtual ParseResultBase* Parse(const char* json, size_t length) const {
     (void)length;
     GasonParseResult* pr = new GasonParseResult;
     char* end = 0;
     // gason uses insitu parsing, the source json must make a copy.
     pr->json = (char*)malloc(length + 1);
     memcpy(pr->json, json, length + 1);
     if (jsonParse(pr->json, &end, &pr->value, pr->allocator) != JSON_OK) {
         delete pr;
         return 0;
     }
 	return pr;
 }
 virtual bool ParseDouble(const char* json, double* d) const {
     GasonParseResult pr;
     char* end = 0;
     pr.json = strdup(json);
     if (jsonParse(pr.json, &end, &pr.value, pr.allocator) == JSON_OK &&
         pr.value.getTag() == JSON_ARRAY && 
         pr.value.toNode() &&
         pr.value.toNode()->value.getTag() == JSON_NUMBER)
     {
         *d = pr.value.toNode()->value.toNumber();
         return true;
     }
     else
         return false;
 }
 virtual bool ParseString(const char* json, std::string& s) const {
     GasonParseResult pr;
     char* end = 0;
     pr.json = strdup(json);
     if (jsonParse(pr.json, &end, &pr.value, pr.allocator) == JSON_OK &&
         pr.value.getTag() == JSON_ARRAY && 
         pr.value.toNode() &&
         pr.value.toNode()->value.getTag() == JSON_STRING)
     {
         s = pr.value.toNode()->value.toString();
         return true;
     }
     else
         return false;
 }
Ejemplo n.º 18
0
/**
	@brief Translate a JSON array into an osrfList of osrfMessages.
	@param string The JSON string to be translated.
	@param list Pointer to an osrfList of osrfMessages (may be NULL)
	@return Pointer to an osrfList containing pointers to osrfMessages.

	The JSON string is expected to be a JSON array, with each element encoding an osrfMessage.

	Translate each element of the JSON array into an osrfMessage, and store a pointer to the
	osrfMessage in an osrfList.

	If the @a list parameter is NULL, create a new osrfList (with osrfMessageFree() as the
	callback function for freeing items), populate it, and return a pointer to it.  Otherwise
	clear the osrfList provided and reuse it.

	When calling osrfMessageDeserialize repeatedly, a reasonable strategy is to pass a NULL
	for the @a list parameter on the first call, and pass the value returned from the first
	call on subsequent calls.

	The calling code is responsible for eventually freeing the returned osrfList by calling
	osrfListFree().
 */
osrfList* osrfMessageDeserialize( const char* string, osrfList* list ) {

	if( list )
		osrfListClear( list );

	if( ! string  || ! *string ) {
		if( ! list ) {
			list = osrfNewList( 1 );
			list->freeItem = (void(*)(void*)) osrfMessageFree;
		}
		return list;                   // No string?  Return empty list.
	}
	
	// Parse the JSON
	jsonObject* json = jsonParse(string);
	if(!json) {
		osrfLogWarning( OSRF_LOG_MARK,
				"osrfMessageDeserialize() unable to parse data: \n%s\n", string);
		if( ! list ) {
			list = osrfNewList( 1 );
			list->freeItem = (void(*)(void*)) osrfMessageFree;
		}
		return list;                   // Bad JSON?  Return empty list.
	}

	const unsigned int count = (int) json->size;
	if( ! list ) {
		// Create a right-sized osrfList
		list = osrfNewList( count );
		list->freeItem = (void(*)(void*)) osrfMessageFree;
	}

	// Traverse the JSON_ARRAY, turning each element into an osrfMessage
	int i;
	for( i = 0; i < count; ++i ) {

		const jsonObject* message = jsonObjectGetIndex( json, i );
		if( message && message->type != JSON_NULL &&
				  message->classname && !strcmp(message->classname, "osrfMessage" )) {
			osrfListPush( list, deserialize_one_message( message ) );
		}
	}

	jsonObjectFree( json );
	return list;
}
Ejemplo n.º 19
0
void parse(const char *csource, bool ok) {
    char *source = strdup(csource);
    char *endptr;
    JsonValue value;
    JsonAllocator allocator;
    int result = jsonParse(source, &endptr, &value, allocator);
    if (ok && result) {
        fprintf(stderr, "FAILED %d: %s\n%s\n%*s - \\x%02X\n", parsed, jsonStrError(result), csource, (int)(endptr - source + 1), "^", *endptr);
        ++failed;
    }
    if (!ok && !result) {
        fprintf(stderr, "PASSED %d:\n%s\n", parsed, csource);
        ++failed;
    }
    ++parsed;
    free(source);
}
Ejemplo n.º 20
0
 void LoadCreatureJSONDataFromString(const std::string& string_in,
                                     CreatureLoadDataPacket& load_data)
 {
     char *endptr;
     size_t source_size = string_in.size();
     char *source_chars = new char[source_size+1];
     source_chars[source_size]=0;
     memcpy(source_chars,string_in.c_str(),source_size);
     
     JsonParseStatus status = jsonParse(source_chars, &endptr, &load_data.base_node, load_data.allocator);
     
     load_data.src_chars = source_chars;
     
     if(status != JSON_PARSE_OK) {
         std::cerr<<"LoadCreatureJSONData() - Error parsing JSON!"<<std::endl;
     }
 }
Ejemplo n.º 21
0
oilsEvent* oilsUtilsCheckPerms( int userid, int orgid, char* permissions[], int size ) {
    if (!permissions) return NULL;
    int i;
    oilsEvent* evt = NULL;

    // Find the root org unit, i.e. the one with no parent.
    // Assumption: there is only one org unit with no parent.
    if (orgid == -1) {
        jsonObject* where_clause = jsonParse( "{\"parent_ou\":null}" );
        jsonObject* org = oilsUtilsQuickReq(
                              "open-ils.cstore",
                              "open-ils.cstore.direct.actor.org_unit.search",
                              where_clause
                          );
        jsonObjectFree( where_clause );

        orgid = (int)jsonObjectGetNumber( oilsFMGetObject( org, "id" ) );

        jsonObjectFree(org);
    }

    for( i = 0; i < size && permissions[i]; i++ ) {

        char* perm = permissions[i];
        jsonObject* params = jsonParseFmt("[%d, \"%s\", %d]", userid, perm, orgid);
        jsonObject* o = oilsUtilsQuickReq( "open-ils.storage",
                                           "open-ils.storage.permission.user_has_perm", params );

        char* r = jsonObjectToSimpleString(o);

        if(r && !strcmp(r, "0"))
            evt = oilsNewEvent3( OSRF_LOG_MARK, OILS_EVENT_PERM_FAILURE, perm, orgid );

        jsonObjectFree(params);
        jsonObjectFree(o);
        free(r);

        if(evt)
            break;
    }

    return evt;
}
Ejemplo n.º 22
0
    void OnData(
        const happyhttp::Response* r,
        void* userdata,
        const unsigned char* data,
        int n
        )
    {
        std::cout << "reading...\n";

        char *endptr;
        JsonValue value;
        JsonAllocator allocator;
        JsonParseStatus status = jsonParse((char*)data, &endptr, &value, allocator);
        if (status != JSON_PARSE_OK) {
            fprintf(stderr, "error at %zd, status: %d\n", endptr - (char*)data, status);
            exit(EXIT_FAILURE);
        } else { // SUCCESS
            switch (value.getTag()) {
            case JSON_TAG_NUMBER:
                printf("%g\n", value.toNumber());
                break;
            case JSON_TAG_BOOL:
                printf("%s\n", value.toBool() ? "true" : "false");
                break;
            case JSON_TAG_STRING:
                printf("\"%s\"\n", value.toString());
                break;
            case JSON_TAG_ARRAY:
                for (auto i : value) {
                    auto bleh = i->value;
                }
                break;
            case JSON_TAG_OBJECT:
                for (auto i : value) {
                    printf("%s = ", i->key);
                }
                break;
            case JSON_TAG_NULL:
                printf("null\n");
                break;
            }
        }
    }
Ejemplo n.º 23
0
int oilsUtilsGetRootOrgId() {

    // return the cached value if we have it.
    if (rootOrgId > 0) return rootOrgId;

    jsonObject* where_clause = jsonParse("{\"parent_ou\":null}");
    jsonObject* org = oilsUtilsQuickReq(
        "open-ils.cstore",
        "open-ils.cstore.direct.actor.org_unit.search",
        where_clause
    );

    rootOrgId = (int) 
        jsonObjectGetNumber(oilsFMGetObject(org, "id"));

    jsonObjectFree(where_clause);
    jsonObjectFree(org);

    return rootOrgId;
}
Ejemplo n.º 24
0
bool initEffectCache(const char *filename)
{
#define X(str) allEffects.emplace(#str, EffectType::str);
    EFFECT_TYPES
#undef X
#define X(str) allDurations.emplace(#str, Duration::str);
    DURATION_TYPES
#undef X

    rapidjson::Document doc;
    if (!jsonParse(filename, doc)) return false;

    for (auto i = doc.MemberBegin(); i != doc.MemberEnd(); ++i) {
        if (!i->value.IsObject()) {
            std::cerr << "effects: skipping id '" << i->name.GetString() <<
                "'\n";
            continue;
        }

        auto effectIter = allEffects.find(to_upper(i->name.GetString()));
        if (effectIter == std::end(allEffects)) {
            std::cerr << "effects: unknown type '" << i->name.GetString() <<
                "'\n";
            continue;
        }

        auto type = effectIter->second;
        if (type == EffectType::BOUND) {
            cache.emplace(static_cast<int>(type),
                          make_unique<EffectBound>(type, i->value));
        }
        else {
            cache.emplace(static_cast<int>(type),
                          make_unique<EffectSimple>(type, i->value));
        }
    }

    return true;
}
Ejemplo n.º 25
0
void performance(std::string& msg) {
	const int iterations = 100000;
	char* herp = new char[1024*1024];
	char* endptr = nullptr;

	JsonAllocator allocator;

	std::cout << "Parsing: " << msg << std::endl;
	auto start = std::chrono::high_resolution_clock::now();
	for (int i = 0; i < iterations; ++i) {
		memcpy(herp, msg.c_str(), msg.length() + 1);
		JsonValue value;

		int status = jsonParse(herp, &endptr, &value, allocator);
		if (status != JSON_OK) {
			std::cout << "Failure?" << std::endl;
		}
		allocator.deallocate();
	}
	delete herp;
	auto end = std::chrono::high_resolution_clock::now();

	std::cout << iterations  / (0.000001 + std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count())<< " iterations per millisecond" << std::endl;
 }
Ejemplo n.º 26
0
static void speedTest() {

    /* creates a giant json object, generating JSON strings
     * of subobjects as it goes. */

    int i,k;
    int count = 50;
    char buf[16];
    char* jsonString;

    jsonObject* array;
    jsonObject* dupe;
    jsonObject* hash = jsonNewObject(NULL);

    for(i = 0; i < count; i++) {
        
        snprintf(buf, sizeof(buf), "key_%d", i);

        array = jsonNewObject(NULL);
        for(k = 0; k < count + i; k++) {
            jsonObjectPush(array, jsonNewNumberObject(k));
            jsonObjectPush(array, jsonNewObject(NULL));
            jsonObjectPush(array, jsonNewObjectFmt("str %d-%d", i, k));
        }
        jsonObjectSetKey(hash, buf, array);

        jsonString = jsonObjectToJSON(hash);
        printf("%s\n\n", jsonString);
        dupe = jsonParse(jsonString);

        jsonObjectFree(dupe);
        free(jsonString);
    }

    jsonObjectFree(hash);
}
Ejemplo n.º 27
0
void syncOneRecord(struct sqlConnection *conn, char *type, struct jsonWrite *json, 
    char *table, long long id)
/* Send over one record and save UUID result to row of table defined by id in idField. */
{
/* Construct dyString for URL */
struct dyString *dyUrl = dyStringNew(0);
dyStringPrintf(dyUrl, "http://%s:%s@%s/%s/", gUserId, gPassword, gHost, type);
verbose(2, "%s\n", dyUrl->string);

/* Construct dyString for http header */
struct dyString *dyHeader = dyStringNew(0);
dyStringPrintf(dyHeader, "Content-length: %d\r\n", json->dy->stringSize);
dyStringPrintf(dyHeader, "Content-type: text/javascript\r\n");

/* Send header and then JSON */
int sd = netOpenHttpExt(dyUrl->string, "POST", dyHeader->string);
mustWriteFd(sd, json->dy->string, json->dy->stringSize);

/* Grab response */
struct dyString *dyText = netSlurpFile(sd);
close(sd);
uglyf("%s\n", dyText->string);

/* Turn it into htmlPage structure - this will also parse out http header */
struct htmlPage *response = htmlPageParse(dyUrl->string, dyText->string);
uglyf("status %s %d\n", response->status->version, response->status->status);

/* If we got bad status abort with hopefully very informative message. */
int status = response->status->status;
if (status != 200 && status != 201)  // HTTP codes
    {
    errAbort("ERROR - Metadatabase returns %d to our post request\n"
	     "POSTED JSON: %s\n"
             "URL: %s\n"
	     "FULL RESPONSE: %s\n",  status, json->dy->string, dyUrl->string, dyText->string);
    }

/* Parse uuid out of json response.  It should look something like
	{
	"status": "success", 
	"@graph": [
	     {
	     "description": "The macs2 peak calling software from Tao Liu.", 
	     "name": "macs2", "title": "macs2", "url": "https://github.com/taoliu/MACS/", 
	     "uuid": "9bda84fd-9872-49e3-9aa0-b71adbf9f31d", 
	     "schema_version": "1", 
	     "source_url": "https://github.com/taoliu/MACS/", 
	     "references": [], 
	     "@id": "/software/9bda84fd-9872-49e3-9aa0-b71adbf9f31d/", 
	     "@type": ["software", "item"], 
	     "aliases": []
	     }
	],     
	"@type": ["result"]
	}
*/
struct jsonElement *jsonRoot = jsonParse(response->htmlText);
struct jsonElement *graph = jsonMustFindNamedField(jsonRoot, "", "@graph");
struct slRef *ref = jsonListVal(graph, "@graph");
assert(slCount(ref) == 1);
struct jsonElement *graphEl = ref->val;
char *uuid = jsonStringField(graphEl, "uuid");
uglyf("Got uuid %s\n", uuid);

/* Save uuid to table */
char query[256];
sqlSafef(query, sizeof(query),
    "update %s set metaUuid='%s' where id=%lld", table, uuid, id);
sqlUpdate(conn, query);

/* Clean up */
dyStringFree(&dyUrl);
dyStringFree(&dyHeader);
dyStringFree(&dyText);
response->fullText = NULL;  // avoid double free of this
htmlPageFree(&response);
}
Ejemplo n.º 28
0
 bool addAliasFromRoute(PathNode &node, std::string const &route,
                        AliasPriority priority) {
     auto val = jsonParse(route);
     auto alias = applyPriorityToAlias(convertRouteToAlias(val), priority);
     return AliasProcessor().process(node, alias);
 }
Ejemplo n.º 29
0
UINT32   http_snd_req(HTTPParameters ClientParams, HTTP_VERB verb, CHAR* pSndData, u8 parseXmlJson)
{
		INT32                   nRetCode;
    UINT32                  nSize,nTotal = 0;
    CHAR*                   Buffer = NULL;
    HTTP_SESSION_HANDLE     pHTTP;
    UINT32                  nSndDataLen ;
#if DEMO_HTTP_XML_PARSE
    XML_Parser parser;
#elif DEMO_HTTP_SXML_PARSE
    CHAR * buf_cache = NULL;
    UINT32 cur_pos = 0;
#endif
#if DEMO_HTTP_JSON_PARSE
    json_parser jsonParser;
    json_printer printer;
#endif
    do
    {
#if !DEMO_HTTP_XML_PARSE && DEMO_HTTP_SXML_PARSE
        buf_cache = (CHAR*)tls_mem_alloc(HTTP_CLIENT_BUFFER_SIZE);
        if(buf_cache == NULL)
            return HTTP_CLIENT_ERROR_NO_MEMORY;
        memset(buf_cache , 0, HTTP_CLIENT_BUFFER_SIZE);
#endif
        Buffer = (CHAR*)tls_mem_alloc(HTTP_CLIENT_BUFFER_SIZE);
        if(Buffer == NULL)
        {
#if !DEMO_HTTP_XML_PARSE && DEMO_HTTP_SXML_PARSE
            tls_mem_free(buf_cache);
#endif
            return HTTP_CLIENT_ERROR_NO_MEMORY;
        }
        memset(Buffer, 0, HTTP_CLIENT_BUFFER_SIZE);
        printf("\nHTTP Client v1.0\n\n");
        nSndDataLen = (pSndData==NULL ? 0 : strlen(pSndData));
        // Open the HTTP request handle
        pHTTP = HTTPClientOpenRequest(0);
        if(!pHTTP)
        {
            nRetCode =  HTTP_CLIENT_ERROR_INVALID_HANDLE;
            break;
        }
        // Set the Verb
        nRetCode = HTTPClientSetVerb(pHTTP,verb);
        if(nRetCode != HTTP_CLIENT_SUCCESS)
        {
            break;
        }
#if TLS_CONFIG_HTTP_CLIENT_AUTH
        // Set authentication
        if(ClientParams.AuthType != AuthSchemaNone)
        {
            if((nRetCode = HTTPClientSetAuth(pHTTP,ClientParams.AuthType,NULL)) != HTTP_CLIENT_SUCCESS)
            {
                break;
            }

            // Set authentication
            if((nRetCode = HTTPClientSetCredentials(pHTTP,ClientParams.UserName,ClientParams.Password)) != HTTP_CLIENT_SUCCESS)
            {
                break;
            }
        }
#endif //TLS_CONFIG_HTTP_CLIENT_AUTH
#if TLS_CONFIG_HTTP_CLIENT_PROXY
        // Use Proxy server
        if(ClientParams.UseProxy == TRUE)
        {
            if((nRetCode = HTTPClientSetProxy(pHTTP,ClientParams.ProxyHost,ClientParams.ProxyPort,NULL,NULL)) != HTTP_CLIENT_SUCCESS)
            {

                break;
            }
        }
#endif //TLS_CONFIG_HTTP_CLIENT_PROXY
	 if((nRetCode = HTTPClientSendRequest(pHTTP,ClientParams.Uri,pSndData,nSndDataLen,verb==VerbPost || verb==VerbPut,0,0)) != HTTP_CLIENT_SUCCESS)
        {
            break;
        }
        // Retrieve the the headers and analyze them
        if((nRetCode = HTTPClientRecvResponse(pHTTP,30)) != HTTP_CLIENT_SUCCESS)
        {
            break;
        }
	 printf("Start to receive data from remote server...\n");
#if DEMO_HTTP_XML_PARSE
        if(parseXmlJson == 1)
            xmlParseInit(&parser);
#endif
#if DEMO_HTTP_JSON_PARSE
        if(parseXmlJson == 2)
            jsonParseInit(&jsonParser, &printer);
#endif
        // Get the data until we get an error or end of stream code
        while(nRetCode == HTTP_CLIENT_SUCCESS || nRetCode != HTTP_CLIENT_EOS)
        {
            // Set the size of our buffer
            nSize = HTTP_CLIENT_BUFFER_SIZE;   
            // Get the data
            nRetCode = HTTPClientReadData(pHTTP,Buffer,nSize,300,&nSize);
            if(nRetCode != HTTP_CLIENT_SUCCESS && nRetCode != HTTP_CLIENT_EOS)
                break;
            printf("%s", Buffer);
#if DEMO_HTTP_XML_PARSE
            if(parseXmlJson == 1)
                xmlParse(parser, Buffer, nSize, nRetCode == HTTP_CLIENT_EOS);
#elif DEMO_HTTP_SXML_PARSE
            if(parseXmlJson == 1)
            {
                if(cur_pos + nSize < HTTP_CLIENT_BUFFER_SIZE-1)
                {
                    memcpy(buf_cache+cur_pos, Buffer, nSize);
                    cur_pos += nSize;
                    if(nRetCode == HTTP_CLIENT_EOS)
                        sxml_parse_all(buf_cache);
                }
            }
#endif
#if DEMO_HTTP_JSON_PARSE
            if(parseXmlJson == 2)
                jsonParse(&jsonParser, &printer, Buffer, nSize, nRetCode == HTTP_CLIENT_EOS);
#endif
            nTotal += nSize;
        }
    } while(0); // Run only once
    tls_mem_free(Buffer);
#if !DEMO_HTTP_XML_PARSE && DEMO_HTTP_SXML_PARSE
    tls_mem_free(buf_cache);
#endif
    if(pHTTP)
        HTTPClientCloseRequest(&pHTTP);
    if(ClientParams.Verbose == TRUE)
    {
        printf("\n\nHTTP Client terminated %d (got %d kb)\n\n",nRetCode,(nTotal/ 1024));
    }
    return nRetCode;
}
Ejemplo n.º 30
0
IPState WunderGround::updateWeather()
{    
      CURL *curl;
      CURLcode res;
      std::string readBuffer;
      char requestURL[MAXRBUF];

      // If location is not updated yet, return busy
      if (wunderLat == -1000 || wunderLong == -1000)
          return IPS_BUSY;

      char *orig = setlocale(LC_NUMERIC,"C");

      snprintf(requestURL, MAXRBUF, "http://api.wunderground.com/api/%s/conditions/q/%g,%g.json", wunderAPIKeyT[0].text, wunderLat, wunderLong);

      curl = curl_easy_init();
      if(curl)
      {
        curl_easy_setopt(curl, CURLOPT_URL, requestURL);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
      }

      char srcBuffer[readBuffer.size()];
      strncpy(srcBuffer, readBuffer.c_str(), readBuffer.size());
      char *source = srcBuffer;
      // do not forget terminate source string with 0
      char *endptr;
      JsonValue value;
      JsonAllocator allocator;
      int status = jsonParse(source, &endptr, &value, allocator);
      if (status != JSON_OK)
      {
          DEBUGF(INDI::Logger::DBG_ERROR, "%s at %zd", jsonStrError(status), endptr - source);
          DEBUGF(INDI::Logger::DBG_DEBUG, "%s", requestURL);
          DEBUGF(INDI::Logger::DBG_DEBUG, "%s", readBuffer.c_str());
          setlocale(LC_NUMERIC,orig);
          return IPS_ALERT;
      }

      JsonIterator it;
      JsonIterator observationIterator;

      for (it = begin(value); it!= end(value); ++it)
      {
          if (!strcmp(it->key, "current_observation"))
          {
              for (observationIterator = begin(it->value); observationIterator!= end(it->value); ++observationIterator)
              {
                  if (!strcmp(observationIterator->key, "weather"))
                  {
                      char *value = observationIterator->value.toString();

                      if (!strcmp(value, "Clear"))
                          setParameterValue("WEATHER_FORECAST", 0);
                      else if (!strcmp(value, "Unknown") || !strcmp(value, "Scattered Clouds") || !strcmp(value, "Partly Cloudy") || !strcmp(value, "Overcast")
                               || !strcmp(value, "Patches of Fog") || !strcmp(value, "Partial Fog") || !strcmp(value, "Light Haze"))
                          setParameterValue("WEATHER_FORECAST", 1);
                      else
                          setParameterValue("WEATHER_FORECAST", 2);

                      DEBUGF(INDI::Logger::DBG_SESSION, "Weather condition: %s", value);
                  }
                  else if (!strcmp(observationIterator->key, "temp_c"))
                  {
                      if (observationIterator->value.isDouble())
                          setParameterValue("WEATHER_TEMPERATURE", observationIterator->value.toNumber());
                      else
                          setParameterValue("WEATHER_TEMPERATURE", atof(observationIterator->value.toString()));
                  }
                  else if (!strcmp(observationIterator->key, "wind_kph"))
                  {
                      if (observationIterator->value.isDouble())
                          setParameterValue("WEATHER_WIND_SPEED", observationIterator->value.toNumber());
                      else
                          setParameterValue("WEATHER_WIND_SPEED", atof(observationIterator->value.toString()));
                  }
                  else if (!strcmp(observationIterator->key, "wind_gust_kph"))
                  {
                      if (observationIterator->value.isDouble())
                        setParameterValue("WEATHER_WIND_GUST", observationIterator->value.toNumber());
                      else
                        setParameterValue("WEATHER_WIND_GUST", atof(observationIterator->value.toString()));
                  }
                  else if (!strcmp(observationIterator->key, "precip_1hr_metric"))
                  {
                      char *value = observationIterator->value.toString();
                      double mm=-1;
                      if (!strcmp(value, "--"))
                          setParameterValue("WEATHER_RAIN_HOUR", 0);
                      else
                      {
                          mm = atof(value);
                          if (mm >= 0)
                              setParameterValue("WEATHER_RAIN_HOUR", mm);
                      }
                  }
              }
          }
      }

      setlocale(LC_NUMERIC,orig);
      return IPS_OK;
}