memory leak using cJson ESP32 - esp32

Please could someone help me to identify why there is a memory leak using cJson I could not find the problem. whenever I do an authentication the live memory decreases.
The json is created only at that point, I have already changed the control logic but in any case it always ends up leaking memory
esp_err_t loginWS(httpd_req_t *request) {
JwtService jwtService;
AutenticationModel autenticationModel;
AutenticationService autenticationService;
autenticationModel = autenticationService.loadRegister();
cJSON *jsonWs;
cJSON *params;
std::string token = "";
std::string msg = "";
std::string body = "";
std::string login = "";
std::string password = "";
bool error;
body = _getBody(request); //json received
jsonWs = cJSON_Parse(body.c_str());
login = cJSON_GetObjectItem(jsonWs, "_login")->valuestring;
password = cJSON_GetObjectItem(jsonWs, "_password")->valuestring;
if (login == autenticacaoModel.getLogin() && senha == autenticacaoModel.getPassword()) {
token = jwtService.criarJwt();
msg = "";
error = false;
} else {
token = "";
msg = "Login or password invalid";
error = true;
}
cJSON_AddItemToObject(jsonWs = cJSON_CreateObject(), "token", params = cJSON_CreateObject());
cJSON_AddItemToObject(params, "token", cJSON_CreateString(token.c_str()));
cJSON_AddItemToObject(jsonWs, "message", params = cJSON_CreateObject());
cJSON_AddItemToObject(params, "error", cJSON_CreateBool(erro));
cJSON_AddItemToObject(params, "msg", cJSON_CreateString(mensagem.c_str()));
const char *texto = cJSON_Print(jsonWs);
cJSON_Delete(jsonWs);
httpd_resp_set_hdr(request, "Content-Type", "application/json");
httpd_resp_sendstr(request, texto);
free((void *)texto);
return ESP_OK;
}

Related

Syntax help for creating a filter in aws ec2 describeinstance api call in c++

Using DescribeInstancesRequest (c++ sdk) to get response about a particular instance_id. I am having a problem constructing the filter.
I am adapting the example code provided by the aws-doc-sdk-examples c++ example code describe_instances.cpp. I have added code to filter the response to use a known valid (now hard coded) instance ID.
I have tried multiple variations to set up the filter, but the docs aren't clear to me about the "value pair" format for the filter.
Here is the complete code. It compiles just find, but always responds with the "Could not find: ..."
Please let me know what I am getting wrong with the filter syntax! (See commented section Filter an instance id)
Thanks
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
// Filter an instance_id
Aws::EC2::Model::Filter filter;
filter.SetName("instance_id");
Aws::String filter_val{"Name=instance_id,Values=i-0e120b44acc929946"};
Aws::Vector<Aws::String> filter_values;
filter_values.push_back(filter_val);
filter.SetValues(filter_values);
Aws::Vector<Aws::EC2::Model::Filter> DIRFilter;
DIRFilter.push_back(filter);
request.SetFilters(DIRFilter);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: " + filter_val;;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}
I just couldn't get the filter to work. Any input would be appreciated. However, there is an alternate method using the WithInstanceIds member function. Reading the API docs is always a good idea!!
Here is the subroutine that works:
void Server::set_instance_info()
{
// Get server instance information via aws sdk
Aws::SDKOptions options;
Aws::InitAPI(options);
{
/* #TODO Make this a startup config value */
Aws::Client::ClientConfiguration clientConfig;
clientConfig.region = "us-west-2";
Aws::EC2::EC2Client ec2(clientConfig);
Aws::EC2::Model::DescribeInstancesRequest request;
/* #TODO Make this a startup config value */
const Aws::String instanceId{"i-0e120b44acc929946"};
Aws::Vector<Aws::String> instances;
instances.push_back(instanceId);
request.WithInstanceIds(instances);
auto outcome = ec2.DescribeInstances(request);
if (outcome.IsSuccess())
{
const auto &reservations =
outcome.GetResult().GetReservations();
for (const auto &reservation : reservations)
{
const auto &instances = reservation.GetInstances();
for (const auto &instance : instances)
{
Aws::String instanceStateString =
Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
instance.GetState().GetName());
Aws::String type_string =
Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
instance.GetInstanceType());
Aws::String name = "Unknown";
const auto &tags = instance.GetTags();
auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
[](const Aws::EC2::Model::Tag &tag)
{
return tag.GetKey() == "Name";
});
if (nameIter != tags.cend())
{
name = nameIter->GetValue();
}
Server::id_ = instance.GetInstanceId();
Server::name_ = name;
Server::type_ = type_string;
Server::dn_ = "Not implemented";
Server::ip_ = "Not implmented";
}
}
} else {
Server::id_ = "Could not find: "+ instanceId;
Server::name_ = "";
Server::type_ = "";
Server::dn_ = "";
Server::ip_ = "";
}
}
return;
}

Response status code does not indicate success: '400' ('Bad request')

i want to POST data to API in my android xamarin app using refit i've tested the API at Postman and it's working fine but at android app i'm getting exception Bad request.
Here is my android code i added the interface and the model i don't know what is the problem .
public interface RequestAPI
{
[Post("/request")]
Task<create_request> submit([Body] create_request request);
}
requestAPI= RestService.For<RequestAPI>("http://courier-magconsulting.azurewebsites.net/api");
button.Click += async delegate
{
try
{
create_request request = new create_request();
request.PickUpPhone = "7664554";
request.DownPayment = 89;
request.DeliveryFees = 56.8;
request.Note = "i need a help!";
request.RequestID = 88; // replace the value yourself
request.DekiveryLocationLatitude = 2323;
request.DeliveryLocationLongitude = 232;
request.PickUpLocationLatitude = 898;
request.PickUpLocationLongitude = 1123;
BroadcastType type = new BroadcastType();
type.Name = "All";
type.ID = 60; // replace the value yourself
request.BroadcastType = type;
Cargosize size = new Cargosize();
size.Name = "Small";
size.ID = 1; // replace the value yourself
request.Cargosize = size;
Cargoweight weight = new Cargoweight();
weight.Name = "Large";
weight.ID = 2; // replace the value yourself
request.CargoWeight = weight;
Sender sender_ = new Sender();
sender_.Name = "Ahmad";
sender_.SenderID = 1; // replace the value yourself
sender_.Phone = "8788";
sender_.SocialID = "8787";
sender_.RatingAvg = 5;
SenderStatus status = new SenderStatus();
status.ID = 1;
status.Name = "Active";
sender_.Senderstatus = status;
request.Sender = sender_;
create_request result = await requestAPI.submit(request);
Toast.MakeText(this, "Request created", ToastLength.Long).Show();
}
catch(Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
};

While Mail body being received, how to fetch the Image from multipart body

My application actually has mail send / receive functionalities to handle.
While receiving the mail, i am unable to view the image which is an inline image being sent from outlook.
Can some one help me how can i catch the image and make available always.
I have java code like below,
try (InputStream stream = new ByteArrayInputStream(Base64
.getMimeDecoder().decode(mail))) {
MimeMessage message = new MimeMessage(null, stream);
Object messageContent = message.getContent();
if (messageContent instanceof String) {
body = (String) messageContent;
} else if (messageContent instanceof MimeMultipart) {
content = (MimeMultipart) messageContent;
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
String disposition = bodyPart.getDisposition();
if (disposition == null
|| disposition
.equalsIgnoreCase(Part.INLINE)) {
Object object = bodyPart.getContent();
if (object instanceof String) {
body = object.toString();
} else if (object instanceof MimeMultipart) {
MimeMultipart mimeMultipart = (MimeMultipart) object;
String plainBody = null;
String htmlBody = null;
for (int j = 0; j < mimeMultipart.getCount(); j++) {
BodyPart multipartBodyPart = mimeMultipart
.getBodyPart(j);
String multipartDisposition = multipartBodyPart
.getDisposition();
String multipartContentType = multipartBodyPart
.getContentType();
if (multipartDisposition == null
&& multipartContentType != null) {
if (multipartContentType
.contains(MediaType.TEXT_HTML)) {
htmlBody = multipartBodyPart
.getContent().toString();
} else if (multipartContentType
.contains(MediaType.TEXT_PLAIN)) {
plainBody = multipartBodyPart
.getContent().toString();
}
}
}
if (htmlBody != null) {
body = htmlBody;
} else {
body = plainBody;
}
}
}
}
}
Client side i am using CKEditor to handle email body data.
Thanks a lot.
i got a solution from the example shared below
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
But, this example explains, how to find the image in body and store.
I have also done below to replace src
`
Pattern htmltag = Pattern.compile("]src=\"[^>]>(.?)");
Pattern link = Pattern.compile("src=\"[^>]\">");
String s1 = "";
Matcher tagmatch = htmltag.matcher(s1);
List<String> links = new ArrayList<String>();
while (tagmatch.find()) {
Matcher matcher = link.matcher(tagmatch.group());
matcher.find();
String link1 = matcher.group().replaceFirst("src=\"", "")
.replaceFirst("\">", "")
.replaceFirst("\"[\\s]?target=\"[a-zA-Z_0-9]*", "");
links.add(link1);
s1 = s1.replaceAll(link1, "C:\\//Initiatives_KM\\//image.jpg");
}
`
And on top of this, i gonna do Base64 encoding so that i dont require store in file system.
encodedfileString = Base64.getEncoder().encodeToString(bArray);
With all these i can conclude to say, i got solution for my issue. Thank you.

Can't find way to debug Internal Server Error (500) caused by new class

I've read a lot of the postings about 500 errors because of the channel emulator, but this is not the case here. I took the standard bot template, which works just fine with the emulator, and replaced it with
ConnectorClient connector = new ConnectorClient(new
Uri(activity.ServiceUrl));
// calculate something for us to return
// int length = (activity.Text ?? string.Empty).Length;
string responseText=
***Bot_Application2.SilviaRestClass.GetRestResult(activity.Text);***
So the issue is in executing the GetRestResult method in the SilivaRestClass.
The code itself works, I'm using it in lots of other places, as it basically sets up a simple 1)get an input utterance in text, 2)send to my SILVIA AI server, and 3)get an utterance back routine. I have a feeling it has something to do with either private vs public methods, and/or [Serializable], based on what I have read so far. The code (minus the credentials) is below. Many thanks, in advance, for any suggestions to try.
`
bool exit = false;
restResponse = "Hello";
bool sessionNew = true;
string viewMessage = null;
string SILVIAUri = "";
string SILVIACore = "/Core/Create/unique/silName";
string SILVIASubmit = "/IO/SetInputManaged/unique/hello";
string SILVIARead = "/IO/GetAll/unique";
string SILVIARelease = "/Core/Release/{unique}";
string SILVIASubKey = "";
string silName = "";
string returnMessage = null;
string holdit = null;
string holdit2 = null;
int forHold = 0;
string responseFromServer = null;
string isfalse = "false";
string myURI = null;
string unique = null;
//CREATE CORE from SILVIA SERVER
myURI = SILVIAUri + SILVIACore;
myURI = myURI.Replace("silName", silName);
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest request = WebRequest.Create(myURI);
request.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
if (sessionNew)
{
Random rnd1 = new Random();
unique = rnd1.Next().ToString() + "askgracie";
sessionNew = false;
WebResponse wResponse = request.GetResponse();
Stream dataStream = wResponse.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
// Clean up the streams and the response.
reader.Close();
wResponse.Close();
}
//SEND UTTERANCE to SILVIA
holdit = null;
myURI = null;
myURI = SILVIAUri + SILVIASubmit;
holdit = restResponse;
// holdit = HttpUtility.UrlEncode(holdit);
myURI = myURI.Replace("hello", holdit);
myURI = myURI.Replace("unique", unique);
if (holdit == "exit")
{
exit = true;
myURI = SILVIAUri + SILVIARelease;
}
System.Net.WebRequest sendRequest = WebRequest.Create(myURI);
sendRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse sendResponse = sendRequest.GetResponse();
Stream sendStream = sendResponse.GetResponseStream();
StreamReader sendReader = new StreamReader(sendStream);
string send_ResponseFromServer = sendReader.ReadToEnd();
// Clean up the streams and the response.
sendReader.Close();
sendResponse.Close();
holdit = send_ResponseFromServer;
forHold = holdit.IndexOf("success");
holdit2 = holdit.Substring(forHold + 9, 5);
if (holdit2 == isfalse)
{
var simpleUtterResponse = "The bot failed to send the
utterance to SILVIA";
}
//GETRESPONSES FROM SILVIA
returnMessage = null;
holdit = null;
responseFromServer = null;
myURI = SILVIAUri + SILVIARead;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest readRequest = WebRequest.Create(myURI);
readRequest.Headers["Ocp-Apim-Subscription-Key"] = SILVIASubKey;
WebResponse readResponse = readRequest.GetResponse();
Stream readStream = readResponse.GetResponseStream();
StreamReader readReader = new StreamReader(readStream);
string read_ResponseFromServer = readReader.ReadToEnd();
viewMessage = read_ResponseFromServer;
string lastRead = "ID ";
List<string> myArray = new List<string>(viewMessage.Split(new
string[] { "\r\n" }, StringSplitOptions.None));
foreach (string s in myArray)
{
if (lastRead == "type: voice")
{
returnMessage = returnMessage + " " + s.Substring(8);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
if (s.Length < 11)
{ lastRead = s;
}
else
{ lastRead = s.Substring(0, 11);
}
}
// Clean up the streams and the response.
//readReader.Close();
//readResponse.Close();
if (exit)
{
myURI = SILVIAUri + SILVIARelease;
myURI = myURI.Replace("unique", unique);
System.Net.WebRequest closeRequest =
WebRequest.Create(myURI);
closeRequest.Headers["Ocp-Apim-Subscription-Key"] =
SILVIASubKey;
WebResponse closeResponse = closeRequest.GetResponse();
}
return returnMessage;
}
}
}`
I ended up resolving this by cut/paste the class inside the same namespace and physical .cs file. – Brian Garr just now edit

j2me midlet chinese character display message garbled

My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?

Resources