19 December 2012

Android: activating screen disconnects phone call

When you are calling the customer service of a Belgian phone company you can go into the waiting queue for a looooooong time. So i put the speaker on and have the waiting music loop while I continue working. When they finally pick up the phone, half an hour later, the phone screen has gone in sleep mode. So... I press the power button to switch the screen on (and switch the speaker off), which ... ends the call I've been waiting for so long. Aaaaargh...

How to disable call disconnection when you activate your screen with the power button on Android (4.0)?
Go to Settings > "Accessibility" and uncheck "Power button ends calls".
Unfortunatly you will also loose the intuitive facility to end a phone call using the power button.
 
Pushing the button when the screen is off should wake up the screen, pushing the button when the screen is on and a call is ongoing should end the call.
Hope Google guys correct his in the future. Please?

11 December 2012

Upcoming features for Hybris 4.8

Next week a new minor 4.8 release is expected for the Hybris e-commerce platform.
This should be the last release before the major Hybris 5.0 release (expected Q2 2013).
Expected new features:

  • Subsrciptions and bundling module
    • recurring price models
    • product bundles (e;g. sell entire digital publication or individual chapters and articles, sell mobile with phone contract)
      • dynamic, rule based bundling and pricing
    • cockpit: graphical dashboard for managing bundles and subscriptions
    • great for any digital content provider(newspapers, platform subscriptions, eBooks, Steam-like online game buying...)
  • New Telco accelerators, built on subscription and bundling module. An accelerator is a prebuilt Hybris application targeted at a specific market.
    • B2B accelerator mobile front

    6 December 2012

    KeyKash: transfer money from mobile to mobile

    Keytrade bank introduced the KeyKash Android application that allows you to transfer money to another mobile phone (also running KeyKash). As a Keytrade customer you can send money to any belgian bank account.
    You can transfer money using NFC (put the phones back to back and tap your screen) or QR code (let the receiver scan the QR code for the transfer).

    15 November 2012

    Paperless conference

    No brochures anymore @devoxx.
    Just Mobile apps & web.

    If Java had true garbage collection, most programs would delete themselves upon execution.

    Robert Sewell

    5 November 2012

    Windows 8 restricted boot

    The new Windows 8 UEFI (Unified Extensible Firmware Interface) secure booting system will prevent hardware from booting anything that has not been signed, using keys from Microsoft or the OEM.
    This will prevent the hardware from booting anything else than Microsoft software, like malware (the target) or Linux (collateral benefit).
    The effective rules are discussed here:

    • Windows 8 certification requires that hardware ship with UEFI secure boot enabled.
    • Microsoft's certification requirements eventually revealed that that UEFI firmware on x86 systems must allow users to re-configure or turn off secure boot, but that this must not be possible on ARM-based systems (Windows RT)
    • Windows 8 certification does require that the user be able to disable UEFI secure boot, , but this must not be possible on ARM-based systems (Windows RT)
    • Windows 8 certification does not require that the system ship with any keys other than Microsoft's.
    • Developers (e.g. for drivers) must pay $99 (which goes to VeriSign) to access the Microsoft sysdev portal in order to get binaries signed by the Microsoft key.
    On the same site you can find information on Shim, a Linux project to develop a first stage boot loader for supporting UEFI Secure Boot.

    30 October 2012

    Agile motivation

    Nice summary here:

    • Upfront planning requires upfront knowledge
    • Business does not need perfection, it wants action

    29 October 2012

    New computer: software to add (updated)

    Installing a new laptop today. Here's the software I put on it:

    22 October 2012

    Amazon: The e-book library

    Amazon advertizes itself as a book shop. That's correct for hard copies.
    For e-books it's different: you can only borrow them.
    Amazon is an e-book library.
    And they can take back your books as they see fit.
    Without warning, without explanation, without an independent judge.
    Here's the story about a customer who had her kindle e-reader books removed,
    because Amazon linked her account to another account that was closed for abuse of policy.
    The customer asked:

    1. How my account is linked to the blocked account
    2. The name/id of the related blocked account
    3. What policy that was violated
    She never got an answer.

    11 October 2012

    We run on any Java EE Server ...

    ... except JBoss, WebLogic and WebSphere.

    My colleague, Romain, found this beauty in the features supported by Magnolia CMS Community Edition:

    Feature Description CE EE Std EE Pro
    100% Java/J2EE compliance Magnolia is developed in Java and runs on any J2EE compliant application server.
    Compatibility with Tomcat All editions of Magnolia are compatible with Tomcat application server.  ✔
    Compatibility with JBoss Standard and Pro versions of Enterprise Edition are compatible with JBoss application server.
    Compatibility with Websphere, Weblogic Only the Pro version of Magnolia Enterprise Edition can be deployed on Websphere or Weblogic application server.

    3 October 2012

    SHA-3 secure hash standard selected

    NIST has selected Keccak as the new SHA-3 cryptographic hash standard.
    Keccak was designed by Guido Bertoni (Italy),Joan Daemen (Belgium), Michaƫl Peeters (Belgium) and Gilles Van Assche (Belgium).
    Joan Daemen previously co-designed Rijndael, which was selected as the AES symmetrical cipher standard in 2001.

    The Object Relational Gap (updated)

    The Object Relational Gap
    transient persistent
    classes tables
    • inheritance
    attributes columns
    objects rows
    • instance attribute
    • implicity ID: reference 
    • field
    • explicit ID: primary key 
    relations relations
    • references
    • unidirectional 
    • ordered (lists) 
    • foreign keys
    • bidirectional 
    behaviour centric data centric
    • navigate to object
    • behaviour based partitioning
    • methods 
    • operate on set
    • relation based partitioning
    • stored procedures 
      • tight behaviour-data coupling
      • triggers, constraints
      • data hiding, encapsulation


      • Permissions

    2 October 2012

    Spam assasin

    This is the most aggressive scam i received until now.
    Similar to this report.
    ________________________________________
    From: Hakeem Mohammad [Hakeem@killer.pk]
    Sent: monday 1 october 2012 16:55
    To: Recipients
    Subject: Reply Me Immediately

    To your attention

    I want you to read this message very carefully and that you keep the secret until further notice. You do not need to know or who I am or where I come from. I was paid an advance of $50,000 to eliminate you. My sponsors one of which is what we can call a friend gave me the reasons I noted. I am more than ten days and now I know that you are innocent of what you are accused. Do not try to warn or send this message to the FBI or the police because I know that I'll have to do the job for which I was paid. Note that this is the first time that I betrayed my employer.

    Look, I'll do everything I can so that we can meet before but I need $20,000. You have nothing to afraid of me, I can come see you in your office or home, it is up to you to decide. Never attempt recording or filming our upcoming meeting. It will pay $20,000 to the account I will tell you, this before our first meeting. Once payment is made, I will give you the file that contains the names and queries sponsors. This is a good evidence that can be used to sue if you wish. The balance of the payment will be settled later. For the moment this is not the trouble I give you my phone number because you will cooperate. I have your picture and other important information about you. I was involved with my team in the Yemen
    Arab Republic. You must not ask me any questions.

    Quickly confirm for your good.

    27 September 2012

    Google cuts gmail for youngsters

    My friends daughter is eleven years old and Google has closed down access to her email.
    Without any warning she loses all stored emails and contacts. 
    She has 30 days to prove she is at least twelve years old (which she isn't) before all gmail contents will be permanently removed.
    The only thing my friend can do is lie about her age. He has to do this by making a $0.3 credit card payment to Google to prove the lie has been told by someone who is old enough to own a credit card.

    Google has been pushing users to convert their Google accounts to Google+ accouonts.
    But privacy restrictions for social accounts are much stricter for children.
    So now Google is kicking all children who have converted to Google+ out.

    This experience shows that free Google services come without any guarantee and Google can decide to throw away all your work  at any time.
    We have seen this in the past with other free Google services

    • Google apps: I had to give my credit card number when i signed up for the free Google Apps. When it became paying my application was below the paying limits, still Google started taking small amonts from my credit card. Without any justification, invoice or contact person I could turn to for an explanation. In the end I had to get a new credit to make this stop.
    • iGoogle retirement

    7 September 2012

    Oracle drops Java EE7 out of the cloud

    Cloud support (PaaS) was Oracle's main focus for Java EE7.
    Oracle has now proposed to the expert group to remove cloud support from Java EE7 in order to keep the planned release schedule.
    Expert group members react positively.
    I just don't know: dropping your main feature to reach your deadline?
    We delivered your car on time, Sir (but the engine's missing).

    EJB version history

    Year
    Java EE
    EJB
    What’s new
    1998

    1.0
    Stateful Session Beans
    Stateless Session Beans
    Entity Beans
    JNDI
    Thread safe
    JTA
    1999
    1.2
    1.1
    XML descriptors
    RMI over IIOP
    2001
    1.3
    2.0
    local beans
    2003
    1.4
    2.1
    SOAP support
    Message driven beans
    2006
    5
    3.0
    JPA replaces Entity beans
    POJOs/annotations
    2009
    6
    3.1
    CDI
    @Asynchronous
    @Singleton
    2013
    7
    3.2

    29 July 2012

    Programmatic servlet configuration

    Servlet 3 allows you to configure your webapplication in Java.
    A set of methods have been added to ServletContext to support this, e.g.

    • addFilter
    • addListener
    • addServlet
    When your application starts, you can call these methods from a  ServletContextListener:
    @WebListener
    public class MyServletContextListener implements ServletContextListener {
      public void contextInitialized(ServletContextEvent event) {
        ServletContext ctx = event.getServletContext();
        ServletRegistration servlet = ctx.addServlet ("ProServlet","org.edu.ProServlet");   
        servlet.addMapping("/dyna/*");
      }
      public void contextDestroyed(ServletContextEvent event) {}
    }
    After the ServletContext is initialised, you can't call these methods anymore.

    Servlet listeners

    Scope Lifecycle listeners Attribute change listeners Register
    Application ServletContextListener ServletContextAttributeListener @WebListener
    Servlet HttpServlet @PostConstruct
    @PreDestroy
    Session HttpSessionListener HttpSessionAttributeListener @WebListener
    Request ServletRequestListener ServletRequestAttributeListener @WebListener
    Asynchronous Request AsyncListener AsyncContext#addListener

    What’s new in Servlet 3 (edit)

    Servlets 3 (JSR 315) highlights:

    • Instead of configuring the web application in the web.xml deployment description you now have more options
      • modular deployment descriptor
        jars can be bundled with your webapp containing a web-fragment.xml file. These files are merged with the main web.xml file of your webapp. This allows for easy plugging in of web application modules. If you plugin a framework jar, you won’t have to modify the web.xml of your application anymore (e.g. to send all *.do files to a framework servlet).
      • annotations
        @WebServlet ("/jeeves")
        public class ZServlet extends HttpServlet {
        ....
        }
        • Extends HttpServlet, no POJO (yes!)
      • programmatic configuration
      • Asynchronous servlets
        @WebServlet ("/jeeves", asyncSupported=true) 
        public class ZServlet extends HttpServlet { 
        private AsyncContext ctx
        
        public void doGet( HttpServletRequest req, HttpServletResponse res) { 
        
           ctx = req.startAsync(); 
          // kick off a thread for async work
          ctx.start(new L8r());
          //method returns immediatly, no response sent
        } // end doGet method
        
        class L8r implements Runnable{
           public void run(){
            // do work
            ...
            // response ready
            ctx.complete();
            // alternative: ctx.dispatch("responseViewer.jsp");
          } // end run method
         } //end L8r class
        } //end ZServlet class

        The asynchronous servlet doGet() method does not wait for the L8r thread to complete. The request/response parameters however are not committed, but they are cached in AsyncContext. The L8r thread can then use these to reply to the waiting client.
      • Security
        • ProgrammaticLogin class
        • Java EE5 authorisation annotations
          • @RolesAllowed
          • @PermitAll
          • @DenyAll
        • @transportprotected: use SSL
        • Session security
        • <session-config>
          <!-- do not expose session id by using URL rewriting --> 
            <tracking-mode>COOKIE</tracking-mod>
            <cookie-config>
              <!-- do not expose cookie to javascript-->
              <http-only>true</ttp-only>
              <!-- only transit cookie over encrypted connection-->
              <secure>true</secure>
            </cookie-config>
          </session-config>
          
      • EL 2.2
        Method calls are now possible from EL, e.g.:
          #{portfolio.add('ORCL',100)}

      • File upload (aka multipart support) 

      26 July 2012

      Web components: extra exercises

      Module 3 Exercise 2 (extra): a DAO model

      1. Extend the Anniversary class with an extra attribute: flowers
      2. Add the following files with a new model to the project: AnniversaryMemoryDao with interface AnniversaryDao
      3. Modify the  AnniversaryControl servlet
        1.  Instantiate an AnniversaryDao
          AnniversaryDao dao = AnniversaryMemoryDao.getAnniversaryDAO();
        2. Use anniversaryDao as the model
      4. Modify the JSP to show the flowers you get at the anniversary
      5. (Optional) Create a trivial unit test for the model
        1. Right click the project and select New > Other... > Unit TestsTest Packages  > JU Test for existing class
          1. Browse to the AnniversaryDao class
          2. Click Finish
        2. In the generated Test class
          1. Remove the TestGetAnniversaryDao class
          2. In the testGetByYear method
            1.  Create an AnniversaryDao instance like you did in the Controller servlet
            2. Supply an anniversary year to the getByYear method
            3. Modify the assertEquals method
              1. As a first argument type the name of the flowers matching the anniversary year
              2. As a second argument call the getFlowers method
            4. Add another assertEquals method testing the material
            5. Remove the fail method at the end of the test
          3. In the project window, right click the AnniversaryMemoryTest class and select Test File

      Module 4 Exercise 2 (extra): working with sessions

      1.      Add a “Set colour preferences” link to the Anniversary application index page
      a.    The link should take the user to a colourpicker web page.
      2.      Create the ColourPicker web page, that shows a drop down list with some of these colours:
      a. Aqua Black Blue Fuchsia Gray Green Lime Maroon Navy Olive Purple Red Silver Teal Yellow
        (these are HTML color names defined in the HTML 3 standard)
      b.   Add an OK button that takes you to the ColourControl servlet
      3.      Create the ColourControl servlet. In the servlet
      1. Save the colour in the session
      2. Go back to the home page
      4.      On the showAnniversary.jsp, show the text in the chosen colour. If there is no chosen colour, use black. 

       Hints:

      HTML font tag example: <font color=”Black">  See the difference? </font>
      EL ternary expression example ${aVariable == “”?”empty”:bVariable}

      Module 5 Exercise 2 (extra): Default Colour

      1. Specify an initialization parameter with a default colour for the ColourControl servlet.
      2. Save the value in a session attribute
      3. Use the session attribute to set this colour as the default selected colour in the drop down list in the colourpicker page
      4. Test your application.
      5. The first time you go to the page the default colour is not selected. If you choose a colour and go back to the page the default colour is selected. Explain this behaviour.

      Hint: HTML to set an option as the selected option:

        <option selected>Peach</option>

      Module 6 Exercise 1 Task 2 (extra): Display multivalued headers

      Write a version of the HTTP Headers list that is capable of displaying headers with multiple values

      Module 6 Exercise 3 (extra): Call methods from EL

      1. Add a method calculateWeddingYear() to the Anniversary class in the wedding anniversary project.
      2.  Add a message to showAnniversary.jsp: You were married in the year xxxx!
      3. Test the project and correct any errors until you have the expected result.
      4. Optional: If the AnniversaryMemoryDao does not have an anniversary (e.g. 100) in its list it will return an Anniversary object where the material is empty. Show the message with material and flowers only if you have found an Anniversary object with a material. Show the message with the year of marriage only if you have found an Anniversary object with an empty material.

       

      Module 8 Exercise 3 (extra): Count headers

      Change Module 6 exercise 1 to display the number of headers on top of the list.

       

      Module 8 Exercise 4 (extra): Colourpicker

      Modify the colourpicker in the anniversary project:
      1. supply the colours as a comma separated string: aqua,black,blue,fuchsia gray,green,lime,maroon,navy,olive,purple,red,silver,teal,yellow.
      2. generate the choice menu using a foreach loop
      3. Optional: When you return to the picker the previously chosen color should be selected by default.

       

      Module 8 Exercise 5 (extra): Write a jspx document

      1. Copy index.jsp from Module 6 exercise 1 to index.jspx.
      2. Modify the code to be compliant with a jspx document.
      Solution.

       

      Module 10 Exercise 2 (extra): AnniversaryJpaDao

      In the wedding anniversary project, add a AnniversaryJpaDao.
      1. Create the AnniversaryJpaDao class that implements the AnniversaryDao interface
        1. Add a constructor that takes an EntityManagerFactory as an argument.
        2. Implement the interface methods
          1. In the methods create an EntityManager:
            Entitymanager em = emf.createEntityManager();
          2. Use the EntityManager to access the database.
          3.  Adapt the AnniversaryControl servlet to use the AnniversaryJpaDao.
          4. Inject an EntityManagerFactory in the AnniversaryControl
            @PersistenceUnit private EntityManagerFactory emf;
          5. When the servlet is created, create the AnniversaryJpaDao and assign it to an AnniversaryDao attribute.
          6. Remove any reference to other AnniversaryDao implementations.
      2. Change the Anniversary class into a JPA Entity. 
        1. Use the year as a primary key.
      3.  Create a persistence unit in the project, use an existing glassfish DB resource
      4. Run the project.
        1. Ignore any errors that complain that the Anniversary table already exists.
        2. Correct other errors
      5. Enter the flowers entries into the database
        1.  Collect database characteristics
          1. In the services tab, right click Servers> GlassFish Server> Resources> JDBC> JDBC Resources
          2. Right click the database you used in the project, and select Properties
          3. Write down the Pool Name
          4. Rght click Servers> GlassFish Server> Resources> JDBC> Connection Pools
          5. Right click the pool name you found and select properties
          6. Write down the properties
        2. Create a connection to the database in Netbeans
          1.  Right click the Databases tab and select New Connection...
          2. Select a Java DB (Network) driver and click Next>
          3. Enter the properties of the server database
          4. Append to the JDBC URL
             ;create=true
          5.  Click Finish
        3. Insert the entries
          1. Right click the database connection you created an select Connect...
          2. Right click the database connection you created an select Execute Command...
          3. Copy the contents of this file into the window
          4. Right click in the window and select Run File
      6. Test the application. Verify that all entries returned from the database are in CAPITALS.

      12 July 2012

      Java EE Applications: Calling a JSF page from a non-JSF page

      Lab 6 replaces the CustomerController servlet with the ustomerDetails.xhtml JSF page.
      Existing JSP pages need to be adapted to call the JSF page. Here's how you call a JSF page from a JSP or plain HTML page and pass a parameter to it.

      1. Change the AllCustomers.jsp page to call the JSF page.
        • Existing call to the servlet
        •  <a href="CustomerController?customerIdentity=<%= customers[i].getId()%>&submit=Get Customer">
        • New call to the JSF page
        • <a href="CustomerDetails.xhtml?customerIdentity=<%= customers[i].getId()%>">  
        • Change the JSF backing bean to receive parameters and call code when it is created by a GET request.
          1. Receive a GET parameter in an attribute
          2. @ManagedBean(name="customerDetails")
            @RequestScoped
            public class CustomerManagedBean {
            
               @ManagedProperty("#{param.customerIdentity}")
               private String customerId = "";
               ...
            }
          3. Call a method when the bean is created. The method looks up data using the value stored in the attribute in the previous step.
          4. @PostConstruct
            public void initCustomer() {
              if (customerId != null && customerId.length()!= 0){
                retrieveCustomer();
              }
            }
            

      4 July 2012

      iGoogle to retire

      Google will retire their personalised home page iGoogle on 11/2013.
      This was a pretty neat service combining RSS feeds, overview of discussion groups and financial portfolio's. You had nice gadgets like currency convertors and art of the day, all embedded in changing themes (comics, travel photo's...).
      The logic behind this is not clear to me. There will be some cost shavings, but i can not imagine that iGoogle is that expensive.
      Google encourages you to use Android and Chrome as a replacement. Android has nothing to do with desktops so they may be wanting to push Chrome. Strange: retiring a service is not encouraging for using another service of that same company.
      There will be some collateral damage too: iGoogle gadgets pushed you towards Google discussion groups, Google Finance etc.
      So it's back to My Yahoo for me, which is close, but not as slik.
      Maybe I should start preparing for WordPress as well...

      24 June 2012

      Servlet 3 (JSR 315) containers (edit)

       Servlet v3 support in different web application containers + current support state

      • Glassfish 3+ (12/2009)
      • Resin 4 (2/2010)
      • JBoss 6 (12/2010)
      • Tomcat 7 (1/2011)
      • IBM WebSphere v8 (6/2011)
      • Oracle WebLogic 12c (12/2011) 
      • Jetty 8 (milestone)

      21 June 2012

      Expression Language 3.0 is in public review

      The Expression Language (EL) is widely used in JSP and JSF. With version 3 the EL now becomes an independent specification. The EL v3 (JSR 314) is in public review until the end of July. It will be released in sync with Java EE 7 (Update: EL 3.0 was released in may 2013). New features include:

      •  As an independent specification, EL now comes with a standalone API, allowing usage outside a web container.
        • You can write your own ELProcessor. The source code is available, but I wish they had put the javadoc for  browsing at the project site as well.
      • Java 8 stuff
        • Lambda expressions
        • Collection literals follow proposed Java 8 syntax
          • List: [1, "two", 3.0]
          • Set: {1, 2, 3}
          • Map: {"one":1, "two":2, "three":3}
        • Collection streaming
      • Assignment operator (=) for changing values:
        • ${customer.name = 'Jan'}
      • String concatenation: + or cat operator
        • ${‘Welcome ‘ += customer.name += ‘ to our site’}.
      • Support for static references using the T construct (Type). 
        • By default only java.* and javax.* packages are available, but you can modify this using the EL API.
          • ${T(java.util.Calendar).APRIL}
          • ${T(java.util.Calendar).getInstance()}
        •  You can call constructors as a static method without a name. To call the default Calendar constructor:
          • ${T(java.util.Calendar).()}
        • For java.lang you can use the class without using the T construct
          • ${Boolean.TRUE}

      7 June 2012

      Little known truths

      Microsoft OneNote does not have find and replace.

      Install the OneMore OneNote plugin to add this incomprehensible omission.

      16 May 2012

      Java 7 (Dolphin) new features (edit)

      Now that Java 7 will soon become the default Java JRE version for download, let's have a look at some new features:

      String switch

      You can use a String as a selector for a switch/case statement now

      Enhanced try/catch

      • multicatch: catch multiple exceptions in one catch statement
        try {  
         ... 
        
        }catch(IOException | FileNotFoundException ex){…}
      • resources implementing java.lang.AutoCloseable resources (most resources in the JDK) can be automatically closed in a try-with-resources. You do not need a finally clause for this anymore.
        • Java 6 code
          try {                
            Scanner input = new Scanner (new File(“client.txt”));            
            …             
          } finally {             
            input.close();
          }
        • Java 7 code
          try(Scanner input = 
            new Scanner (new File(“client.txt”))){ 
            …
          }
        • You can also have multiple resources in a try
          try(Scanner input = 
            new Scanner (new File(“client.txt”)); 
            Formatter output = 
            new Formatter (new File(“adress.txt”)){ 
            …
          }

      NIO.2 revamped file handling

      is discussed in a separate blog entry.

      Small syntax enhancements

      • Diamond operator
      • When the compiler can infer a generics type in a constructor, you can leave it empty
        List<Currency> currencies= new ArrayList<> ();
      • Literal enhancements
      • // binary numbers
        int localhost=0b1111111000000000000000000000001; 
        //underscores (for readability)
        double million=2_000_000.00; 

      static java.util.Objects utilities

      Examples:
      • null tolerant equals/hashCode/toString

      • hash (Object... values)

      CSS styled javadoc 

      With Java 7 Oracle is starting to modernise javadoc. In this release javadoc is restyled:












      I'm not a big fan of the new look because the method names do not stand out enough for easy scanning the text for the method you need. Fortunatly the pages are styled using CSS. So I went to the topdirectory of the javadoc API and appended the contents of this file to stylesheet css, et voila:











      The -stylesheetfile <path> option can be used to specify a stylesheet other than the default when using the javadoc command to generate the documentation.

      Fork/Join

      Fork/Join is an additional concurrent ExecutorService. It allows a pool of threads to concurrently work on a task, that can dynamically be split up into parallel subtasks. A busy thread is able to chew of a part of the task he’s doing and make it available for other threads.

      JDK7

      This is not really part of the Java language, but some tools in the JDK were upgraded.

      JavaDB

      JavaDB was updated to a more recent version of Apache Derby (10.8). Some noteworthy new features:
      • SQL Sequences
      • In memory databases (with disk based backup/restore)
      • SSL/TLS client/server communication
      • role based authorisations
      • stored procedures with elevated permissions

      9 May 2012

      Apache Tommee is Java EE6 web profile certified. (edit)


      Apache Tommee is not a new product, but a bundle of Tomcat and Apache Java EE projects (OpenEJB, OpenJPA,...) by the Apache OpenEJB team. The lot is certified as a Java EE 6 Web Profile server.
      Tommee is pretty lean (24Mb) and can run embedded.
      The server bundles a set of components, all Apache gear: 
      EJBOpenEJB
      CDI OpenWebBeans
      JSP/servlet Tomcat
      JSF MyFaces
      JPAOpenJPA
      JTA Geronimo Transaction
      JavaMailGeronimo JavaMail

      Version 1.0 of Tommee was released on april 30th 2012.

      25 April 2012

      Payload extractor superclass

      This post by Jonathan Wright contains an alternative strategy for Adam Bien's payload extractor. It uses a superclass instead of interceptors.

      23 April 2012

      Builder-Style DTO

      MyDto is a Data Transfer Object that can be built using a chain of building calls.
      You start by calling a factory method and then you add the info for MyDto step by step to the Builder. Each time this returns the builder, so you can chain the calls.
      When you are finished, you call the build call, which returns the Data Transfer Object:

      MyDto dto  = new MyDto.Builder()
             .name("Jef Blaaskop")
             .address("Antigoon 4")
             .city("Amoras")
             .build(); 
       
      The constructor of MyDto is private: you can only make it using the Builder. The Builder is an inner class of MyDto, so it can call the private constructor.
      public class MyDto implements Serializable{
          private String address;
          private String name;
          private String city;
      
          private MyDto (String name,String address,String city) {
              this.city= city;
              this.address = address;
              this.name = name;
          }
      
          private MyDto() {}
      
          public static class Builder{
              private MyDto dto;
               Builder(){
                  this.dto= new MyDto ();
              }
      
              public Builder address(String address){
                 // some checking
                  this.dto.setAddress(address);
                  return this;
              }
      
              public Builder name(String name){
                  if(name == null)
                      throw new IllegalArgumentException("Anonymous not allowed");
                  this.dto.setName(name);
                  return this;
              }
      
            public Builder city(String city){
                 // some checking
                  this.dto.setCitys(city);
                  return this;
              }
      
              public MyDto build(){
                  return this.dto;
              }
           }      // end Builder 
      // remaining getters / setters ommitted
      } // end MyDto
      

      22 April 2012

      DAO Example

      public interface AnniversaryDao {
        Anniversary getByYear(int years);
      }
      
      public class AnniversaryJdbcDao implements AnniversaryDao{
        private static final String GET_BY_YEAR = 
          "SELECT * from Anniversary WHERE years = ?";
        //...
        public Anniversary getByYear(int years) {
          //…
          PreparedStatement statement = connection.prepareStatement(GET_BY_YEAR);
          statement.setInt(1,years);
          ResultSet rs = statement.executeQuery();
          if (rs.next()){
            result = new Anniversary(
            rs.getInt("years"),
            rs.getString("material"),
            rs.getString("flowers"));
          }
         //  ....
        return result;
        }
      }
      
      public class AnniversaryJpaSeDao implements AnniversaryDao{
         EntityManagerFactory emf = Persistence
          .createEntityManagerFactory("JPA-03PU");
      
        private EntityManager getEntityManager() {
          return emf.createEntityManager();
        }
        //...
        public Anniversary getByYear(int years) {
          return getEntityManager().createNamedQuery(findAnniversayByYear)
            .setParameter("years", years)
            .getSingleResult();
        }
      }
      
      @ManagedBean
      @RequestScoped
      public class AnniversaryJpaEe6Dao implements AnniversaryDao{
        @¨PersistenceContext private EntityManager em;
      
        //...
        public Anniversary getByYear(int years) {
          return em.createNamedQuery(findAnniversayByYear)
            .setParameter("years", years)
            .getSingleResult();
        }
      }
      

      Light field cameras are out

      The Lytro light field camera on which we reported earlier, receives a mixed review. Apparently the camera does not work too well in bad light conditions.
      The camera snaps pictures that you can refocus later on.So there's only a snap button on a tiny camera.
      I think that this idea hitting the market exactly at the moment that we are shifting from paper to screens for viewing photos, makes this a promising technology.

      15 April 2012

      Java enum demo

      import java.util.EnumSet;
      import java.util.HashMap;
      import java.util.Map;
      
      public enum EnumDemo {
        // For this enum each value has an identification code
        // other than the internal ordinal value
        DEMANDED(10),
        SPECIFIED(20),
        EVALUATED(30),
        DUPLICATE(33),
        ESTIMATED(35),
        WORKAROUND (36),
        ACCEPTED(37),
        PLANNED(40),
        BUSY(50),
        IMPLEMENTED(60),
        REJECTED(100);
      
        private int code;
      
        /**
         * @param code  constructor takes code to  be associated with enum
         */
        EnumDemo(int code) {
          this.code = code;
        }
      
        /**
         * Helper map for reverse lookup in getByCode method
         */
        private static Map<Integer,EnumDemo> enumByCode;
        static{
          enumByCode = new HashMap<Integer, EnumDemo>();
          for (EnumDemo val: EnumDemo.values()) {
            enumByCode.put(val.getCode(),val);
          }
        }
      
        public int getCode() {
          return code;
        }
      
        /**
         * reverse lookup
         * @param code the code of the enum
         * @return the enum or null if the code does not exist
         */
        public static EnumDemo getByCode(int code){
          return enumByCode.get(code);
        }
      
        /**
         * test if a code exists
         * @param code
         * @return  true if the code exists
         */
        public static boolean isCodeValid(int code){
          return enumByCode.containsKey(code);
        }
      
        /**
         * enumToString: EnumDemo.DEMANDED to "DEMANDED"
         * @return enum value name as a String
         */
        public String getName(){
          return toString();
        }
      
        /**
         * StringToEnum: "  demanded" to EnumDemo.DEMANDED
         * @param name case insensitive and leading and trailing spaces are ignored
         * @return  the enum constant
         */
        public static EnumDemo getByName(String name){
          return EnumDemo.valueOf(name.trim().toUpperCase());
        }
       
        /**
         * convert between enum and internal ordinal number
         * not recommended to expose this, just here for demo purposes
         * @return internal ordinal number of the constant
         */
        public int getOrdinal(){
          return getOrdinal();
        }
       
        /**
         * convert from ordinal number to enum. Not recommended.
         * @param ordinal
         * @return  the enum
         */
        public static EnumDemo getByOrdinal(int ordinal){
          return EnumDemo.values()[ordinal];
        } 
       
        // some tests and subsets
        // alternate methods can be written using the codes
          
        /**
         *
         * @return  is this enum in a range?
         */
        public boolean isOK(){
          return ACCEPTED.compareTo(this) <= 0 && IMPLEMENTED.compareTo(this)  >= 0;
        }
      
        /**
         * @return  an enum subrange
         */
        public static EnumSet<EnumDemo> getOK(){
          return EnumSet.range(ACCEPTED,IMPLEMENTED);
        }
      
        /**
         * @return  is this enum in a subset?
         */
        public boolean isNOK(){
          return this == DUPLICATE
            || this == WORKAROUND
            || this == REJECTED;
        }
      
        /**
         *
         * @return  get an enum subset
         */
        public static EnumSet<EnumDemo> getNOK(){
          return EnumSet.of(DUPLICATE,WORKAROUND,REJECTED);
        }
      } 

      12 April 2012

      idPhone

      The Arabian Emirates is planning to incorporate the ID card in residents mobile phones.
      This opens unprecedented possibilities for monitoring the population

      • Through the mobile phone operator the government will know the location of every single citizen
      • The ID card will also work using NFC. NFC allows the contents to be read from a short distance (currently max 20cm, and for practical purposes 4 cm), even if your battery is dead. If they improve this distance a bit it will be very easy to register everybody passing a checkpoint.
      All in all this allows a small group of people to effectively monitor and control a large group of people.

      18 March 2012

      NetBeans 7 new features (edit)

      NetBeans 7 is approved for release now. Here's a list of new features
      • Remote glassfish interaction
      • Java 7 support
        • Maven 3 support
        • HTML 5 support
        • JSON formatter
        • Git natively integrated
        • JUnit is now an unbundled plugin (Oracle legal had problems with the old CPL license)
        • easy JPA 2 metamodel generation
        The netbeans 7/Java 7/Glassfish 3.1 combination is still a bit flaky though.

            15 March 2012

            Java How To Program: alternate labs

            Chapter 2

            Preparation

            1. Make sure your PATH environment variable contains the JDK bin directory
              1. On windows separate PATH entries using ; (semicolon)
            Blogger Rijkswatch - Edit post - Mozilla Firefox_2012-03-14_21-40-17 - cropped

            Body Mass Index Calculator

            1. Using an editor create a file called BmiTest.java
            2. Add a public class called BmiTest to the file
            3. Add a main method to the BmiTest class. In the main method
              1. Ask the user for his weight in grams
              2. Ask the user for his height in centimeters
              3. Print the Body Mass Index of the user, using the formula
                BMI = weight x 10 / (height x height)
            4. Save the file
            5. Compile the file using the javac compiler
            6. Run the file using the java command
            7. Correct any errors.
            8. Compile, run and correct errors until all is well.

            Chapter 3

            Body Mass Index Calculator

            1. Create a new Java Application project called javase
              1. Consult the tutorial on creating a NetBeans Java project
                1. Do not create a main class
            2. In the project browser window, right click your project and select New => Java Class
              1. Call the class Bmi
            3. Add private double fields to the class called weight and height
            4. Add a constructor to the class
              1. constructor signature: public Bmi (double myWeight, double myHeight)
              2. In the constructor initialise the object fields using the constructor parameters
            5. Add a method that calculates the BMI
              1. Signature: public double calculate()
              2. In the method return the calculated bodymass. Adapt the calculation to use weight in kilogram and height in meters.
            6. Copy the BmiTest class to the project
            7. Modify the class to
              1. Request weight in kilogram and height in meters
              2. Accept floating point numbers
              3. Replace the calculation with
                1. Creation of a Bmi object called bmi
                2. Calculate the body mass index using the calculate() method on the  bmi object
            8. In the main method, print out the result of the calculation
            9. Run the main method by clicking on the green arrow button in the top toolbar
            10. Correct any errors and run again until all is well.

            Chapter 4

            Body Mass Index Calculator

            A normal BMI is between 18.5 and 24.9.
            1. In the BMI class add a method with signature: public double deviation()
              1. The method should return 0.0 if the BMI is within the normal range
              2. The method should return a negative number indicating the difference with 18.5 if the BMI is lower
              3. The method should return a positive number indicating the difference with 24.9 if the BMI is higher
            2. In the BmiTest main class
              1. print a message indicating that the weight is normal if the difference with the bounds is less than 0.1
              2. otherwise print a message indicating how much the weight should change to be within the normal range
            3. create a main class

            Chapter 5

            Facebook Growth Prediction

            In July 2010 facebook had 500 million users and was growing with a rate of 5% each month.
            Assume the  growth continues at this pace.
            Write a class called FacebookFuture with a main method that lists the number of users for each of the following months, until the number of users exceeds one billion. For each month print out a line with
            • an incrementing number indicating how many months this is from the start date
            • the month and year in a mm/yyyy format
            • the number of users
            Align numbers vertically in each line of output.
            Tip: since Java 7 you may use underscores in numbers to enhance readability. Example:
            long billion=1_000_000_000;
            Info: At the beginning of 2012 facebook numbered 850.000 users

            Chapter 6

            Facebook Growth Prediction

            To calculate the target amount you have after a number of months the formula is
            target = (1 + rate)months X amount
            To calculate the number of months it takes to the target amount, the formula is
            log(target/amount)/log(1+rate)=months
            1. Create a class GrowthPrediction. 
              1. Add an attribute for the current amount (double)
              2. Add a constructor that initializes the amount.
              3. Add a method with signature: public int growthCycles(double target, double rate).
            2. Create a test class called GrowthPredictionTest
              1. Right click the GrowthPrediction class and select Tools => Create JUnit Tests
                1. Accept all defaults
                2. Use JUnit 4
              2. In the testGrowthCycles method add a test that verifies the numbers you obtained in the previous excercise.
                1. Put the number of months obtained in the previous exercise in the expResult variable
                2. Remove the fail statement and the comment above it
                3. Print out a message saying how many months it would take for the number of facebook users to reach one billion
              3. Run the test using the top menu Run => test
              4. Using the same conditions add code to the test method to calculate how many months it would take for facebook to have as many users as a world population of 7_000_000_000
                1. Print out the result

            Chapter 7

            Game of Craps

            1. Make these modifications to the Craps code (Fig 6.9):
              1. Comment out all printing in the Craps class
              2. Make the number of rolls and the result attributes instead of local variables
              3. Add methods
                1. public int getRolls();
                2. public boolean getResult();
            2. Make these modifications to the CrapsTest class.
              1. Run the games for a number of times passed as a command like argument 
                • Run CrapsTest from the command line
                • If you run in netbeans, in the project pane, right click the project => properties => run and set the command line arguments
              2. Print out how many games were won and lost on the first, second,… , twentieth roll and after the twentieth roll.
              3. Print out the percentage of games won
              4. Print out the average number of rolls in a game

            Chapter 8

            Bank

            Implement the Bank case study.
            1. Put classes in two packages
              1. jhtp.bank
              2. jhtp.bank.atm
            2. Start with the classes at the right bottom of Fig 8.24 and work up
            3. Return dummy 0 equivalents from the methods to comply with the method return types
            4. Add attributes for the relations in Fig 8.25

            Cards

            1. Add two new enum classes to example 7.09:
              1. Face
              2. Suit
            2. Modify the example to use the enums
            3. Replace the decksize (52) with a number calculated from the available enums
            4. Run the test program and correct errors until it succeeds

            Chapter 9

            Bank

            1. Make the SavingsAccount from exercise 8.6 a subclass of the Account from the ATM case study.
            2. Replace the usage of the savingsBalance with getter/setter methods using the totalBalance of the Account class.
              1. Add the necessary support to the Account class
            3. Remove the savingsBalance attribute
            4. Test the modified savingsBalance using the SavingsAccount test and correct errors until it succeeds

            Javadoc

            1. Comment the bank classes, methods and attributes with javadoc
            2. In the project browser richt click on the project and select Generate javadoc
            3. Review the generated javadoc, adapt and regenerate
            4. Go to the files prowser tab and open the dist/javadoc directory where the javadoc is generated. Open the file stylesheet.css and append the contents of this file to it and save it. Reload the javadoc in another browser tab and check if anything changed in the presentation.

            Chapter 10

            Bank

            1. Add The Transaction class to the Bank exercise

            CommissionEmployee

            1. Start from the BasePlusCommissionEmployee code in example fig09_12_14
            2. BasePlusCommissionEmployee inherits from CommissionEmployee. We will replace inheritance with composition.
            3. Rename CommissionEmployee to CommissionOnlyEmployee
            4. Create an interface CommissionEmployee that contains the public methods of CommissionOnlyEmployee (except toString())
              1. In CommissionOnlyEmployee choose Refactor => Extract Interface
            5. Adapt BasePlusCommissionEmployee  to delegate to CommisionOnlyEmployee instead of inheriting from it
              1. Replace inheritance in BasePlusCommissionEmployee  with inplementation of the CommissionEmployee interface.
              2. Add an attribute CommissionOnlyEmployee called delegate to BasePlusCommissionEmployee 
              3. Instantiate the attribute in the constructor
              4. Replace all calls to super with calls to delegate
              5. implement all interface methods and call the corresponding method on delegate from them.

            Chapter 13

            Game Of Craps

            Add exception handling to handle bad program parameters to the CrapsTest class in the Game Of Craps from Chapter 7.
            Handle two specific exceptions using one catch statement:
            1. no command line parameter was supplied
            2. the command line parameter was not an integer

            Chapter 19

            FileMatch 1: Collections

            1. Rewrite exercise 14.8, this time loading all accounts in a Collection in memory.
            2. Make sure the output is still ordered by account number.

            FileMatch 2: ResourceBundles

            Localise the messages in the application using resource bundles.
            1. Pass a parameter to FileMatchTest indicating the language (fr or nl)
            2. In the main method construct a ResourceBundle with parameters
              1. “errormsg” as name for the properties files
              2. If the language was passed,  a Locale for this language
                1. if no language was passed, use the one parameter constructor
            3. Pass the ResourceBundle to the FileMatch constructor and save it in an attribute
              1. Print errormessages using the ResourceBundle
              2. Use MessageFormat to substitute parameters in the message
            4. In the src directory create
              • errormsg.properties (english)
              • errormsg_fr.properties  (french)
              • errormsg_nl.properties (dutch)
            5. Add the keys used in the FileMatch error messages to all files and add translated messages in the three languages

            Chapter 23

            FileMatch

            In this exercise we will process multiple transaction files concurrently.
            1. Create a class bank.TransactionProcessor that implements Runnable
              1. Add a constructor TransactionProcessor(Map<Integer, Account> accounts, Path transactionFile)
                1. store the parameters in attributes.
              2. Implement the run method of TransactionProcessor. Move the code from FileMatch that reads the transaction file and adds the transaction amount to the corresponding accounts here. Adapt the code to use the instance attributes.
            2. Make about 5 copies of the trans.txt file.
              1. Give them similar names so you can retrieve them using a wildcard.
            3. Adapt the FileMatch class
              1. Make the Account Collection synchronised to allow concurrent access.
              2. Read the oldmast.txt file and store all accounts in the Account Collection
              3. Create an ExecutorService cached trheadpool
              4. For each transaction file
                1. create a TransactionProcessor thread. Pass the Account collection and the file Path to it.
                2. execute the thread
              5. shutdown the threadpool and awaitTermination of all threads
              6. Write the updated Account Collection to the newmast.txt file.
            4. Add some System.out.println statements throughout your code to  track the processing of the files
            5. Run the program and verify the results.

            Chapter 30

            FileMatch

            Write a program that replaces the blank character separators in oldmast.txt with a colon (:) separator. A sequence of blank characters should be replaces with only one colon separator.

            13 March 2012

            QR code shopping

            Uniway adds QR codes to TV shopping program.
            You can consult product info on your smartphone and get called by the call center to take your order.

            30 January 2012

            Telesys opent bescheiden datacenter in Oudenaarde

            De foto in Datanews toont wat bedoeld wordt met bescheiden :













            Voeg daarbij een website met 404 links in het nieuws menu...
            Het motto van Telesys maakt alles duidelijk:

            25 January 2012

            German states use spyware to eavesrop on suspects

            While a laptop was being checked when passing through German customs, spyware was allegedly installed on the computer by the authorities.
            More...