Blog do projektu Open Source JavaHotel

wtorek, 20 września 2011

GWT, editable table

I found very usable a Cell Table which allows to edit its cells (sample). It is quite easy to use it : while adding new column to the table use 'editable' cell in the constructor.
But standard editable cell types (EditTextCell, TextInputCell, DatePickerCell) have one limitation :  these columns in all rows are eligible to edit. So I found impossible to implement the following scenario:
  1. User is browsing through the table. Edit mode is blocked to avoid changing something by accident.
  2. Decides to edit one row.  Set on the switch 'edit this row' and this row is transformed to edit mode. But edit mode for all other rows is blocked.
  3. After finishing editing set off the switch and the row is again in look mode.
So in order to implement this scenario I was forced to create my own 'editable' cells by extending standard editable cell type.
Example - switchable version of 'TextInputCell'
private class EditStringCell extends TextInputCell implements IGetField {

        private final IVField v;

        EditStringCell(IVField v) {
            this.v = v;
        }

        @Override
        public void render(Context context, String value, SafeHtmlBuilder sb) {
            Object key = context.getKey();
            Integer i = (Integer) key;
            boolean editenabled = eCol.isEditable(i, v);
            if (editenabled) {
                super.render(context, value, sb);
                return;
            }
            // Get the view data.
            // copy and paste from TextInputCell
            // the only difference is different HTML for displaying value
            TemplateDisplay template = GWT.create(TemplateDisplay.class);
            ViewData viewData = getViewData(key);
            if (viewData != null && viewData.getCurrentValue().equals(value)) {
                clearViewData(key);
                viewData = null;
            }
            String s = (viewData != null) ? viewData.getCurrentValue() : value;
            if (s != null) {
                sb.append(template.input(s));
            } else {
                sb.appendHtmlConstant("");
            }
        }

The difference is only in 'render' method. If 'edit mode' is on it simply invokes standard method. If 'edit mode' is off it overrides standard and displays the content. In order to have it working correctly I had to copy and modify the body of standard method to deal with specific way of storing value of the cell in 'ViewData' type.
Although I'm not very happy with that is seems working for me.
The all 'switchable' edit cell I'm using are implemented in this source.

niedziela, 11 września 2011

New version Boa tester

New version of Boa test framework.
In order to avoid CR/LF (DOS) and LF (Linux) hell I had to change a method for file comparison. I replaced standard filecmp.cmp function with manual line by line comparison. Source file.

Before:
  eq = filecmp.cmp(sou, dest)
  if not eq:
    logging.info("  different")
    res = 0

Now:
f1 = open(sou, "r")
 f2 = open(dest, "r")
 li1 = f1.readlines()
 li2 = f2.readlines()
 if len(li1) != len(li2) :
    logging.info(" number of lines is different")
    res = 0
    continue
 for i in range(0, len(li1))  :
 line1 = li1[i].rstrip()
 line2 = li2[i].rstrip()
 if line1 != line2 : 
    logging.info(" line number: " + str(i)  + " different")
    logging.info(line1)
    logging.info(line2)
    res = 0
    break

niedziela, 21 sierpnia 2011

Trusted context and LBAC

Introduction
I decided to create another example to demonstrate the power of trusted connection. This time I will use LBAC Label Based Access Control in DB2. It enables more granular control on access  to the data than standard SQL GRANT and REVOKE clause. We can limit access not only the whole database objects (like tables and views) but also to the particular rows and columns in tables. Important: LBAC is not available in DB2 Express Edition (free). But it is accessible in demo (90 day) version of DB 9.7.
More information on LBAC: http://www.ibm.com/developerworks/data/tutorials/dm0605wong/

Example
Let's use the standard SAMPLE database. Assume that out of the blue very restrictive access policy in our HR department has been announced - women can only look at the data of female workers and men only male workers (or opposite). How to enforce that policy without costly and time consuming rewrtiting of our HR software ?
The rescue is the usage of LBAC. To cut the long story short it is based on labels which are assigned to the rows in the EMPLOYEE table. Than the same label is assigned to the user and by comparing these labels DB2 limits access to the row in the table.
Enabling LBAC policy on EMPLOYEE table is little bit complicate and requires several steps. But very important: it is done at the database level, does not involve any changed in the software.

Step1 - create LBAC enabled table
In order to avoid spoiling SAMPLE database I will create additional LBAC_EMPLOYEE table being a copy of the EMPLOYEE_table

create table lbac_employee like employee
grant select on table lbac_employee to role samplereadaccess
insert into lbac_employee (select * from employee)

Step 2 - create security label component and policy
CREATE SECURITY LABEL COMPONENT SEX SET {'F','M'}
CREATE SECURITY POLICY SEX_POLICY COMPONENTS SEX WITH DB2LBACRULES
ALTER SECURITY POLICY SEC_POLICY USE ROLE AUTHORIZATIONS

Step 3 - enable LBAC on a table

ALTER TABLE LBAC_EMPLOYEE ADD SECURITY POLICY SEX_POLICY

ALTER TABLE lbac_employee ADD COLUMN SEX_PROTECTION DB2SECURITYLABEL
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL20402N Authorization ID "DB2INST1" does not have the LBAC credentials to
perform the "ALTER" operation on table "DB2INST1.LBAC_EMPLOYEE".
SQLSTATE=42519

The second command failed - it means that our LBAC protection over EMPLOYEE table is working. Only an user having valid LBAC security level can modify the table. Even instance owner (db2inst1) cannot modify LBAC protected table without LBAC authorization !

Step 4 - create role and security labels

CREATE SECURITY LABEL SEX_POLICY.ADM COMPONENT SEX 'F','M'
GRANT SECURITY LABEL SEX_POLICY.ADM TO user db2inst1 FOR WRITE ACCESS
DB21034E The command was processed as an SQL statement because it was not a
valid Command Line Processor command. During SQL processing it returned:
SQL0554N An authorization ID cannot grant a privilege or authority to itself.
SQLSTATE=42502

Again - the second command failed. Starting from DB2 9.7 security role has been separated from the database administrator role. Only the user having SECAMD (security administrator) role can assign LBAC privileges to users.

Step 5 - create SECADM user
# linux commmand
adduser db2sec1
grant secadm on database to user db2sec1
# connect to SAMPLE database as db2sec1 user and rerun the command
GRANT SECURITY LABEL SEX_POLICY.ADM TO user db2inst1 FOR WRITE ACCESS
(passed this time)

Step 6 - Finalize LBAC table protection
Reconnect as db2inst1 user and rerun the command again
ALTER TABLE lbac_employee ADD COLUMN SEX_PROTECTION DB2SECURITYLABEL
(passed this time)

Step 7 - Create roles and additional security labels
Assume that role LBAC_F enables access to female employees and LBAC_M to male employees.

create role LBAC_F
create role LBAC_M
CREATE SECURITY LABEL SEX_POLICY.F COMPONENT SEX 'F'
CREATE SECURITY LABEL SEX_POLICY.M COMPONENT SEX 'M'
alter security policy sex_policy user role LBAC_F
alter security policy sex_policy user role LBAC_E
GRANT SECURITY LABEL SEX_POLICY.F TO ROLE LBAC_F for all access
GRANT SECURITY LABEL SEX_POLICY.M TO ROLE LBAC_M for all access
GRANT samplereadaccess to role LBAC_F
GRANT samplereadaccess to role LBAC_M
Step 8 - assign labels to the LBAC_EMPLOYEE rows

update lbac_employee set sex_protection=seclabel('SEX_POLICY','M') where Sex='M'
update lbac_employee set sex_protection=seclabel('SEX_POLICY','F') where Sex='F'
select substr(seclabel_to_char('SEX_POLICY',sex_protection),1,6) from lbac_employee
Step 9 - modify trusted connection object
Assume the user 'PETER' is allowed to read only males workers and user 'DOROTHY' only female workers.
ALTER TRUSTED CONTEXT MYTCX ADD USE FOR PETER ROLE LBAC_M WITHOUT AUTHENTICATION
ALTER TRUSTED CONTEXT MYTCX ADD USE FOR DOROTHY ROLE LBAC_F WITHOUT
AUTHENTICATION

Step 10 - run application and watch the output

I modified the application a little bit - look at the source code. It is very simply - just run and print the "SELECT * FROM LBAC_EMPLOYEE" statement. The same code is executed firstly by 'PETER' and secondly by 'DOROTHY'.  The first time the code yields 23 rows and the second time 11 rows. What more important - the user is unaware about the presence of the other rows so the access to this rows is forbidden at the database (not application) level.

piątek, 29 lipca 2011

Find all subsets recursively

Problem
Having a set of positive numbers from 0 to 9 find recursively all subsets which sums up to 10.

Algorithm 1
Take a subset. If sums up to 10 then print it. Is sums less than 10 then break. Then apply the same algorithm for any subset received by removing from the first subset one element.
Start with the initial set.
C++ code :
#include <iostream>
#include <vector>

const int SET_SIZE = 10;
typedef std::vector<bool> settype;
const int SUM=10;

void print(const settype &set) {
  for (int i=0; i<SET_SIZE; i++) {
    if (set[i]) std::cout<<i+1<<' ';
  }
  std::cout<<std::endl;
}

void run_set(settype set,int sum, int remove) {
  if (remove != -1) {
    set[remove] = false;
    sum -= (remove + 1);
  }
  if (sum < SUM) return;
  if (sum == SUM) print(set);

  for (int i = remove+1; i<SET_SIZE; i++) {
    if (set[i]) {
      run_set(set,sum,i);
    }
  }
}

int main(int argc, char **argv) {
    bool init_set[SET_SIZE] = { true,false,true,true,false,true,true,true,false,true};
    settype setOfNum(init_set,init_set + sizeof(init_set) / sizeof(bool));
    int sum = 39;
    run_set(setOfNum,sum,-1);   
    return 0;
}


Algorithm 2
Apply a variant of 0-1 snapsack problem.
Take a subset.
  1. If subset sums to less than 10 then break.
  2. Remove last element and find all subsets which sums to 10.
  3. Remove last element and find all subsets which sums to 10 minus the last element.
  4. Sums set of sets received in point 1) and set of sets received in point 2) plus the last (removed) element.
C++ code:
#include <iostream>

#include <vector>
#include <algorithm>
using namespace std;

const int SUM=10;

typedef std::vector<int> settype;
typedef std::vector<settype> listofset;

void print(const settype &set) {
    for (int k=0; k<set.size(); k++) {
      cout << set[k] << ' ';
    }
    cout << endl;
}  

void D(int i,int w,const settype &set,listofset &outlist) {
  listofset list1,list2;
  i--;
  if ((w == 0) || (i == -1)) {
    outlist = list1;
    return;
  }
  D(i,w,set,list1);
  D(i,w-set[i],set,list2);
  outlist = list1;
  for (int k=0; k<list2.size(); k++) {
    list2[k].push_back(set[i]);
    outlist.push_back(list2[k]);
  }
  if (set[i] == w) {
    settype t;
    t.push_back(set[i]);
    outlist.push_back(t);
    return;
  }
}
  

int main(int argc, char **argv) {
    int init_set[] = { 1,9,10,2,7 };
    settype set(init_set,init_set + sizeof(init_set) / sizeof(int));
    listofset outset;
    D(set.size(),SUM,set,outset);
    for (int i=0; i<outset.size(); i++) {      
     cout << i << ":";
      print(outset[i]);
    }  
    return 0;
}

Remarks
Of course - it is an artificial problem, the best way is to apply simple iteration without recursion.
Another problem is the complexity. The number of all subsets of n-element set is exponential (2 to power n). So the algorithm is no worse than that. But is it possible to do it faster - in polynomial complexity.

niedziela, 24 lipca 2011

BenchmarkSQL

I started playing with the opensource tool "BenchmarkSQL". It allows to run TPC-C like test allowing measuring OLTP performance on different databases. Unfortunately, I had to fix several minor bugs - it seemed that loading data does not work correctly - the order of columns in several tables does not match INSERT and LOAD command. I also added additional run-time parameters for setting some settings related to test.
-DNoW={number of warehouses}
-DNoT=10 {number of terminales}
-DNoM=5 {number of minutes for test to run}
The fixed version can be downloaded from : BenchmarkSQL. 
I run the test again DB2, Oracle and Postgress databases running on the same box : Ubuntu, ThinkPad T-42, 1.7 GH IntelPentium, 2 GB RAM.
The databases have been installed out of the box, using default settings. The current score is as follows (10 warehouses, 10 terminals, 5 minute test)
Oracle: tpmC = 410
DB2: tpmC = 260
Postgres : tpmC = 240
I will try to improve DB2 performance by providing some tunning.

wtorek, 19 lipca 2011

Byliśmy na przedstawieniu

Dnia 18 lipca 2011 roku byliśmy na przedstawieniu opery Mozarta "Idomeneo, król Krety" wystawianego w ramach XXI Festiwalu Mozartowskiego, ale wyszliśmy mocno rozczarowani.
"Idomeneo" to mniej znana opera Mozarta, pozostająca trochę w cieniu sławniejszych oper tego kompozytora. A zupełnie niesłusznie, to także piękna muzyka i efektowne arie. Tego samego zdania był przecież sam Mozart, który kilka zapożyczeń z "Idomeneo" przeniósł do późniejszych dzieł. Na przykład, marsz z towarzyszeniem recytatywu Elektry z pierwszego aktu jako żywo przypomina słynny "Ecco la marcia" z trzeciego aktu "Wesela Figara". Tylko, że w tym przedstawieniu zupełnie nie było tego słychać, jakby realizatorzy chcieli nas przekonać, że mniejsza popularność tej opery jest w pełni zasłużona.
Zupełnie zawiódł odtwórca głównej roli, wyraźnie czuł się bardzo niepewnie, kilkakrotnie niezbędna była pomoc suflera. W konsekwencji, w miarę upływu czasu każde pojawienie się tej postaci powodowało rosnący niepokój, czy coś znowu nie pójdzie źle. Zły nastrój udzielił się chyba także orkiestrze, która wyraźnie nie była w formie, czasami bardziej przeszkadzała wykonawcom niż pomagała. 
Także inscenizacja nie trafiła mi do przekonania, nie potrafiłem zrozumieć zamiłowania inscenizatora do pogrążania sceny w mroku, cały czas odnosiłem wrażenie, że wykonawcy śpiewają z piwnicy. W operze istotną rolę pełni morski potwór pustoszący Kretę jako karę za złamaną obietnicę Idomenea. Na scenie widzimy dwie istoty z zaświatów - raz to prawdziwe monstrum, zaś potem na scenie nam towarzyszy ubrane w złoto bóstwo, sądząc z trojzębu trzymanego w ręku miał to być bóg Posejdon. Ale to bóstwo pada pod ciosem Idamanta, zaś potem głos z zaświatów oznajmia ostateczną wolę Posejdona i sztuka znajduje szczęśliwe zakończenie. Więc jeśli był tutaj jakiś zamysł inscenizatorski, to sens całkowicie mi umknął.
Na szczęście pozostali wykonawcy stanęli na wysokości zadania. Nie zawiódł ani Sylweser Smulczyński jako Idamante, ani Marta Boberska jako Ilia. Zaś każde pojawienie się Gabrieli Kamińskiej w roli Elektry podnosiło temperaturę o kilka stopni. Końcowe wykonanie brawurowej arii ""D'Oreste, d'Ajace" zapadało w pamięć.
Także chór wypadł znakomicie. W "Idomeneo", inaczej niż w innym operach Mozarta, chór ma dużą rolę do odegrania, w tym partie solowe.
Ale złe wrażenie jednak pozostało. Trzeba mieć tylko nadzieję, że jeśli Warszawska Opera Kameralna utrzyma w programie to przedstawienie w następnym roku, to poprzedzi występ bardziej starannymi przygotowaniami i z lepszym przemyśleniem, co zaprezentować widzom.

poniedziałek, 18 lipca 2011

Byliśmy na koncercie

16 lipca 2011 roku byliśmy na przedstawieniu (a właściwie projekcji) inscenizacji "Króla Rogera" w ramach tegorocznego Festiwalu "Ogrody Muzyczne", podobało nam się bardzo, chociaż z pewnymi zastrzeżeniami. Była to rejestracja przedstawienia, które miało swoją premierę w 2009 roku w paryskiej "Opéra Bastille". Przedstawienie odbyło się w atmosferze skandalu spowodowanego kontrowersyjną inscenizacją Krzysztofa Warlikowskiego. Przykłady druzgocących recenzji można znaleźć w Gazecie Wyborczej lub w polskiej edycji Newsweeka. 
Zacytuję fragment z tej drugiej recenzji:
Widzowie znający utwór słabo – Francuzi, którzy go dotąd nie widzieli, albo Polacy z rzadka bywający w operze – skłonni byli tej inscenizacji bronić.
 Jestem skłonny bronić tej inscenizacji, aczkolwiek z przyczyn innych niż to zakłada autor recenzji.
Gdyż o czym opowiada nam libretto opery (autorstwa Iwaszkiewicza) ? Na dwór mądrego króla Rogera, spędzającego wieczór w towarzystwie uroczej żony Roksany (równolegle odprawiana jest liturgia religijna) przybywa tajemniczy Pasterz, szukający zbłąkanych stad w imieniu nieznanego boga. W zetknięciu z Pasterzem, cały ten uporządkowany i zorganizowany świat świecki i religijny rozpada się w gruzy porywając także Rogerowi ukochaną Roksanę.
Pod to libretto można podkładać czy doszukiwać się dowolnych znaczeń, można także tego nie robić. I wyraźnie tą drugą drogą poszedł Warlikowski. Nie próbuje nam opowiadać jakiejś historii czy sugerować, że kryją się pod tym głębokie i ponadczasowe treści. Na scenie widzimy absurdalny i nierzeczywisty świat, przypominający atmosferą dawne filmy science-fiction. Chociaż końcowa scena, gdzie Pasterz ma założoną głowę Myszki Miki, zaś tłum oddaje cześć słońcu wyobrażonemu w postaci neonu przypominającego wejście do baru sugeruje, że owym nowym bogiem, do którego prowadzi Pasterz są nasze współczesne bożki kultury masowej.
Można próbować to zrozumieć, ale wtedy ryzykujemy porażkę niczym tytułowy król Roger usiłujący zrozumieć, co się wokół niego dzieje.Oczywiście, tego typu inscenizacja odniesiona do np. opery Mozarta pewnie by raziła tanim efekciarstwem.
Głównym zarzutem jaki można postawić tej inscenizacji, jak zauważył we wprowadzeniu Zygmunt Krauze, jest to, że tutaj gubi się niestety piękna i oryginalna muzyka Szymanowskiego. Zamiast słuchać muzyki śledzimy na scenie kolejne pomysły inscenizatorskie.
Ogromnym atutem przedstawienie jest także doskonałe wykonawstwo: Mariusz Kwiecień, Olga Pasiecznik oraz Eric Cutler (jako Pasterz). Chociaż też można odnieść wrażenie, że czasami ekspresja o charakterze aktorskim przytłacza stronę muzyczną.
Część osób zgromadzonych w namiocie, gdzie odbyła się projekcja, była zniecierpliwiona długim wprowadzeniem w muzykę Szymanowskiego Zygmunta Krauze i Krzysztofa Baculewskiego. My jednak słuchaliśmy z zainteresowaniem, obaj rozmówcy doskonale znali temat, zaś Szymanowski - chociaż "pierwszy po Chopinie" - to ciągle człowiek i kompozytor mało znany, także w Polsce.
Uderzała także wysoka frekwencja, namiot na kilkaset osób był prawie pełny, i to pomimo tego, że muzyka Szymanowskiego nie jest łatwa w odbiorze, wymaga pewnego przygotowania od słuchacza. Dzieło Szymanowskiego zostawia dużo swobody wykonawcom,  na pewno jest dużo pola do popisu dla innych inscenizatorów i na pewno znajdą się widzowie i słuchacze.