scalatra < squeryl < select ALL | Always - scalatra

I want to read elements from the database and return them as JSON objects.
Scalatra is set up to return JSON.
Databaseschema is created.
Players are added.
The following code seems to be the main problem:
get("/") {
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)))
}
}
I get the following error:
"No session is bound to current thread, a session must be created via Session.create and bound to the thread via 'work' or 'bindToCurrentThread' Usually this error occurs when a statement is executed outside of a transaction/inTrasaction block "
I want to do it right so simply adding something like "Session.create" may not really be the right way.
Can anyone help a scalatra-noob? :-)

I think that your comment is on the right track. The inTransaction block will bind a JDBC connection to a thread local variable and start the connection on it. If the select doesn't occur on the same thread, you'll see an error like the one your received. There are two things I would suggest that you try:
Start your transaction later
List(inTransaction {
from(MassTournamentSchema.players)(s => select(s))
})
I'm not familiar with Scalatra's List, but it's possible that it's accepting a by-name parameter and executing it later on a different thread.
Force an eager evaluation of the query
inTransaction {
List(from(MassTournamentSchema.players)(s => select(s)).toList)
}
Here the .toList call will turn the Query object Squeryl returns into a Scala List immediately and guard against any lazy evaluation errors caused by later iteration.

Related

Emberjs inside of get computed making request to backend multiple times cause infinite loop

I have a table basically in every row i have get function that makes a backend request with store service. But somehow when there is one row it works expect, but when there is multiple rows it always try to recalculate get function which makes sending infinite request to backend. I am using glimmer component
I cannot use model relation on ember side at this point, there is deep chain on backend side. Thats why i am making backend request.
get <function_name>() {
return this.store.query('<desired_model_name>', { <dependent1_id>: <dependent1_id_from_args>, <dependent2_id>: <dependent2_id_from_args> });
}
I fixed this problem with using constructor. But do you have any idea why this get function re-calculate all the time? Dependent_ids are constant.
Weird thing is when results are [] empty array it does not re calculate every time. Even the query results are same it still try to recalculate every time and making infinite request to backend.
But do you have any idea why this get function re-calculate all the time?
When something like this happens, it's because you're reading #tracked data that is changed later (maybe when the query finishes).
because getters are re-ran every access, you'll want to throw #cached on top of it,
// cached is available in ember-source 4.1+
// or as early as 3.13 via polyfill:
// https://github.com/ember-polyfills/ember-cached-decorator-polyfill
import { cached } from '#glimmer/tracking';
// ...
#cached
get <function_name>() {
return this.store.query(/* ... */);
}
this ensures a stable object reference on the getter that the body of the getter only re-evaluates if tracked data accessed within the getter is changed.
Weird thing is when results are [] empty array it does not re calculate every time. Even the query results are same it still try to recalculate every time and making infinite request to backend.
Given this observation, it's possible that when query finishes, that it's changing tracked data that it, itself is consuming during initial render -- in which case, you'd still have an infinite loop, even with #cached (because tracked-data is changing that was accessed during render).
To get around that is fairly hard in a getter.
Using a constructor is an ok solution for getting your initial data, but it means you opt out of reactive updates with your query (if you need those, like if the query changes or anything).
If you're using ember-source 3.25+ and you're wanting something a little easier to work with, maybe ember-data-resourecs suits your needs
the above code would be:
import { query } from 'ember-data-resources';
// ...
// in the class body
data = query(this, 'model name', () => ({ query stuff }));
docs here
This builds off some primitives from ember-resources which implement the Resource pattern, which will be making a strong appearance in the next edition of Ember.

Lucee/Adobe ColdFusion - Setting/getting information from thread{}

I'm working on creating a simple email server status page that calls two different CFCs.
The status page requirements:
Query a MariaDB database table via a CFC and return data from two fields: server_name (ie. MyServerName) & server_domain (ie. mail.domain.com). Currently, there are 4 rows in the database table to pull.
Hand the database data from step 1 to a CFC that checks if port 25 is listening. If the CFC can reach port 25 the result is true, if not the result is false. This step needs to be threaded.
Hand the boolean result from step 2 through a loop to print the server_name and boolean result.
Output something similar to this:
MyServerName - <up arrow>
MyServerName2 - <up arrow>
MyServerName3 - <up arrow>
MyServerName4 - <down arrow>
The code:
RetrieveEmailServers = APPLICATION.selectQueries.RetrieveEmailServers()
if (RetrieveEmailServers.recordCount) {
for(i = 1; i <= RetrieveEmailServers.recordCount(); i++) {
LOCAL.theDomains = RetrieveEmailServers.check_servers_domain[i];
LOCAL.theNames = RetrieveEmailServers.check_servers_name[i];
thread action="run" name="thread#i#" theDomains="#LOCAL.theDomains#" theNames="#LOCAL.theNames#" {
VARIABLES.theServers = APPLICATION.emailCheck.checkSMTPServer('#domains#',25,'','');
}
}
thread action="join" timeout="6000"{}
for(i = 1; i <= RetrieveEmailServers.recordCount(); i++) {
VARIABLES.theResult = cfthread["thread#i#"];
if (VARIABLES.theResult.theServers) {
LOCAL.theStatus = "<i class='fad fa-angle-double-up text-success fs-1'></i>"
}
else {
LOCAL.theStatus = "<i class='fad fa-angle-double-down text-danger fs-1'></i>"
}
writeOutput(ATTRIBUTES.theNames & " - " & LOCAL.theStatus & "<br>");
}
}
else {
writeOutput("No servers listed at this time.")
}
The error: The key [THESERVERS] does not exist, the structure is empty
For consideration:
I know my code is not great and I know it could be written better. I'm working hard to improve.
I'm not a full time coder but I have been coding off and on for many
years. I still consider myself a newbie with CFML so a lot of the methodology goes over my head.
The above code mostly works but I'm having difficulty understanding
how to pass information outside of a CFTHREAD to be used in the rest
of the page, especially when dealing with CFLOOP.
I have read many times, but still don't completely understand, how
to correctly use the thread-local scope, the Thread scope and the
Attributes scope.
The code above has a simple task, to check a port, but the end goal is to use similar code for other parts of my application. I'm aware there are better monitoring tools available; this is an exercise to help me understand and learn.
Specific to Lucee, I'm aware that threadData()['thread#i#'].status; or similar may be a required modification to cfthread[].
Attributes
The Attributes scope is only for holding values passed into a thread. Therefore, the scope is short-lived and only exists within a thread. Each thread has its own "attributes" scope, which doesn't exist before that thread runs or after it completes.
For example, this snippet passes in an attribute named "theDomains". The variable Attributes.theDomains only exists inside the thread.
thread action="run" name="thread1" theDomains="example.com" {
writeDump( attributes.theDomains );
}
thread action="join" name="thread1" {};
writeOutput( thread1.output );
Thread-local
"Thread-local" is another short-lived scope whose purpose is to hold variables used only within a thread. Each thread has its own private "local" scope, separate from all other threads. Like the attributes scope, it only exists while a thread is executing and is wiped out when the thread completes.
For example, this snippet creates a local variable named "MyLocalVar". Displaying the thread output demonstrates the variable exists within the thread
thread action="run" name="thread1" {
// Un-scoped v
myLocalVar = "foo";
writeOutput( "myLocalVar ="& myLocalVar );
}
thread action="join" name="thread1" {};
writeOutput( thread1.output );
But attempting to access it after the thread completes will cause an error
// fails with error "key [MYLOCALVAR] doesn't exist"
writeOutput( "myLocalVar ="& thread1.myLocalVar );
Thread Scope
The Thread scope has a longer life-span. It's designed to store "..thread-specific variables and metadata about the thread...". More importantly, this scope can be used to pass information back to the calling page (or even other threads).
For example, this snippet creates a thread scoped variable that's visible to the calling page, even after the thread completes its execution:
thread action="run" name="thread1" {
// use scope prefix "thread."
thread.myThreadVar = "foo";
}
thread action="join" name="thread1" {};
writeOutput( "thread1.myThreadVar="& thread1.myThreadVar );
writeDump( thread1 );
The Problem: key [THESERVERS] does not exist
When you've been looking at an error for what feels like days, it's easy to forget the basics :) First thing to do with undefined errors is dump the object and see if actually contains what you expected before trying to use it.
for(i = 1; i <= RetrieveEmailServers.recordCount(); i++) {
VARIABLES.theResult = cfthread["thread#i#"];
writeDump( variables.theResult );
/* temporarily comment out rest of code
...
*/
}
A dump of VARIABLES.theResult shows the threads are actually failing with a different error
Due to the wrong attribute name within the thread. It should be attributes.theDomains, not domains.
thread ...{
APPLICATION.emailCheck.checkSMTPServer( attributes.theDomains, ... );
}
Okay, I fixed it. Still getting "key [THESERVERS] does not exist", now what?
Another dump of the threads reveals the error message wasn't lying. The threads really DON'T contain a variable named theServers, due to incorrect scoping. Use the thread scope, not `variables.
thread ...{
thread.theServers = ....;
}
Yet another error?! variable [ATTRIBUTES] doesn't exist
Even after fixing the previous two issues, you'll still get yet another error here
for(i = 1; i <= RetrieveEmailServers.recordCount(); i++) {
...
writeOutput(ATTRIBUTES.theNames & " - " & LOCAL.theStatus & "<br>");
}
Remember the attributes scope only exists within a thread. So obviously it can't be used once the thread is completed. Either store theNames in the thread scope too, or since you're looping through a query, use the query column value, RetrieveEmailServers.the_query_column_name[ i ].
Joining threads
One last potential problem. The join statement isn't actually waiting for the threads you created. It's just waiting for 6000 ms. If for some reason any of the threads take longer than that, you'll get an error when trying to retrieve the thread results. To actually wait for the threads created, you must use thread action="join" name=(list of thread names) {}. I'll leave that as an exercise for the reader (:
Tbh, there are other things that could be cleaned up and/or improved, but hopefully this long rambling thread explains WHY the errors occurred in the first place AND how to avoid them when working with threads in future

Rolling back a deletion to handle a server error in Ember.js

We have an Ember.js application which uses Ember Data. We are trying to do the following:
Delete a record.
If there is a server error (due to the fact that the application can have a "locked" state where records can not be deleted), roll the record back to its previous state, prompt the user to unlock app, and continue.
If there is no server error, continue as normal.
We have found that this does not work
object.destroyRecord().then ->
# handle success
, (reason)->
object.rollback()
# prompt for the unlock
In both cases, we see an error that looks like:
Error: Assertion Failed: calling set on destroyed object
But it isn't clear how to remove the isDestroyed state once it has been set.
In general, it seems that, in either case, once we call destroyRecord, there is no way to rollback the changes to a pre-deleted state once, even if there is a server error.
Try deleteRecord, followed by save. The docs explicitly state that this allows you to rollback on error.
object.deleteRecord()
object.save().then( ->
# handle success
, (reason) ->
object.rollback()
)
I've found that you need to put the rollback call in becameError() function.
// Overwrite default destroyRecord
destroyRecord: function () {
this.deleteRecord();
this.save().then(
function (){
//Success
},
function () {
//Failure
}
);
},
becameError: function (item) {
this.rollback();
}
The item will disappear from views until the server returns the error and then magically reappear.

Unit-testing a simple usage of RACSignal with RACSubject

(I may be using this in a totally incorrect manner, so feel free to challenge the premise of this post.)
I have a small RACTest app (sound familiar?) that I'm trying to unit test. I'd like to test MPSTicker, one of the most ReactiveCocoa-based components. It has a signal that sends a value once per second that accumulates, iff an accumulation flag is set to YES. I added an initializer to take a custom signal for its incrementing signal, rather than being only timer-based.
I wanted to unit test a couple of behaviours of MPSTicker:
Verify that its accumulation signal increments properly (i.e. monotonically increases) when accumulation is enabled and the input incrementing signal sends a new value.
Verify that it sends the same value (and not an incremented value) when the input signal sends a value.
I've added a test that uses the built-in timer to test the first increment, and it works as I expected (though I'm seeking advice on improving the goofy RACSequence initialization I did to get a signal with the #(1) value I wanted.)
I've had a very difficult time figuring out what input signal I can provide to MPSTicker that I can manually send values to. I'm envisioning a test like:
<set up ticker>
<send a tick value>
<verify accumulated value is 1>
<send another value>
<verify accumulated value is 2>
I tried using a RACSubject so I can use sendNext: to push in values as I see fit, but it's not working like I expect. Here's two broken tests:
- (void)testManualTimerTheFirst
{
// Create a custom tick with one value to send.
RACSubject *controlledSignal = [RACSubject subject];
MPSTicker *ticker = [[MPSTicker alloc] initWithTickSource:controlledSignal];
[ticker.accumulateSignal subscribeNext:^(id x) {
NSLog(#"%s value is %#", __func__, x);
}];
[controlledSignal sendNext:#(2)];
}
- (void)testManualTimerTheSecond
{
// Create a custom tick with one value to send.
RACSubject *controlledSignal = [RACSubject subject];
MPSTicker *ticker = [[MPSTicker alloc] initWithTickSource:controlledSignal];
BOOL success = NO;
NSError *error = nil;
id value = [ticker.accumulateSignal asynchronousFirstOrDefault:nil success:&success error:&error];
if (!success) {
XCTAssertTrue(success, #"Signal failed to return a value. Error: %#", error);
} else {
XCTAssertNotNil(value, #"Signal returned a nil value.");
XCTAssertEqualObjects(#(1), value, #"Signal returned an unexpected value.");
}
// Send a value.
[controlledSignal sendNext:#(1)];
}
In testManualTimerTheFirst, I never see any value from controlledSignal's sendNext: come through to my subscribeNext: block.
In testManualTimerTheSecond, I tried using the asynchronousFirstOrDefault: call to get the first value from the signal, then manually sent a value on my subject, but the value didn't come through, and the test failed when asynchronousFirstOrDefault: timed out.
What am I missing here?
This may not answer your question exactly, but it may give you insights on how to effectively test your signals. I've used 2 approaches myself so far:
XCTestCase and TRVSMonitor
TRVSMonitor is a small utility which will pause the current thread for you while you run your assertions. For example:
TRVSMonitor *monitor = [TRVSMonitor monitor];
[[[self.service searchPodcastsWithTerm:#"security now"] collect] subscribeNext:^(NSArray *results) {
XCTAssertTrue([results count] > 0, #"Results count should be > 0";
[monitor signal];
} error:^(NSError *error) {
XCTFail(#"%#", error);
[monitor signal];
}];
[monitor wait];
As you can see, I'm telling the monitor to wait right after I subscribe and signal it to stop waiting at the end of subscribeNext and error blocks to make it continue executing (so other tests can run too). This approach has the benefit of not relying on a static timeout, so your code can run as long as it needs to.
Using CocoaPods, you can easily add TRVSMonitor to your project:
pod "TRVSMonitor", "~> 0.0.3"
Specta & Expecta
Specta is a BDD/TDD (behavior driven/test driven) test framework. Expecta is a framework which provides more convenient assertion matchers. It has built-in support for async tests. It enables you to write more descriptive tests with ReactiveCocoa, like so:
it(#"should return a valid image, with cache state 'new'", ^AsyncBlock {
[[cache imageForURL:[NSURL URLWithString:SECURITY_NOW_ARTWORK_URL]] subscribeNext:^(UIImage *image) {
expect(image).notTo.beNil();
expect(image.cacheState).to.equal(JPImageCacheStateNew);
} error:^(NSError *error) {
XCTFail(#"%#", error);
} completed:^{
done();
}];
});
Note the use of ^AsyncBlock {. Using simply ^ { would imply a synchronous test.
Here you call the done() function to signal the end of an asynchronous test. I believe Specta uses a 10 second timeout internally.
Using CocoaPods, you can easily add Expecta & Specta:
pod "Expecta", "~> 0.2.3"
pod "Specta", "~> 0.2.1"
See this question: https://stackoverflow.com/a/19127547/420594
The XCAsyncTestCase has some extra functionality to allow for asynchronous test cases.
Also, I haven't looked at it in depth yet, but could ReactiveCocoaTests be of some interest to you? On a glance, they appear to be using Expecta.

Asynchronous network calls

I made a class that has an asynchronous OpenWebPage() function. Once you call OpenWebPage(someUrl), a handler gets called - OnPageLoad(reply). I have been using a global variable called lastAction to take care of stuff once a page is loaded - handler checks what is the lastAction and calls an appropriate function. For example:
this->lastAction == "homepage";
this->OpenWebPage("http://www.hardwarebase.net");
void OnPageLoad(reply)
{
if(this->lastAction == "homepage")
{
this->lastAction = "login";
this->Login(); // POSTs a form and OnPageLoad gets called again
}
else if(this->lastAction == "login")
{
this->PostLogin(); // Checks did we log in properly, sets lastAction as new topic and goes to new topic URL
}
else if(this->lastAction == "new topic")
{
this->WriteTopic(); // Does some more stuff ... you get the point
}
}
Now, this is rather hard to write and keep track of when we have a large number of "actions". When I was doing stuff in Python (synchronously) it was much easier, like:
OpenWebPage("http://hardwarebase.net") // Stores the loaded page HTML in self.page
OpenWebpage("http://hardwarebase.net/login", {"user": username, "pw": password}) // POSTs a form
if(self.page == ...): // now do some more checks etc.
// do something more
Imagine now that I have a queue class which holds the actions: homepage, login, new topic. How am I supposed to execute all those actions (in proper order, one after one!) via the asynchronous callback? The first example is totally hard-coded obviously.
I hope you understand my question, because frankly I fear this is the worst question ever written :x
P.S. All this is done in Qt.
You are inviting all manner of bugs if you try and use a single member variable to maintain state for an arbitrary number of asynchronous operations, which is what you describe above. There is no way for you to determine the order that the OpenWebPage calls complete, so there's also no way to associate the value of lastAction at any given time with any specific operation.
There are a number of ways to solve this, e.g.:
Encapsulate web page loading in an immutable class that processes one page per instance
Return an object from OpenWebPage which tracks progress and stores the operation's state
Fire a signal when an operation completes and attach the operation's context to the signal
You need to add "return" statement in the end of every "if" branch: in your code, all "if" branches are executed in the first OnPageLoad call.
Generally, asynchronous state mamangment is always more complicated that synchronous. Consider replacing lastAction type with enumeration. Also, if OnPageLoad thread context is arbitrary, you need to synchronize access to global variables.