zwwcn

Just another WordPress.com site

Endless loop with ListIterator .hasNext()

The following code will create an endless loop because java creates new iterator everytime you call list.iterator():

while(someList.iterator().hasNext()){
   someList.iterator().next().toString();
}

We should do it this way:

Iterator iterator = someList.iterator();
while(iterator.hasNext()){
   iterator.next().toString();
}

POI read cell value as string

When you get error for reading cell value as string:

Cannot get a numeric value from a text cell
or Cannot get a boolean value from a text cell

The code below will format the cell properly and return string value:

final DataFormatter df = new DataFormatter();
final XSSFCell cell = row.getCell(cellIndex);
String valueAsString = df.formatCellValue(cell);

Request URI too long

I had a task to add a link in a chart. Depends on the area user clicks,  the system will create a get request, forward the user to next page.  The URL looks like “http://localhost:8080/nextpage?q=para1:1,2,3,4;para2:3,2,2,3;para3:test1,test2,test..”. The URL becomes too long and gives an error in the browser: request URI too long.

All we need to do is to change the request to post request. We create a hidden form on the page, which contains one input field and one button. the input field is used to save the parameters value (q in the example), and when user click the chart. I set the parameters value to the input field, then trigger a click on the button to submit the form.


And the code in javascript listener:

 ......
 $("#hsChartForm\\:queryStringFromCharts").val("monthString:"+monthString+";siteids:"+...);
 $("#hsChartForm\\:chartLink").click();
.....

Jquery mobile multiple select with many options

When multiple select has too many options, jquery mobile will open a dialog rather than popup, which is a new page. Every time the popup is closed the pagecontainerbeforeload and pagecontainershow events are triggered again and thereby the initialisation code. We could add a check on the prevPage to avoid unwanted initialisation.

    $(document).on( "pagecontainerbeforeload", function( event, data ) {
         if(ui.prevPage.attr("id").indexOf("-dialog")>-1){
              return;
         }
         ......initialisation code....
    }

Create copy of a list

Sometimes we want to pass a list as parameter to a method, we will do some work on the list but don’t want to affect the origin list.

The code below is not good, as we are passing the orginal reference to the method, all changes will affect the orginal list

     DoSomeWork(SelectedPerson.getAllAddresses());

Instead, we should do something like:

     DoSomeWork(new ArrayList(SelectedPerson.getAllAddresses()));

Pleaes be awared that the second example passed a copy of the list to DoSomeWork, but the elements in the copy still hold reference to the orginal elements. Modifying any object element in the copy list will also change the element in the original.

hibernate criteria on composite id

@Embeddable
public class TeacherStudentPK  implements java.io.Serializable{
    @ManyToOne
    @JoinColumn(name = "STUDENT_ID")
	private Student student;
    @ManyToOne
    @JoinColumn(name = "TEACHER_ID")
public class TeacherStudent implements java.io.Serializable {

	/* primay key*/
	@EmbeddedId 
	private TeacherStudentPK teacherStudentPK;
      public class Student{
	@OneToMany(mappedBy="teacherStudentPK.student")
	private Collection teachers = new ArrayList();

The crieteria is shown below:

criteria = em.createCriteria(Student.class, "student")
		   .createAlias("student.teachers", "teacherStudent")
.add(Restrictions.eq("teacherStudent.teacherStudentPK.teacher", selectedTeacher))
									

JMS queue listener

Let’s say we are saving a note along some pics into the database. We will need to resize the pics and only save thumbnails. The resizing images part could take a couple seconds and we don’t want user to wait on the page, so we do it asynchronously.

The workflow would be: 1 save note;  2 flush session; 3 send resizing images request to jms ; 4 JMS queue listener receive the msg and find service action to create thumbnail.

During the resizing image process, I need to link the resized images to the note and then save the thumbnail. I had some code like below:

     ......
     saveNote(note);
     em.flush();
     AddNoteToJMSQueue(note);
    public void createThumbnail(Note note){
        Note note = em.merge(note);
        createThumbnailMethod(note);
    }

This doesn’t work because the process is asynchronous, when the resizing starts in JMS the note may not be in the database yet. What I had in my case the createThumbnail method then create another record for note, so I have duplicate record in the database.

To solve this problem, we should use find to look up the record in database before perform any action. If we can’t find the record in database then we should rollback and retry in JMS.

so the code goes:

    public void createThumbnail(Note note){
        Note newNote = em.find(note);
        if(newNote == null){
           ctx.setrollbackOnly();
        }
        createThumbnailMethod(note);
    }

collections.singletonMap

singtonMap and singletonList allow you quickly create an unmodifiable collection:

methodTakesAMap(Collections.singletonMap(key, value));

rather than this:

Map<KeyType, ValueType> m = new HashMap<KeyType, ValueType>();
m.put(key, value);
methodTakesAMap(m);

singletonList example:


List sampleList = collections.singletonList("theOnlyOption");

JQuery notes

  1. How to add listener for html content loaded by ajax call?

    Bind on a non-dynamic parent container using .on()

    $('.some-parent-class').on('click', '.element', function() {
      // DO STUFF!
    });
  2. AddClass function

      AddClass function always check exisitng classes before adding new one, so we don’t need to check duplicate classes

     3. Find function

       The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree

     4. text() and textarea

       The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method

      5. checkbox and prop

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

      6. toggle

Quick way to switch show/hide, checked/unchecked state

$('#checkBoxId').click(function() {
    $("#otherCheckbox").toggle(this.checked);
});

       7. event.preventDefault()

Cancel the default action (navigation) of the click, this is used when we only want to trigger a js function but don’t want the page navagation.

 

access javascript object property using variable

I want to assign data to a js object as a property, but the new property name is dynamic.

The bracket notation should be used here:

var apiDynamicString = "dynamicStringFromOtherFunction";

var apiDynamicData ="somedata...";

example.data[apiDynamicString] = apiDynamicData ;

Then you can access the property this way:

console.log(example.data[apiDynamicString]);

OR (if you know the variable value)

console.log(example.data.dynamicStringFromOtherFunction);