How to maintain the cache in the servlet? - servlets

I want to maintain db cache(some keywords) in the servlet. When I am typing for 'a' I have 1000 keywords in Db which starts with 'a' and presently I am using js file to store all the keywords in cache. I want to maintain the DB cache in servlet also and decrease the browser cache and next hitting keyword matches in the servlet Db, I want to retrieve the top 10 keywords for the this hitting.
Can you tell me how can I create the servlet cache? Can you provide any pseudo code for that?
Thanks,
Murali

I can imagine you have a Servlet that accesses the Database in order to retrieve the top 10 keyboards based on the input delivered. That means whenever an A is pressed in the input field, you must use an XMLHttpRequest to call the servlet with that input.
The servlet should return you a list of keywords which you should parse and translate properly to your user again. (you could do this in multiple ways. An easy way is to just let the servlet respond with HTML for you,which you can set with Javascript in an element (innerHTML)).
As for caching, the servlet could use some cache and identify the requested input. You can build an own cache by generating a key from the input and the result of that input should be put into a Map.
You could also use an existing caching framework, like EHCache.

Related

Dynamic Property File Loading in Spring based on the URL Argument for every request for data validation

I am working in a environment(in Spring, version 4.x) which needs to load/change the property files based on the URL argument for every request.
After successful build of application, for the first request I need to get an argument from the URL, and based on that argument I have to load the properties i.e, my application has to run with new properties and I'll be using this property file for validation.
But the problem is based on the configuration all the property files are loading before getting the URL argument and I am not able to load the property file dynamically after every request.
For example, if I am having two customers using my product and both have different set of rules(based on which, validation needs to be performed), from there request I'll get to know which customer is requesting and which set of rules I should apply for validation(for which, I am thinking of using property files).
I tried using different ways(but not working): http://www.baeldung.com/2012/02/06/properties-with-spring/#usage
Similar question: http://forum.spring.io/forum/spring-projects/web/119875-dynamic-property-file-loading-in-spring-based-on-the-url-argument

Webmatrix 2: Storing static values

Where would be the best place to store static values.
And how would I access it.
I want to be able to access static values from any page. But only have to define them in one place.
For example 'email' and 'phoneNumber'
I have tried things like Session and PageData, and defining the variables in my header (used by all pages) but this does not work.
The partial is initialised after the page, so it either doesnt work at all, or doesnt work on first time load.
E.g. First time Load:
Page Loaded <- Tries to Access variable. Not initialised.
Header Partial Loaded <- Variable initalised.
Result. Page does not show variable.
I have considered storing it in the config file. But I have no idea how to access this from Webmatrix 2.
I could just create a txt/ini file or something but surely parsing a file isn't the best way to do it. - I have since tried this and it doesnt seem valid like in mvc3 (config),and txt files are not practical to read for each request.
By "static", if you mean values that don't change across the lifetime of the application, you would normally use HelperPage.App property for storage. It is based on the dynamic type so you can create arbitrary properties:
App.Email = "someone#somewhere.com";
Or you can use the more traditional name/value collection approach with AppState:
AppState["email"] = "someone#somewhere.com";
However, if your "static" variables are user-specific, you should use Session as that is scoped to the user. Or use a database if you want to store them permanently.
You can set session values in _PageStart.cshtml (may need creating), or in the Session_Start event of the global.asax file and then access them in any partial / view you desire.

What's the RESTful way of attaching one resource to another?

this is one of the few moments I couldn't find the same question that I have at this place so I'm trying to describe my problem and hope to get some help an ideas!
Let's say...
I want to design a RESTful API for a domain model, that might have entities/resources like the following:
class Product
{
String id;
String name;
Price price;
Set<Tag> tags;
}
class Price
{
String id;
String currency;
float amount;
}
class Tag
{
String id;
String name;
}
The API might look like:
GET /products
GET /products/<product-id>
PUT /prices/<price-id>?currency=EUR&amount=12.34
PATCH /products/<product-id>?name=updateOnlyName
When it comes to updating references:
PATCH /products/<product-id>?price=<price-id>
PATCH /products/<product-id>?price=
may set the Products' Price-reference to another existing Price, or delete this reference.
But how can I add a new reference of an existing Tag to a Product?
If I wanted to store that reference in a relational database, I needed a relationship table 'products_tags' for that many-to-many-relationship, which brings us to a clear solution:
POST /product_tags [product: <product-id>, tag: <tag-id>]
But a document-based NoSQL database (like MongoDB) could store this as a one-to-many-relationship for each Product, so I don't need to model a 'new resource' that has to be created to save a relationship.
But
POST /products/<product-id>/tags/ [name: ...]
creates a new Tag (in a Product),
PUT /products/<product-id>/tags/<tag-id>?name=
creates a new Tag with <tag-id> or replaces an existing
Tag with the same id (in a Product),
PATCH /products/<product-id>?tags=<tag-id>
sets the Tag-list and doesn't add a new Tag, and
PATCH /products/<product-id>/tags/<tag-id>?name=...
sets a certain attribute of a Tag.
So I might want to say something link this:
ATTACH /products/<product-id>?tags=<tag-id>
ATTACH /products/<product-id>/tags?tag=<tag-id>
So the point is:
I don't want to create a new resource,
I don't want to set the attribute of a resource, but
I want to ADD a resource to another resources attribute, which is a set. ^^
Since everything is about resources, one could say:
I want to ATTACH a resource to another.
My question: Which Method is the right one and how should the URL look like?
Your REST is an application state driver, not aimed to be reflection of your entity relationships.
As such, there's no 'if this was the case in the db' in REST. That said, you have pretty good URIs.
You talk about IDs. What is a tag? Isn't a tag a simple string? Why does it have an id? Why isn't its id its namestring?
Why not have PUT /products/<product-id>/tags/tag_name=?
PUT is idempotent, so you are basically asserting the existance of a tag for the product referred to by product-id. If you send this request multiple times, you'd get 201 Created the first time and 200 OK the next time.
If you are building a simple system with a single concurrent user running on a single web server with no concurrency in requests, you may stop reading now
If someone in between goes and deletes that tag, your next put request would re-create the tag. Is this what you want?
With optimistic concurrency control, you would pass along the ETag a of the document everytime, and return 409 Conflict if you have a newer version b on the server and the diff, a..b cannot be reconciled. In the case of tags, you are just using PUT and DELETE verbs; so you wouldn't have to diff/look at reconciliation.
If you are building a moderately advanced concurrent system, with first-writer-wins semantics, running on a single sever, you can stop reading now
That said, I don't think you have considered your transactional boundaries. What are you modifying? A resource? No, you are modifying value objects of the product resource; its tags. So then, according to your model of resources, you should be using PATCH. Do you care about concurrency? Well, then you have much more to think about with regards to PATCH:
How do you represent the diff of a hierarchial JSON object?
How do you know what PATCH requests that conflict in a semantic way - i.e. we may not care about DELETEs on Tags, but two other properties might interact semantically.
The RFC for HTTP PATCH says this:
With PATCH, however, the enclosed entity contains a set of
instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH
method affects the resource identified by the Request-URI, and it also
MAY have side effects on other resources; i.e., new resources may be
created, or existing ones modified, by the application of a PATCH.
PATCH is neither safe nor idempotent as defined by [RFC2616], Section
9.1.
I'm probably going to stop putting strange ideas in your head now. Comment if you want me to continue down this path a bit longer ;). Suffice to say that there are many more considerations that can be done.

Ways to keep track of dynamically created DOM elements in ASP.NET

Assume you have a page in ASP.NET where it makes sense to use JavaScript/jQuery to modify the DOM with values that will eventually be read by the server on submit. For example, you have a form that allows end users to add/remove objects (like dependents on a health insurance form or assets on a loan application).
What are some ways to ensure that these items are detected and retrieved by the server once the information is submitted?
I've tried a few things that work, but none of them seem perfect so I wanted to see what the community had to offer.
Also, I'm not looking for suggestions that avoid dynamic DOM elements (like use a Wizard, etc.). I'm specifically trying to improve my technique with dynamically created DOM elements.
There are two ways to do something like this:
First: post only the information on submit. As long as you add both a name and an id attribute to every element in your DOM, every element is represented in Request.Form, so you can easily iterate through this collection.
I tend to have a naming convention like insurance_row_1, insurance_row_2 and so forth. You can find all rows like Request.Form.AllKeys.Where(k=>k.StartsWith("insurance_row_")).
When you want to save every action on the server:
Maintain a state container in javascript, that holds information in some dictionary-like control, where you put every action that has been performed by your application, and a state whether the server has processed them. Something like:
var stateContainer = [
{ 'put-insurance-row-1', false },
{ 'delete-insurance-row-1', false }
];
Do an AJAX request to the server to perform such an action, and use the state-container's key to track whether the request succeeded or failed. Set the state to 'true' when the request has been successfully submitted. Make sure to do this in order in which you receive the events, so send them one-by-one to the server to ensure that you keep a valid state.
You can (try) to prevent closing the browser if some states aren't persisted yet.
why are you using client side code to do this? i would go the route of doing a postback and adding a control from server side code. the built in ajax updatepanel should handle this very quickly.

SWFUpload multiple files server-side handling

I need the user to be able to upload multiple files to my server, thus I am using the SWFUpload utility. SWFUpload sends the files one by one, and I need to store them all in the same temporary directory. My ASP.NET handler recieves the files one by one and I can store the file appropriately.
My problem is: How do I know which files belong to the same upload? Rephrased, how do I connect the files in my handler?
I see 2 ways to do this (but they inherit the same idea).
The idea is based on the thing you should have something like sessionId parameter. This value should be unique for each set of files. You could use javascript uuid generators or something like so.
Further, this sessionId variable may be passed through query string(a little bit modified your handler url): ~/UploadHandler.ashx?sessionId={whatever} or as post parameter(guess, the better way).
The value may be retrieved on the server side by using: context.Request["SessionId"] for example.
On the client side you should be able to change post parameters or handler url dynamically. It could be done by using:
void addPostParam(name, value)
The addPostParam function adds a
name/value pair that will be sent in
the POST for all files uploaded.
The name/value pair will also appear
in the post_params setting.
or
void setUploadURL(url)
Dynamically modifies the upload_url
setting.
client methods. They should be called from the
fileDialogComplete(number of files selected, number of files queued, total number of files in the queued)
The fileDialogComplete event fires
after the File Selection Dialog window
has been closed and all the selected
files have been processed. The 'number
of files queued' argument indicates
the number of files that were queued
from the dialog selection (as opposed
to the number of files in the queue).
method.
Hope, this helps.

Resources