Cross-origin resource sharing on IBM Bluemix

Update: A newer version of this post has been published to the IBM Bluemix blog.

The IBM Bluemix Platform-as-a-Service (based on Cloud Foundry) naturally supports applications that are composed of many services that are in turn deployed to different hostnames.

For example, if you push an application to Bluemix, the name you provide will be prepended to .mybluemix.net resulting in an address such as:

  • http://my-sample-app.mybluemix.net

If your cloud-native app follows the best practices of a microservices architecture you’ll probably have two or more subcomponents that live on discrete hostnames like this.

But what if you have a JavaScript based front-end that needs to aggregate information from the disparate hosts? By default you won’t have access to data on these other subdomains.

The solution is to take advantage of the HTTP headers that are available to allow you to control cross-origin resource sharing (CORS).

To illustrate the problem and the solution, consider the simple Ajax application here:

If you click the red box, you’ll initiate an asynchronous HTTP call in JavaScript to a servlet on another host at:

The source of this servlet shows that no particular HTTP headers are set, thus the JavaScript call never reaches it.

However, if you click the blue box, you’ll initiate a call to a different servlet on that host:

This time the Ajax call will successfully consume data from the service, because the HTTP headers allow services from a different domain to access the servlet.

response.setHeader(
  "Access-Control-Allow-Origin",
  "http://krook-service-consumer.mybluemix.net"
);

response.setHeader(
  "Access-Control-Allow-Methods",
  "POST, GET, DELETE, PUT"
);

response.setHeader(
  "Access-Control-Allow-Headers",
  "x-requested-with,Content-Type"
);

If you need to allow access to all client hostnames, replace the whitelist with a wildcard:

response.setHeader(
  "Access-Control-Allow-Origin",
  "*"
);

There you have it; a simple way to build dynamic JavaScript applications composed of several microservices on IBM Bluemix (or any other Cloud Foundry PaaS).

I used Java in this example, but the same HTTP headers apply whether you’re using Ruby, Node.js, PHP, Python or any other runtime.

Upcoming WebSphere and PHP book reviews

04 December 2009 » Java, PHP, Web architecture, WebSphere, Writing, Zend

With several vacation days to cash in through the end of 2009, I hope to catch up on some reading and learn more about the latest developments in the two areas where I do most of my work as a Web application developer – Java EE Web applications built on IBM WebSphere and PHP Web applications using various Zend products.

About a month ago I performed a technical pre-publication review of the second edition of the MySQL to DB2 Conversion Guide that was just released this week, but the following books will be covered from an end user point of view, after general availability.

IBM WebSphere eXtreme Scale 6
First up will be IBM WebSphere eXtreme Scale 6 by Anthony Chaves.

Packt Publishing – who have sent me a free review copy – have made “Chapter 7: The DataGrid API” (PDF) available as a free download.

WebSphere eXtreme Scale is an in-memory data grid used to cache objects and improve both performance and scalability in Java EE applications. It’s analogous to memcached.

I’ve read the first chapter so far and am looking forward to diving into the rest shortly, particularly as I continue to tune a high-volume WebSphere application set to launch an update later this month.

Pro IBM WebSphere Application Server 7 Internals
My next review will be a related middleware title, Pro IBM WebSphere Application Server 7 Internals by Colin Renouf. Apress also sent me a review copy of this book, along with the next title.

I’ve read a few chapters so far, and am quite intrigued by how the author has exploited the modular Eclipse (didn’t know that!) underpinnings of WebSphere 7 to produce some interesting system administration plug-ins.

Of most interest to me about this book is that the author is neither an IBMer with access to WebSphere’s source code, nor writing to sell the reader on IBM middleware, but rather a seasoned pro with lots of practical experience getting the most out of WebSphere.

Zend Enterprise PHP Patterns
Finally, I’ll have a look at Zend Enterprise PHP Patterns by John Coggeshall with Morgan Tocker, also from Apress.

Rather than a catalog of architectural, object-oriented software patterns, this book describes several techniques for developing effective and efficient PHP applications using best practices based on Coggeshall’s years at Zend working on several large scale projects for enterprise customers.

I’ve read two of the chapters in this book that are of prime interest to me, “Web Application Performance and Analysis” and “Data-Caching Strategies in PHP.”

The former looks at diagnosing whether an application is CPU, memory, or I/O bound. This server level approach moves beyond profiling PHP code and looking at the hardware itself. Even for applications moving to the Cloud, this should remain extremely relevant.

The latter chapter has much in common with the WebSphere eXtreme Scale product above, so it will be interesting to learn more about the state-of-the-art in both PHP and Java EE Web application performance techniques.

So far so good
Stay tuned for the more complete reviews in the coming month or two. Right now it seems that all three titles are solid additions to any Web application developer’s library, but I’ll hold out my final verdict until I have a chance to evaluate each more thoroughly.

WebSphere sMash at New York PHP April 28th

Next Tuesday night we’re excited to have WebSphere guru Roland Barcia introduce the latest PHP and Web 2.0 capabilities in IBM’s WebSphere sMash environment (built on Project Zero) to the New York PHP community:

IBM WebSphere sMash is a platform for developing and running agile Web applications using scripting languages and Web 2.0 technologies such as RESTful Web services, JavaScript Object Notation, and Atom and RSS feeds.

It supports the Groovy language, familiar to Java programmers, and PHP for access to thousands of PHP applications and libraries,and the huge PHP developer community.

IBM WebSphere sMash is focused on significant improvement in time-to-value for Situational Applications and Mashups.

Partners and community have found that by combining PHP applications and libraries with new code written in PHP or Groovy for the IBM WebSphere sMash platform, they can achieve significant reduction in development time for Situational Applications and Mashups.

We cover an overview of the PHP support in IBM WebSphere sMash and the support for generating new PHP code before exploring more detailed scenarios demonstrating PHP applications being extended, integrated and mashed up.

The presentation comes on the heels of the latest WebSphere sMash v1.1.0.1 release that includes PHP performance improvements and the new PHP to Groovy bridge (call Groovy classes from PHP).

Here’s a little background on how sMash relates to Project Zero (you can find more info on the about page):

  • Project Zero experimental builds (latest are named LeMans and Sebring). Includes the latest/greatest functional enhancements, tools, and bug fixes that haven’t yet made it into the generally available product. No-charge for development and limited deployments. Support via the Project Zero community.
  • WebSphere sMash Developer Edition – includes tooling as well as the stable, production-ready runtime. No-charge for development and limited deployments. Support via the Project Zero community.
  • WebSphere sMash – same stable, production-ready runtime as WebSphere sMash Developer Edition, but warranted & licensed for full production deployments. Available for purchase from IBM. Support available via the Project Zero community and 24x7x365 voice & electronic IBM support included with each new license purchase.

On a personal level, I’m excited to learn more about the PHP capabilities at this meeting first hand. I had a chance to work with sMash recently on an internal situational application. It used Groovy however, not PHP.

There’s also a slew of articles on developerWorks to learn about writing apps for sMash. In particular, Introducing IBM WebSphere sMash, Part 1: Build RESTful services for your Web application is a good place to start.

Back to the NYPHP meeting, please make sure you RSVP at least 24 hours in advance, by 6pm ET on Monday, April 27th for the meeting Tuesday night.

Hope to see you there!

Instant XML feeds via the JSTL SQL tags

20 December 2007 » DB2, Java, MySQL, Web architecture, WebSphere, XML

A dusty old Java tag library can help conjure up siloed Web site data for new uses.

Some background
I’ve developed a number of server-side Java Web applications over the years, first with scriplets embedded in JSP, then with the template and tag driven paradigm offered by ATG Dynamo before the J2EE standards, and most recently with the Model-View-Controller architecture pattern in Struts and Spring MVC.

Each of those technologies (mostly) improved on its predecessor and enforced a better separation of concerns between the database, application logic, and presentation of the end result in the browser. This in turn has helped my teams divide and conquer Web application development among specialized job roles.

That’s why I’ve long been puzzled why the SQL tags in the JavaServer Pages Standard Tag Library exist as a standard part of J2EE 1.3 onward. These tags enable a front-end developer to embed SQL directly into a JSP page without the need for scriptlet code.

This tag library seemed an ill-conceived reversion (anti-pattern even) to the days before MVC took hold as a best practice in the Java world, and I’m pretty sure I skipped that section of the objectives when studying for the SCWCD exam.

That said, the SQL tags came in pretty handy this week for a particular challenge, and the more I think about how I can use them beyond their intended purpose, the more every new requirement I see looks like a nail.

My particular application context
I support a content management application which was designed, developed, and deployed circa Web 1.9. It’s stable, performant, and most importantly, met its functional requirements of the day.

In the two years that it’s been deployed, several new requirements have arisen that have expanded its anticipated scope as a traditional Web application.

In particular, the ubiquity of XML feeds have driven the need for it to present its core data outside of the templates existing in the confines of its own Web site. The rise of tagging and the popularity of multimedia as syndicatable content has also made it creak.

Compounding the architectural limitations of the application itself is its inflexible hosting environment. The data center that this site is deployed to is governed by CYA-driven restrictions (rightly so) which constitute a barrier to frequent application deployment cycles that add new functionality.

This environment makes it difficult to adopt nascent technological advances – the next big thing in “coolness” or usability – but have also kept it exceptionally stable and available to meet its codified requirements without introducing undue legal or financial risk.

The application itself consists of two subcomponents. There is a Web application module on the secured intranet for authors to generate new content, and a publicly accessible read-only Web application module to display published content.

It’s primarily this latter Internet application where the use of JSTL SQL tags comes in most handy, but I can imagine uses on the intranet side as well (ad hoc reports, for example).

The case for SQL tag driven XML feeds
The JSTL standard defines a tag library for issuing queries against a data source defined in the Web deployment descriptor without using JDBC in Java scriptlet code in a JSP.

If this sounds like a simple concept that harks back to the type 1 JSP days, that’s because it is. The documentation shows its own apprehension about the inappropriate use of these tags:

The JSTL SQL tags for accessing databases … are designed for quick prototyping and simple applications. For production applications, database operations are normally encapsulated in JavaBeans components.

But therein lies their simplicity, flexibility and power for this particular production application scenario.

In order to take any slice of your data that can be exposed via a SQL query to the authorized user mapped to the JNDI entry for that data source, all you need to do is is write your query and iterate through the result set in an XML template defined in your JSP.

Think about that outside of this technology’s intended use as a prototype or simple application building block. Instead, imagine how you could use these tags to improve the value of a complex existing production application.

For example, suppose you’ve always provided an RSS feed for your latest ten published news stories. You’ve written your Controller or Action in your chosen MVC framework of choice and deployed it.

But now your users are demanding the latest five thumbnails of images published with a story to accompany its syndicated title and abstract in their latest mashup. Or perhaps they only want to see the last 10 stories which contain a given keyword.

What do you do? You could write a new Action or Controller and proper Command class in Java to meet that requirement. That would require updating some configuration files or deploying an EAR or WAR.

But look, you have an existing deployed stable application. Why risk introducing new code or downtime to a perfectly good application? Why not just free your data for use by your users’ new requirements in a quick hitting, low risk way?

Reuse your data by plugging in new JSTL SQL tag driven JSP files, don’t rebuild your application for every new data usage requirement.

To the tag library!
Ok, so you’ve read this far. I promise, the implementation itself will be much shorter :)

So your users want more information delivered via your feeds, or they wish to query by keyword or otherwise filter your data in a way you never anticipated.

Let’s see if we can free up that data for them.

  1. Write your query, with or without input parameters.

    SELECT ID, TITLE, ABSTRACT FROM NEWS_ARTICLES;

    SELECT ID, TITLE, ABSTRACT
      FROM NEWS_ARTICLES
      WHERE BODY LIKE ‘%?%’
      FETCH FIRST 5 ROWS ONLY;

    SELECT ID, TITLE, ABSTRACT, THUMBNAIL
      FROM NEWS_ARTICLES NA, NEWS_ARTICLE_IMAGES NAI
      WHERE NA.ID = NAI.NA_ID;

  2. Determine what XML format it should be in, whether a standard such as Atom or something custom like the following.

    <?xml version="1.0" encoding="UTF-8" ?>
    <results>
      <result id="">
        <title></title>
        <abstract></abstract>
        <thumbnail></thumbnail>
        <body></body>
      </result>
    </results>
  3. Tie the query to the format in a JSP file using the JSTL SQL tag library (and optionally, the Core tag library to escape output) and the JNDI name of the data source you already have configured in web.xml.

    Consult the documentation if you want to use placeholders.

    <%@ page contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8" session="false"%>

    <?xml version="1.0" encoding="UTF-8" ?>

    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    <sql:setDataSource dataSource="jdbc/yourdatasource"/>
    <sql:query var="items">
      SELECT ID id, TITLE title, ABSTRACT abstract, BODY body, THUMBNAIL thumbnail
        FROM NEWS_ARTICLES NA, NEWS_ARTICLE_IMAGES NAI
        WHERE NA.ID = NAI.NA_ID;
    </sql:query>

    <results>
     <c:forEach var="row" items="${items.rows}" >
      <result id="<c:out value="${row.id}"/>">
        <title><c:out value="${row.title}"/></title>
        <abstract><c:out value="${row.abstract}"/></abstract>
        <thumbnail><c:out value="${row.thumbnail}"/></thumbnail>
        <body><c:out value="${row.body}"/></body>
      </result>
     </c:forEach>
    </results>

  4. Deploy the JSP file as your application server requires. If reloading is not enabled, restart the application (consider setting a 15 minute timeout or similar, so you gain the performance boost but provide a hook for updating JSPs individually).

Conclusion
That’s it, you’ve now added an aspect of functionality to your application which frees up any data you can query for via SQL (or XQuery, if your data server is so enabled). You’ve done it in a pluggable fashion and haven’t needed to build any new Java code within your existing application and its framework.

Of course, the flip side is that you’ve done it outside of your application framework and may have circumvented some well-intended best practices. However, you may to prefer to think of this approach as a temporary, low-risk way to share the data available to the users of your application in novel ways that may justify investing in the development of longer term solutions.

Ironically enough, this reversion to single file deployment can make an application buzzword compliant with the one of the most touted recent enterprise targeted architectural pattern – SOA. It reduces the barrier between the value an application has – its data – and the consuming end point of that data – to a simple JSP.

Thoughts on the Spring Framework

One of my goals for the year was to learn more about the Spring Framework, a layered set of modules that intend to make enterprise Java development easier.

In September, I took a class on Spring. Last month, I put together a presentation to share what I learned with my colleagues.

The bootcamp
I attended the Core Spring bootcamp in New York City. If you’re looking to learn about Spring in a classroom environment, there is perhaps no better source than Interface21‘s consultants as they are the company behind the project.

The course materials were solid and the class revolved around a real-world application scenario. For each segment presented, corresponding before and after projects for the lab were available in a workspace used by the free, Eclipse-based Spring IDE that was distributed to the class.

A copy of Pro Spring was included with tuition, but I’ve found the newer Spring in Action, second edition a better read. The instructors also noted that the older Pro Spring book had information on AOP and transactions that weren’t up to speed with the latest 2.x versions of Spring.

As you would expect from a technology that in practice killed EJBs, the Spring bootcamp focuses on middle-tier applications. However, there was good coverage of Spring MVC, which I hope to a adopt for a new project built on WebSphere 6.1 and J2SE 5.0.

Like Baldwin home from Paris
Some time after the course I had the opportunity to present an overview of the Spring Framework to my department. The audience consisted of developers as well as project managers and other non-technical types, so the goal was to keep the presentation accessible as well as sufficiently informative.

To sum up the philosophy of Spring in a nutshell, I hit on three characteristics with real world parallels. I hope they went over well, and I think some of the other learning materials out there would benefit from a similar approach. It seems the ideas behind Spring could be conveyed easier than they often are (another reason I like Spring in Action).

  • Inversion of Control / Dependency Injection
    Give code what it needs, don’t make it ask
    Does your car buy its own gas? Should it have its own credit card? Or use yours?
  • Interchangeability through Interfaces
    Keep things “black box” enough that you can swap individual pieces out when you need to
    Your twenty year old lamp can take either a traditional incandescent light bulb or a new compact fluorescent light bulb which provides a 75% more efficient way to do the same thing in the same standard socket.
  • Aspect Oriented Programming
    Terrible name and difficult vocabulary for an easy-to-grasp concept
    Consolidate logging and access control code, don’t repeat it all over the place
    Imagine an assistant tracking your billable hours to several projects during the day for you while you focus on your real job.

Silly middle-tier guys, or, what’s with that goofy .htm extension?
I have one outstanding gripe about Spring. Spring MVC in particular. I let it slide in the class, but since the foolishness is repeated in other materials for learning Spring I felt I had to speak my mind.

In a lot of examples for configuration of the Spring MVC DispatcherServlet, folks will tell you that “.htm” is the preferred convention for the mapping requests to the front controller.

The argument goes that we should trick the search engines into thinking this is static HTML content and besides, the mapping reflects that even though the page is dynamic, it is indeed rendered in HTML. Furthermore, the “.do” convention from Struts is pure tomfoolery.

This is dogsqueeze.

I take exception with all those arguments. In fact, I’d go as far as to say the “.htm” extension for dynamic content is actually harmful:

  • Most developers deploy Java Web applications to an application server which is not also the front-end Web server. Application servers, such as WebSphere, are configured to serve only dynamic content, such as servlets and JSPs. The HTTP server, such as Apache, serves the static files such as HTML documents, stylesheets and images.

    What if you really did have a static file with a “.htm” extension deployed by one of your Web developers? Do you want to see her go bonkers when she can’t figure out why her file is not being found because you decided to map that extension to your servlet? WTF?

  • Do you really want to make the impression that you’re hosting your Fortune 500 or high volume e-commerce site on MS-DOS?
  • The “search-engine friendly” argument for the “.htm” extension goes out the window when you start using query string parameters anyway.
  • You’ve introduced goofiness at the cost of elegance, another tenet core to Spring. Sigh.

But honestly, if you’re going to go through with it anyway, just add the damn extra “l”, filename limitations (virtual as they may be) are a thing of the past.

A new ibm.com

IBM unveiled a significant upgrade to its Web site earlier this month. There were many folks who drove this successful launch and we’re all pretty proud of the result.

Beyond the aesthetic touch ups and usability improvements seen in the new v16 and v15 templates (Here’s a v14 page for comparision), there were quite a few personalization features packed in.

Visitors can now:

  • Add a given page to their interest areas based on the subject or topic indicated in the meta tags. For example, by clicking Add to My Interests.
  • Navigate based on those interests and country/language preference.
  • Sign in anywhere and share content with others via “E-mail this page” links always available in the masthead and footer.
  • Save time with forms that are pre-filled with information from their profiles when logged in.

My team’s contributions were to the client-side JavaScript and server-side Java functionality, which comprised the overall asynchronous, services-oriented architecture.

This system design enables customization to be plugged in regardless of the underlying hosting infrastructure of the existing Web site.

For example, areas of ibm.com that are hosted on static file Web servers or those which only use CGI are still able to use the new features provided by the central WebSphere application since they are enabled via a single new JavaScript file and use the id of elements in the DOM of the new HTML templates.

I had the opportunity to work with a new team and learned quite a bit over the short run of the project. I was able to pick up or improve my skills with asynchronous JavaScript programming, JSON, DOM, Java build tools such as Ant, high-performance WebSphere hosting, and the CMVC version control system.

The services-oriented architecture was probably the most fundamentally different part of this Web application from others I’ve been involved with and I’m pretty excited about applying that pattern in future projects now that I’ve seen the value of a real world implementation.

Code review in version 7 of Rational tools

26 April 2007 » Java, RAD, RSA, Web architecture

A quick note to help out other folks who are looking for the Code Review feature they used in version 6 of Rational Application Developer or Rational Software Architect in version 7 of these tools.

Instead of selecting the Code Review view from within the Java perspective, you’ll now find the same functionality under Analysis Results.

In general, references to “Code Review” in the help documentation have been changed to “Static Analysis.”

Kathy Sierra and the Blogger’s Code of Conduct

The blogosphere was aflutter last week after a slew of nasty comments and death threats were leveled at one of my favorite authors, Kathy Sierra of Head First fame, by one or more anonymous posters on her blog and in other high-profile forums.

Kathy’s reaction to the punks (and the owner’s of the sites themselves) was covered on Slashdot and even hit the BBC. CNN was slated to air a segment on it this morning.

The incident spurred a call for a “Blogger’s Code of Conduct,” and Tim O’Reilly has led the way with a first draft on his blog. Mostly common sense I suppose, but still a good start and cause for reflection when posting or replying to blogs.

In any case, I hope to see Kathy back and writing soon. Readers like myself owe much to her ability to help us understand complex software development concepts through humor, and to drive the point home by involving beer consumption as the logical end goal of any proper sample application.

Next page »