Blog do projektu Open Source JavaHotel

środa, 30 października 2013

Java properties and UTF-8

Introduction
There is an evergreen problem how to read Java properties from UTF-8 files. The source file should be ISO 8859-1 oriented and even overmighty Hercules cannot contend that.
Solution
But I found simply method which works for me. Just read a file in standard way, change all characters above 128 to Unicode escaped sequence and push through Properties.load method. Source file is available here.

public class ReadUTF8Properties { 

        private static String getFileContent(String name) throws IOException {
// does not work in Google App Engine, use Guava goodies            
//              return new String(Files.readAllBytes(Paths.get(name)));
            return Files.toString(new File(name),  Charsets.UTF_8);
        }

        private static String toLatin1(String s) {
                StringBuilder b = new StringBuilder();

                for (char c : s.toCharArray()) {
                        if (c >= 256 && c < 1000)
                                // 3 digits, add one leading 0
                                b.append("\\u0").append(Integer.toHexString(c));
                        else if (c >= 1000)
                                // 4 digits
                                b.append("\\u").append(Integer.toHexString(c));
                        else
                                b.append(c);
                }
                return b.toString();
        }

        public static Properties readProperties(String propName) throws IOException {

                Properties prop = new Properties();
                String p = toLatin1(getFileContent(propName));
                prop.load(new StringReader(p));
                return prop;
        }

}

wtorek, 15 października 2013

JavaHotel, first version

First version
I uploaded the first version of JavaHotel to Google App Engine. Test version is available: Java hotel for user (U/P user/user) and Java hotel for administrator (U/P admin/admin). Source files are available here. It is Google App Engine version but I'm planning to use it only for demo purpose. Also regular JEE version is created as a primary target. It will be available for Tomcat and Glassfish. Tomcat version is a single web application, Glassfish version is divided into persistence layer available as Session Stateless Bean and business logic layer. It was tested with Derby, Postgress and DB2.
It is the first version and everything is rough. But basic functionality is covered.
  • Prepare database: hotel, users, room, services, pricelist
  • Reservation panel
  • Booking
  • Check-in
  • Registering additional services during the stay
  • Billing
Reservation panel

Empty places denote free rooms, green booked and yellow with guests currently checked-in. Clicking at the empty place allows to make reservation starting from this day forward, clicking at the green allows to make check-in if customer just arrived and clicking at the yellow gives access to options related to stay (for instance: billing)
Reservation

It is the reservation dialog available after clicking at the empty room. User can modify number of days (default is one), calculate rating and enter the customer data. It is also possible to select the customer from the list of customers already registered.
Check-in
Check-in dialog pops up after clicking at the green (reservation) place. It allows transforming reservation to stay and starting billing the guest. In the check-in dialog it is also possible to register additional guests if the booking was done for more then one person.
Registering additional services

After stay has been started it is possible to append additional services to the stay. User can select a standard service prepared before or add a new services ad-hoc.
Billing
During and after the stay a bill can be issued. It is possible to issue more then one bill for one stay and every bill having a different payer. In the tab panel 'Not paid yet' page contains services not paid yet (without the bill issued for them) and 'All billable' contains the list of all services. The payment can be specified as 'Pay now' or 'Not paid now'. There is also possibility to register payment later for bills not paid now.
Conclusion
It is the first version so everything is basic and rough. But the most important functionality is implemented already. Next steps:

  • Booking of more then one room,  searching. For instance: implement scenario like: "Find the first available reservation for 5 persons: two double rooms and one single".
  • Issuing and printing the invoice.
  • Synchronization with calendar. Alerts when reservation or stay expires. 

niedziela, 22 września 2013

MVP framework, new features

Introduction
I added several enhancements to the MVP Jython framework. Source code is available here, sample application developed for Google App Engine can be launched using this web URL.
New types of main menu
So far only left side list of button has been available. Two new types of main menus have been added: "Up" menu and stack menu. "Up" menu is nothing more then image at the top status bar which expands after clicking giving a list of choices. Stack menu is an implementation of GWT StackPanel. "Up" menu can coexist with tab menu and stack menu but stack menu and tab menu excludes each otther. An example of stack menu is available here. More technical description.
"Up" menu

Stack menu














Image column
Image column contains icon or list of icons instead of text or number. Image list can be static or dynamic. In the second case a JavaScript code is executed to determine the list of images displayed depending on the row content. More detailed description. Icons plays also a role of buttons. After user clicks the icon a Jython server side action is raised. This way it is possible to implement an action depending on the row content and which icon has been clicked.

A running example is available here. Click "up" menu -> "List with icon". The up arrow is displayed for positive number and down arror for negative number. Left and right arrow is displayed depending if number is odd or even.
Different type for column and footer
As a default the footer type (and other properties like align and decimal position) are copied from column type. But it is possible to change this behavior.


A running example is available here. "Status" -> "List footer". The footer is under string column but the footer content is a number. Also align schema is different. More detailed description is available here.
Other changes
  • Dynamically modify the content of the status bar. The the status bar content can be customized depending on the context. More detailed description is available here. Running example can be launched. "Status" - > "Status text".
  • Load tab panel page on demand. An action is raised after clicking the page header. This way the tab panel page can be modified dynamically. More detailed description.
  • XML usage. XML format is often connected with love-hate relationship. But it is very convenient if data schema is not stable or can be changed. It is also very convenient if we want to pack a lot information in one entry without creating a table with tens or hundreds of columns. So I added some automation for packing and unpacking forms using XML file. More information is available here.  A running example (although nothing spectacular is visible) can be launched here. Click on "Dialog base xml".


środa, 28 sierpnia 2013

Clojure and polynomials

Introduction
I started reading through Clojure tutorial and found very interesting implementation of calculating polynomial and its first derivative. So I decided to stretch my math muscle and perform more polynomial arithmetic in Clojure basing on this article.
I'm assuming all the time that polynomial in Clojure is a list of coefficients from left to right (like in the written form). So list [2 8 9]  means 2x² + 8x + 9, [7 0 1 7] means: 7x³ + x + 7
Addition
Almost nothing more than (map + ...) function. The only problem is to expand shorter list (lower degree polynomial). Also improvement should be added to reduce the leading zeros from the result. Example:
(2x² + 8x + 9) + (-2x² + 2x + 4) = 0x² + 10x + 13

(defn addpol
  [pol1 pol2]
  ; degree of the sum polynomial 
  (let [nsize (max (count pol1) (count pol2) ) ]
  ; expand polynomial to the new degree by adding 0 coefficient at the frot
    (defn expandpol 
        [pol] 
            (concat ( repeat (max 0 (- nsize (count pol))) 0 ) pol )
    )
  )
  ; having both polynomials at the same degree just sum them
  (map + (expandpol pol1) (expandpol pol2))
)
Subtraction
Just use the previous function and negate the subtrahend.
(defn subtractpol
  [minuend subtrahend]
  ; negate subtrahend and run summing
  (addpol minuend ( map #(- 0 %) subtrahend))
)
Product
Multiply every coefficient of the first polynomial by every coefficient of the second polynomial. Recursion is used to iterate but this algorithm is a good candidate for loop->recur for better performance.

(defn mulpol
  [pol1 pol2]
  ( let
    ; level of the product
      [newlevel (- (+ (count pol1) (count pol2)) 1)]  
    ; multiply polynomial by digit and add zeros at the frond and end keeping it at the degree necessary
    (defn muldigit 
       [beg coeff end]
       (concat (repeat beg 0) (map #(* % coeff) pol2) (repeat end 0))
    )
    ; recursive as replacement for iteration
    (defn muladd
       ; 'beg' number of left zeros
       ; 'currentsum' list of coefficient multiplications peformed so far
       ; 'restpol1' list of coefficients not used yet
       ; 'end' number of right zeros
       [beg currentsum restpol1 end]
       (condp = restpol1
       ; end of recursion
       [] currentsum
       ; multiply and move to the next digit
       (
         map
            +
            currentsum
            (muladd 
               (+ beg 1)
               (muldigit beg (first restpol1) end)
               (rest restpol1)
               (- end 1)
            )
       )
       )
     )
  ; start of the recursion
  ( muladd 0 (repeat newlevel 0) pol1 (- newlevel (count pol2)))
  )
)
Division
Is more complicated because two results are expected: quotient and remainder. So to bring the result a map is used. Polynomial long division is implemented as easier. This function should be expanded to exclude division by zero (empty divisor) and reduce leading zeros from divisor. Example: (0 4 5)

; returns a map with two keys :quotient and :remainder
(defn divpol 
   [divident divisor]
   ; perform (lead(r)/lead(divisor)) * divisor
   (defn multerm
     [r resdiv]
       (concat (map #(* resdiv %) divisor) (repeat (- (count r) (count divisor)) 0))
   )
   ; recursive
   (defn div 
     [mapd]
   ( let [ q (get mapd :quotient)
           r (get mapd :remainder) 
           dv (/ (first r) (first divisor)) 
         ]
   ; end of recursion, pass down the result
   (if (or (< (count r) (count divisor)) (empty? r))
       mapd
   ; pull down the next digit from divident
       (div ( hash-map 
              :quotient (conj q dv)
              :remainder (rest (map - r (multerm r dv)))
            )
       )
   )
   )
   )   
   ; beginning of the recursion
   (div ( hash-map :quotient [], :remainder divident))
)   

niedziela, 18 sierpnia 2013

MVP Jython framework, html panel and javascript code

Introduction
The dialog is displayed using default layout. The default layout is convenient at the beginning but later probably something more useful and better looking is necessary. So it is possible to replace default layout by means of GWT HTMLPanel widget. Just add to the dialog definition file containing dialog layout in shape of html page and new display is visible. Also custom Javascript code can be added to the page.
TabPanel is very useful way of displaying a lot of data on the screen without scrolls. TabPanel can be built by combining html, css and javascript code but GWT contains TabPanel widget.
HTMLPanel and JavaScript custom code

Sample application is available here (click at "Dialog HTML panel"). The html, css and JavaScript code was downloaded from this page. It does not make a lot of sense here, it is only a presentation how default layout can be enriched with html, css and custom Javascript code. More detailed description is available here.
Adding HTMLPanel definition impacts only presentation part. It does not involve any change in backing Jython code.
TabPanel

Sample application is available here (click at "Dialog tab panel"). The usage of the TabPanel is limited currently. For instance it is not possible to disperse buttons between different tab pages. More detailed description is available here.  
Problems
  • Current implementation of HTMLPanel does not allow to use custom (internationalized) labels. It will be added later.
  • Current implementation of TabPanel is limited. More flexible approach will be added later.

czwartek, 1 sierpnia 2013

MVP Jython framework and edit grid

Introduction
I added a new widget to my MVP framework. It is an "edit grid" which allows modification data in the list directly (like in this GWT showcase) but allowing adding and removing rows dynamically.

This widget can be used when a number of fields is relatively small (containable in one line) and line editing is more natural then standard CRUD editing. Google App Engine live demo version is available here. Detailed description here, also source code and Selenium unit tests.
Problem
The main problem I found was to detect "the end of edit single line". There is no any direct "finish" button. This action is necessary to perform data validation and store data in persistence layer (assuming that one line reflects one record). The only solution I found was to discover the end of line editing after moving to the another line. In this case editing of the next line is suspended for moment and actions related to the last line are executed. If data validation fails then user is forced to return to the previous line and fix the data.
From that stems another problem. When user wants to finish editing he simply clicks "Accept" (or any other) button without moving to the next line. So it was necessary also to provide a way to declare which buttons requires validation of the last line.
 There are two ways of making data persisted. One is to persist data after any action relating to data change (after single column or whole line) or store all lines at the end of editing (after pressing "Accept" button or any other). In this case it is necessary to transport all data from the client to the server side. In order to avoid unnecessary traffic there is a way to specify which buttons trigger data transportation and which buttons do not. When data persisting is done at the end of editing there is a risk of losing all data just entered in case of any failure.
Next steps
I plan to use this widget in the JavaHotel application is several cases. The first case will be manually changing list price for reservation and bypass prices provided from regular price list.

wtorek, 30 lipca 2013

Byliśmy na przedstawieniu

20 lipca byliśmy na przedstawieniu filmu operowego "Kopciuszek" wyświetlonego w ramach 13 edycji Festiwalu "Ogrody Muzyczne" na Zamku Królewskim w Warszawie, podobało nam się bardzo.
Opera Rossiniego jest pozbawiona elementów bajkowych w porównaniu do wersji baśni Charles Perraulta, nie ma tutaj czarów dobrej wróżki. Autorzy przedstawienia postanowili jednak przypomnieć baśniowy charakter w postaci pięknych animacji pojawiających się w przerwach miedzy aktami opery.
Samo przedstawienie jest częścią szerszego projektu mającego na celu nagrywanie oper w historycznych wnętrzach z pełnym użyciem nowoczesnej techniki, tutaj za scenę posłużyły zabytkowe budowle z Turynu.
Samo przedstawienie nie ma jednego bohatera czy wiodącego solisty, tutaj wszystkie elementy są tak samo ważne i stanowią istotny element całości.
Autorzy nie zamierzali intrygować widzów jakimś rewolucyjnym i nowatorskim odczytaniem dzieła operowego, a raczej odwrotnie. Za pomocą nowoczesnej techniki wydobyć i pokazać to co najpiękniejsze, czyli wspaniałe wnętrza, piękną muzykę i postacie wykonawców, którzy nie tylko śpiewają swoje role ale także z wielkim talentem je odgrywają.
To zamierzenie udało się z całą pewnością. Mimo  iż cały film trwa blisko trzy godziny, to śledzi się od początku do końca z niesłabnącą przyjemnością i zainteresowaniem.