Sending a audio buffer using C++ Rest SDK - c++

I recently started to use C++ Rest SDK and I'm trying to send an audio buffer to Watson Speech to Text service and the docs didn't make clear to me how to use or upload a buffer using this lib, I started using a Microsfot sample to upload files(https://msdn.microsoft.com/en-us/library/jj950081.aspx) and then a I tried to modify the code to send a buffer as the examples (https://msdn.microsoft.com/en-us/library/jj950083.aspx), but I for some how doesn't work.
This is my current code:
My current code:
#include <codecvt>
#include <cpprest/containerstream.h>
#include <cpprest/http_client.h>
#include <iostream>
#include <cpprest/producerconsumerstream.h>
#include <cpprest/rawptrstream.h>
#include <cpprest/json.h>
#include "ReqHTTP.h"
#include <sstream>
#include <fstream>
#include <Windows.h>
using namespace std;
using namespace web;
using namespace concurrency;
using namespace concurrency::streams;
using namespace web::http;
using namespace web::http::client;
using namespace utility::conversions;
#pragma comment(lib, "winmm.lib")
pplx::task<void> RequestHTTP::UploadFileToHttpServerAsync(streams::ostream outStream, LPSTR buffer)
{
container_buffer<LPSTR> outAudioBuffer(move(buffer));
return outStream.write(outAudioBuffer, outAudioBuffer.size()).then([](size_t
bytesWritten)
{
try {
http_client_config config;
credentials cred(L"c674021d-5a0f-4ec1-84a4-da6fbd50541c", L"WvYMlztHWCbC");
config.set_credentials(cred);
http_request req(methods::POST);
req.headers().add(L"Transfer-Encoding", L"chunked");
req.headers().add(L"Content-Type", L"audio/wav");
req.set_request_uri(L"speech-to-text/api/v1/recognize?continuous=true&model=pt-BR_BroadbandModel");
req.set_body(bytesWritten);
// Make HTTP request with the file stream as the body.
http_client client(L"https://stream.watsonplatform.net/", config);
//concurrency::streams::producer_consumer_buffer<uint8_t> buf;
//buf.putn_nocopy(&body[0], body.size());
return client.request(req).then([bytesWritten](pplx::task<http_response> previousTask)
{
//buffer.close;
std::wostringstream ss;
try
{
auto response = previousTask.get();
response.extract_json().then([=](json::value js) {
int i = 0;
auto campo = js.at(to_string_t("results"));
while (i < campo.size()) {
auto transc = campo.operator[](i).operator[](to_string_t("alternatives")).operator[](0);
wcout << transc.at(to_string_t("transcript")) << endl;
i++;
}
});
}
catch (const http_exception& e)
{
ss << e.what() << std::endl;
}
std::wcout << ss.str();
});
}
catch (const std::system_error& e)
{
std::wostringstream ss;
ss << e.what() << std::endl;
std::wcout << ss.str();
// Return an empty task.
return pplx::task_from_result();
}
});
}

Related

C++ How to parse JSON response using cppRest Library?

I am trying to parse JSON response using cppRest Library, but an exception is raised instead the JSON object, here is the error that is show below:
Incorrect Content-Type: must be textual to extract_string, JSON to extract_json.
And here is my code that I have tried so far:
#include <iostream>
#include <cpprest/http_client.h>
using namespace web::http;
using namespace web::http::client;
using namespace web;
using namespace std;
int main()
{
uri url(L"http://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0");
http_client client(url);
http_response response;
http_request req;
req.set_method(methods::GET);
req.headers().set_content_type(L"application/json");
response = client.request(req).get();
try
{
json::object json_object(response.extract_json().get().as_object());
}
catch (exception &e)
{
cout << e.what() << "\n";
}
return 0;
}
I solved my problem, looks like I need to set the response headers to get the received content type as json:
Updated my code:
#include <iostream>
#include <cpprest/http_client.h>
using namespace web::http;
using namespace web::http::client;
using namespace web;
using namespace std;
int main()
{
uri url(L"http://www.7timer.info/bin/astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0");
http_client client(url);
http_request req;
req.set_method(methods::GET);
pplx::task<json::value> requestTask = client.request(req).then([](http_response response)
{
json::value jsonObject;
try
{
if ( response.status_code() == status_codes::OK )
{
response.headers().set_content_type(L"application/json"); // Set headers to receive content type as JSON
jsonObject = response.extract_json().get();
}
}
catch (const http_exception& e)
{
cout << e.error_code().message() << "\n";
}
return jsonObject; // returned a json value
});
json::array dataseries = requestTask.get().at(L"dataseries").as_array(); // We get the returned response here
for (size_t i = 0; i < dataseries.size(); i++)
{
auto timepoint = dataseries[i].at(L"timepoint");
wcout << timepoint << endl;
}
return 0;
}

How to use boost to put a stream into a buffer

I am new to Streams and Buffers implementation and I do not really know how to fix this:
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <boost/property_tree/json_parser.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;
namespace pt = boost::property_tree;
struct DefaultMessage {
std::string command;
int value;
};
void defaultMessage(DefaultMessage *dm ,pt::ptree *root) {
root->put("command", dm->command);
root->put("value", dm->value);
}
// Echoes back all received WebSocket messages
void do_session(tcp::socket &socket) {
try {
// Construct the stream by moving in the socket
websocket::stream<tcp::socket> ws{std::move(socket)};
// Accept the websocket handshake
ws.accept();
for (;;) {
// Read a message into the buffer
boost::beast::multi_buffer buffer;
ws.read(buffer);
// Make string from buffer
auto s = boost::beast::buffers_to_string(buffer.data());
// Create ptree root
pt::ptree root;
// Create array source from s
boost::iostreams::array_source array_source(&s[0], s.size());
// Create input stream from array source
boost::iostreams::stream<boost::iostreams::array_source> input_stream(array_source);
// Read the json an populate ptree root
pt::read_json(input_stream, root);
// Discard all in buffer
buffer.consume(buffer.size());
// Construct a default message
auto message = DefaultMessage{
root.get<std::string>("command"),
root.get<int>("value")
};
defaultMessage(&message, &root);
// **This won't compile.**
pt::write_json(buffer, root);
// Echo the message back
ws.text(ws.got_text());
ws.write(buffer.data());
}
}
catch (boost::system::system_error const &se) {
// This indicates that the session was closed
if (se.code() != websocket::error::closed) {
std::cerr << "Error: " << se.code().message() << std::endl;
}
}
catch (std::exception const &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
I want to respond with the message struct. So I guess I need to put it back in the buffer. This part is what is do not know how to do.
If efficiency is not your top concern, I'd suggest
std::ostringstream oss;
pt::write_json(oss, root);
to write to a string, and
// Echo the message back
ws.text(ws.got_text());
ws.write(boost::asio::buffer(oss.str()));
to write that buffer out.
Caveats:
this does more allocations than strictly required, probably
Boost PropertyTree is NOT a JSON library

consuming c++ object in json and getting http put response in json, example code errors,REST API

I got the following code from internet. I expect it to print contents of post request of any URL.It is printing ->Added new Id: {"listOfAssets":[{"assetName":"Gold Asset"}]}->which is correct.I guess this is a string output. I want output in json which I need to convert to C++(serialize) Can someone advice what more should I do?I am running the code in linux environment.1st let me know how to get json output.serializing can be done later. To do this I added 2lines
It is giving me errors
terminate called after throwing an instance of 'web::http::http_exception'
what(): Incorrect Content-Type: must be textual to extract_string, JSON to extract_json.
#include <cpprest/http_client.h>
#include <pplx/pplxtasks.h>
#include <cpprest/json.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <cpprest/details/http_constants.dat>
#include <cpprest/http_msg.h>
using namespace std;
using namespace web;
using namespace web::json;
using namespace pplx;
using namespace web::http;
using namespace web::http::client;
using namespace web::http::details;
pplx::task<int> Post()
{
return pplx::create_task([]
{
json::value postData;
postData["name"] = json::value::string("Joe Smith");
postData["sport"] = json::value::string("Baseball");
http_client client("http://54.191.233.99:8080/sparkAPIs/testing.html");
return client.request(methods::POST, "",
/*postData.serialize().c_str(),*/ "application/json");
}).then([](http_response response)
{
if(response.status_code() == status_codes::OK)
{
//auto body = response.extract_string();
//std::cout << "Added new Id: " << body.get().c_str() << std::endl;
auto body = response.extract_json();
body.get();
//return std::stoi(body.get().c_str());
}
return 0;
});
}
int main()
{
cout<<"hello world"<<endl;
Post().wait();
}

cpprest client receive no response

when i build my own cpprestsdk server and client,i found that when my server receive a request and reply to it, my client have no reaction to it,and it never goes into the breakpoint where i handle the http_response,here is my code;
i was stuck for so many days,will someone help me fix this,thanks a lot
(client send request,server receives it and reply, client fail to receive http_response)
Server(i just got it from somewhere on internet):
#include "cpprest/json.h"
#include "cpprest/http_listener.h"
#include "cpprest/uri.h"
#include "cpprest/asyncrt_utils.h"
#include "cpprest/http_client.h"
using namespace web::http::experimental::listener;
using namespace web::http;
using namespace web;
void handle_get(http_request message)
{
message.reply(status_codes::OK, U("Hello, World!"));
};
void handle_post(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_put(http_request message)
{
message.reply(status_codes::NotFound);
};
void handle_delete(http_request message)
{
message.reply(status_codes::NotFound);
};
#define TRACE(msg) std::wcout << msg
#define TRACE_ACTION(a, k, v) std::wcout << a << L" (" << k << L", " << v << L")\n"
int main(int argc, char ** argv)
{
uri_builder uri(U("http://localhost:8888"));
http_listener listener(uri.to_uri());
listener.support(methods::GET, handle_get);
listener.support(methods::POST, handle_post);
listener.support(methods::PUT, handle_put);
listener.support(methods::DEL, handle_delete);
try
{
listener
.open()
.then([&listener](){TRACE(L"\nstarting to listen\n"); })
.wait();
while (true);
}
catch (std::exception const & e)
{
std::wcout << e.what() << std::endl;
}
catch (...)
{
std::wcout << "Unknown exception" << std::endl;
}
return 0;
}
and here is my Client
#include "cpprest/http_client.h"
#include "cpprest/filestream.h"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
int main(int argc, char* argv[])
{
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://www.bing.com/"));
http_client localclient(U("http://localhost:8888"));
return localclient.request(methods::GET);
})
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
system("pause");
return response.body().read_to_end(fileStream->streambuf());
})
.then([=](size_t)
{
return fileStream->close();
});
try
{
requestTask.wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
system("pause");
}
return 0;
}

Can any one resolve this exception in the below Thrift program?

I am new to Thrift.
I am trying to create a table ("sample") in Hbase using the following Thrift program on ubuntu 10.10 and can anyone tell me whether this is correct or not.
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <poll.h>
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocket.h>
#include <transport/TTransportUtils.h>
#include "Hbase.h"
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace apache::hadoop::hbase::thrift;
using namespace std;
int main()
{
boost::shared_ptr<TTransport> socket(new TSocket("localhost", 60010));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
HbaseClient client1(protocol);
try
{
transport->open();
string tableName("Sample");
vector<ColumnDescriptor> columns;
columns.push_back(ColumnDescriptor());
columns.back().name = "cf:";
columns.back().maxVersions = 10;
columns.push_back(ColumnDescriptor());
columns.back().name = "test";
try {
client1.createTable(tableName, columns);
} catch (const AlreadyExists &ae) {
std::cerr << "WARN: " << ae.message << std::endl;
}
}
catch (const TException &tx) {
std::cerr << "ERROR: " << tx.what() << std::endl;
}
return 0;
}
But i am getting the following exception at this place client1.createTable(tableName, columns);
ERROR: No more data to read.
Please help in resolving this.
Got it,
Need to start thrift server on hbase by .<hbaseinstallationpath>/bin/hbase thrift -threadpool start