Beispiel #1
0
void api_hdd_handler(const shared_ptr<restbed::Session> session)
{
  Hdd *hdd;
  JSONArray devices;
  JSONObject obj;
  JSONObject deviceData;
  JSONValue *output;
  double hddTotal;
  double hddUsage;
  vector<string> hddDevices;

  hdd = Hdd::getInstance();
  hddTotal = hdd->getTotalCapacity();
  hddUsage = hdd->getUsedCapacity();
  hddDevices = hdd->getListHardDrive();
  obj[L"total"] = new JSONValue(hddTotal);
  obj[L"usage"] = new JSONValue(hddUsage);
  for (vector<string>::iterator it = hddDevices.begin(); it != hddDevices.end(); ++it)
  {
    deviceData[L"name"] = new JSONValue(s2ws(*it));
    devices.push_back(new JSONValue(deviceData));
  }
  obj[L"devices"] = new JSONValue(devices);
  output = new JSONValue(obj);
  session->close(restbed::OK, ws2s(output->Stringify()), { { "Content-Type", "application/json" } });
}
Beispiel #2
0
/*
{
"contents": [{
"Test": "Test,Obj"
},
"HelloWorld,cswuyg",
"Good Good Studey,Day Day Up"],
"result": "no_way"
}
*/
std::wstring CTestJSON::GetJsonStr()
{
	JSONArray jsArray;
	JSONObject jsObj;
	jsObj[L"Test"] = new(std::nothrow)JSONValue(L"Test,Obj");
	jsArray.push_back(new(std::nothrow)JSONValue(jsObj));
	jsArray.push_back(new(std::nothrow)JSONValue(L"HelloWorld,cswuyg"));
	jsArray.push_back(new(std::nothrow)JSONValue(L"Good Good Studey,Day Day Up"));
	jsArray.push_back(new(std::nothrow)JSONValue((double)1988));

	JSONObject jsObjNew;
	jsObjNew[L"contents"] = new(std::nothrow)JSONValue(jsArray);
	jsObjNew[L"result"] = new(std::nothrow)JSONValue(L"no_way");

	JSONValue jsValue = jsObjNew;
	std::wstring strRet = jsValue.Stringify().c_str();
	return strRet;
}
JSON::JSONArray JSON::fromPoint(const Point& point)
{
    JSONArray array;

    array.push_back(fromNumber(point.x()));
    array.push_back(fromNumber(point.y()));

    return array;
}
Beispiel #4
0
// Initialize a JSON array from a stream
// This is similar to initFromStream() above and may also be called
// recursively by way of initValueFromStream()
// The expectation is that the first character will be a '[' and it
// will run until if finds a matching ']' char.  Along the way it
// may create nested objects and/or arrays.
// Note: It will consume the closing bracket from the stream
void initArrayFromStream(JSONArray &arr, istream &istr) {
  char nextChar;
  istr >> nextChar;
  checkChar(nextChar, '['); // sanity check
  skipWhiteSpace(istr);

  // Check for empty array (and make sure we consume the ])
  nextChar = static_cast<char>(istr.peek());
  if (nextChar == ']') {
    istr.ignore();
  }

  while (nextChar != ']') // process the stream
  {
    // Quick sanity check
    if (istr.eof()) {
      throw JSONParseException("Unexpected end of data stream");
    }

    // We expect to start the loop with the stream pointing to the
    // first character of the value
    // Add the value to our array
    arr.push_back(initValueFromStream(istr));

    istr >> nextChar;
    // nextChar is guaranteed to be either a comma, close brace or close
    // bracket.
    //(If it was anything else, initValueFromStream() would have thrown an
    // exception.)
    // A brace is an error, a bracket means the array is done (and will be
    // checked at
    // the start of the while loop) and a comma needs to be thrown out (along
    // with any
    // following whitespace) to position us for the next value
    if (nextChar == '}')
      throw JSONParseException(
          "Invalid closing brace while initializing array");
    else if (nextChar == ',') {
      skipWhiteSpace(istr);
      // Check to see if another key/value pair really follows the comma
      // (because if one doesn't, the parser will get screwed up and may not
      // actually detect the problem).
      if (istr.peek() == ']') {
        throw JSONParseException(
            "Invalid comma (array ended with no further values)");
      }
    }
  }
}
Beispiel #5
0
std::string serialize_data(data_t *data) {
    std::lock_guard<std::mutex> lk(data->m);

    JSONObject root;

    JSONObject states;
    states[L"isBlink"] = new JSONValue(data->isBlink);
    states[L"isLeftWink"] = new JSONValue(data->isLeftWink);
    states[L"isRightWink"] = new JSONValue(data->isRightWink);
    states[L"isLookingLeft"] = new JSONValue(data->isLookingLeft);
    states[L"isLookingRight"] = new JSONValue(data->isLookingRight);

    JSONObject expressiv;

    expressiv[L"lowerFaceActionName"] = new JSONValue(s2w(data->lowerFaceActionName));
    expressiv[L"lowerFaceAction"] = new JSONValue((double) data->lowerFaceAction);
    expressiv[L"lowerFaceActionPower"] = new JSONValue(data->lowerFaceActionPower);
    expressiv[L"upperFaceActionName"] = new JSONValue(s2w(data->upperFaceActionName));
    expressiv[L"upperFaceAction"] = new JSONValue((double) data->upperFaceAction);
    expressiv[L"upperFaceActionPower"] = new JSONValue(data->upperFaceActionPower);

    root[L"time"] = new JSONValue(data->timestamp);
    root[L"battery"] =  new JSONValue(data->battery);
    root[L"wirelessSignal"] = new JSONValue((double)(data->wireless_signal));
    root[L"states"] = new JSONValue(states);
    root[L"expressiv"] = new JSONValue(expressiv);

    JSONArray array;
    for (int i = 0; i < data->cq.size(); i++) {
        array.push_back(new JSONValue((double) data->cq[i]));
    }
    root[L"contactQuality"] = new JSONValue(array);

    JSONValue *value = new JSONValue(root);
    std::wstring out = value->Stringify();


    std::string ss;
    ss.assign(out.begin(), out.end());

    delete value;

    return ss;
}
Beispiel #6
0
/**
 * Parses a JSON encoded value to a JSONValue object
 *
 * @access protected
 *
 * @param wchar_t** data Pointer to a wchar_t* that contains the data
 *
 * @return JSONValue* Returns a pointer to a JSONValue object on success, NULL on error
 */
JSONValue *JSONValue::Parse(const wchar_t **data)
{
    // Is it a string?
    if (**data == '"')
    {
        std::wstring str;
        if (!JSON::ExtractString(&(++(*data)), str))
            return NULL;
        else
            return new JSONValue(str);
    }

    // Is it a boolean?
    else if ((simplejson_wcsnlen(*data, 4) && wcsncasecmp(*data, L"true", 4) == 0) || (simplejson_wcsnlen(*data, 5) && wcsncasecmp(*data, L"false", 5) == 0))
    {
        bool value = wcsncasecmp(*data, L"true", 4) == 0;
        (*data) += value ? 4 : 5;
        return new JSONValue(value);
    }

    // Is it a null?
    else if (simplejson_wcsnlen(*data, 4) && wcsncasecmp(*data, L"null", 4) == 0)
    {
        (*data) += 4;
        return new JSONValue();
    }

    // Is it a number?
    else if (**data == L'-' || (**data >= L'0' && **data <= L'9'))
    {
        // Negative?
        bool neg = **data == L'-';
        if (neg) (*data)++;

        double number = 0.0;

        // Parse the whole part of the number - only if it wasn't 0
        if (**data == L'0')
            (*data)++;
        else if (**data >= L'1' && **data <= L'9')
            number = JSON::ParseInt(data);
        else
            return NULL;

        // Could be a decimal now...
        if (**data == '.')
        {
            (*data)++;

            // Not get any digits?
            if (!(**data >= L'0' && **data <= L'9'))
                return NULL;

            // Find the decimal and sort the decimal place out
            // Use ParseDecimal as ParseInt won't work with decimals less than 0.1
            // thanks to Javier Abadia for the report & fix
            double decimal = JSON::ParseDecimal(data);

            // Save the number
            number += decimal;
        }

        // Could be an exponent now...
        if (**data == L'E' || **data == L'e')
        {
            (*data)++;

            // Check signage of expo
            bool neg_expo = false;
            if (**data == L'-' || **data == L'+')
            {
                neg_expo = **data == L'-';
                (*data)++;
            }

            // Not get any digits?
            if (!(**data >= L'0' && **data <= L'9'))
                return NULL;

            // Sort the expo out
            double expo = JSON::ParseInt(data);
            for (double i = 0.0; i < expo; i++)
                number = neg_expo ? (number / 10.0) : (number * 10.0);
        }

        // Was it neg?
        if (neg) number *= -1;

        return new JSONValue(number);
    }

    // An object?
    else if (**data == L'{')
    {
        JSONObject object;

        (*data)++;

        while (**data != 0)
        {
            // Whitespace at the start?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // Special case - empty object
            if (object.size() == 0 && **data == L'}')
            {
                (*data)++;
                return new JSONValue(object);
            }

            // We want a string now...
            std::wstring name;
            if (!JSON::ExtractString(&(++(*data)), name))
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // More whitespace?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // Need a : now
            if (*((*data)++) != L':')
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // More whitespace?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // The value is here
            JSONValue *value = Parse(data);
            if (value == NULL)
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // Add the name:value
            if (object.find(name) != object.end())
                delete object[name];
            object[name] = value;

            // More whitespace?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_OBJECT(object);
                return NULL;
            }

            // End of object?
            if (**data == L'}')
            {
                (*data)++;
                return new JSONValue(object);
            }

            // Want a , now
            if (**data != L',')
            {
                FREE_OBJECT(object);
                return NULL;
            }

            (*data)++;
        }

        // Only here if we ran out of data
        FREE_OBJECT(object);
        return NULL;
    }

    // An array?
    else if (**data == L'[')
    {
        JSONArray array;

        (*data)++;

        while (**data != 0)
        {
            // Whitespace at the start?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_ARRAY(array);
                return NULL;
            }

            // Special case - empty array
            if (array.size() == 0 && **data == L']')
            {
                (*data)++;
                return new JSONValue(array);
            }

            // Get the value
            JSONValue *value = Parse(data);
            if (value == NULL)
            {
                FREE_ARRAY(array);
                return NULL;
            }

            // Add the value
            array.push_back(value);

            // More whitespace?
            if (!JSON::SkipWhitespace(data))
            {
                FREE_ARRAY(array);
                return NULL;
            }

            // End of array?
            if (**data == L']')
            {
                (*data)++;
                return new JSONValue(array);
            }

            // Want a , now
            if (**data != L',')
            {
                FREE_ARRAY(array);
                return NULL;
            }

            (*data)++;
        }

        // Only here if we ran out of data
        FREE_ARRAY(array);
        return NULL;
    }

    // Ran out of possibilites, it's bad!
    else
    {
        return NULL;
    }
}
const char* WebModelUnified::website_search(const char* req){
    JSONObject root;
    JSONArray jsarray;
    Connection* conn = connect();
    Query query = conn->query();

    string reqstr(req);
    string reqstr_spaced = replaceChar(reqstr, '+', ' ');
    vector<string> splittedstr;
    split(splittedstr, reqstr_spaced, boost::algorithm::is_any_of(" "));

    int titleForce = 10;
    int descriptionForce = 1;
    int urlForce = 3;

    query << "SELECT * , ";
    //Occurences total
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 != 0){
            query << " + ";
        }

        query << "((" <<
          titleForce << " * (char_length(title) - char_length(replace(title,'" << s << "',''))) + " <<
          descriptionForce << " * (char_length(description) - char_length(replace(description,'" << s << "',''))) + " <<
          urlForce << " * (char_length(url) - char_length(replace(url,'" << s << "','')))" <<
        ") / char_length('" << s << "'))";
    }
    query << " as Occurances " << " FROM website ";

    //Where clause
    for(size_t i1 = 0; i1 < splittedstr.size(); i1++)
    {
        string s = splittedstr[i1];
        if(i1 == 0) {
            query << "WHERE ";
        } else {
            query << "OR ";
        }
        query << "(url LIKE '%" << s << "%' or title LIKE '%" << s << "%' or description LIKE '%" << s << "%') ";
    }

    query << " ORDER BY " << "Occurances desc, title ASC ";

    StoreQueryResult ares = query.store();
    unsigned int numrow = ares.num_rows();

    for(unsigned int i = 0; i < numrow; i++)
    {
        JSONObject result;

        result[L"title"] = new JSONValue(wchartFromChar(ares[i]["title"]));
        result[L"description"] = new JSONValue(wchartFromChar(ares[i]["description"]));
        result[L"url"] = new JSONValue(wchartFromChar(ares[i]["url"]));
        JSONValue* resultVal = new JSONValue(result);

        jsarray.push_back(resultVal);
    }

    root[L"results"] = new JSONValue(jsarray);

    JSONValue* jvalue = new JSONValue(root);

    const char* returnStr = fromWString(jvalue->Stringify());
    delete jvalue;
    return returnStr;
}