NPNInvoke - Passing plugin data back to browser - npapi

I am calling back an object in Javascript using NPAPI. Before this call, the functions I am calling result in proper invocation of functions in JavaScript but it fails in NPN_Invoke calls.
Code Snippet:
sBrowserFuncs->releaseobject(object_temp);
object_temp = NPVARIANT_TO_OBJECT(args[0]);
sBrowserFuncs->retainobject(object_temp);
if (send_msg1(sBrowserFuncs, instance, msg_rcv, NPVARIANT_TO_OBJECT(args[0]), msg, name_id))
sendmsg1 spawns a new thread and this thread calls msg_rcv back. Is it okay for spawned thread to call the main thread function, is that reason of error.
...
Her call to NPN_Invoke is called
NPVariant from;
STRINGZ_TO_NPVARIANT(sdata->from, from);
NPIdentifier methodId = NPN_GetStringIdentifier("new_msg");
int res = NPN_Invoke(sdata->instance, object_temp, methodId, &from, 1, &result);
sdata->instance matches with instance
object_temp is last called object stored
It returns 0, while in successful case it returns 1.
In which case NPN_Invoke generates 0,

As far as i know , any NPN_* call should be issued from the plugin thread. You can check NPN_PluginThreadAsyncCall. I this way you can execute methods from another thread , on the main/plugin thread and avoid a nasty crash :)

Related

Can you help me make sense of this class constructor? (Adafruit_ATParser)

I am building a device for my research team. To briefly describe it, this device uses a motor and load sensor connected to an Arduino to apply a rotational force to a corn stalk and record the resistance of the stalk. We are in the process of building Bluetooth into the device. We are using this BT module.
We have a BLE GATT Service with 2 characteristics for storing DATA and 1 for holding the command which is an integer that will be read by the device and acted on. Reading the command characteristic is where we encounter our problem.
void get_input(){
uint16_t bufSize = 15;
char inputBuffer[bufSize];
bleParse = Adafruit_ATParser(); // Throws error: bleParse was not declared in this scope
bleParse.atcommandStrReply("AT+GATTCHAR=3",&inputBuffer,bufSize,1000);
Serial.print("input:");
Serial.println(inputBuffer);
}
The functions I am trying to use are found in the library for the module in Adarfruit_ATParser.cpp
/******************************************************************************/
/*!
#brief Constructor
*/
/******************************************************************************/
Adafruit_ATParser::Adafruit_ATParser(void)
{
_mode = BLUEFRUIT_MODE_COMMAND;
_verbose = false;
}
******************************************************************************/
/*!
#brief Send an AT command and get multiline string response into
user-provided buffer.
#param[in] cmd Command
#param[in] buf Provided buffer
#param[in] bufsize buffer size
#param[in] timeout timeout in milliseconds
*/
/******************************************************************************/
uint16_t Adafruit_ATParser::atcommandStrReply(const char cmd[], char* buf, uint16_t bufsize, uint16_t timeout)
{
uint16_t result_bytes;
uint8_t current_mode = _mode;
// switch mode if necessary to execute command
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_COMMAND);
// Execute command with parameter and get response
println(cmd);
result_bytes = this->readline(buf, bufsize, timeout, true);
// switch back if necessary
if ( current_mode == BLUEFRUIT_MODE_DATA ) setMode(BLUEFRUIT_MODE_DATA);
return result_bytes;
}
None of the examples in the library use this. They all create their own parsers. For example, the neopixel_picker example sketch has a file called packetParser.cpp which I believe retrieves data from the BT module for that specific sketch, but it never includes or uses Adafruit_ATParser.. There are no examples of this constructor anywhere and I cannot figure out how to use it. I have tried these ways:
bleParse = Adafruit_ATParser();
Adafruit_ATParser bleParse();
Adafruit_ATParser();
ble.Adafruit_ATParser bleParse();
note: ble is an object that signifies a Serial connection between arduino and BT created with:
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
Can anyone give me a clue on how to use the Adafruit_ATParser() constructor? Also, if the constructor has no reference to the ble object, how does it pass AT commands to the BT module?
I know this is a big ask, I appreciate any input you can give me.
Like this
Adafruit_ATParser bleParse;
You were closest with this one Adafruit_ATParser bleParse();. This is a common beginner mistake because it looks right. Unfortunately it declares a function bleParse which takes no arguments and returns a Adafruit_ATParser object.
I can't answer the second question.
EDIT
I've taken the time to have a look at the code. This is what I found
class Adafruit_BluefruitLE_UART : public Adafruit_BLE
{
and
class Adafruit_BLE : public Adafruit_ATParser
{
what this means is that the Adafruit_BluefruitLE_UART class is derived from the Adafruit_BLE class which in turn is derived from the Adafruit_ATParser class. Derivation means that any public methods in Adafruit_BLE can also be used on a Adafruit_BluefruitLE_UART object. You already have an Adafruit_BluefruitLE_UART object (you called it ble) so you can just use the method you want to use on that object.
SoftwareSerial bluefruitSS = SoftwareSerial(BLUEFRUIT_SWUART_TXD_PIN, BLUEFRUIT_SWUART_RXD_PIN);
Adafruit_BluefruitLE_UART ble(bluefruitSS, BLUEFRUIT_UART_MODE_PIN,BLUEFRUIT_UART_CTS_PIN, BLUEFRUIT_UART_RTS_PIN);
ble.atcommandStrReply( ... );

ColdFusion GC Overhead Limit while looping over API Json Response

To start, I understand what the "GC Overhead limit" error means, in general. I received this message while running a script that does the following:
Create Instance of an object that makes a CFHTTP GET request to an external API
Store JSON response (an array) as a property of the object Instance (i.e. VARIABLES.data)
Loop through the JSON response array using a for in loop
Create an instance on an object that calls a SQL Server Stored Procedure passing in the properties of the JSON object (the SQL Stored Procedure performs and UPDATE or INSERT based on the existence of a record for the object's key)
Debug output shows that the SP call takes between 3-12 milliseconds.
When I run this script with a limited dataset (~3,000 records), it runs to completion without throwing a GC exception.
When I run the script with the complete dataset (~14,000 records), the GC exception is thrown.
Here's my pseudo-code:
for (LOCAL.WidgetJson in VARIABLES.data) {
LOCAL.Widget=new Widget();
LOCAL.Widget
.save(argumentCollection=LOCAL.WidgetJson);
}
Widget.cfc:
private void function saveStoredProc() {
cfstoredproc(procedure="SaveWidget") {
cfprocparam(
dbvarname="#id",
type="in",
cfsqltype="CF_SQL_INT",
value=VARIABLES.id
);
<!--- Rest of cfprocparam() tags here --->
}
private void function save() {
for (LOCAL.Property in ARGUMENTS) {
if (StructKeyExists(ARGUMENTS, LOCAL.Property)) {
if (IsSimpleValue(ARGUMENTS[LOCAL.Property])) {
VARIABLES[LOCAL.Property] = Trim(ARGUMENTS[LOCAL.Property]);
}
else {
VARIABLES[LOCAL.Property] = ARGUMENTS[LOCAL.Property];
}
}
}
saveStoredProc();
}
I'm wondering if the way that I'm creating objects or looping could be improved to prevent GC exceptions/memory leaks.
Any ideas for improvements?
I don't think the garbage collection will happen during a single request even if it is necessary. You could either increase memory or split this into multiple threads that process smaller amounts of data.

How to detect a transaction that will fail in web3js

I've just recently finished working on a rather complex contract with the Remix IDE. I'm now attaching web3 to the frontend but when I call functions that should fail, they still go through on Metamask.
When testing my contract in Remix, I would often click on and call certain functions that had require statements that I knew would fail just to confirm that the contract state was recorded correctly. Remix didn't send the transaction to metamask and instead output an error message and I would like to handle the transaction error on my own as well.
How can I check my contract call to see whether it will fail. Must I use the method that predicts gas and detect it that way and if so how? My current code is below:
contract.callFunction(function(error, result) {
if (!error) alert(result);
else alert(error);
}
The above code catches rejecting the metamask confirmation as an error but transactions that should fail go through to metamask with an insanely high gas limit set. The function callFunction is in the contract and takes no parameters but does have an effect on the blockchain so it requires the transaction. The first line of the function is "require(state == 1);" and I have the contract set to state 2 currently so I'm expecting the transaction to fail, I just want to detect it failing.
In order to find out whether the transaction will fail we do have to call estimateGas() and attach a callback function. I assumed we'd have to check the gas estimate returned in order to predict whether it would fail but the process is made rather easy. Here's the full code I ended up with to successfully run a function while catching the two most common error cases.
contract.nextState.estimateGas(function(error, result) {
if (!error) {
contract.nextState(function(error, result) {
if (!error) {
alert("This is my value: " + result);
} else {
if (error.message.indexOf("User denied") != -1) {
alert("You rejected the transaction on Metamask!");
} else {
alert(error);
}
}
});
} else {
alert("This function cannot be run at this time.");
}
});
[EDIT] I'm coming back after the fact to help clear up information for those with a similar question. All of the information discussed below references the following link.
After creating a contract object, you can access any variable or function through using it's name. You can also access these members through array notation which is useful when the name of the variable or function isn't known at the time the code is written.
contract.foobar == contract["foobar"]
Once you have a function object (contract.foobar) you can use either call, send, or estimateGas. After first giving the function the parameters it needs (call it like any other function) you then use either call, send, or estimateGas on the returned object while providing options and a callback function.
This callback function takes 2 parameters. The first is the error which will be undefined if there was no error, and the second will be the result of the call, send, or estimateGas. Call and Send will both return the result of the function while estimateGas always returns a number showing how much gas is estimated to be necessary.

How to force play framework to log exceptions which are thrown in another thread?

I have a function which is running in the separate thread. The code which calls this function not waits for result of it.
def sendEmail(email: String): Future[Unit] = {
...
}
def registration: Future[User] = {
...
// I do not want to wait for result of this function, just fire email sending
// in seprate thread and continue
sendEmail(email)
...
// Do another job
}
The problem is that if something went wrong in sendEmail function, I want to see this exception in log file.
Now log file and console output are empty if some exception is thrown there.
Is there a way to log exceptions from that separate thread?
P.S.: I do not want to log exception manually in sendEmail, but force play framework to log it.
In general, you wrap exceptions in the exceptionally block.
In java, it's like :
foobar.thenComposeAsync(arg -> {
sendEmail();
}).exceptionally(throwable -> {
// Do logging
});

Zend_Json_Server and dojo.rpc.JsonService, can a served class return an object?

I am trying to serve up my user repository via zend_json_server. The problem is the service is returning empty objects. What have i missed?
server side:
$repo = App_User_Repository::getInstance();
$server = new Zend_Json_Server();
$server->setClass($repo);
if ('GET' == $_SERVER['REQUEST_METHOD']) {
$server->setTarget('/service/json-rpc.php')
->setEnvelope(Zend_Json_Server_Smd::ENV_JSONRPC_2);
$smd = $server->getServiceMap();
// Set Dojo compatibility:
$smd->setDojoCompatible(true);
header('Content-Type: application/json');
echo $smd;
return;
}
$server->handle();
client side:
var object = new dojo.rpc.JsonService('/service/json-rpc.php');
var deferred = object.getById(1);
deferred.addBoth(function(result) {console.log(result)});
Firebug console output:
Object {}
This should be a User object
When doing the actual RPC with the "getById()" method, an dojo.deferred object is returned. At this point, a asynchronous request is running. By using the deferred object, you can define callbacks and error handlers in advance whilst waiting for the response to be returned.
Check if the actual response object isn't empty as well. Remember, you still have to use the return keyword in your attached classes to return results back to Zend_Json_Server. Zend_Json_Server will then serialize and send back the returned value automatically. A response from Zend_Json_Server is always a serialized object in JSON, containing an id (which increments automatically with each request), an string indicating what jsonrpc version is being used (ie. 2.0) and of course a result containing the returned data from the attached class.
The setClass() method should not be a object instance, but a string containing the className of the class you want to attach. Zend_Json_Server handles the creation of the object instance by itself, as well as generating the SMD (Service Method/Mapper Description). Remember to document each public method with docblocks, as Zend_Json_Server uses those docblocks to determine the SMD.
Furthermore, it is much more handy to use a fluent-like interface with the then() method like so:
var myService = new dojo.rpc.JsonService('/service/json-rpc.php?');
var deferredObj = myService.doThis('myArgument');
deferredObj.then(callback, errorHandler).then(afterCallback).then(cleanUp);
In above example, the variables callback, errorHandler, afterCallback and cleanUp, are actually references to functions. The first then() method you call, automatically passes the rpc result to the callback function. If you throw an exception from within the attached rpc class, the errorHandler method (second optional argument of the first then() method call) will be called instead.
More information: http://www.sitepen.com/blog/2010/05/03/robust-promises-with-dojo-deferred-1-5/
I recently ran into the same problem and it wasn't a problem with dojo deferred. I'm assuming getById(1) is your remote function call, in which case if your server finds results dojo shouldn't get the empty object. Even using addBoth method on a deferred object would still show the result from the server, which leads me to believe your problem is not in any of the code you've listed, but getById(1) call in your App_User_Repository class. Did you use Zend_Dojo_Data or something else to json encode before returning? That would clobber your result, Zend_Json_Server does the encoding for you.