Java pitfalls: Field access in inner classes

This is not a “pitfall” per se, but an implementation detail worth knowing. Let’s say I have a inner class with a field. Such a field is visible to the enclosing class, but which one of the following ways is the fastest way to access it?
Note! I’m only looking here at the generated bytecode, and not considering any JIT optimizations, so this “performance analysis” is very naïve

public class Test {

  public void testAlternatives() {
    // Alternative 1
    System.out.println(new Inner().field);
    // Alternative 2
    System.out.println(new Inner().getField());
    // Alternative 3
    System.out.println(new Inner2().field);
    // Alternative 4
    System.out.println(new Inner2().getField());
  }

  class Inner {
    private int field;

    public int getField() {
      return field;
    }
  }

  class Inner2 {
    int field;

    public int getField() {
      return field;
    }
  }

}

An intuitive answer is that alternatives 1 and 3 are equally fast because the field is always visible to the enclosing class, and both use field access which is overall slightly faster than method access used in alternatives 2 and 4. However, there’s an implementation detail that causes this to be untrue. The JVM itself does not have a concept called “inner classes”. The whole concept is implemented by the Java compiler and in the bytecode level everything consists of normal classes.

The issue here is that if the inner class has a private field, and the compiler will eventually compile the inner class as a normal class. A private field in a normal class cannot be accessed by other classes, so the enclosing Test class cannot “see” the field without some tricks. Here’s the above code “desugared” to what the compiler actually compiles to bytecode:

public class Test {
  public void testAlternatives() {
    // Alternative 1
    System.out.println(Test$Inner.access$000(new Test$Inner(this)));
    // Alternative 2
    System.out.println(new Test$Inner(this).getField());
    // Alternative 3
    System.out.println(new Test$Inner2(this).field);
    // Alternative 4
    System.out.println(new Test$Inner2(this).getField());
  }
}

class Test$Inner {
  final Test this$0;

  private int field;

  Test$Inner(Test test) {
    this$0 = test;
  }

  public int getField() {
    return field;
  }

  static int access$000(Test$Inner inner) {
    return inner.field;
  }

}

class Test$Inner2 {
  final Test this$0;

  int field;

  Test$Inner2(Test test) {
    this$0 = test;
  }

  public int getField() {
    return field;
  }

}

As you can see, a
package-level static accessor method called access$000 is generated in order to grant access to the private field. Now it’s easier to see that alternative 3 will most likely be the fastest one, because it is the only one that uses direct field access. Using package access in fields is a micro-optimization, but this whole thing is definitely a detail that should be known by Java developers. In performance-critical parts of code it might actually matter, and
the Android performance guide actually mentions this implementation detail.

This implementation detail may also cause slight confusion when field access is attempted on a null reference of the inner class. Consider the following code:

public class NullTest {
  class Inner {
    private int field;
  }

  public void test() {
    Inner inner = null;
    System.out.println(inner.field);
  }

  public static void main(String[] args) {
    new NullTest().test();
  }
}

The variable “inner” is null, so a NullPointerException is obviously thrown. However, what is not apparent from the original code is that the exception is thrown inside the compiler-generated static accessor method!

$ java NullTest
Exception in thread 'main' java.lang.NullPointerException
 at NullTest$Inner.access$000(NullTest.java:2)
 at NullTest.test(NullTest.java:8)
 at NullTest.main(NullTest.java:12)

The stack trace contains the intuitive exception source (line 8), but the real source will confuse developers who don’t know about compiler-generated accessor methods.


Reference:
Java pitfalls: Field access in inner classes from our
JCG partner Joonas Javanainen at the
Jawsy Solutions technical blog blog.

Source : http://www.javacodegeeks.com/2012/05/java-pitfalls-field-access-in-inner.html

The Developer/Non-Developer Impedance Mismatch

Most software developers have probably heard of and even had experiences with the
object-relational impedance mismatch (often addressed with
ORM tools), the
object-XML impedance mismatch (often addressed with
OXM tools), and even the
developer-DBA impedance mismatch. I don’t believe that these impedance mismatches are as difficult as they are
sometimes made out to be, but for those wishing to mitigate them, we have tools such as
Java Persistence API implementations and
JDO implementations for dealing with the object-relational mismatch (and some of the developer-DBA impedance mismatch) and similarly have approaches such as
JAXB,
XMLBeans,
JiBX and
Apache Commons Digester for dealing with the object-XML mismatch (and .NET’s
LINQ deals with both
ORM and
OXM mismatches). At this point in my career, I believe the developer/non-developer impedance mismatch is perhaps the most frustrating impedance mismatch I have run into.


Although there are numerous tools and approaches for dealing with these other types of impedance mismatches, it seems we’re woefully short on similarly powerful tools, approaches, and
proven practices (my new preferred term for what I think "
best practices" was originally intended to mean) for dealing with the developer/non-developer mismatch. In this post, I look at some of the most common areas of developer/non-developer mismatch and speculate as to why they occur and what can be done to address these specific areas of developer/non-developer impedance mismatch.

Sadly, we have much less control over the developer/non-developer impedance mismatch than we do over object-relational or object-XML impedance mismatches. Although in general things like improved communication and education can help, these answers are not as tangible as the ones we’re used to for dealing with other types of software development impedance mismatches. As difficult as it is to deal with the developer/non-developer impedance mismatch, we must do so because there are numerous significant stakeholders in the software development process that are not necessarily developers (managers, clients, testers, customers, business analysts, sales people, and more). 


DRY Principle / Modularity

Almost to a fault, developers have generally adopted (at least in a theory if not always in practice) the DRY (
Don’t Repeat Yourself) principles coined in the often-referenced book
The Pragmatic Programmer: From Journeyman to Master. Although the term was coined in this 1999 book, the practice had been one that developers for decades had understood to some degree. Regardless of native spoken language or favorite programming language, developers today widely recognize virtues of some degree of DRY-ness. There may be
some debate as to what level this should be taken (I’ve seen it taken past the point of common sense), but most of us agree with the perils of repeated documentation at different levels of the software product or of repeated code (
copy-and-paste development).

Benjamin Denckla, in the post "
Faith in DRY; no hope for software," writes, "Today we produce software through a laborious, undisciplined process that combines the low quality work of many with the heroic high quality work of a few. … Not enough people believe in DRY and other good practices like it." I believe this is especially true when one considers the non-developers involved in a software development project. In my experience, the developers generally do see the value in some significant degree of DRY, but non-developer stakeholders see little value in DRY principles.

For purposes of this discussion, I’m including modularity in what I’m calling DRY practices. Most developers know there are numerous reasons to not copy-and-paste the same code into multiple places. For many decades, developers have known to place reusable code in methods, functions, modules, or other constructs that allow the same code to be used in multiple contexts and situations. It doesn’t take long for this to become second nature to the experienced developer. Sadly, many non-developers seem to not acknowledge the risks and problems associated with redundant information copied from place to place or believe these risks and problems are more theoretical than real. Although it may not be code we’re talking about when we discuss non-developers (it may be documentation, requirements, specifications, test procedures, or a host of other non-code things), the principle still applies: reproducing anything in multiple places leads to problems down the road in terms of maintenance and keeping the many versions synchronized with the latest and greatest. Developers seem to almost intrinsically "get it," but I see it less well received from many non-developers.

Readable and Maintainable Code

Many new software developers and even more non-developers do not recognize the value of code that is more readable and more maintainable. Perhaps the best experience a young developer can have is to maintain and reuse someone else’s code. Doing so helps a young developer to recognize the value of writing code as cleanly as possible. Because non-developers never really get this experience, it is not surprising that they don’t value cleanness, maintainability, and readability to the same degree as the experienced developer. Many legitimate cries for time to refactor a code base to improve its future maintainability and readability are ignored or promptly dismissed because such efforts’ value is not obvious to those making the decisions.


Overbearing Processes and Management Decisions

I have occasionally seen non-developers in management roles trying to coerce developers into very narrow and specific behaviors that they (the managers) believe is best (or worse, that they perceive as giving them the power). These folks rarely have the experience to know the full ramifications of their decisions. Good managers listen to their developers (particularly those with significant experience and in technical leadership roles) before pushing out every "good idea" they have. Experienced developers usually know what it takes to write high-quality software, but it almost takes another experienced software developer to appreciate what they argue for. Alternatively, a manager lacking software development experience can sometimes make better decisions by choosing an experienced developer that he or she trusts with technical decisions. The best non-technical managers recognize their own lack of technical knowledge and work with a trusted technical expert to make good decisions. 


Bean Counting and Pencil Pushing

Most software development is done as part of a business venture and it is often inevitable that some degree of
bean counting and
pencil-pushing will be required.. Clients or consumers directly or indirectly finance the creation of software. It can be difficult for developers to recognize and appreciate the legitimate management and metrics collection that goes on during these business-oriented phases. It can be equally difficult for managers and other non-developers to understand that some things are more subtle than the apparent "bottom line." Non-developers may over-emphasize short-term "bottom line" considerations at the expense of long-term quality and maintainability of the product while developers may overly neglect bottom line considerations and create software products that require too much time and investment to justify their likely return on investment.

The bean counter wants nothing more than to be able to count things like beans. He or she wants to use
lines of code, number of defects in various states, number of requirements, and so forth to feel like he or she has a handle on the software development progress being made. It
doesn’t really matter that these are not created equally and should not be counted as if they are equal. 


Battle for Control

It seems to be human nature and common in many relationships between humans to have battles for control. Tension can increase in the relationship between developers and non-developers as each group tries to exert control. Many non-developers, especially if they don’t understand development or coding well, resent not being able to control what is added to the baseline. Many developers resent being told what they can put into the baseline, especially when they strongly believe that the non-developer is making arbitrary calls while lacking sufficient knowledge and background to make that call.

The battle for control can become very onerous when both sides are "know-it-alls." When either side is convinced of its superiority, it can be very difficult to get either to budge. Developers often feel their experience and skillset best qualifies them for making all software decisions while clients, managers, and others often feel their position does the same for them. 


Coding: Job for a Craftsman or for a Technician?

Good software development managers recognize that software development can be a highly creative and challenging effort and requires skilled people who take pride in their work. Other not-so-good software managers consider software development to be a technician’s job. To them, the software developer is not much more than a typist who speaks a programming language. To these managers, a good enough set of requirements and high-level design should and can be implemented by the lowest paid software developers. Some software development is easier than other software development, but the simple technician work has been largely replaced by automation and code generation at this point.

Perhaps the perceptions of technician versus craftsman explain why non-developers tend to be more likely to believe that all developers are plug-and-play while experienced developers realize that there can be a wide disparity in skillsets and knowledge between any two developers. 


Appreciation of Software Development Nuances and Subtleties

It usually does not take long for a developer to realize that relatively little in software development is cut and dry. Software development often has a large amount of creativity to it and there are numerous judgment calls to be made. We sometimes call these design decisions or architecture trade-offs. Unfortunately, many who are not software developers do not understand that there are nuances and subtleties and even large amounts of creativity involved in software development. Without lack of these subtle shades, it’s not surprising that many of these people without development experience can only think in extremes (technique "A" is good and must be be used by everyone all of the time or technique "A" is always wrong and should be absolutely avoided no matter what). New developers often exhibit this trait as well, but experience usually teaches them to be more willing to judge approaches and techniques against particular contexts and reduce the amount of generalization and assumptions. 


Developers Aren’t So Different from Others, But Then They Are

The Mythical Man-Month is one of the
most often-quoted books in the areas of software development and
software development management. One of its great quotes is made early in the work (first sentence of Preface to the First Edition): "In many ways, managing a large computer programming project is like managing any other large undertaking—in more ways than most programmers believe. But in many other ways it is different—in more ways than most professional managers expect." One of the key explanations of the impedance mismatch between developers and non-developer managers seems to lie in this profound statement. Developers, as a group, probably should be more willing to buy into certain proven "traditional" management approaches, but managers need to avoid falling into the trap of thinking that the tactics outlined in the latest business management book will be sufficient for managing software developers. 


Opinions on 
What Values Most

Software developers are people too. As such, they do exhibit the same behaviors as other people. However, there are gross stereotypes of software developers that are not completely without some basis because of the high frequency of those stereotyped traits among software developers. There is great diversity in the software development community in terms of political opinions, interests, and so forth, but the idea of what is most important (quality design and code, work to be proud of, etc.) are fairly common across the industry. On the other hand, software developers (similarly to engineers in various engineering disciplines) seem to overly trivialize the need to respect the bottom line. They often cannot understand when an arguably adequate but not "best" or "perfect" solution is chosen over a better technical solution for non-technical reasons. 


Conclusion

We in the software development community tend to deal with mismatches all the time. We often spend significant energy and time "gluing" things together that weren’t necessarily designed to go together. Despite all of this technical experience we have making incongruent pieces work together, we still seem to have difficulty resolving perhaps the most difficult and most important mismatch of all: the
mismatch between software developers and people who are not software developers. Although there are some positives that come from this (such as checks-and-balances on "science fair projects"), there is significant dysfunction, angst, resentment, and demoralization caused by this impedance mismatch.


Reference:
The Developer/Non-Developer Impedance Mismatch from our
JCG partner Dustin Marx at the
Inspired by Actual Events blog.

Source : http://www.javacodegeeks.com/2012/05/developernon-developer-impedance.html

Java static methods can be a code smell

Definition of code smell (from Wikipedia):



“any symptom in the source code of a program that possibly indicates a deeper problem.”

In Java,
static methods allow you to execute code at a “class scope” as opposed to an instance scope like member methods. This means, they rely on class-level variables (if any), parameters passed to the static method, or any other globally accessible data. They are NOT object oriented. An object has state associated with it and can be manipulated only through methods that implement the object’s “behavior.” Static methods do not operate on state, they are not object oriented, and in fact they are procedural.

Is this bad?

No. Although Java is object oriented, there will be times when procedural-like programming in Java is necessary and/or preferred. The real power in any object-oriented language is the ability to closely implement a model of real-life systems in code (see my
post about object-oriented modeling). But even in the most hard-core object models, there will mostly likely be some glue code, or infrastructure code that will be implemented in a procedural style.

So if procedural-like programming in Java isn’t “that bad” and static methods are a form of procedural programming, are static methods bad?

Ahh… the answer isn’t as simple as a “yes”, or a “no” regardless of what you may read on other blogs But I could probably ramble on and on about why it’s really a decision that has to be made in context, so let’s keep this article focused by examining a set of statements that I encountered in
“How to Mock Static Methods” from Michael Minella’s blog:

“Something that has become a fundimental [sic] piece of the language (all you need to do is look at the Apache Commons project to see that) is so bad that it must be avoided at all costs in the name of testing. Gosling (or someone on his team) put it in the language for a reason and to avoid those uses solely because your toolset doesn’t support the testing of it is nonsense. Time to get a new toolset.”

First, I’d like to point out that just because something has become a fundamental piece of a language doesn’t mean it’s “good” or something that should be done. Take a look at
checked exceptions for reference. I recall EJB 1.x and 2.x becoming a “fundamental” piece of Java EE in the past, so look at that for reference too.

Second, although I do agree with Michael in theory that avoiding a particular language feature because your tools don’t support it is silly, his premise is focused on static methods. Avoiding static methods because your tooling doesn’t support them is NOT nonsense at all. In fact, the type of impedance caused by some of the good testing and/or mocking frameworks (of which
Mockito is my favorite
:) ) and static methods can be confidently identified as a code smell. This does not mean we should not do it, but we should exert extra effort to understand why we are doing it and explore alternatives if there are “deeper problems.”

There are at least two types of static methods that I would like to point out don’t usually show much impedance with testing/mocking frameworks. The first type is static methods used as utility methods, as those found in a lot of the
apache commons libraries, or your own internal commons libraries. These are usually routines that are supportive of a particular method’s objective, and mocking/stubbing them out of a unit test wouldn’t make sense. They are part of the implementation, and should be tested as such. The second type is static methods used in place of constructors as Joshua Bloch showed in his book
“Effective Java.” This use of static methods allows you to construct a new object using a method with a very descriptive name, among some other advantages. An offshoot of this second type of static method could include factory methods, but that would depend on context.

The most glaring code smell as a result of static methods and testing-framework impedance arises when a unit relies on a static method that performs logic outside the scope of the responsibility of that unit. In these cases, your testing framework will fight you because you cannot stub/mock the out-of-scope logic because it is “hardcoded” via a static method. This can be considered a “deeper problem” and is the focus of most blogs that tell you not to use static methods because testing becomes abnormally difficult or impossible. Changing the design approach to follow the Dependency Inversion Principle is one alternative. A better understanding of how to test the unit is yet another.

I assert strongly that in the case of static methods, the push-back you may get from your testing frameworks is indicative of a code smell, not that you need to try and find a framework that uses complex trickery with class loader remapping as a solution. One should be poised to evaluate the use and fundamental drawbacks of a particular approach in their design. Michael’s blog entry lends the reader to too easily assume a new tool/framework just because Java supports static methods and your current testing frameworks illuminate an impedance — in this case, the impedance reflects a code smell and some deeper, more critical thinking is required.


Reference:
Java static methods can be a code smell from our
JCG partner Christian Posta at the
Christian Posta Software blog.

Source : http://www.javacodegeeks.com/2012/05/java-static-methods-can-be-code-smell.html

Software Development Metrics that Matter

As an industry we do a surprisingly poor job of measuring the work that we do and how well we do it. Outside of a relatively small number of organizations which bought into expensive heavyweight models like CMMI or TSP/PSP (which is all about measuring on a micro-level) or Six Sigma, most of us don’t measure enough,
don’t measure the right things or understand what to do with the things that we do measure. We can’t agree on something as basic as
how to measure programmer productivity or even on consistent measures of system size –should we count lines of code (LOC, SLOC, NCLOC, ELOC) or IFPUG function points or object oriented function points or weighted micro function points or COSMIC Full Function Points, or the number of classes or number of something else…?

Continue reading

Google App Engine JAX-RS REST service

In this article you will learn how to create a REST service using JAX-RS reference implementation (Jersey) and deploy it on Google AppEngine.

Prerequisites 

For this tutorial you will need:
  • a Google AppEngine account
  • Eclipse Galileo (3.5.x)
  • Google App Engine SDK for Java
    • Install the Google Plugin for Eclipse as documented here (Check that you are using the release 1.3.1 of the GAE Java SDK, if not download it and configure the plugin to use it)
    • it is also useful to have the AppEngine documentation locally, you can download it from here.
  • JAX-RS Reference Implementation, be sure you take the Jersey 1.1.5 release. You can download it from here
    • Unzip the file in a directory that we will call $JERSEY_HOME
  • JAXB 2.2 Implementation to simplify the marshalling/unmarshalling of the XML, and also facilitate the JSON support. Download it from here
    • Install it using thejava -jar JAXB2_20091104.jar command. The installation directory of JAXB will be called $JAXB_HOME



Creating new application

To create a new App Engine project in Eclipse:

  1. Click on the "New Web Application Project" button in the toolbar . It is also possible to do it using the menu File > Web Application Project
  2. The "Create a Web Application Project" wizard opens:
  • Project Name: EmployeeService
  • Package : com.grallandco.employee.service
  • Uncheck "Use Google Web Toolkit"
  • Check that the SDK version your are using is "App Engine 1.3.0"; if not configure the project to use it.
  • The screen should look like the following screen :
  • Click Finish
  • The project should look like the following screen :

Running the application

The App Egine SDK, installed with the Eclipse plugin contains a Web server (based on Jetty), that could be used for testing and debugging. To test that your application has been created correctly select the menu Run > Run As > Web Application. I personnaly most of the time run my server using the debug command Run > DebugAs > Web Application. In debug mode you can change source code and test is without restarting the server.

The web server is starting automatically, you should see the following message in the Eclipse console

The server is running at http://localhost:8080/

You can access the application, and the sample servlet that has been created using the URL: http://localhost:8080/employeeservice

To stop the server, click on the terminate button
in the Eclipse console.

Configuring the REST support in the application

To be able to create and run REST services in your application you need to:

  • Add the JAX-RS, JAXB Jars in your project and application
  • Configure the web application (web.xml) to handle REST requests

Add JAX-RS, JAXB to your project

  1. Right click on the project and select menu entry Build Path > Configure Build Path…
  2. Click on the Add External JARs button
  3. Select all the JARs located in $JERSEY_HOME/lib and $JAXB_HOME/lib folders. You can for better visibility and reuse create a user library with all these JARs
  4. You also need to copy the JARs in the web-inf/lib directory of your application, this step is mandatory to be sure that the JARs are included in the application when deployed to App Engine.
    Note: I do not like this step. I would prefer to do that by configuration of the build path, to automatically add the JARs to the WEB-INF/lib directory when executing/deploying the application. Unfortunately I did not find the way to do it, so if you know it, feel free to post a comment and I will update the article.

Configure the web application

In this step you will register a new URI to handle REST requests. To do that you need to register a new servlet that is using the Jersey API and configure it to a specific URI (eg: /ressources and/or /rest) and configure what are the Java packages that contain the REST implementation classes. So you need to modify the web.xml of your application with the following entries:

  <servlet>
    <servlet-name>Jersey Web Application</servlet-name>
     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
     <init-param>
     <param-name>com.sun.jersey.config.property.packages</param-name>
     <param-value>com.grallandco.employee.service.rest.impl</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/resources/*</url-pattern>
  </servlet-mapping>
   <servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
This servlet that will answer to the /resources/ and /rest/ URL. The configuration parameter com.sun.jersey.config.property.packages is used by Jersey to list the packages where REST services implementation are located.Note that you can put as many package as you need to, you just need to separate the package names by a ; 


Creating a simple REST Service to test the environment

The project is now ready to contain REST service. It is time to create one.Create for example the class com.grallandco.employee.service.rest.impl.HelloWorldResource, be sure to use the package name that you have configured in the web.xml for the Jersey servlet, based on the configuration we have made in previous step the package is com.grallandco.employee.service.rest.impl

Here a sample class with the JAX-RS annotations:

package com.grallandco.employee.service.rest.impl;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
@Path("/hr/")
public class EmployeeResource {
 
 @GET
 @Produces("text/plain")
 @Path("/employee") 
 public String getEmployee() {
        return "Hello World!";
    }
}

You should be able to test it, stop the server and run it again, enter the following URL in your browser:

http://localhost:8080/resources/hr/employee

or

http://localhost:8080/rest/hr/employee

Deploying the application to Google App Engine

Before deploying the application you need to register a new application in Google App Engine using the Administartion Console, see the documentation
here. In my example I have used " tugdual" as Application ID.

You can easily now deploy the application to Google App Engine by clicking on the "Deploy App Engine Project" button available in the Eclipse toolbar.

To be able to deploy your application to Google App Engine, you need to check that your application can be registered, the application ID is stored in the WEB-INF/lib/appengine-web.xml.

<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
 <application>[your-application-id]</application>   
 <version>1</version>    
 <!-- Configure java.util.logging -->
  <system-properties>
   <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
 </system-properties>    
</appengine-web-app>

The App Engine deploy button prompts you for multiple informations: username (your Google account) and password.

When the deployment is complete you can access your application using the following URL:

http://%5Byour-application-id%5D.appspot.com/resources/hr/employee

or

http://%5Byour-application-id%5D.appspot.com/rest/hr/employee

Ading XML and JSON support to the service

Let’s now add new method to manipulate an "Employee" object using the service, and the data format should be based on JSON and XML. This is where JAXB is useful, since it allows easily to transform marshall/unmarshall Java objects in XML -obviously- and JSON (cool isn’t!)

Creating an Employee Class

Start with the creation of a new class to manipulate Employee data, this is a very simple Java class that could look like the following code:

package com.grallandco.employee.service.model;
import java.util.Date;

public class Employee {
    private String firstName;
    private String lastName;
    private Date hireDate;
    private String email;   
    public Employee(String firstName, String lastName, Date hireDate, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.hireDate = hireDate;
        this.email = email;
    }
    public Employee() {}
    public String getFirstName() {
 return firstName;
 }
    public void setFirstName(String firstName) {
 this.firstName = firstName;
 }
    public String getLastName() {
 return lastName;
 }
    public void setLastName(String lastName) {
     this.lastName = lastName;
 }
    public Date getHireDate() {
 return hireDate;
 }
    public void setHireDate(Date hireDate) {
 this.hireDate = hireDate;
 }
    public String getEmail() {
        return email;
 }
    public void setEmail(String email) {
        this.email = email;
   }
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("First: ").append(getFirstName());
        sb.append(" - Last: ").append(getLastName());
        sb.append(" - Date: ").append(getHireDate());
        sb.append(" - Email: ").append(getEmail());
        return sb.toString();
    }
}

When implementing your "real" application with some persistence layer this POJO is the one as JDO/JPA entity.

Create a Converter class for your entity

I usually encapsulate all the transformation in some converter class, like that I do not directly couple my business class to the serialisation mechanism. (So I do that for classes and lists of classes). So instead of adding the JAXB annotations to the Employee class itself, let’s create an EmployeeConverter class that will be responsible of the transformation and used by your REST service.

package com.grallandco.employee.service.converter;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.grallandco.employee.service.model.Employee;

@XmlRootElement(name = "employee")
public class EmployeeConverter {
 private Employee entity = null;
 public EmployeeConverter() {
 entity = new Employee();
 }

 public EmployeeConverter(Employee entity) {
 this.entity = entity;
 }

 @XmlElement
 public String getFirstName() {
 return entity.getFirstName();
 }

 @XmlElement
 public String getLastName() {
 return entity.getLastName();
 }

 @XmlElement
 public Date getHireDate() {
 return entity.getHireDate();
 }

 @XmlElement
 public String getEmail() {
 return entity.getEmail();
 }

 public Employee getEmployee() {
 return entity;
 }

 public void setFirstName(String firstName) {
 entity.setFirstName(firstName);
 }

 public void setHireDate(Date hireDate) {
 entity.setHireDate(hireDate);
 }

 public void setLastName(String email) {
 entity.setEmail(email);
 }

 public void setEmail(String lastName) {
 entity.setLastName(lastName);
 }
}

You can now update your service to use this utility/converter class to return XML or JSON ojbect based on the content type of the request.

Add support to JSON and XML to your REST service

You need to change the EmployeeRessource class, to change the signature and add new annotations of the getEmployee() method.

The annotation you are adding:

  • @Produces({"application/xml", "application/json"}) : indicates which type of content will be produced by the service. Based on the type of the request.
  • @Path("/employee/{employeeEmail}/") : change the Path to indicate a Path parameter, here for example the URL can accept an email in the URI – not the best example, but you get the point…
  • public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email) : change the type returned by the method and take a parameter as String that match the Path param defined in the @Path annotation

Here the complete class code:

package com.grallandco.employee.service.rest.impl;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import com.grallandco.employee.service.converter.EmployeeConverter;
import com.grallandco.employee.service.model.Employee;

@Path("/hr/")
public class EmployeeRessource {

 
 @GET
 @Produces({"application/xml", "application/json"})
 @Path("/employee/{employeeEmail}/") 
 public EmployeeConverter getEmployee( @PathParam ("employeeEmail") String email) {
 //dummy code
 Employee emp = new Employee();
 emp.setEmail(email);
 emp.setFirstName("John");
 emp.setLastName("Doe");
 EmployeeConverter converter = new EmployeeConverter(emp);
 return converter;
 } 
}

Test the service

You can now run the server locally and test the service

http://localhost:8080/resources/hr/employee/tug@grallandco.com

This will return an XML document.

If you want to test the JSON call you have multiple choice:

  • Using following command
tgrall$ curl -H "Accept: application/json" http://localhost:8080/resources/hr/employee/tug@grallandco.com
{"email":"tug@grallandco.com","firstName":"John","lastName":"Doe"}
  • Using an HTTP client that allows your to configure/set the HTTP request completely, I am using the Poster Firefox Plugin
  • Using some Javascript code in an application

You can repeat the test on your deployed application on Google App Engine.

Conclusion

In this article you have learned how to create and deploy a new REST Service on Google App Engine. This service has been created with the JAX-RS Reference Implementation the Jersey project. In the next article you will learn how to add persistence and create a CRUD Rest service on Google App Engine.


Reference:
Create and Deploy a JAX-RS REST service on Google App Engine from our
JCG partner Tugdual Grall at the
Tug’s Blog blog.

Source : http://www.javacodegeeks.com/2012/05/google-app-engine-jax-rs-rest-service.html

ADF BC: Create a UI table binded to Business Components

In this example we are going to show how to create a simple UI table (af:table) which is binded to Business Components.

Once again, I tried to search on the net with the simple criteria:

‘How to create an af:table binded to business components ADF 11g’

And I must admit thatI did not get the answer I was looking for. The information was there, but hidden among other solutions and examples. This can be confusing some times.. So this is a small example of how to this. I hope it will clarify you some things.

Here we go.

Do not forget to always consult the official documentation:

http://docs.oracle.com/cd/E28389_01/web.1111/b31974/web_tables_forms.htm

First, I suppose you already have an 11g version installed on your machine along with some database connection already imported to your JDeveloper. In this example we are using JDeveloper 11.1.1.6.0

Start your Engines! JDeveloper, ok..

After creating the Business Components. You should have something like this on your JDeveloper:

In this example we are using the Countries table from the HR schema.

Next we are going to create a simple page.

1) Go to View Controller

2) Double Click the adfc-config.xml file to open it in the editor. We choose adfc-config in this example simply because we want to focus on the af:table. We could use Bounded Task Flows but it is no mandatory for this example.

3) We open the components section from the Components palette.

4) We select the View component and we drag and drop it to the adfc-config Diagram.

We havent created our jspx just yet. As you will see in the above screen, the name of the view component is changed to index. The default name was view1. I changed it just forconvenience. You can rename it or leave it as is.

5) We double click the the index View component in order to create the page:

In this example we are going to accept the default values and we will just press ok:

After pressing ok:

6) Now it is time to create our af:table which is binded to BC.

But lets just wait a second.

What is an af:table?

According to the Documentation ( click toEnlarge):

Well, this means that we have to provide a Data Collection to an af:table.

AData Collection can be a tree binding in the pageDefinition of our jspx!

But wait.. how are we going to create this… what you say… tree binding.. and how are we going to map it to our table?? It is getting a bit complicated.. is not it?

Well, of course not! We will do it with one drag and drop!! Yes thats right! In ADF and JDeveloper, With one drag and drop we can do everything! We can create the table, and map it to our Business Components!

All we have to do is to locate the Data Controls section in our application navigator.

After locating this section, we are gong to find the HRModuleDataControl and then we will find the
CountriesView1.

Long Story Short, this Data Control, one might say, that is the Data Control produced by the HRModule Application Module (Data Model).

So, every application module we create, we have it as a Data Control in the Data Controls section of the Application Navigator.

All we have to do is to select the Iterator (View object in the Application Module) and drag-and-drop it onto the jspx as a table.

7) select the CoutnriesView1 iterator. Have the jspx open in the editor. Drag and drop it as a table:

After selecting the ADF table option, another window will appear:

8) set the table options:

The above options, let you decide basic functionalities of the table with simple checkBoxes. Furthermore, they let you control which component you want to use for every attribute of the table. You can set the value of the Display label of every attribute. Furthermore you can add or remove attribute as you want. the most common option is the Row Selection, where you can decide wether you want to select none, one or many rows in your table.

All those options, and more can be configured after you actually create the table.

9) press ok in order to create the table AND the pageDefintion file and the DataBindings file (if the pageDef already exists for this page it will be created again. It will simply be updated. The same goes for the DataBindings as well.)

the pageDef. As you can see, a tree iterBindings was created by the wizard that points to the CoutnriesViews1 iterator which leads to HRModuleDataControl:

DataBindings.cpx file. This files holds the mappings between pageDefs and their pages or method calls and generally, whatever accepts pageDefs. It is the file where you can see those mappings.

And that is it! As you can see, it is pretty easy and rather fun! a simple drag and drop, some options and here we are! we have a live and kicking af:table ready !

Of course, you can always change the properties and experiment further with this component.


Reference:
Getting Started. How to create a UI table (af:table) binded to Business Components. ADF BC from our
JCG partner Dimitrios Stassinopoulos at the
Born To DeBug blog.

Source : http://www.javacodegeeks.com/2012/05/adf-bc-create-ui-table-binded-to.html

JavaME: Google Static Maps API

Whether you need a map for your location based application or just for fun, you can use the easiest way ever: Google Static Maps API. In this post, we are going to see how you can get a Map as an Image from a latitude and longitude point. The latitude and longitude can be obtained using Location API which we won’t discuss in this post.


When writing this post, I realized there is some license restrictions in the use of Google Static Maps API in mobile Apps… I am posting it anyway just for research purposes, but I must warn you about this restriction:

 


http://code.google.com/intl/en/apis/maps/faq.html#mapsformobile

Google Static Maps API Quick Review


 

This API lets you get an Image based on a URL and several parameters you can pass in to obtain a personalized map. You can play with the zoom, type of map, size of the image (width, height), markers at locations of the map, etc. There is a limit you have to keep in mind, the use of the API is subject to a query limit of 1000 unique (different) image requests per viewer per day, which is a lot of images… but if you need more, there is also a Premium license. For more information:

http://code.google.com/intl/en/apis/maps/documentation/staticmaps/

OK, what we do is the following:

  • Create a method that receives a latitude and longitude point and the size of the image as parameters.
  • Request the map image using the URL: http://maps.googleapis.com/maps/api/staticmap, and adding some parameters.
  • Create an Image object and return it, so we can show it on screen.


Hands on Lab

Following is the method we were talking about. It has parameters for the latitude and longitude, and also for the width and height of the image we are requesting. The latitude and longitude can be retrieved using Location API, and the width and height can be retrieved using the Canvas class.

public Image getMap(double lat, double lon, int width, int height) 
throws IOException 
{
    String url = "http://maps.google.com/maps/api/staticmap";
    url += "?zoom=15&size=" + width + "x" + height;
    url += "&maptype=roadmap";
    url += "&markers=color:red|label:A|" + lat + "," + lon;
    url += "&sensor=true";

    HttpConnection http = (HttpConnection) Connector.open(url);
    InputStream in = null;
    byte[] imgBytes = null;
    try {
        http.setRequestMethod(HttpConnection.GET);
        in = http.openInputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            bos.write(buffer, 0, n);
        }
        imgBytes = bos.toByteArray();
    } finally {
        if (in != null) {
            in.close();
        }
        http.close();
    }
    Image img = Image.createImage(imgBytes, 0, imgBytes.length);

    return img;
}

As you may see, it is pretty simple to get the image of the map. The retrieving is pure HTTP request.

Next you can find an image retrieved by Google Static Maps from a location in my home town.

OK, you just saw how simply it would be if no restriction exists… What do you think about that restriction? It’s kind of confusing, isn’t it?

Anyway, we are going to need to find another way to show maps on our mobile apps.


Reference:
Google Static Maps API and JavaME from our
JCG partner Alexis Lopez at the
Java and ME blog.

Source : http://www.javacodegeeks.com/2012/05/javame-google-static-maps-api.html