Configuring server side Datatables for an unknown number of tables - java

I am using DataTables with the tables being generated in a java controller class that talks to the database. Given a category id, the controller class returns an unknown number of preformatted HTML tables, one for each section in the given category queried. Ideally I would like to display each table as a DataTable on the same page, but unsure if that's possible given that I don't know how many tables I will be getting back so I can't set up their behavior before the query.
Is there a way to format the tables when/as I get them from the controller? I attempted to prepend each table with its own .ready block but that didn't seem to do the trick though I'm fairly new to jQuery and could just be missing something. I used the barest of configuration to try to get it working first
$(document).ready(function(){
$("#results").dataTable({
"bJQueryUI" : true
});
});

$(document).ready(function() {
$('.dataTable').dataTable();
} );
Turns out to work after all, but ONLY if you specify the tables as class="dataTable" which isn't well documented or explained, hopefully this un-confuses someone else!

Related

How to remove all records of the table in Hybris?

In my development environment, I have added wrong data to my custom ItemType. Now I want to remove all data for that Type. Basically I want to truncate my ItemType table.
Run the below Impex (Change MyItemType with your ItemType)
$targetType=MyItemType
REMOVE $targetType[batchmode=true];itemtype(code)[unique=true]
;$targetType
You can also run SQL query from HAC, refer this post for more detail

ElasticSearch - Using FilterBuilders

I am new to ElasticSearch and Couchbase. I am building a sample Java application to learn more about ElasticSearch and Couchbase.
Reading the ElasticSearch Java API, Filters are better used in cases where sort on score is not necessary and for caching.
I still haven't figured out how to use FilterBuilders and have following questions:
Can FilterBuilders be used alone to search?
Or Do they always have to be used with a Query? ( If true, can someone please list an example? )
Going through a documentation, if I want to perform a search based on field values and want to use FilterBuilders, how can I accomplish that? (using AndFilterBuilder or TermFilterBuilder or InFilterBuilder? I am not clear about the differences between them.)
For the 3rd question, I actually tested it with search using queries and using filters as shown below.
I got empty result (no rows) when I tried search using FilterBuilders. I am not sure what am I doing wrong.
Any examples will be helpful. I have had a tough time going through documentation which I found sparse and even searching led to various unreliable user forums.
private void processQuery() {
SearchRequestBuilder srb = getSearchRequestBuilder(BUCKET);
QueryBuilder qb = QueryBuilders.fieldQuery("doc.address.state", "TX");
srb.setQuery(qb);
SearchResponse resp = srb.execute().actionGet();
System.out.println("response :" + resp);
}
private void searchWithFilters(){
SearchRequestBuilder srb = getSearchRequestBuilder(BUCKET);
srb.setFilter(FilterBuilders.termFilter("doc.address.state", "tx"));
//AndFilterBuilder andFb = FilterBuilders.andFilter();
//andFb.add(FilterBuilders.termFilter("doc.address.state", "TX"));
//srb.setFilter(andFb);
SearchResponse resp = srb.execute().actionGet();
System.out.println("response :" + resp);
}
--UPDATE--
As suggested in the answer, changing to lowercase "tx" works. With this question resolved. I still have following questions:
In what scenario(s), are filters used with query? What purpose will this serve?
Difference between InFilter, TermFilter and MatchAllFilter. Any illustration will help.
Right, you should use filters to exclude documents from being even considered when executing the query. Filters are faster since they don't involve any scoring, and cacheable as well.
That said, it's pretty obvious that you have to use a filter with the search api, which does execute a query and accepts an optional filter. If you only have a filter you can just use the match_all query together with your filter. A filter can be a simple one, or a compund one in order to combine multiple filters together.
Regarding the Java API, the names used are the names of the filters available, no big difference. Have a look at this search example for instance. In your code I don't see where you do setFilter on your SearchRequestBuilder object. You don't seem to need the and filter either, since you are using a single filter. Furthermore, it might be that you are indexing using the default mappings, thus the term "TX" is lowercased. That's why when you search using the term filter you don't find any match. Try searching for "tx" lowercased.
You can either change your mapping if you want to keep the "TX" term as it is while indexing, probably setting the field as not_analyzed if it should only be a single token. Otherwise you can change filter, you might want to have a look at a query that is analyzed, so that your query wil be analyzed the same way the content was indexed.
Have a look at the query DSL documentation for more information regarding queries and filters:
MatchAllFilter: matches all your document, not that useful I'd say
TermFilter: Filters documents that have fields that contain a term (not analyzed)
AndFilter: compound filter used to put in and two or more filters
Don't know what you mean by InFilterBuilder, couldn't find any filter with this name.
The query usually contains what the user types in through the text search box. Filters are more way to refine the search, for example clicking on facet entries. That's why you would still have the query plus one or more filters.
To append to what #javanna said:
A lot of confusion can come from the fact that filters can be defined in several ways:
standalone (with a required query, for instance match_all if all you need is the filters) (http://www.elasticsearch.org/guide/reference/api/search/filter/)
or as part of a filtered query (http://www.elasticsearch.org/guide/reference/query-dsl/filtered-query/)
What's the difference you might ask. And indeed you can construct exactly the same logic in both ways.
The difference is that a query operates on BOTH the resultset as well as any facets you have defined. Whereas, a Filter (when defined standalone) only operates on the resultset and NOT on any facets you may have defined (explained here: http://www.elasticsearch.org/guide/reference/api/search/filter/)
To add to the other answers, InFilter is only used with FilterBuilders. The definition is, InFilter: A filter for a field based on several terms matching on any of them.
The query Java API uses FilterBuilders, which is a factory for filter builders that can dynamically create a query from Java code. We do this using a form and we build our query based on user selections from it with checkboxes, options, and dropdowns.
Here is some Example code for FilterBuilders and there is a snippet from that link that uses InFilter as shown below:
FilterBuilder filterBuilder;
User user = (User) auth.getPrincipal();
if (user.getGroups() != null && !user.getGroups().isEmpty()) {
filterBuilder = FilterBuilders.boolFilter()
.should(FilterBuilders.nestedFilter("userRoles", FilterBuilders.termFilter("userRoles.key", auth.getName())))
.should(FilterBuilders.nestedFilter("groupRoles", FilterBuilders.inFilter("groupRoles.key", user.getGroups().toArray())));
} else {
filterBuilder = FilterBuilders.nestedFilter("userRoles", FilterBuilders.termFilter("userRoles.key", auth.getName()));
}
...

How to store all user activites in a website..?

I have a web application build in Django + Python that interact with web services (written in JAVA).
Now all the database management part is done by web-services i.e. all CRUD operations to actual database is done by web-services.
Now i have to track all User Activities done on my website in some log table.
Like If User posted a new article, then a new row is created into Articles table by web-services and side by side, i need to add a new row into log table , something like "User : Raman has posted a new article (with ID, title etc)"
I have to do this for all Objects in my database like "Article", "Media", "Comments" etc
Note : I am using PostgreSQL
So what is the best way to achieve this..?? (Should I do it in PostgreSQL OR JAVA ..??..And How..??)
So, you have UI <-> Web Services <-> DB
Since the web services talk to the DB, and the web services contain the business logic (i.e. I guess you validate stuff there, create your queries and execute them), then the best place to 'log' activities is in the services themselves.
IMO, logging PostgreSQL transactions is a different thing. It's not the same as logging 'user activities' anymore.
EDIT: This still means you create DB schema for 'logs' and write them to DB.
Second EDIT: Catching log worthy events in the UI and then logging them from there might not be the best idea either. You will have to rewrite logging if you ever decide to replace the UI, or for example, write an alternate UI for, say mobile devices, or something else.
For an audit table within the DB itself, have a look at the PL/pgSQL Trigger Audit Example
This logs every INSERT, UPDATE, DELETE into another table.
In your log table you can have various columns, including:
user_id (the user that did the action)
activity_type (the type of activity, such as view or commented_on)
object_id (the actual object that it concerns, such as the Article or Media)
object_type (the type of object; this can be used later, in combination with object_id to lookup the object in the database)
This way, you can keep track of all actions the users do. You'd need to update this table whenever something happens that you wish to track.
Whenever we had to do this, we overrode signals for every model and possible action.
https://docs.djangoproject.com/en/dev/topics/signals/
You can have the signal do whatever you want, from injecting some HTML into the page, to making an entry in the database. They're an excellent tool to learn to use.
I used django-audit-log and I am very satisfied.
Django-audit-log can track multiple models each in it's own additional table. All of these tables are pretty unified, so it should be fairly straightforward to create a SQL view that shows data for all models.
Here is what I've done to track a single model ("Pauza"):
class Pauza(models.Model):
started = models.TimeField(null=True, blank=False)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
audit_log = AuditLog()
If you want changes to show in Django Admin, you can create an unmanaged model (but this is by no means required):
class PauzaAction(models.Model):
started = models.TimeField(null=True, blank=True)
ended = models.TimeField(null=True, blank=True)
#... more fields ...
# fields added by Audit Trail:
action_id = models.PositiveIntegerField(primary_key=True, default=1, blank=True)
action_user = models.ForeignKey(User, null=True, blank=True)
action_date = models.DateTimeField(null=True, blank=True)
action_type = models.CharField(max_length=31, choices=(('I', 'create'), ('U', 'update'), ('D', 'delete'),), null=True, blank=True)
pauza = models.ForeignKey(Pauza, db_column='id', on_delete=models.DO_NOTHING, default=0, null=True, blank=True)
class Meta:
db_table = 'testapp_pauzaauditlogentry'
managed = False
app_label = 'testapp'
Table testapp_pauzaauditlogentry is automatically created by django-audit-log, this merely creates a model for displaying data from it.
It may be a good idea to throw in some rude tamper protection:
class PauzaAction(models.Model):
# ... all like above, plus:
def save(self, *args, **kwargs):
raise Exception('Permission Denied')
def delete(self, *args, **kwargs):
raise Exception('Permission Denied')
As I said, I imagine you could create a SQL view with the four action_ fields and an additional 'action_model' field that could contain varchar references to model itself (maybe just the original table name).

Spring Hibernate, updating JSP view while selecting from dropdown menu

my controller:
public String showWeather(Model model) {
model.addAttribute("weather", weatherService.listCities());
return "weather";
}
my weather.jsp
<select class="data">
<c:forEach items="${weather}" var="city">
<option>${city.name}</option>
</c:forEach>
</select>
How can I make that everytime I highlight/select something from the dropdown menu, new info would be displayd next to it from database according to the City?
First of all, must I send all data from database to my JSP with controller at first, or can data be transfered from database to JSP meanwhile I highlight/select items on the list(so when I select city "A", then the query will get all information about city "A" and I can use the info)?
here are my tables:
CITIES(id serial, name varchar(40))
WEATHER(id serial, city_id int, temp int, data date)
So basically I have list of CITIES in my dropdown menu, and when city is selected, then the WEATHER with that city_id will be queried from database in theory.
If the live updating is not possible, how should I do it otherways?
Feel free to ask questions or give suggestions.
I think you should use AJAX in this case
use JQUERY on change event whick will send your cityId to SpringMVC controller, as the response your controller should return wheather, and then update your GUI component with this result:
then main difference is that your controller should return anything but the view. You can do it using #ResponseBody annotation:
for example this controller will return you temperature as String when you request
it for city with id=222
/getTemperature/222
#RequestMapping(value="/getTemperature/{id}", method=RequestMethod.GET)
#ResponseBody
public String getTemparature(#PathVariable("id") Integer id){
String weather = someDaoObect.getTemperature(id);
return weather;
}
in this case that code behaves exactly like Servlet where you write your result in HttpServletResponse.
Hope it will help you.
What are you talking about it is exactly what Ajax is focused on (see Ajax Programming), bring data between the server and client (browser), sending and retrieving data asynchronously. In your case, when the user selects and item the application must go and query to the server what is needed to do it (update information in the db, return something to the browser, etc).
In your case, I don't know if you can include a new library and use it, but there are so many to use within a web project in Java, and are so easy to integrate and use it:
AjaxTags JavaScript-JSP Library - http://ajaxtags.sourceforge.net/
AjaxAnywhere - http://ajaxanywhere.sourceforge.net
jMaki - http://ajax.java.net/
Also you can include one of the beautiful JavaScript libraries (ex: jQuery, Prototype, Ext, Dojo, etc) that provides same functionality to send and receive information asynchronously between the browser and the server.

DisplayTag error

I am using the DisplayTag with pagination to display a List objects. The Transactions has a property called 'company' / getCompany() which is the Company object. The Company object contains a String called 'name' / getName().
My code looks like this:
<display:table name="${transactions}" id="transaction" pagesize="2" defaultsort="1">
<display:column property="id" title="ID" href="showTransactionDetails.html" paramId="id" />
<display:column property="company.name" title="Company Name" sortable="true" >
<display:column property="status" title="Status" sortable="true">
</display:table>
Here is the strange part.... Everything works great when the first page is displayed and there are a total of 11 pages with each page containing 2 records.
I can click on a page number and see the page advance. But for some strange reason, when I click on page (2-4) I get an exception:
org.apache.jasper.JasperException:
javax.servlet.ServletException:
javax.servlet.jsp.JspException:
Exception: [.LookupUtil] Error looking
up property "company.name" in object
type
"com.replacements.entity.Transaction".
Cause: null
(It's also important to note that all of the Transaction records contain a value for the company.name since its a required field in my DB)
Is it possible that the company is null. That is, you have a transaction with no company in the database.
I solved it by changing the company property in Hibernate mapping to "lazy=false"
I'm still not sure why the pagination worked from some pages and not all. But this fixed it.
Thank you all for your ideas.
As #Vincent says, likely company is null. You may have a value in your database, but maybe there is an issue where your Transaction class isn't properly reading the db value and setting its company member. Have you tried setting a breakpoint and looking at the Transaction instance?
My first guess is that there is an empty company list. I would suggest you print dump to output your transaction results before they get to the display part.
If that’s not the problem I’ve seen display problems caused by special characters. One of the company names might contain a control character or some other non-displayable character.
Try changing the name="${transactions}" in the display:table tag to name="transactions".
Assuming you have the transactions collection in the session or request or whatever.
The exception message literally tells that the Transaction is null. Thus, there's apparently a null item in the transaction list behind ${transactions}. Look like a fault in the loading/populating logic of the transaction list. Maybe the last item is null? Or maybe the list is request scoped and dependent from some request parameters which are missing in the subsequent request so that loading/populating the list failed?
For the interested, if Company was null as some suggests, EL would not have error'ed that way. It would have mentioned object type Company instead.
A requestURI tag...like so.... requestURI="
Make sure you have setters and getters methods for all attributes in your class and names matching attributes names.

Categories

Resources