Thursday, November 3, 2011

Rolling Back Transactions

While doing a spot check on code and configuration – I noticed that the developer wasn’t throwing a runtime exception nor was he setting rollbackOnly in a CMT EJB.

I was told that any exception will rollback a transaction and it is not possible to setRollbackOnly, and there are only 4 types of transaction attributes on CMT. Wrong, wrong and wrong.

1. If your code throws an application exception – the container expects the bean to handle it. However, if your bean throws a runtime exception (or subclass), like javax.ejb.Exception – the container will rollback the transaction.

2. If you don’t want to throw RTEs all around your code – and/or you have massive catch all exception code blocks, you should context.setRollbackOnly – to rollback transactions.

3. There are various transaction attributes – 6 to be exact: Requires, Requires New, Supports, Not Supported, Never & Mandatory. Never and Mandatory are opposite to one another. Requires starts a transaction if not called with one, Mandatory will throw an exception if called without a transaction, Supports will use one if there is one, but won’t complain….rest are self explanatory.

What’s most important about Transactions are how the transaction propagates in both directions (commit and more importantly rollback)

Thursday, October 20, 2011

GoF: Polymorphism, Encapsulation, Inheritance and Delegation

Polymorphism is when your client has a reference to an interface, and it’s concreate class can be one of many implementations. A different different behavior or value in a subclass can be utilized without a switch or an if. Parent class class defaults can be inherited and overridden where necessary. A method can be declared in a parent class, but each subclass can have a specialized implementation/logic of that method e.g. calculateArea();


Encapsulation is a core principal, it refers to the bundling of data with the methods that operate on that data. Basically, logic and data go together. If you have a class, with properties and logic together – it is encapsulated. Helps separation of concerns and reduces surface areas – also supports immutability – since only the object can control the data.

 
Inheritance is the ability of objects in an Object-Oriented language to inherit properties and methods of other objects e.g. in Java, use extends or implements keywords.

Delegation is when at runtime you can invoke a different object to complete a task dynamically. A useful OO pattern that has seen several implementations in Java EE.

The ability to frequently modify or add functionality, or quickly fix defects (Extensibility & Maintainability) comes from early design decisions.

All in all – these are core design principles – any object oriented analysis and design must respect, consider and apply these principles.

Wednesday, October 19, 2011

Java SE Security APIs and Frameworks

 Java SE has a deep foundation for security – there are a variety of APIs and frameworks that plug on top of various security impls.

  1. JAAS: Java Authentication and Authorization Services
  2. GSS: Generic Security Services. Think Tokens.
  3. JCE: Java Cryptography Extension. Keys and Ciphers.
  4. JSSE: Java Secure Sockets Extensions. SSL and TLS.
  5. SASL: Simple Authentication and Security Layer. Layer between Client and Server – describes the how. RFC 2222

 

TLS (SSL) is a point-to-point, transient only solution which provides no context, discrimination to content. Authentication, confidentiality and integrity is provided.
MLS (Message Layer Security) is an end-to-end security because it stays encrypted at rest and in motion. It is encrypted by the sender and can only be decrypted by the intended recipient. It does not depend on the transport layer.

Realm is the complete database of users and group, a user is an individual, a group is a collection of individuals, each group or individual can be assigned a key to the locks (aka role). In Java EE you can specify whether to propagate a client identity to the bean container or specify a run as. There is no choice either way but to trust the identify – as there is not authentication data propagated just the identity.

The EJB interoperability protocol is based on IIOP/GIOP 1.2 and CSIv2 (Common Secure Interoperability protocol).

Tuesday, October 18, 2011

Gang of Four Patterns for Java EE developers : Cheat Sheet

Here is the list of Gang of Four patterns related with an actual implementation in Java EE. Read on – it will make sense (hopefully).

Strategy: EJB interface.

Defines a family of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients who use it.

Decorator: Dependency Injection.

Attach additional responsibilities to an object dynamically. Provide a flexible alternative to sub-classing for extending functionality.

Factory: EJBs .

Define an interface for creating an object, but let the subclasses decide which class to instantiate.

Chain: Filters.

Decoupled requester and handler. Chain the handlers, one of them must handle it.

Singleton: JNDI

Ensure a class only has one instance, and provide a global point of access

Flyweight: JDBC Connection Pooling.

JDN

Adapter : Use the same interface, but adapt to other classes.

Façade: Single point of entry for a sub-system.

Template: Defer implementation to subclass.

Builder: For complex varying structures.

Iterator: Access items in any collection implementation.

Thursday, October 13, 2011

XML Processing in Java EE 5

All of the new Web Services API requires XML processing. Thankfully there have been changes to how Java EE will handle that as well with a fresh batch of updates.


JAXB 2.0: Improves vastly over JAXB 1.0

W3C XML Schema features (fixes missing bindings)

Adds javax.xml.bind.annotation and supports Java-to-XML binding.

Reduction in generated schema-derived classes.

Validation via JAXP 1.3 validation APIs

Smaller runtime binaries.

Schema compiler, Schema generator and Binding runtime framework.

JAXB 1.0 allowed validation: at unmarshall time, and on-demand validation on the content tree. JAXB 2.0 allows validation at marshall time and unmarshall time.


Streaming API for XML (StAX)

StAX is the all new efficient API for XML, it has a lot of great features:

  • Stream-oriented
  • Event-Driven
  • Pull-design
  • Read/WriteYou can create fast, light-weight, bi-directional parsers that is easy on the heap.
    JAXP (Java API for XML Processing) family includes StAX, TrAX, SAX, and DOM. StAX is good for low memory and limited extensibility applications.
    Pull Parser – simpler than SAX, more memory efficient than DOM.
    SAX can’t write – and isn’t bidirectional. DOM is way more powerful and flexible. One would dump SAX for StAX. An iterative pull parser – stax, an event driven push parser – then go for SAX.
    I can’t see anyone using SAX anymore. Why would you? Unless you don’t want a cursor and iterator concept in your code – or you simply hate procedural and believe everything should be read-only events for XML processing. XMLStreamReader or XMLEventReader are the Cursor and Iterator APIs – well, Iterator APIs can do things a Cursor cannot do: Iterator is more extensible and flexible. Cursor is efficient, performant and memory friendly – ideal for small JVMs and JME

        Wednesday, October 12, 2011

        JAX-WS in Java EE 5

        JAX-WS: Java API for XML Web Services. Does message oriented as well as RPC oriented services. Hides complexities of SOAP. No need to generate or parse SOAP messages (or understand the structure or format).

        The JAX-WS endpoints must be annotated with @WebService or @WebServiceProvider. The business method must be annotated @WebMethod – a Service Endpoint Implementation (SEI) will be generated for this. JAXB compatible parameters are required.

        Um, if you think Web Services or Clouds are NOT important, I hope the following stat will convince you.

         

        The Client needs @WebServiceRef – the reference to the service (or wsdlLocation). Get the port from the service and then invoke the exposed method on the service. Yes you need the interface to the service.

        JAX-WS 2.0 Support WS-I Basic Profile Version 1.1, SOAP 1.1 and WSDL 1.1.

        There is support for doc/lit, rpc/lit, static ports, dynamic proxies, and DII.

        All in all JAX-WS seems like a winner!

        Well, can you still use SAAJ? Yes – it gives you direct access to the SOAP protocol and the SAAJ 1.3 API supports SOAP 1.1 and SOAP 1.2 specifications.

        <Message>

        <Part>

        <Envelope>

        <Header>

        </Header>

        <Body>

        </Body>

        </Envelope>

        </Part>

        </Message>

        You can have Attachment Parts as peers to the Part. all Under the soap message but outside the envelope.

        The attachment part will contain MIME headers and the content (any).

        Um – BTW – you can use JAX-B to send SOAP Attachments too – so why would you want to bother with the SAAJ APIs is going to remain a mystery. But it’s there.

        i18n APIs

        If you’re designing an application that may be distributed to other nations, what you want to avoid is hardcoding English user text.

        The following interfaces and objects are foundational to enable internationalization (i18n).

        java.text package

        Locale: Where is this running?

        Resource Bundle: Alien language resource (LOL)

        InputStreamReader OutputStreamWriter: UTF-8 and UTF-16

        Internationalization is essential for a global impact


        Abstraction, abstraction and more abstraction. Decouple everything with a minimal surface area allows for a low friction system. Internationalizing any application is probably a great test of software flexibility.

        In order to prepare an application, several changes need to be considered:

        1. Screen Text

        2. Dates, Calendars

        3. Numbers, Formats, Currency

        4. Icons, Images

        5. Text File formats (e.g. UTF-8, UTF-16).

         

        It is possible that your program writes to ASCII, however that’s not going to work for the Japan market, you need to be able to write in UTF-16.

        Tuesday, October 11, 2011

        Distributed Garbage Collection and Stub Downloads–and other dirty solution architecture alternatives

        Technology choices can make the difference between meeting the customers’ immediate needs and failing to complete a project on time. No can do if you’re using IIOP. If you’re still stuck in CORBA or IIOP, and trying to get remote objects talking to one another – don’t expect RMI-IIOP to help do what pure RMI does – DGC. Stub downloads and DGC are never going to be supported across technologies – it’s not possible to standardize it.

        Think about refactoring to expose encapsulated business services instead. Use HTTP – it is connection based and stateless. Alternatively think about using messaging architectures, if you are at the systems programming level – IP Multicasting can be used of TCP that can serve as an unreliable messaging infrastructure – but it can also have layers of high speed health checks and retry mechanisms built. Virtual channels like queues (p2p) and topics with durability attributes can be used as well.

        If a non-EJB Java application requires integration with your CORBA system, Java IDL is officially recommended – the communication protocol then is native IIOP. CORBA clients needs to talk to Java, Java IDL on the client end don’t make sense. If you want to integrate with the mainframe, and all you need is some fancy GUI, but the mainframe source code is unavailable – guess what? Screen scrapers via terminal emulator inputs may be recommended. Depends. If the goal is to meet the customer’s need quickly – don’t forget to do a trade off analysis and make target state recommendations. An architects job is to accelerate business not make perfect solutions at all costs. Judging trade offs is where we make money for the clients. Know when where and how to make short cuts if needed. Use a reverse proxy to target different servers for servicing different types of requests. Have failure management systems up to the wazoo. Avoid EJBs if you have no need for transactions and business logic in the solution. KISS.

        If you must use CORBA and RMI-IIOP (for EJB type communications), and Session Beans provide good memory management like Pooling and Passivation (SLSB & SFSB). If you must integrate with existing native C++ code/business logic, it is advisable to wrap that with JNI calls, and remote it via RMI. Don’t over use web-services if you don’t need a business service. SOA isn’t API over the web.

        All in all, Java IDL is business as usual for CORBA programming. Use RMI-IIOP is for Java programming over IIOP, it can interoperate with CORBA objects but those interfaces must be available as Java RMI. If you must use pure IIOP – then you have existing CORBA objects in play that can’t have Java interfaces – so you must use Java IDL. CORBA provides lots and lots of nice services; Naming Services, Security, Transaction Service, Event and Concurrency Control.

        Regardless of how you meet your customers’ expectations – plan to leave them with an awesome build/deploy strategy & matching execution.

        Monday, October 10, 2011

        Don’t forget data replication strategies

        It is still important to decide on your data, server replication strategy when you deploy your core business services and data assets to an internal, external or hybrid cloud models.

        Understanding the implications of Active Replication, Passive Replication, Hot Backup, Warm Backup, Cold Backup, State Change Synchronization, Load Balancing and Fault Tolerance are key to making essential choices for a solid deployment architecture on the cloud.

        Elasticity, capacity flexibility, horizontal and vertical scalability and dynamic resource allocation makes life a lot easy on the cloud.

        Active replication is not achieved by taking cold backups, state changes are not logged for periodic flushes to the replicas, state is not synchronized to only support backup replica when the primary fails. Instead each replica is identical, each replica attempts to process each request – an interceptor takes care of idem potency between replicas. If you want a Primary Service to support all incoming requests, and periodically synchronize its state with the replicas – what you have is a Warm Backup or Passive Replication.

        Take a hot backup during times when you have low scalability needs on the RDBMS systems, whereas a cold backup should be reserved for “Sundays” or in the 70s. If you’re going to support the cloud – forger cold backups and start thinking CA (Continuous Availability).

        Sunday, October 9, 2011

        Dealing with $$$$? You need ACID

         

        If you’re deploying business logic to an EJB container, you’re probably dealing with some durable transactional stuff that’s needed by the customer. You need som ACID baby!

        Atomicity – do it all or don’t do anything at all.
        Consistency – Ensure everything is left integral.

        Isolated – Nothing else should alter or interfere.

        Durable – persist prior to finishing.

        For financially significant applications you need transactions – with four quality attributes together: ACID.

        Saturday, October 8, 2011

        How to remove Linux partition from a dual-boot PC? lilo & gparted

        Now that Windows 7 and Macs have improved their security architectures, it is possible to take tentative steps away from linux for desktop computing, if cost is not a factor.

        Every GB counts, so machines that have dual partitions, freeing up the swap, home and primary partition is the only reasonable option.

        Remove grub, linux distro and reallocate space.

        If you have a dual-boot PC with a Windows XP partition and an Ubuntu 11.04 (or other) partition – and want to simply have the windows partition only then read on.

        One 4-letter word: lilo

        It can create an MBR on your Windows partition.

        Before you do that, make sure you run check disk on all drives from your windows partition. Then boot up with a live Ubuntu CD and run GParted. Delete the partitions, and resize them as needed.

        Run lilo to recreate your MBR on the windows main partition, and you are all set.

        Tuesday, October 4, 2011

        Creating Objects Design Situations

         

        Understanding how to create an object goes beyond the new() syntax, a good designer will think about the current requirement and future requirements to ensure decoupling layers, build in flexibility and maintainability. For example,

        So you have an object that needs to create another class, however

        …it cannot anticipate the class of objects it must create

        …it wants only its subclass to specify the object it wants to create

        …it wants to localize knowledge of which helper subclass is the delegate

        How would you design for these quality attributes?

        How about the following:

        A client class needs a complex object, however it also

        … wants to vary the product’s internal representation

        …isolate code for construction and representation

        …gives you greater control over the construction process

        How would you design for these quality attributes?

         

        What if you wanted to:

        … isolate the concrete class from the client that needs it, and

        … allow for exchanging classes of products easily

        …enforce a common consistent product interface across families of products

        What’s going to be the pattern of choice, designer?

        If you answered Factory, Builder and Abstract Factory – then that’s pretty darn good – you remember your GOFs, which are like the ABCs for software architects (or should be).

        Monday, October 3, 2011

        Java EE 5 Security

        Enterprise Java provides abstracted security APIs and concept that sit on a robust security foundation at the Java Language Specification and implemented by Java Virtual Machines:

        Automatic Memory Management

        Secure Class Loading

        Strong Typing

        Byte code Verification

        At the time the security design was unprecedented, nothing came close to the security model of an interoperable platform. However with the advent of Java Applets and sandboxing, clunky jar signing processes and key stores, users and system designers shed away.

        Java EE 5 continues to build and extend a robust security platform for its EJB and Web containers – the simplified API looks for isCallerInRole and isUserInRole respectively. Unfortunately not all real security threats can be handled from within the container.

        Denial Of Service attacks require man-in-the-middle and session hijacking to be addressed, typically outside the container – at the network layer. Additionally, nothing can be done to prevent social engineering. That’s a human only vector.

        Sunday, May 8, 2011

        Updating Grub 2 Config

        Updating Grub 2 - 

        If you want to change your grub configuration (reorder, change, remove etc) - there are TWO steps

        1. Make The Change

        2. Update Grub

         

        For example, If you want to change the selected OS to boot from (usually the first one is selected by default).

        rohit@lenovo:~$ sudo gedit /etc/default/grub 

        rohit@lenovo:~$ sudo update-grub

        Generating grub.cfg ...

        The steps above, essentially means, I opened the grub file in a text editor, made changes and saved it. Then I ran update-grub to cement my changes. Done

        Sunday, May 1, 2011

        5 Things Ubuntu STILL needs your support on

        I have been an avid Ubuntu user for 4 years and Linux user for 10, there have been significant several improvements over the years that have made it a pleasure to use Linux 80% of the time.

        But listing these will help guide the next few releases and help early adopters understand the risks.

         

        TOP 5 Missing Features in UBUNU (and Linux)

        5. Speed

        Ubuntu boots up way faster than Windows XP, Vista and Win7. However, once Gnome (or KDE) startsup the user-perception of performance lags. Ubuntu/Gnome and Kubuntu are markedly slower to start applications than Win Xp or Win7.


        4. Office 2010-like features

        OpenOffice and OfficeLibre don't compare with Microsoft Office 2010. Features like One Note and Smart Art, MS Visio (yes, it's still better than Dia), has left the open source community challenged to meet or beat the new features provided in Office. 


        3. Better screen real estate utilization

        Screen real-estate is precious, and Win Xp did an awesome job on rendering the toolbars and icons to optimize on both low resolution monitors as well as high resolution monitors. For WSXGA screens, XP is still far better that Gnome 2x. A partial workaround is to use a compact theme, but it does not suffice. KDE does a better job than Gnome, and XP does a better job than KDE in screen real estate utilziation.


        2. Support for Apple products: iPad, iPod

        Support for iPads and iPods is essentially missing. You cannot use iTunes on Linux. Shame on Apple. Not only is iTunes a poorly designed and resource hungry software, it is not cross-platform. Windows is the only 'other' OS that is supported.


        1. Support for Netflix

        Shame on MIcrosoft and Netflix. Microsoft has not allowed DRM to be ported. Netflix seems committed to Silverlight. The combination has left Linux and Android operating systems in the cold, when it comes to Netflix movies. This is major strategic risk to Netflix. Not from Linux, but from Android users. Watch for Amazon in the this space. If Amazon supports a true cross-platform movie-watching experience Netflix will have a serious competitor.


        Conclusion

        If you are planning to check out Linux and any of its distributions for the first time, I strongly reccommend Ubuntu/Gnome or Kubuntu which is closer to the Windows user experience. Be aware of the missing features on the platform. In the next 3-5 years, Linux needs support from you and the corporations to be a viable platform for day to day computing needs.

         

         

        Thursday, March 31, 2011

        3 rules to understand attitudes and actions

        Here are my 3 rules to understand people's attitudes and actions.

         

        Rule #1. If you want to understand people's attitudes, first understand their motives.

        Rule #2. If you want to understand people's actions, understand their incentives.

        Rule #3. If you want to understand people politics, read Rule #1, Rule #2.

         

        ----
        Case in point 

         

        Health Care Reform, War

        Thursday, February 3, 2011

        When the Demon wants your Wallet

        Ubuntu 10.10 has an issue when you run Gnome and KDE.
        On startup KDE prompts 'KDE Daemon' has requested to open the wallet 'kdewallet'.


        The solution is to install WICD



        rohit@lenovo:~$ sudo apt-get install wicd

         

        [sudo] password for rohit: 

        Reading package lists... Done

        Building dependency tree       

        Reading state information... Done

        The following extra packages will be installed:

          python-iniparse python-wicd wicd-daemon wicd-gtk

        The following NEW packages will be installed:

          python-iniparse python-wicd wicd wicd-daemon wicd-gtk

        0 upgraded, 5 newly installed, 0 to remove and 0 not upgraded.

        Need to get 562kB of archives.

        After this operation, 3,121kB of additional disk space will be used.

        Do you want to continue [Y/n]? Y

        WARNING: The following packages cannot be authenticated!

          python-wicd python-iniparse wicd-daemon wicd-gtk wicd

        Install these packages without verification [y/N]? y

        Get:1 http://us.archive.ubuntu.com/ubuntu/ maverick/universe python-wicd all 1.7.0+ds1-5 [76.8kB]

        Get:2 http://us.archive.ubuntu.com/ubuntu/ maverick/main python-iniparse all 0.3.2-1 [19.8kB]

        Get:3 http://us.archive.ubuntu.com/ubuntu/ maverick/universe wicd-daemon all 1.7.0+ds1-5 [277kB]

        Get:4 http://us.archive.ubuntu.com/ubuntu/ maverick/universe wicd-gtk all 1.7.0+ds1-5 [147kB]

        Get:5 http://us.archive.ubuntu.com/ubuntu/ maverick/universe wicd all 1.7.0+ds1-5 [41.0kB]

        Fetched 562kB in 6s (80.3kB/s)          

         

                                              

         

        Preconfiguring packages ...

        Selecting previously deselected package python-wicd.

        (Reading database ... 258926 files and directories currently installed.)

        Unpacking python-wicd (from .../python-wicd_1.7.0+ds1-5_all.deb) ...

        Selecting previously deselected package python-iniparse.

        Unpacking python-iniparse (from .../python-iniparse_0.3.2-1_all.deb) ...

        Selecting previously deselected package wicd-daemon.

        Unpacking wicd-daemon (from .../wicd-daemon_1.7.0+ds1-5_all.deb) ...

        Selecting previously deselected package wicd-gtk.

        Unpacking wicd-gtk (from .../wicd-gtk_1.7.0+ds1-5_all.deb) ...

        Selecting previously deselected package wicd.

        Unpacking wicd (from .../wicd_1.7.0+ds1-5_all.deb) ...

        Processing triggers for ureadahead ...

        ureadahead will be reprofiled on next reboot

        Processing triggers for man-db ...

        Processing triggers for python-gmenu ...

        Rebuilding /usr/share/applications/desktop.en_US.utf8.cache...

        Processing triggers for desktop-file-utils ...

        Processing triggers for hicolor-icon-theme ...

        Processing triggers for menu ...

        Processing triggers for python-support ...

        Setting up python-wicd (1.7.0+ds1-5) ...

        Setting up python-iniparse (0.3.2-1) ...

        Setting up wicd-daemon (1.7.0+ds1-5) ...

         * Starting Network connection manager wicd                              [fail] 

        Setting up wicd-gtk (1.7.0+ds1-5) ...                                           

        Setting up wicd (1.7.0+ds1-5) ...

        Processing triggers for python-support ...

        Processing triggers for menu ...

        localepurge: Disk space freed in /usr/share/locale: 828 KiB

        localepurge: Disk space freed in /usr/share/man: 20 KiB

        localepurge: Disk space freed in /usr/share/gnome/help: 0 KiB

        localepurge: Disk space freed in /usr/share/omf: 0 KiB

        localepurge: Disk space freed in /usr/share/doc/kde/HTML: 0 KiB

         

        Total disk space freed by localepurge: 848 KiB

        Sunday, January 30, 2011

        Weather.com Software Platform: Open Source

        This is a snippet from a 2004 article that I never publicly published, but is serves as a good case study relevant in 2011 (and beyond).

        In 2004, weather.com site served more than 50 million pages on stormy days, and it ran almost entirely on open-source software and commodity hardware. The Atlanta-based Web site’s adoption of a new architecture and open source products “has slashed IT costs by one-third and increased Web site processing capacity by 30%”  (King 2004). However cost slashing was not their primary goal of switching to an open source product. The quality of open source products was its main “selling” point. Weather.com claimed that their transition from IBM’s server software product to open source Apache Tomcat to run their website served correct operations, ease of use and better quality attributes overall. Of course, there are different organizational dynamics that lead to a decision to drop COTS (and support) to an open source solution.

        Performance and scalability issues were cited as the main reasons for switching to Apache’s web server. The team switched from IBM’s commercial offering to Apache’s open source implementation primarily for its quality. Apache’s open source web servers host 68% of web servers in the world according to an August 2004 analysis of Netcraft (Gustafson, Koff).

         

        Graph: Totals for Active Servers Across All Domains June 2000 - June 2010

         

        IBM has since started to use a modified version Apache Web Server in it’s commercial offerings. This is a trend that is likely to repeat itself across multiple technology domains depending on various factors: it remains to be seen if the penetration projections hold true over time.

        Sunday, January 9, 2011

        6 Traits of an Impoverished Leader

        Impoverished Leadership Style
        1. Uninvolved: Is not involved with the effort at hand
        2. Unmotivated: Does not motivate and is not moved by the effort
        3. Indifferent: Does not care about the outcomes or your efforts
        4. Noncommittal: Does not provide straight answers and is not ready to support the effort.
        5. Resigned: Is not positive about the effort and is basically non caring.
        6. Apathetic: No emotion, no enthusiasm.
        Have you worked for a manager in your career that you thought was disconnected and unmotivated? The LeaderShip Grid (developed by Ohio State University) defines what they call the "Impoverished Leadership Style". Rest assured - this is a common leadership patter in dysfunctional organizations.

        Is WSJF "better" than traditional ROI calculations for Applications?

        I love road trips, and i like analogy.   The Premise: Two couples are planning a road trip. The "Perfection" group: This group spe...