Pages

Monday, December 21, 2009

JSF PhaseListeners With Annotations

Although JSF 2 moved most of it's configuration to annotations still some must be made on xml's, like the phase listeners.
The most straight forward way to implement a mechanism that would enable defining them with annotations are treating phase listeners as singletons. Than we could simply annotate static methods with after phase, before phase annotations.
A second and more elegant/useful way would be to treat phases as cdi events and observe these events.
Annotating static methods
I have created @BeforePhase and @ActionPhase annotations that take phase id as parameter and mark static methods with that :
1:  public class ActionContext extends AbstractThreadLocalMapContext {
2:
3: private static ActionContext instance = new ActionContext();
4: ...
5: @BeforePhase(CycleId.RESTORE_VIEW)
6: public static void activate() {
7: instance.setActive(true);
8: instance.setBeanStore(new ConcurrentHashMapBeanStore());
9: }
10:
11: @AfterPhase(CycleId.RENDER_RESPONSE)
12: public static void deActivate() {
13: instance.destroy();
14: instance.setActive(false);
15: instance.setBeanStore(null);
16: }
17:
18: @AfterPhase(CycleId.INVOKE_APPLICATION)
19: public static void reActivate() {
20: instance.deActivate();
21: instance.activate();
22: }
23:
24: }
Now we need a phase listener that would scan for these annotations and act as a proxy for these methods. I used the Scannotation to scan for the annotations and proxy phase listener still must be defined in faces-config.xml:
1:  public class ProxyPhaseListener
2: implements PhaseListener {
3:
4: private Map<Integer, Set<Target>> afterregistry;
5: private Map<Integer, Set<Target>> beforeregistry;
6:
7: public ProxyPhaseListener() {
8: try {
9: URL ucp = new URL(ClasspathUrlFinder.findClassBase(getClass()).toString().replaceAll("%20", " "));
10: AnnotationDB db = new AnnotationDB();
11: db.setScanClassAnnotations(false);
12: db.setScanFieldAnnotations(false);
13: db.setScanParameterAnnotations(false);
14: db.scanArchives(ucp);
15: afterregistry = new HashMap<Integer, Set<Target>>();
16: beforeregistry = new HashMap<Integer, Set<Target>>();
17: Map<String, Set<String>> map = db.getAnnotationIndex();
18: registerMethods(map, afterregistry, new AfterPhaseRegisterer());
19: registerMethods(map, beforeregistry, new BeforePhaseRegisterer());
20: } catch (Exception ex) {
21: throw new RuntimeException(ex);
22: }
23: }
24:
25: public void afterPhase(PhaseEvent event) {
26: invoke(event, afterregistry);
27: }
28:
29: private void invoke(PhaseEvent event,Map<Integer, Set<Target>> registry) {
30: Set<Target> targets = registry.get(event.getPhaseId().getOrdinal());
31: if (targets != null) {
32: for (Target target : targets) {
33: target.invoke();
34: }
35: }
36: }
37:
38: public void beforePhase(PhaseEvent event) {
39: invoke(event, beforeregistry);
40: }
41:
42: public PhaseId getPhaseId() {
43: return PhaseId.ANY_PHASE;
44: }
45:
46: private void registerMethods(Map<String, Set<String>> annotationIndex,
47: Map<Integer, Set<Target>> registry,
48: PhaseRegisterer phaseRegisterer) throws ClassNotFoundException, SecurityException {
49: Set<String> classes = annotationIndex.get(phaseRegisterer.getPhaseMetaData().getName());
50: if(classes != null) {
51: for (String c : classes) {
52: Class clazz = Class.forName(c);
53: Method[] ms = clazz.getDeclaredMethods();
54: for (Method m : ms) {
55: for (Annotation an : m.getDeclaredAnnotations()) {
56: Class antype = an.annotationType();
57: if (antype.equals(phaseRegisterer.getPhaseMetaData())) {
58: phaseRegisterer.register(an, registry, m, clazz);
59: }
60: }
61: }
62: }
63: }
64:
65: }
66:
67: protected class AfterPhaseRegisterer implements PhaseRegisterer {
68: public void register(Annotation an, Map<Integer, Set<Target>> registry, Method m, Class clazz) {
69: AfterPhase ap = (AfterPhase) an;
70: Integer key = ap.value().ordinal();
71: Set<Target> value = registry.get(key);
72: if (value == null) {
73: value = new HashSet<Target>();
74: }
75: value.add(new Target(m, clazz));
76: registry.put(key, value);
77: }
78:
79: public Class<? extends Annotation> getPhaseMetaData() {
80: return AfterPhase.class;
81: }
82: }
83:
84: protected class BeforePhaseRegisterer implements PhaseRegisterer {
85: ...
86: }
87:
88: interface PhaseRegisterer {
89: void register(Annotation an, Map<Integer, Set<Target>> registry, Method m, Class clazz);
90: public Class<? extends Annotation> getPhaseMetaData();
91: }
92:
93: protected class Target {
94: private Method method;
95: private Class clazz;
96:
97: public Target(Method method, Class clazz) {
98: this.method = method;
99: this.clazz = clazz;
100: }
101:
102: private void invoke() {
103: try {
104: method.invoke(null);
105: } catch (Exception ex) {
106: throw new RuntimeException(ex);
107: }
108: }
109: ...
110: }
111:
112: }
113:
I believe this may improved, so that it could use singleton beans instead of static methods. Also more work has to be done to pass the phase event as a parameter.
An easier way to implement this with non-static methods would be using the CDIs event producer/observer api.
Producer/Observer
Here is my client bean looks like :
1:  @ApplicationScoped
2: @Named
3: public class TestBean implements Serializable {
4:
5: public void afterRestoreView(@Observes
6: @PhaseEventDefinition(value=CycleId.RESTORE_VIEW, when=AfterBeforeEnum.AFTER)
7: PhaseEventHolder holder) {
8: System.out.println("after restore view : " + holder.getEvent().getPhaseId());
9: }
10:
11: }
@Observers annotation states that this bean will observe events and the @PhaseEventDefinition tells which phase we will listen to. PhaseEventHolder object holds the PhaseEvent parameters that's missing on the previous example. Again we will need a phase listener that would listen to all phases and forward them as events, wrapping a jsf PhaseEvent with our PhaseEventHolder.
1:  public class ProxyPhaseListener
2: implements PhaseListener {
3:
4: private PhaseProducer phaseProducer;
5:
6: public void afterPhase(PhaseEvent event) {
7: fireEvent(event,AfterBeforeEnum.AFTER);
8: }
9:
10:
11: public void beforePhase(PhaseEvent event) {
12: fireEvent(event,AfterBeforeEnum.BEFORE);
13: }
14:
15: private void fireEvent(PhaseEvent event, AfterBeforeEnum when) {
16: final int ordinal = event.getPhaseId().getOrdinal();
17: final CycleId[] cycles = CycleId.values();
18: PhaseEventHolder phaseEventHolder = new PhaseEventHolder(event);
19: AnnotationLiteral<PhaseEventDefinition> annotationLiteral =
20: new PhaseLiteral(cycles[ordinal], when);
21: getPhaseProducer().fireEvent(phaseEventHolder,annotationLiteral);
22: }
23:
24: private PhaseProducer getPhaseProducer() {
25: if(phaseProducer == null) {
26: FacesContext context = FacesContext.getCurrentInstance();
27: phaseProducer = (PhaseProducer) context.getApplication()
28: .getELResolver().getValue(context.getELContext(),null,"phaseProducer");
29: }
30: return phaseProducer;
31: }
32:
33: public PhaseId getPhaseId() {
34: return PhaseId.ANY_PHASE;
35: }
36: }
37:
PhaseProducer is the bean that fires the phase holders as events:
1:  @ApplicationScoped
2: @Named
3: public class PhaseProducer implements Serializable {
4:
5: @Inject @Any
6: private Event<PhaseEventHolder> phaseEvent;
7:
8:
9: public void fireEvent(PhaseEventHolder phaseEventHolder, AnnotationLiteral<PhaseEventDefinition> annotationLiteral) {
10: phaseEvent.select(annotationLiteral).fire(phaseEventHolder);
11: }
12: }
This approach is much simpler, usefull and clearer than the first one. Only thing I am not happy with it is that I had use EL to access the phaseProducer object.
I keep the source here so, chek it out. It should run in a glassfish-v3 environment.

Wednesday, December 16, 2009

Developing Custom Scopes/Contexts For Weld

This one came up while developing an example JEE6 project, which I'll add it up here in the future. The case is I had a textbox bound to a request scoped bean. When user triggers the paint action the value in the textbox is to be added to the list below and the textbox should be empty. I thought marking the component request scoped should have been enough to empty its values but it didn't.Apparently to empty the value;
1. I might set the value of the field at the action method. Use a clone for the list.
2. Use a JSF component that doesn't redisplay value after post back like the inputSecret.
3. Develop a custom scope that recreates it self after actions are invoked.
Anyway maybe I am missed a simpler solution but I chose number 3 :) .
To do that first thing is to create a new scope type. I called my scope the "ActionScoped":
1:  @NormalScope(passivating=false)
2: @Retention(RUNTIME)
3: @Target({TYPE, METHOD})
4: @Inherited
5: public @interface ActionScoped {
6: }
@NormalScope annotations marks an annotation as a scope-type. Next we need a context that would define when these action scoped objects exist like the request scope exist while there is a http request... This is the action context :
1:  import org.jboss.weld.context.AbstractThreadLocalMapContext;
2: import org.jboss.weld.context.api.helpers.ConcurrentHashMapBeanStore;
3:
4: public class ActionContext extends AbstractThreadLocalMapContext {
5:
6: private static ActionContext instance = new ActionContext();
7:
8: private ActionContext() {
9: super(ActionScoped.class);
10: }
11:
12: public static ActionContext getInstance() {
13: return instance;
14: }
15:
16: @Override
17: protected boolean isCreationLockRequired() {
18: return false;
19: }
20:
21: public void activate() {
22: setActive(true);
23: setBeanStore(new ConcurrentHashMapBeanStore());
24: }
25:
26: public void deActivate() {
27: destroy();
28: setActive(false);
29: setBeanStore(null);
30: }
31:
32: public void reActivate() {
33: deActivate();
34: activate();
35: }
36: }
It's backed with an thread local object which is handled by the weld parent class. Bean store is where we are going to store the scoped beans. Plus I added some methods to activate (set a new bean store) /deactivate (destroy the bean store) the context. Now this context has to be activated with the start of the restore view.Deactivated and reactivated after the invoke application phase. Here is a phase listener that does that :
1:  public class ActionScopedPhaseListener implements PhaseListener {
2:
3: public void beforePhase(PhaseEvent event) {
4: if (event.getPhaseId().equals(PhaseId.RESTORE_VIEW)) {
5: ActionContext.getInstance().activate();
6: }
7: }
8:
9: public void afterPhase(PhaseEvent event) {
10: if (event.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
11: ActionContext.getInstance().deActivate();
12: } else if (event.getPhaseId().equals(PhaseId.INVOKE_APPLICATION)) {
13: ActionContext.getInstance().reActivate();
14: }
15: }
16:
17:
18: public PhaseId getPhaseId() {
19: return PhaseId.ANY_PHASE;
20: }
21: }
22:
Now last thing we have to do is register our context object. In order to do that we need to define an 'extension'. There is a nice example here about extensions, spi... Without an extension we are not able listen to events fired from the weld container which we could use to add our new context object. To define an new context we need the META-INF/services/javax.enterprise.inject.spi.Extension file which contains the qualified name of our extensions class. In this case it's 'org.mca.ewall.extensions.Extensions'. Here is what the class looks like :
1:  public class Extensions implements Extension, Service{
2:
3: public void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager manager) {
4: event.addContext(ActionContext.getInstance());
5: }
6:
7: public void cleanup() {
8: }
9: }
It simply registers the context object after the application starts up (after the beans are discovered by the weld container). Now the beans could be annotated as @ActionScoped.

Wednesday, December 9, 2009

State of the 'Dependecy Injection'

"Dependecy Injection" is one of the most popular design patterns on the Java platform. It was suggested by Martin Fowler, here, instead of the term "Inversion of control". Article was published on 2004.
What it brings to a application is a way to create, compose, use and destroy any java object, which are called beans.
The leading framework that first used this approach was the "the Spring Framework". The approach emerged as a alternative to EJB's. The applications built with it are easier to test and offered a easy way to integrate to most of the other frameworks and technologies out there. If you check out the api packages you can see the support for other frameworks like jsf, hibernate etc.
Today "Dependecy Injection" is part of JEE6 named CDI, JSR-299. Reference implementation is called Weld. Here are some of the highlights of CDI:
XML vs. Annotations
CDI dumps the xml approach. However there are still some use for xml's. Every bean archive must have a META-INF/beans.xml even if its empty. This file marks the jar archive as a bean archive and is scanned for beans. 'beans.xml' is also where you enable and define the ordering of 'alternative' beans and interceptors.
Qualifiers
First thing that CDI takes to account while trying to inject a bean is the type of the bean. If however there are more than one bean that could qualify CDI requires a Qualifier meta-data to resolve the ambiguity. CDI has a way to define this meta-data as an annotation, thus making our app. strong typed apposed to the usual string based qualifier approach.
Events
By defining a few annotations we could implement the Observer pattern without any boilerplate code.
Decorators
Again with annotations we could implement the decorator pattern.
Part of JEE6
Now we could inject our beans to servlets and filters like we do to any other class.
Overall as far as I could tell CDI looks like it could improve an applications code quality making it decoupled and strong-typed. JEE6 still needs some time though, best implementation out there seems to be JBoss 6 Milestone 1.

Thursday, November 19, 2009

Sinek, spreadsheet component, for JSF 2

Here are some notes on developing a spreadsheet component for JSF. Here is how it looks like :Cells contents are being updated with ajax, user is able to add rows/columns by clicking the buttons on the bottom-right corner. I am calling this component 'sinek'. Probably I will rename it later. To check the source code click here.
Here are the parts that make up the component :
  • org.mca.sinek.jsf
This package has 3 files that make up the main component. UISinek, SinekRenderer and WorkSheet.
  • WorkSheet is the datamodel. Its basically a two dimensioned array of Strings:
 public class WorkSheet {
List<List<String>> sheet;
public Integer getNumOfColumns() {
...
public int getNumOfRows() {
...
public List<String> addEmptyRow() {
...
public void addEmptyCol() {
...
}
It also has methods that return the number of rows, add rows/cols.
  • UISinek is the component that holds the state values. After its added to view it adds the sheet cells as its children. Cells are made up of inputtext components :
 @FacesComponent(value = "sinek")
@ListenerFor(systemEventClass = PostAddToViewEvent.class)
@ResourceDependency(name = "jsf.js", library = "javax.faces", target = "body")
public class UISinek extends UIInput {
...
@Override
public void processEvent(ComponentSystemEvent event) throws AbortProcessingException {
Map<String, String> requestParameterMap = getFacesContext().getExternalContext()
.getRequestParameterMap();
String exec = requestParameterMap.get("javax.faces.source");
if((getClientId()+ "_addr").equals(exec)) {
getWorkSheet().addEmptyRow();
} else if((getClientId()+ "_addc").equals(exec)) {
getWorkSheet().addEmptyCol();
}
int count = getChildCount();
createRows();
}
...
private void createRow(List<String> row, int rindex) {
ValueExpression ve = this.getValueExpression("value");
String exp = ve.getExpressionString();
exp = exp.substring(0, exp.length() - 1);
int cl = 0;
for (String cell : row) {
String id = getId() + "_" + rindex + "_" + cl;
if(findComponent(id) != null) {
continue;
}
HtmlInputText in = new HtmlInputText();
ValueExpression el = ELUtils.createValueExpression(exp + ".sheet[" + rindex + "][" + cl + "]}");
in.setId(id);
in.setValueExpression("value", el);
in.setLocalValueSet(true);
in.setOnkeyup("jsf.ajax.request(this,event);");
getChildren().add(in);
cl++;
}
}
}
We are annotating it with the @FaceComponent annotation. It listens for the PostAddToViewEvent with the @ListenFor annotation. When the event fires processEvent method will be fired. Process events creates HtmlInputText components whose values are backed up with the datamodel. Also sets up the ajax call which will update the component values. Because we will be using ajax we have to define it with the @ResourceDependency annotation. The "javax.faces.source" will be used to identify the add col/row events.
  • SinekRenderer is the renderer. It renders our cells into the cells of a table:
 @FacesRenderer(rendererType = "sinek", componentFamily = "javax.faces.Input")
@ResourceDependencies({
@ResourceDependency(name = "sinek.css", library = "org.mca", target = "head"),
@ResourceDependency(name = "jsf.js", library = "javax.faces", target = "body")})
public class SinekRenderer extends Renderer {
@Override
public void encodeBegin(FacesContext facesContext, UIComponent comp) throws IOException {
UISinek sinek = (UISinek) comp;
ResponseWriter writer = facesContext.getResponseWriter();
writer.write("<table id=\"" +sinek.getClientId()+"\" class=\"mctable\">");
int R = sinek.getWorkSheet().getNumOfColumns();
renderFooter(writer, R, sinek);
renderColumnHeaders(writer, R);
renderCells(facesContext, writer, sinek);
writer.write("</table>");
}
private void renderCells(FacesContext facesContext, ResponseWriter writer, UISinek sinek) throws IOException {
int i = 0;
int rno = 1;
int r = sinek.getWorkSheet().getNumOfColumns();
List<UIComponent> rows = sinek.getChildren();
for (UIComponent c : rows) {
if (i % r == 0) {
if (i % 2 == 1) {
writer.write("<tr class=\"altrow\">");
} else {
writer.write("<tr>");
}
rno = renderRowHeader(writer, rno);
}
writer.write("<td>");
c.encodeAll(facesContext);
c.setRendered(true);
writer.write("</td>");
if (i % r == (r - 1)) {
writer.write("</tr>");
}
i++;
}
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
}
@Override
public boolean getRendersChildren() {
return true;
}
}
Renderers are defined with the @FacesRenderer annotation and again @ResourceDependecy annotation is used for the css and ajax scripts. It renderers the children (cells) so we need to override the encodeChildren and getRendersChildren methods.
  • mca.taglib.xml : Defines the namespace and components.
  • sinek.css : Style sheet for our project.
My example also contains Hello class which is a example bean used on page index.xhtml.
Thats all for now drop me a line if you need more info and be sure to check-out the source.

Tuesday, November 10, 2009

JSF2 Notes

These are the notes I derived from blogs on JSF 2 :
  • Composite Components
Ed Burn's have a number of articles on developing 'composite components'. CC's are for creating true components that we can attach converters, listeners etc. Previously you could do the similar things with the help of the facelets, which was somewhat limited. Rick Hightower has an excelent series of articles about this, called 'Facelets fits JSF like glove'. Here is what a CC looks like in JSF2 :
 <cc:interface
name="inputtext"
displayName="label plus text"
expert="true"
hidden="false"
preferred="true">
<cc:attribute name="label" required="true" />
<cc:attribute name="id" required="true" />
<cc:attribute name="value" required="true" />
</cc:interface>
<cc:implementation>
<h:outputLabel id="lbl_#{cc.attrs.id}" for="#{cc.attrs.id}"
value="#{cc.attrs.label}" />
<h:inputText id="#{cc.attrs.id}" value="#{cc.attrs.value}" />
</cc:implementation>
This forms a common element with an inputtext and its label. Apparently there are many tricks to learn here. Its formed of two parts, first is the interface. As far as I can tell this is the UIComponent part. We define valueholders, attributes, actionsources that our CC will respond to. Second part is the implementation. This is like the renderer part. We glue the components together here.
One thing that I didn't like while trying out these was, with the facelets way I could use the CC with panelGrid component and the components forming the CC would be on different grids. This way I could easily align the components. Now on jsf2, CC truely acts like one component and all the sub components fit into the same grid.
  • We can define exception handlers on faces-config.
From Ryan Lubke's blog, http://blogs.sun.com/rlubke/
  • There is a javax.faces.PROJECT_STAGE context parameter we can play with which will make our application behave differently in different stages. Like on 'development' stage certain components will be added to the view root automatically like perhaps facestrace. We are able to access it through Application.getProjectStage()
  • There is a new Resource handling architecture. By default resources are searched under (webapp_root)/resource or (webapp_root)/META-INF/resources and there is a EL support to load them from the pages. #{resource['lion.jpg']} will generate a url to a image under these locations I mentioned. Spec also enables that different versions of the same resource be available to application.
  • Components can be annotated with @ResourceDependency annotation and provide the list of resources (css, js, images...) they need inorder to work. These resources might be rendered on different parts of the page with the help of h:body and h:head tags.
  • There is 'View Scope' which as long as the view is not changed. It's accessible using UIViewRoot.getViewMap and #{viewScope} through EL.
  • There is a system event listener api where you could listen to events like 'configuration complete'.
  • Now we have control over request parameters. We can validate convert them if needed.

Looks like JSF2 has more nice stuff in it like the 'View Declaration Language'. Spec it self seems to be the best resource at the moment though.

Tuesday, October 27, 2009

ICEFaces

Nice people at 'Packt Publishing' are sending me a copy of their new ICEfaces book, 'ICEfaces 1.8: Next Generation Enterprise Web Development', for me to review. You can check it out here.

Wednesday, October 21, 2009

Hibernate Journey

Now
So we have started our new project and by default (not my decision, not saying its a bad decision either, just saying that there could be a better decision) we are going to be using Hibernate.
For those who don't know Hibernate is 'the' ORM solution. ORM is for 'Object Relation Mapping' which is pretty much self explanatory. It maps your relational data model, such as a database schema, to the object model.
The Begining
Back in 2005 we started our project with Hibernate2. There were no annotations yet so we had to use XML files to map the object domain. So here is how the object domain looks like ;
 public class City {
private Long id;
private String name;
... more fields and getter / setters
Our object-domain is made of classes with complex (like other classes or lists...) or primitive (String, Long ...) fields and their getter / setter methods, which is called the 'POJO' (Plain Old Java Object). These POJOs will be representing the rows of a table. String's will be mapped to VARCHAR's on Oracle, complex types will be foreign keys to other tables. Of course we need to specify which POJO is related with which table or which field is mapped to what column. This is done in the mapping XML and here is how it might look like ;
 <class name="foo.City" table="CITY">
<id column="ID" name="id" type="java.lang.Long">
... some mechanism to generate id's
</id>
<property column="NAME" name="name" type="java.lang.String"/>
...
With this model we could save ( 'persist' ) our POJOs to databases with out us explicitly writing insert statements and query our object-domain with a special query language (similar to sql) HQL and get POJOs as result.
The Plugin
We were creating our POJOs through a class modeler (RSAs class diagram plugin) and we realised that we could write a plugin that could also generate the mapping XMLs. All we had to do was mark the class diagrams with some 'StereoType's that we have created;
The things with '<<...>>' are the stereotypes where we could add the table names and such through attributes.
The Evil
I was happily programming until I was told that we were to update to a newer version of Hibernate. Well after the update nothing worked :) . The main reson was that with this version all the relations were 'Lazy' by default (which is the correct way to work with hibernate by the way). To better understand the problem suppose that we are querying the City object. Now we might not be needing the Park's of the City so loading them since it will cause more selects or joins would not be desirable. This is what is trying to be achived with the 'Lazy'. Loading the partial object graph and loading the specific lazy relations only when required.
When we have a City with lazy parks we could load the parks at the time when its getter is called however the city object must have an open session (session is hibernate's transaction unit). If the hibernate session where the city object has been loaded was closed a LazyInitializationException is thrown. Here is a code piece which shows whats ok and whats not :
 session.open();
City aCity = session.load(City.class,1);
City anotherCity = session.load(City.class,2);
aCity().getParks(); <= OK to call parks here
session.commit();
session.close();
aCity().getParks(); <= Still OK to call parks here because its already initialized
anotherCity.getParks(); <= This will throw an exception !
The thing to note here is that Hibernate POJOs are not so 'Plain'. A POJO is actually wrapped with hibernate generated proxies to do the initializing when required. You should always think POJOs with the underlying session object. There are numerous patterns to manage the sessions like 'Session Per View', 'Session Per Conversation' pattern ... You should always think of the object graph you will be using and join the objects on your queries according to that.
5
With the Java 5 came the annotations and it replaced the need to have XMLs. XML is still supported but I don't see any reason why someone choose that to annotations. Here is how our POJO might look like with annotations:
 @Table(name="DIL")
@Entity
class City {
@Id
private Long id;
@Column(name="NAME")
private String name;
...
Back
Hibernate has a indexing integration (lucene) , a validation framework and caching frameworks. It should be used with care and respect :)

Wednesday, September 23, 2009

Choosing an Expression Language

On previous posts I talked about that I liked Jboss-EL. Here is an example of what you can do with jboss-el and not with the standard el:
1:  #{cityService.listCities(selectedCountry)}
This EL is usefull on scenerios where the user selects a country from a combo (selectedCountry) which fires a ajax call and witch returns the cities of the country listing them in a sub combo.
Since I relay wanted use this on my myfaces + spring project I searched googled and found this. Here is how you use Jboss-EL with MyFaces.
  1. We need the myfaces 1.2.7
  2. Add jboss-el to classpath
  3. Add to web.xml :
1:    <context-param>
2: <param-name>org.apache.myfaces.EXPRESSION_FACTORY</param-name>
3: <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
4: </context-param>
If you are using RI :
1:  <context-param>
2: <param-name>com.sun.faces.expressionFactory</param-name>
3: <param-value>org.jboss.el.ExpressionFactoryImpl</param-value>
4: </context-param>
Should do the trick.

Monday, September 7, 2009

a ping-pong game (2)

Continuing where we left from part 1.
First we need a platform that the user control. Our platform will be a BarCallbacks with key handler. To control the movement of the objects we will introduce a new object 'World' which will handle the movement code. The world object is a timer object that will tick every few seconds and recalculate the coordinates of the registered vectors and redisplay the screen. Also the VectorBox object now will have distance and angle making it a real vector. VectorBox object here :
1:  @interface VectorBox : NSObject {
2: float x, y, xr, yr, distance, angle;
3: }
4: @property float x, y, xr, yr, distance, angle;
5: -(id) initWithX:(float)_x y:(float)_y xr:(float)_xr yr:(float)_yr;
6: -(id) initWithX:(float)_x y:(float)_y xr:(float)_xr yr:(float)_yr distance:(float) _d angle:(float) _a;
7: @end
Distance will determine how many pixels will the object travel with the tick of the clock. Angle is at what angle will the object move. The init function without the distance and angle will set these values to zero.
And the World object :

1:  @interface World : NSObject {
2: NSMutableArray * boxes;
3: NSUInteger milis;
4: }
5: @property (readonly) NSUInteger milis;
6: @property (readonly) NSMutableArray * boxes;
7: -(id) addVectorBox:(VectorBox *) vbox;
8: -(id) startTickingEveryMilis:(NSUInteger) milis;
9: +(id) world;
10: void worldTick(int value);
11: @end
The 'boxes' parameter will hold the vectors that will be animated. The 'milis' parameter is the number of milliseconds that our code will wait before firing to animate our vectors. addVectorBox method adds new vectors and startTickingEveryMilis method sets the timer. The world object is to be used as a 'singleton', one copy of it should be available at any time, and to access that instance we will use the static 'world' method. worldTick function is the our glut timer callback function. Its registered first as the startTickingEveryMilis method is called. worldTick function :
1:  void worldTick(int value) {
2: World * world = [World world];
3: int len = [world.boxes count];
4: for( int i = 0; i < len; i++) {
5: VectorBox * vbox =[world.boxes objectAtIndex:i];
6: vbox.x += vbox.distance*cos(vbox.angle);
7: vbox.y += vbox.distance*sin(vbox.angle);
8: }
9: glutPostRedisplay();
10: glutTimerFunc(world.milis,worldTick,1);
11: }
It traverses of the boxes array and moves them using a simple trigonometric function and updates the coordinate values. Then the glutPostRedisplay function is called so the screen is redrawn. Using the glutTimerFunc we reregister our callback function. PlatformCallbacks extends from the BarCallbacks it just adds the key handler code to it.
1:  -(void) keyHandler:(unsigned char) key x:(int) x y:(int) y {
2: if(key =='d') {
3: box.angle = 0;
4: box.distance = distance;
5: } else if(key =='a') {
6: box.angle = M_PI;
7: box.distance = distance;
8: }
9: }
10: -(void) keyUp:(unsigned char) key x:(int) x y:(int) y {
11: box.distance = 0;
12: }
Glut calls the keyHandler function as long as the key is pressed. So when the 'd' key is pressed we will set the registered vectors distance to move right. keyUp function is called when the key is released so we will use it to set the vectors distance to zero thus making it stop.
Now we need to implement our bouncing ball. First thing I am going to do is refactoring the code so that we may have a common base class for BarCallbacks and BallCallbacks. I will call it the BaseCallbacks. All my callbacks will extend from this base. OpenGL does not have circle driving function by default so we need to come up with a approximate formula :
 @implementation BallCallbacks
-(void) display {
// loads the identity matrix
glLoadIdentity();
glColor3f(1.0,0.0,0.0);
glBegin(GL_POLYGON);
for (int i = 0; i < 360; i++) {
float x1 = (cos((M_PI*i)/180) * box.xr) + box.x;
float y1 = (sin((M_PI*i)/180) * box.yr) + box.y;
glVertex3f(x1,y1,0);
}
glEnd();
}
@end
Using glBegin function we start drawing vertex to vertex. Our circle is actually a polygon with 360 vertexes. We end drawing with glEnd function. After initializing with distance and angle our ball will start moving. As its now our ball will pass through our walls. To make it bounce we need to detect collision and change the angle appropriately. We will be checking for collisions at every tick of the clock in the World object :
 void worldTick(int value) {
World * world = [World world];
int len = [world.boxes count];
for( int i = 0; i < len; i++) {
VectorBox * vbox =[world.boxes objectAtIndex:i];
vbox.x += vbox.distance*cos(vbox.angle);
vbox.y += vbox.distance*sin(vbox.angle);
}
for( int i = 0; i < len; i++) {
VectorBox * vbox =[world.boxes objectAtIndex:i];
if( !vbox.changesAngleAfterCollision) {
continue;
}
for( int j = 0; j < len; j++) {
if( i == j) {
continue;
}
VectorBox * obox =[world.boxes objectAtIndex:j];
[vbox detectCollision:obox];
}
}
glutPostRedisplay();
glutTimerFunc(world.milis,worldTick,1);
}
We check for collision with objects which changes its angle after collision. In our case we only need to check collision of ball and the other objects.
 -(id) detectCollision:(VectorBox *) obox {
// check if this object collides with other from bottom
if(obox.x + obox.xr > x && obox.x - obox.xr < x ) {
if(obox.y + obox.yr > y + yr && obox.y - obox.yr < y + yr) {
angle = 2*M_PI - angle;
}
}
if(obox.x + obox.xr > x && obox.x - obox.xr < x ) {
if(obox.y + obox.yr > y - yr && obox.y - obox.yr < y - yr) {
angle = 2*M_PI - angle;
}
}
if(obox.y + obox.yr > y && obox.y - obox.yr < y ) {
if(obox.x + obox.xr > x + xr && obox.x - obox.xr < x + xr) {
angle = 3*M_PI - angle;
}d
}
if(obox.y + obox.yr > y && obox.y - obox.yr < y ) {
if(obox.x + obox.xr > x - xr && obox.x - obox.xr < x - xr) {
angle = 3*M_PI - angle;
}
}
return self;
}
This works pretty smoothly most of the time but sometime ball gets stuck.
This is how it looks like in the end :

Tuesday, September 1, 2009

What should new JEE developers learn

We now started a new Enterprise project for Telecom and my first job is helping the new team get started. We are using, and seems will be using, the JSF, Spring and Hibernate technology stack. I am told that although some of them know some of the technologies we use, none know all.
So what should they learn and where to start;

JEE
  • The request & response lifecycle,
  • State on AS. How does Session works.
  • Servlet's and Filter's
  • JSPs, JSTLs and Custom Tags
  • A simple blogging application can be created with the above.
Spring Framework
  • The "Dependecy Injection" Pattern
  • Creating & managing Beans with Xml or Annotations
  • Proxying and Interceptors
  • JDBC Support
  • We can improve our app. with the above. Move the data to spring beans, and actually use database at this point.
  • Although we don't use the MVC it could be introduced here and see how much it will help with our app.
JSF
  • The components
  • JSF Lifecycle and how its manupilated with immediate attribute...
  • How facelets add to JSF
  • At this point we can improve app. with the JSF
  • Introduce the ajax and ajax enabled components
  • How to create custom JSF components
WebFlow
  • How state machine logic helps the navigation
  • New scopes the webflow introduces
  • Improve the app.
Hibernate
  • ORM concept
  • JPA annotations
  • Startegies to manage the hibernate session
  • Improve the app.
Reporting
  • We are using JasperReports which I don't know much about that at the moment :)
After this point I am thinking that new requirements could be introduced and the team could work on them as pairs. Pairs will be swapped often and there could be nightly reviews.
As for learning these one also needs some nice examples, one is mesir developed by my buddy Mert. It's a showcase of most of the technologies I wrote above.
For "Dependecy Injection" pattern Martin Fowler has this paper.
As for me Spring's and Hibernate's reference and api documentation is pretty solid.
For JSF Richard Hightower's "JSF for Non Believers" and "JSF fits facelets like glove" are quite fun to read articles.
On extreme programming practices here is a article at objectmentor site which demonstrates a session between two programmers.
Although pretty boring, working for sun certificates are helpful and good to learn the basics (SCJP and SCWCD).
These are what comes to my mind.

Monday, August 31, 2009

a ping-pong game (1)

One of the goals that I postponed long ago was learning OpenGL and creating games with it. I started learning OpenGL, and started building a toy project on the process.
I decided to build a ping-pong game which will be simply a ball moving and hitting around. A simple 2D toy project.
I chose to develop on my mac with XCode & Objective-C. XCode is a simple IDE that works fast and Objective-C is a Object Oriented programming language much simpler that C++. A mac comes with a OpenGL so on a Mac there is not any prerequisite to start developing. Although the source code is written on such platform it wont be hard to port to other platforms.
Code is on svn here.
I have also tagged bar and bars versions which I will be blogging about now.
Setting Up the OpenGL
This is how (code snippets from main.m) :
1:  glutInit(&argc, argv);
glutInit function initializes the GLUT. Parameters are for the underlying Windowing System.
1:       glutInitWindowPosition(400,100);
2: glutInitWindowSize(400,300);
We initialize the windows size & position.
1:       glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
We use a single buffer & rgb values for now.
1:       glutCreateWindow("Intro");
This sets the title of the window.
1:       glClearColor(0.0,0.0,0.0,0.0);
This function is like setting the background color.
Setting the Callback Functions
OpenGL is designed with the "Hollywood Principle"; "Don't call me, I'll call you...". To draw on screen and listen to events you register a set of callback functions (from BarCallbacks.m);
1:       glutDisplayFunc(display);
2: glutReshapeFunc(reshape);
3: glutKeyboardFunc(keyHandler);
4: glutKeyboardUpFunc(keyUp);
Display callback function is for actually drawing on screen. Reshape function is for redisplaying after the window moves or resizes. Keyboard functions are for detecting key strokes of the user.
These callback function are 'C' functions and this means that you can not use Objective-C methods directly. To use the Objective-C methods you have to use a static variable. I set up a pattern where the 'C' callback functions delegate to Objects and their appropriate methods. This way I can take advantage of the object oriented paradigm.
I created a BarCallbacks Object which is simply responsible of drawing rectangles on screen. Here is the display function and its delegate;
1:  static BarCallbacks * workingCallback;
2: void display() {
3: glClear(GL_COLOR_BUFFER_BIT);
4: [workingCallback display];
5: glFlush();
6: }
7: -(void) display {
8: // loads the identity matrix
9: glLoadIdentity();
10: // floating point red, green, blue values
11: // 0 to 1 probably but may change I guess 3if ?
12: glColor3f(0.0,0.0,1.0);
13: glRectf(box.x - box.xr, box.y - box.yr, box.x + box.xr, box.y + box.yr);
14: }
workingCallback is the static variable used to delegate from the C function to the Object method.
glClear function (line 3) clears the screen with the color we previously specified. Then we draw the rectangle. glColor3f (line 12) sets the drawing color to blue and glRectf draws the rectangle to specified coordinates.
Another thing we need to setup is the perspective. There are two types of perspectives. I used the Orthogonal Perspective which is I think is easier to use for this kind of app.
1:  glOrtho(0, x, y, 0, 0, 1);
x and y are the width and height of the window. Since this will be a 2D app. I gave the Z-index 1. This function is called from the reshape function.
MainLoop
After setting up the callbacks OpenGL system, machine is more appropriate I think, is started with;
1:  glutMainLoop();
Our rectangle will be displayed, if you put break points you will observe that user key-strokes are caught. I tagged all the code up to this point as bar.
With the BarCallbacks Object we created, I wanted to make some walls where our ball will bounce around. Here are the changes I made to delegating system so that we can use multiple BarCallbacks;
1:  static NSMutableArray * callbacks;
2: void display() {
3: glClear(GL_COLOR_BUFFER_BIT);
4: for( int i = 0; i < callbacks.count; i++) {
5: BarCallbacks * cb = [callbacks objectAtIndex:i];
6: [cb display];
7: }
8: glFlush();
9: }
I changed the static variable to an mutable array. Then looped on on callback methods and delegated.
Here is my three walls;
1:       [[BarCallbacks alloc] initWithRect:390 y1:10 w:10 h:280];
2: [[BarCallbacks alloc] initWithRect:0 y1:10 w:10 h:280];
3: [[BarCallbacks alloc] initWithRect:0 y1:0 w:400 h:10];
And how it looks;Next we need a ball, a platform and some collision detection.

Wednesday, July 29, 2009

Summing up the photo gallery (part 6)

I started building a photo gallery app., flickr in mind, as a means to learn the seam framework. To sum up here is my previous posts :
1. "little restfull photo gallery example, with seam, which seams fine", here.
2. "seamy photo gallery, securing it (part 2)", here.
3. "seamy photo gallery, securing it (part 2)", here.
4. "seamy photo gallery, resting easier (part 4)", here.
5. "seamy photo gallery, writing an authentication filter (part 5)", here.
Here is what I did on last couple of days:
Firstly I publish the source code here on google code. Named it jhoto rather hastely. This will probably be an internal name :)
Polished it a little so that it has a original look. I ended up creating some simple bubbley look using paint and some css. Here is how it looks now :
And lastly using jquery to gave the bubbles some animation so that they wiggle a little:
        <script type="text/javascript">
$(document).ready(function() {
var animationLoop = function(it) {
it.animate({
opacity: 0.5 + Math.random() / 2,
marginLeft: (Math.round(Math.random()*10) - 5)+"px",
marginTop: (Math.round(Math.random()*10) - 5)+"px"
}, 1500, "linear",
function() {
animationLoop($(this));
});
};
$("table.aframe").each(function() {
animationLoop($(this));
});
});
</script>
What the above code does is move my bubbles (tables) randomly whit in some threshold.
Will probably do more on this...

Thursday, July 2, 2009

Groovy Impressions

Groovy is a superset of the Java programming language with dynamic language constructs. Here are my notes on Groovy.
1. Java is Groovy
Every Java sentence is a valid Groovy sentence but not the other way around. Which means you can use every Java library out there with Groovy classes. Infact Groovy classes in the end compile into Java code.
2. Loose Syntax
No need for a main method. No more a class should be defined in its own named file requirement. Following is a complete "Hello, World!" program for Groovy:
println "Hello, World!"
We don't need the System.out.... or the semicolon ending commands. Though we could have used them also.
3. Integrated Template Engine
It has a embeded templating engine which does all sort of things. And here is the "Hello, World" of templating :
world = "World"
println "Hello, ${world}!"
4. Constructers, Getters and Setters
Getters and Setters are automatically generated for properties of the class and there is a simple property initialization mechanism. And the example :
new Salutor(hello:true,who:"World")
5. Safe Navigation & Elvis Operators
With Java Often we may have to these null checks :
if(state != null &&
state.getTransitions() != null &&
state.getTransitions().size() > 0) {
states = state.getTransitions().values();
...
With groovy we can navigate with the '?' operator safely with out cluttered if checks :
states = state?.transitions?.values()
And the Elvis operator is used for assigning default values other than null :
name = user.name ?: "Anonymous"
As far as I know these will be available in Java 7.
6. Closures
The folowing closure (the thing between curly brackets) finds even integers inside the int array.
ints?.find {n -> n % 2 == 0}
Closures are passable function block. You can also check out the commons-collections api to see how similar code could be written in Java.
7. Meta Programming
e = new Euro()
prop="value";
op="plus";
e."${prop}"= 5;
e."${prop}"=e."${prop}"."${op}"(1)
println e
The above example succesfully computes to 6.
8. Build DSL's
Using the MetaClass api you can create simple inline DSL's. Here is a example whit euros:
package tr.mca.dsl;
import static tr.mca.dsl.MoneyDomain.*;

println "1 euro + 2 euro :" + money {
1.euro + 2.euro
}
Here whit in the money block we create "new Euro(3)" but we are doing it in a more brain friendly way.
There is two ways I know to achive that:
a. DelegatingMetaClass
DelegatingMetaClass helps us to intercept the method and property accesses. Here is the extended version I crated for money example :
public class MoneyDelegatingMetaClass extends DelegatingMetaClass {

MoneyDelegatingMetaClass(Class delegate) {
super(delegate);
}

public Object getProperty(Object obj, String property) {
if (isDynamicProperty(property)) {
return new Euro(obj);
}
return super.getProperty(obj, property);
}

private boolean isDynamicProperty(String property) {
return "euro".equals(property) || "€".equals(property)
}

}
We are able to intercept the "euro" property access and upon access we create the Euro object. Here is the code that activates this interceptor for a given code block :
class MoneyDomain {

static Object money(Closure closure) {
def orgMetaClass = InvokerHelper.metaRegistry.getMetaClass(Integer.class)
MoneyDelegatingMetaClass myMetaClass = new MoneyDelegatingMetaClass(Integer.class)
InvokerHelper.metaRegistry.setMetaClass(Integer.class, myMetaClass)
try {
return closure.call()
} finally {
InvokerHelper.metaRegistry.setMetaClass(Integer.class, orgMetaClass)
}
}

}
InvokerHelper.metaRegistry.setMetaClass call lets us register and unregister when we are done.
b. ProxyMetaClass
Another way of doing is using the ProxyMetaClass api. We again wrote a similar interceptor :
class MoneyDomainInterceptor implements PropertyAccessInterceptor {

public Object beforeGet(Object obj, String property) {
if ("euro".equals(property)) {
return new Euro(obj);
} else {
return obj.getProperties().get(property);
}
}

public void beforeSet(Object obj, String property, Object newValue) {
}
}
This time we implemented the PropertyAccessInterceptor. And here is how we gonna use it :
class MoneyDomain {

def static proxy = ProxyMetaClass.getInstance(Integer.class);
static {
proxy.interceptor = new MoneyDomainInterceptor();
}

static void moneyProxy(closure) {
proxy.use(closure);
}
}
}
And thats my short journey of the Groovy language.

Friday, June 19, 2009

SCWCD

I hate exams. Especially multi choice tests. Yet I have worked on the SCWCD exam fort the last weeks.
I choose the "Head First Servlets and JSP" book to study for the exam mainly because it had more stars than this one. Besides "Head First ..." books are usually more brain friendly. Read the "Head First Design Patterns", a very good introduction to design patterns, so that you know what I mean by brain friendly. Servlet book covers the old JSP's. I think Sun should have put some JSF questions instead. The book has a mock exam at the back. I scored %69 on it. On the real exam I scored %79 so the questions are a bit harder and some of them are a bit unclear.
Anyway I passed the exam :)

Thursday, May 28, 2009

seamy photo gallery, writing an authentication filter (part 5)

On the 4th part I used an simple authentication filter, to secure my urls, that come out of the box. It only supported basic & digest authentication. With basic authentication what you get is a ugly browser dependent box which asks the credentials of the user. On IE its like:
Instead of that I wanted the user to use the login page which I created. In order to do that I first removed basic authentication filter component and started coding mine :
@Scope(APPLICATION)
@Name("customAuthenticationFilter")
@Install(precedence = Install.DEPLOYMENT)
@BypassInterceptors
@Filter(within = "org.jboss.seam.web.exceptionFilter")
public class CustomAuthenticationFilter extends AbstractFilter {
@Logger
protected Log log;

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("This filter can only process HttpServletRequest requests");
}

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.getSession();
Context ctx = new SessionContext(new ServletRequestSessionMap(httpRequest));
Identity identity = (Identity) ctx.get(Identity.class);
if (identity.isLoggedIn()) {
chain.doFilter(request, response);
}
else {
// go login than come back
httpResponse.sendRedirect("/seams/login?serviceUrl="
+ httpRequest.getRequestURL());
}

}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
setUrlPattern("/seam/resource/rest/*");
super.init(filterConfig);
}
}
Seam handles the creation and order of the filters with the help of @Filter annotation. Instead of adding web.xml entries we annotate our filters and specify where they should be in the filter chain. 
I have extended my filter from the seam AbstractFilter class and on the init method I setted the url pattern which the filter mappes to. 
On the doFilter method first thing to do is try to see if the user is already logged in. We have to access the Identity component but seams injections mechanism does not work with the filters. So instead of injecting you have to create a context (and such) to access the Identity component.
Once we have the Identity component we see if the user is already logged in. If so we proceed with the rest of the chain if not we redirect to our custom login page and pass the original page that the user tried to access with a request parameter that I named serviceUrl.
Once the user successfully logs in we need to redirect the user to original resouce pointed by the serviceUrl. To do that I wrote a Listener class which will fire after the user successfully logs in :
@Name("loginRedirect")
@Scope(ScopeType.SESSION)
public class LoginRedirectListener {
private String serviceUrl;

@Observer("org.jboss.seam.security.postAuthenticate")
public void postAuthentication() throws IOException {
if (serviceUrl != null && serviceUrl.length() > 0) {
FacesContext.getCurrentInstance().getExternalContext().redirect(serviceUrl);
}
}
...
The good old observer pattern is implement with annotations on seam. Here using the @Observer annotation we get notified of authentication event end redirect to the serviceUrl if there is one. I have created it as a session bean so that each user will his own serviceUrl. One last thing to do is injecting the serviceUrl parameter to my listener which is done through pages.xml:
<page view-id="/login.xhtml">
<rewrite pattern="/login" />
<param name="serviceUrl" value="#{loginRedirect.serviceUrl}"/>
</page>
Thats all there is...

Wednesday, May 27, 2009

seamy photo gallery, resting easier (part 4)

On my previous post I made a restful photo gallery that has a nice little feature where upon a restful request like 'http://.../mygallery/photo/photo/yoda' served the image named 'yoda' to the user. In order to achive that what I did was first I edited the pages.xml so that it could extract the name (id) part from the request url:
<page view-id="/photo/photo.xhtml" login-required="true">
<rewrite pattern="/photo/photo/{fotoId}" />
<param name="fotoId" value="{fotoId}" />
</page>
Here the name is extracted into el context as 'fotoId'. Second thing is that I created the photo.xhtml mentioned above:
<f:view>
<s:graphicImage id="imaj" value="#{photoService.getFoto(fotoId)}"
style="border: 1px solid black;" lt="image could not be found">
</s:graphicImage>
</f:view>
I used a 's:graphicImage' component which serves the photo using a little service bean using our 'fotoId' parameter. For completeness here is the service bean:
@Name("photoService")
@Scope(ScopeType.APPLICATION)
public class PhotoService {
public byte[] getFoto(String fotoId) {
Photo p = getPhoto(fotoId);
if (p == null) {
return null;
}
return p.getData();
}
...
What bugged me on this method was that although I just wanted the serve the image here I was actually serving a html page which linked to the image. 
After looking around I learned that what I wanted, came with the seam & resteasy integration. RESTEasy (jaxrs) comes with annotations where you can use to serve the result of methods & beans directly. Seam package comes with the required jars  (dont go downloading for a resteasy package from jboss.org) for integrating it. You just put them in your classpath. So inorder to serve my 'photoService.getFoto' I can use the @Get, @Path and other annotations :
@Name("photoService")
@Scope(ScopeType.APPLICATION)
@Path("/foto")
public class PhotoService {

@GET
@Path("/{fotoId}")
@ProduceMime("image/jpeg")

public byte[] getFoto(@PathParam("fotoId")
String fotoId) {
...
Rest access is by default configured under '.../seam/resource/rest/'. So by using the path and get annotions I can access the 'photoService.getFoto' method with the '.../seam/resource/rest/foto/yoda' request. ProduceMime annotation tells that we are serving an jpeg image and the PathParam annotation is used so that we can get the 'yoda' out of the request and used it as a parameter to our method.
Now are we done ? No, because we need to secure it!. We dont want Vader to see the comprimising images of the Yoda (hehe) so we need to secure it with the restrict annotation :
@GET
@Path("/{fotoId}")
@ProduceMime("image/jpeg")
@Restrict("#{s:hasRole('user') || s:hasRole('admin')}")
public byte[] getFoto(@PathParam("fotoId")
String fotoId) ...
Now what happens when someone not logged in tries to acces the yoda is we will see a NotLoggedInException on the stacktrace. Of course we need to handle that and give the user the option to log in. Seam has a 'web:authentication-filter' component that supports the http basic or digest authentication which I configured like this on components.xml:
<web:authentication-filter url-pattern="/seam/resource/rest/*"
auth-type="basic" />
Now the yoda is safe I guess and I am sure there will be different authentication types supported in the future. I got few that could be implemented like the oauth which I belive is used by twitter and such.

Wednesday, May 20, 2009

Moving the keyboard out of the way

After happily doing a little work for iphone, being content for that I was finished with it, I made realize that the text boxes near the bottom of the screen disappeared when the keyboard appeared after saying "hmmmm...", I started searching for a solution. Apples iphone developer library suggest this solution and here I am going to write about how I used it in my project. 
Here is how the problem looks like  in a simple case(a before),
What we are going to do is, we are going to define UIScrollView and put our view inside it and scroll it up when the keyboard shows up. In order to do it in a OO fashion I defined a base class that will handle the scroll details.
#import <UIKit/UIKit.h>

@interface BaseViewController : UIViewController <UITextFieldDelegate> {
bool keyboardShown;

UITextField * activeField;

UIScrollView * scrollView;

UIView * mainView;
}

@property (nonatomic, retain) IBOutlet UIScrollView * scrollView;
@property (nonatomic, retain) IBOutlet UIView * mainView;

@end
I will bind the mainView with the original view which contains the text field. The scrollView will be inside a proxy view. The implementation;
#import "BaseViewController.h"

@implementation BaseViewController

@synthesize mainView, scrollView;

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
return [theTextField resignFirstResponder];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField {
activeField = textField;
}

- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
if (keyboardShown)
return;

NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Resize the scroll view (which is the root view of the window)
CGRect viewFrame = [scrollView frame];
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;

// Scroll the active text field into view.
CGRect textFieldRect = [activeField frame];
[scrollView scrollRectToVisible:textFieldRect animated:YES];
keyboardShown = YES;

}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];

// Get the size of the keyboard.
NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;

// Reset the height of the scroll view to its original value
CGRect viewFrame = [scrollView frame];
viewFrame.size.height += keyboardSize.height;
scrollView.frame = viewFrame;
[scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
keyboardShown = NO;
}

- (void)viewDidLoad {
[super viewDidLoad];
keyboardShown = false;
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollView.scrollEnabled = NO;
scrollView.pagingEnabled = NO;
[scrollView setContentSize:CGSizeMake(320, 480)];
[scrollView addSubview:mainView];
[self registerForKeyboardNotifications];
}

@end
The example is here under KeyboardLift. And this is the after screenshot;