Tuesday, February 25, 2014

Avoiding CORS security issues

CORS is security policy, according which a page could not be iframe-d from page from another site.

ajax requests are implemented via iframe, so if we want to do ajax requests to another site, we encounter CORS error.

How to enable this?

Solution is to tell server to allow the page/JSON/webservice to be iframed. This is done this way:
    public String getUserById(@PathVariable("id") Long id, HttpServletResponse httpResponse) throws JsonProcessingException {
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        // do real work


Access-Control-Allow-Origin is the header that allows this. Check wikipedia for other solutions.

solved: Spring + Hibernate used with JPA and EntityManager => HibernateException: collection is not associated with any session

When I started using lazy loading in Spring + Hibernate project, I encounter this error.

What does NOT solve my issue:
  • @Transactional annotation
  • OpenSessionInViewInterceptor

The error message was:


Problem accessing /user/1. Reason:
    Server Error

Caused by:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: collection is not associated with any session
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)

Solution for Spring with JPA approach and EntityManager, is to use OpenEntityManagerInViewFilter. Register it in web.xml this way:

http://stackoverflow.com/questions/9304020/lazy-initialisation-with-openentitymanagerinviewfilter - not the selected answer, but this from Jhonathan

Monday, February 24, 2014

How to serialize only the ID of a child with Jackson?

Solution from stackoverflow.com

public class Parent {
   @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
   @JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
   public Child child; // or use for getter or setter

   // if using 'PropertyGenerator', need to have id as property -- not the only choice
   public int id;

Friday, February 21, 2014

Jackson + Spring + Maven = http error 406 - workarounded

I get this error in Spring project with Jackson, with annotations:


Problem accessing /xxx/4. Reason:
    Not Acceptable

Powered by Jetty://

I have tested it with Jackson 2.3.1, 2.2.3 and 2.1.3 - same. Spring 3.1.1 and 3.1.0 - same. Application server jetty and tomcat - same, but in Tomcat dies with no error/log text.

So my conclusion is:

Jackson sucks!

And this is not for its error (there are no errors in controller method, it passes fine), but in dieing with no single line of message.

I will revert to jackson 1, where this error is not absolute blocker to me (i get it only on one page in version 1).

P.S. No answer on stackoverflow uptill 2014.2 helped me :(

Edit: the solution.
Holly *hit, I finally overcome the issue in very simple way!

Clean, not working way:
    public Dummy getT() {
        Dummy t = new Dummy();
        System.out.println( "hello from t" );
        return t;

    @RequestMapping(value = "/manualDummy", method = RequestMethod.GET)
    public String manualDummy(/*HttpServletRequest request, ModelMap model*/) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper(); // com.fasterxml.jackson.databind.ObjectMapper
        Dummy t = new Dummy();
        return mapper.writeValueAsString(t);

P.S. Jackson continues to sucks...

Monday, February 17, 2014

How to Stop Netbeans: Transferring repository index

I see at status bar, that Netbeans is Transferring repository index : java.net repository. It slows down my computer very much. Very annoying.

Solution for Netbeans 7.4 (and possibly later versions, 8.0):
Tools | Options | Java | Index”, find “Index Update Frequency” and then adjust how often it should be updated (Never :).

Friday, February 14, 2014

My dummy html template

    <style scoped>
        color: red;
    if( console )
        console.log("console is working");
    <h3>Normal heading</h3>
    <h3 class='red_text'>Red heading</h3>
    Normal text

Thursday, February 13, 2014

KendoUI Mobile: force refresh / reload / update on a ListView

Lets have a list view, initialized with data from variable employees this way:

<ul id="employeesListView" data-role="listview" data-title="Employee list title" data-source="employees" data-template="employees-template" />

If we have updated the variable employees, the listview stays the same. To force update, we have to do this:

        $("#employeesListView").kendoMobileListView({            dataSource: employees,
            template:  $("#employees-template").text(),

KendoUI Mobile: catching connection errors in accesing remote datasource

    var dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "https://ala.bala.com:443/test/test.json2",
                timeout: 3900,
                dataType: "json",
                data: {
                    q: "javascript"
        schema: {
            data: "results"
        error: function(e) {

KendoUI Mobile: working example with remote json listview databinding

Source could be downloaded from this thread. Tested and working.

In the example .json file has to be placed in folder of index.html, but you could move it in any remote server and point "url" to its location.

Wednesday, February 12, 2014

How to check for “undefined” in JavaScript?

This is useful thread in stackoverflow - http://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript

My suggestion is:
var myVariable; // theFu has been declared, but its value is undefined
"myVariable" in window; // true
"otherVariable" in window; // false 

Thursday, February 6, 2014

Using JSON web services in jQuery - simple example

Lets web-service returns this data:

Here is the JavaScript code:
                var ws_url = 'http://example.webservice.com:8002/xxx-ws/management/usr/10';
                  url: ws_url,
                  dataType: 'json',
                  timeout : 5000,
                }).success(function( data, textStatus, xhr ) {
                        alert( "returned user name = " + data.user.firstName + " " + data.user.lastName );
                        gdata = data;
                }).error(function(httpObj, textStatus) {       

You will get [returned user name = Bill Clinton]

Wednesday, February 5, 2014

jetty 9 in maven. Newer jetty, older jetty

Update from jetty 6 to jetty 9 done - solved!

Fixed version Jetty 9:

Latest Jetty:

Older jetty 6 was with non-eclipse groupId, which cause auto version update to 7+ not to works. If you want Jetty 6, this is the pom.xml fraction you need.

Custom configuration
Some useful configuration options for Jetty:
                <contextPath>/my-context</contextPath><!-- default is / -->