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.

Sunday, October 16, 2011

Java EE 5 idiosyncrasies

In the Java Persistence API, you don’t need to provide an XML descriptor to specify the primary key, while you do need to provide a back pointer reference in a bidirectional relationship, unlike the Entity Bean specification version 2.1.

Java Server Faces can act as a front controller (i.e. no GUI) and unlike Custom Tag Libraries and much like a Servlet.

JSF does save view state, but cannot be previewed outside the container.

JCA = Java Cryptography Architecture as well as Java Connector Architecture. Having overloaded acronyms in the same domain is confusing. Java Cryptography Extension is packaged with JCA – guess which JCA? JAAS is the Java Authentication and Authorization Service. While the former supports RSA, DSA, AES etc, the latter abstracts authentication APIs as well as permissions API. JSSE is Java Secure Socket Extension – it is primarily used for TLS, SSL, Kerberos, SASL.
Weirdly enough JNLP applications that are running without their jars signed can interact with System properties and the clipboard. Well, in a way that’s understandable if you know what Web Start is supposed to be used for.

A single Sign-On delegator pattern is great for improving availability of remote security services, but doesn’t protect against weak session identifiers. Filtering for HTML tags is a good idea when accepting input reviews  - especially look for applet, script or frames and possibly div tags too. You don’t want folks entering scripts that get rendered somehow to grab other users data when viewed.

Friday, October 14, 2011

JSF in Java EE 5

Java Server Faces seems to have a lot to offer in Java EE 5, one would really question the existing Web Frameworks – traditional Struts or Web Works – seem antiquated immediately.

Backing Beans – deferred evaluation, bound listeners, validators and convertors provide powerful flexibility.

JSF has a powerful lifecycle, with events, renderers, components orchestrated prior to the response going out.

Renderer Kit provides output in any format, if none is provided you get HTML rendering by default.

JSF must be compliant with at least Servlet Specifications 1.3 or later. JSP 1.2 or later, and packaged in a standard war file.

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

        Cloud 9? 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.