Why isKeyInCache (by EHCache) return true when the element of key doesn't exist anymore? - ehcache

sometimes the method isKeyInCache return true, but the element of key doesn't exists anymore.
Example:
Element element = new Element("test", "hello ehcache");
element.setTimeToLive(60);
element.setEternal(false);
cache.put(element);
if immediately i call get:
Element element = cache.get(key);
return element.getObjectValue();
this works perfectly. but after 60 seconds, the method isKeyInCache return true , but the get method throws NullPointerException. Any idea why?
===
another example:
CacheManager manager = new CacheManager(MainTeste.class.getResourceAsStream("/ehcache.xml"));
Cache cache = manager.getCache("siaep");
System.out.println("exists? " + cache.isKeyInCache("hello"));
Element element = new Element("hello", "hello world");
element.setTimeToLive(10);
cache.put(element);
System.out.println("exists? " + cache.isKeyInCache("hello"));
Thread.sleep(1000 * 11);
System.out.println("exists? " + cache.isKeyInCache("hello"));
output:
exists? false
exists? true
exists? true

As stated in the javadoc, the isKeyInCache method is a pretty inexpensive way of checking whether a key is currently present in the cache. However, it does not perform any status check, so it will return true even if the mapping is currently expired.

Related

#returns throwing error when running locally on docker

I'm trying to return array of asset from transaction. So as per the syntax I have added #returns and #commit(false) in cto file but its throwing error as
✖ Installing business network. This may take a minute...
ParseException: Expected ")", "-", "false", "true", comment, end of
line, number, string or whitespace but "P" found. File
models/org.zcon.healthcare.cto line 370 column 10
Command failed
And when i'm removing the #returns annotation its not throwing any error.
And well its not throwing any error when i'm removing parameter "Patient[]" from #returns annotation.. But it's against the syntax right?
I'm running the application locally using docker swarm.
My docker composer version is v0.19.12
What's wrong? Is this any bug?
In case if you want to see the transaction definition in cto file.
#commit(false)
#returns(Patient[])
transaction SearchPatient{
o String firstName optional
o String lastName optional
}
And in logic file
/**
* Sample transaction
* #param {org.zcon.healthcare.SearchPatient} tx
* #returns{org.zcon.healthcare.Patient[]}
* #transaction
*/
async function SearchPatient(tx){
let queryString = `SELECT org.zcon.healthcare.Patient WHERE (`;
let conditions = [];
if (tx.hasOwnProperty('firstName')) {
var firstName =tx.firstName;
conditions.push(`(firstName == "${firstName}")`)
};
if (tx.hasOwnProperty('lastName')) {
var lastName = tx.lastName;
conditions.push(`(lastName == "${lastName}")`)
};
queryString += conditions.join(' AND ') + ')';
let finalQuery = buildQuery(queryString);
const searchPatient = await query(finalQuery);
if(searchPatient.length ==0){
throw "No Patient Records found!!"
}else
return searchPatient;
}
I've not seen this error with composer network install (deploying to a running Fabric) I did the network install just fine (see screenshot) with your model and code. I suggest that your error may lie elsewhere in your business network ? Can you add the complete sequence of what you got to get the error? How did you build your bna file?
I also tried your code (ending....):
const searchPatient = await query(finalQuery);
console.log("results are " + searchPatient);
console.log("element 1 of array is " + searchPatient[0]);
if(searchPatient.length ==0){
throw "No Patient Records found!!"
} else
return searchPatient;
}
and can see the returned results fine (as shown in console.log - just using a different network name obviously FYI)

Parse Cloud "beforeSave" not saving data

I'm using parse beforeSave method to save an order, here is the code:
//Before save an order - if finish - set priority to 0
Parse.Cloud.beforeSave("UserToOrders", function(request, response) {
Parse.Cloud.useMasterKey();
var preStatus = request.object.get("OrderStatus");
if (preStatus == "Finish") {
request.object.set("Priority",0);
console.log("beforeSave(\"UserToOrders\")\t Order (" + request.object.id + ") Status is 'Finish' So Priority set to '0'");
}
else {
console.log("beforeSave(\"UserToOrders\")\t Order (" + request.object.id + ") Status Changed to: " + preStatus);
request.object.set("OrderStatus",preStatus);
}
response.success();
});
Here is the log:
I2016-03-09T20:56:05.779Z]v136 before_save triggered for UserToOrders for user pSi0iCGJJe:
Input: {"original":{"ACL":{"*":{"read":true},"vxgEWFQ7eu":{"read":true,"write":true}},"OrderStatus":"Ready","OrderStatusActivity":"Active","ResturantID":"g1bzMQEXoj","TimeToBeReady":{"__type":"Date","iso":"2016-03-08T23:35:23.916Z"},"UserETA":{"__type":"Date","iso":"2016-03-08T23:35:23.916Z"},"UserID":"vxgEWFQ7eu","createdAt":"2016-03-08T21:06:06.605Z","objectId":"t3NoxcSp5z","updatedAt":"2016-03-08T21:40:59.538Z"},"update":{"OrderStatus":"Finish","objectId":"t3NoxcSp5z"}}
Result: Update changed to {"OrderStatus":"Finish","Priority":0}
I2016-03-09T20:56:05.975Z]beforeSave("UserToOrders") Order (t3NoxcSp5z) Status is 'Finish' So Priority set to '0'
but nothing is being changed in the DB.
What do i miss?
Thanks.
in var preStatus is the same value as you wanted to save...
var preStatus = request.object.get("OrderStatus");
and you are "saving" the same value, you can just delete this line
request.object.set("OrderStatus",preStatus);
if it is not what you want, provide the log from "OrderStatus" = Finish
I've figured it out. It was an ACL permissions issue.
The Order created by one client, while the chance made by another one.

How to continue running a mocha `it` that has already failed?

The following mocha it statement:
it('should do truthy and falsey things', function() {
var val = true;
assert.equal(val, true, "true should be true!");
console.log('state 1:', val);
val != val;
assert.equal(true, false, "should continue running even after failing");
console.log('state 2:', val);
val != val;
assert.equal(false, false, "false should be false!");
});
results in the following log:
state 1: true
1) should do truthy and falsey things
And that's it. Once the second assert fails, the rest of the function doesn't run.
Is it possible to have the rest of the function (in this case, the last three lines), and if so, how?
The most direct way to prevent an assertion failure from ending the test right there would be to catch the exception thrown by the failure and rethrow it later. However, I do not recommend doing this because this creates complications. If more than one test fails, which exception are you going to rethrow? Also, you have to remember to rethrow the exception you caught, otherwise the test will seem to be passing.
Generally I just live with the fact that if I have a test with multiple assertions then the the test will stop on the first failure. In cases where I cannot live with it, I've generally adopted a strategy of recording checks into a structure and then comparing the structure to an expected value at the very end of the test. There are many ways a structure can be constructed. Here's an example:
it('should allow multiple tests', function () {
var expected = {
"something should be true": true,
"something should be false": false,
"forgot this one": 1
};
var actual = {};
var thing_to_test = true;
// First test
actual["something should be true"] = thing_to_test;
// Second test
actual["something should be false"] = thing_to_test;
// We forget the third test.
assert.equal(actual, expected);
});
When I run the test above, I get the following output:
1) should allow multiple tests
0 passing (12ms)
1 failing
1) should allow multiple tests:
AssertionError: { 'something should be true': true,
'something should be false': true } == { 'something should be true': true,
'something should be false': false,
'forgot this one': 1 }
+ expected - actual
{
- "something should be false": true
+ "forgot this one": 1
+ "something should be false": false
"something should be true": true
}
at Context.<anonymous> (test.js:22:12)

How to properly initialize Elasticsearch for queries?

I wrote a program that inserts an element, then it searches all elements in the store. Thus, it finds one more element every time the program runs. I’d expect to be able to comment out the insert and still run the program, just finding the stuff that was already inserted. Whenever I do though, I get an exception “Failed to execute phase [query_fetch], all shards failed”. Any ideas?
Hypothesis: inserting the element does some sort of implicit initialization on my node. However, I’m looking through the ES source, and I can’t figure out what that would be.
try (Node node = NodeBuilder.nodeBuilder().clusterName("tesssst").build().start()) {
try (Client client = node.client()) {
//insert an entry; if this part is removed, the program crashes
client.prepareIndex("movies", "movie", UUID.randomUUID().toString()).setSource(
"{\"title\": \"Lawrence of Arabia\",\"director\": \"David Lean\",\"year\": 1962,\"genres\":"
+ " [\"Adventure\", \"Biography\", \"Drama\"]}").execute().actionGet();
//search all entries
System.out.println("***************");
SearchResponse response = client.prepareSearch("movies")
.setTypes("movie")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchHit[] results = response.getHits().getHits();
System.out.println("Current results: " + results.length);
for (SearchHit hit : results) {
System.out.println("------------------------------");
Map<String, Object> result = hit.getSource();
System.out.println(result);
}
System.out.println("***************");
client.close();
}
node.close();
}
The problem was that Elasticsearch didn't have enough time to startup, but the initial insert gave it enough time. Simply adding an appropriate wait fixes it:
final ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest("movies")
.timeout(TimeValue.timeValueSeconds(60)).waitForGreenStatus();
final ClusterHealthResponse clusterHealth = client.admin().cluster()
.health(clusterHealthRequest).actionGet();
if (clusterHealth.isTimedOut()) {
System.out.println("ElasticSearch cluster health timed out");
} else {
System.out.println("ElasticSearch cluster health: Status "
+ clusterHealth.getStatus().name() + "; " + clusterHealth.getNumberOfNodes()
+ " nodes; " + clusterHealth.getActiveShards() + " active shards.");
}
(if your standards are lower, you can save time with waitForYellowStatus)

Django Session Persistent but Losing Data

I have been working for hours trying to understand the following problem: I have a user send an Ajax request to dynamically send a form and record that the number of forms to read on submission has increased. Toward this end I use request.session['editing_foo'] = { 'prefix_of_form_elements' : pkey } so that I can associate them with the database for saving and loading (-1 is for new forms that haven't been saved yet).
However, when I use the following code (see bottom) I get the following bizarre output:
1st Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
2nd Click:
{} foousername
next_key 1
1
{u'1-foo': -1}
3rd Request:
{} foousername
next_key 1
1
{u'1-foo': -1}
What the heck is going on?
id_fetcher = re.compile(r'\d')
#login_required
def ajax_add_foo(request):
def id_from_prefix(key):
return int( id_fetcher.search(key).group(0) )
if 'editing_foos' not in request.session:
print "reinitializing"
request.session['editing_foos'] = {}
print request.session['editing_foos'], request.user
keys = request.session['editing_foos'].keys()
if len(keys) == 0:
next_key = 1
else:
print [ id_from_prefix(key) for key in keys ]
next_key = max([ id_from_prefix(key) for key in keys ]) + 1
print "next_key", next_key
fooform = FooForm(prefix=next_key)
print next_key
request.session['editing_foos'].update( {create_prefix(FooForm, next_key) : -1 } ) # This quote is new and has no pkey
print request.session['editing_foos']
return render_to_response( 'bar/foo_fragment.html',
{'fooform' : fooform, },
context_instance=RequestContext(request))
Thank you all very much!
Note: This is a followup to a previous question concerning the same source code.
I don't think I completely understand the question, but you may want to take a look at which session engine you're using
if you're using the cache session engine you need to make sure you have caching properly set up (for instance the dummy cache would just throw out your session data)
another possibility is that your session isn't being saved because you're not changing the session, you're changing a mutable object that is stored in the session. you can try forcing the session to save by adding this somewhere in your view:
request.session.modified = True

Resources