Archive for the ‘java’ Category

But really, why java is enterprise and PHP is not.

Monday, January 21st, 2013

I have a lot of experience with Java and until this was only language I knew well I could not say out the real answer. Now recently I have been working with PHP + Laravel and finally I know the answer.

PHP by itself is not bad. Programmer can quickly hack all kinds of great things, deploy it just by copying new files to webroot and done. In that sence PHP is easy to learn and use, it is flexible and in that sense great tool for beginners.

Java, however, is more cumbersome. It requires more setup and compiling. All the data types must be strict, all kinds of places have to try catch Exceptions. It feel like a lot of extra work for nothing.

Now when we look how enterprise projects looks like. There are thousands or even millions lines of code, huge number of files, classes etc. Stack traces traces are tens and hundreds of rows. Maintaining such a projects must not leave any room for error. Making simple typecasting mistake or typing method for object that is not supported is not an option.

So the answer is:  Java is more refained, it forces you to think harder and make it more right on first try. IDE-s allow you to traverse code much more easily, leaving out all possible confusion with data types in inheritance.

How to hire a freelancer – 10 lessons learnt

Friday, May 11th, 2012

These days everybody are full of ideas but no time to make these happen. Same here, I have great business ideas every a few weeks but while working full-time on my day job I have hard time to implement these on my own and all my friends are also very busy.

I decided to try out the www.getacoder.com service to find affordable quality help to my projects and so far I have not been disappointed while following the below steps.

1. Write down IN DETAIL what you want to be done.

Before posting a job to www.getacoder.com make sure you have as detailed as possible overview of your requirements. This is called BRD – Business Requirement Document. This must list everything like, user must be able to register, user must be able to login etc. Programmers can take this doc and can implement every feature step by step. (more…)

Eclipse HTML formatter tips

Saturday, January 28th, 2012

Eclipse has decent HTML editor included with WTP.

When editing HTML files, for example PhoneGap project, then hitting CTRL+SHIFT+F formats code nice an neat. Unfortunately sometimes formatting rules are lot exactly what we want. HTML form contains several label and input elements and all of these are considered as one long line.

Open Window>Preferences>Web>HMTL Files>Editor and you will find list of HTML keywords in textbox called “Inline Elements:”. Remove input and label from this list and all of these statements will be each on separate lines.

You can modify more formatter settings there. Line wrapping width is reasonable to be increased with nowadays widescreen monitors.

Basic PhoneGap Android app from scratch step-by-step

Friday, January 27th, 2012

This tutorial assumes that you have eclipse which is set up for regular android development and you can create new android projects. Phonegap files are now named cordova

  1. Create new Android project in eclipse.
  2. Download package and extract cordova-2.6.0.jar  from zip file from http://phonegap.com/download/
  3. Add cordova-2.6.0.jar to your projects build path. In eclipse open project properties > Java Build Path > Add Jars
  4. Change main Activity superclass to DroidGap
  5. Replace setContentView(R.layout.main); with super.loadUrl(“file:///android_asset/www/index.html”);
  6. Create folder xml into the project res folder. Add there plugins.xml and cordova.xml from the package you download before.
  7. Add into AndroidManifest.xml <uses-permission android:name=”android.permission.INTERNET” /> and     <uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
  8. Create folder www into projects assets folder.
  9. Add index.html file into assets/www. File content is regular HMTL.

By now you can already run the program. Next steps are starting to use PhoneGap special HTML5 features and try accessing hardware. If It fails to run then make sure you have logcat view activated in eclipse or try in linux commandline: (more…)

PhoneGap performance measurement results

Sunday, January 8th, 2012

I was wondering how much is loss in performance is one would write application in PhoneGap and javascript instead of native code. I wrote 2 very basic programs one in android and second in PhoneGap. This program did standard busy looping and common string operation indexOf in the for loop. One interesting issue i found is that when you use body onload and do not finish in time then you will get error “Application Error: The connection to the server was unsuccessful. (file:///android_asset/www/index.html)”

3 different loop times were measured in javascript and native android java. Examlpe Code in Android  was : (more…)

Identity ‘signupBean’ does not reference a MethodExpression instance

Friday, September 9th, 2011

Problem itself is simple. JSF h:commandButton or h:commadLink is pressed and error below happens.

javax.el.ELException: /index.xhtml @12,78 action="#{signupBean}": Identity 'signupBean' does not reference a MethodExpression instance, returned type: com.project.beans.SignupBean

If you see something similar then you have typo in your code. In your commandButton/commandLink is missing bean method specification.

<h:commandButton value="Login with gmail" action="#{signupBean}"></h:commandButton>

must be replaced with

<h:commandButton value="Login with gmail" action="#{signupBean.signup}"></h:commandButton>

Full stack trace to follow  (more…)

Get callback working in Scribe and OAuth

Wednesday, August 3rd, 2011

I was developing LinkedIn API and had some trouble getting callback working after getting user authentication from LinkedIn. I even had configured “OAuth Redirect URL:” in application settings, adding oauth_callback to redirect when asking user authorization did not help either. I kept getting OOB eg out-of-band style authentication where user must manually type in the security code. Examples in scribe website did not help to fix the problem.

In JSF bean i used following code

OAuthService service=new ServiceBuilder().provider(LinkedInApi.class).apiKey("apikey").apiSecret("apisecret").build();
Token requestToken = service.getRequestToken();
String authUrl=service.getAuthorizationUrl(requestToken);
FacesContext.getCurrentInstance().getExternalContext().redirect(authUrl);

Problem was fixed by adding .callback to ServiceBuilder when building service.

OAuthService service=new ServiceBuilder().provider(LinkedInApi.class).apiKey("apikey").apiSecret("apisecret").callback("http://localhost:8084/WebApplication1/authenticated.jsf").build();

Ajax menu navigation in JSF with OpenFaces

Monday, January 3rd, 2011

Problem: Webpage must change body contents fast without reloading whole page when user clicks link in menu.

Solution: It can be achieved using OpenFaces o:layeredPane component.

In menu can be used commandLinks surrounded with form. Commandlinks include f:param which sends to server what contents must be displayed. When clicking link then browser sends ajax request to server and bean action method is performed.

        <h:form>
            <h:panelGrid columns="1">
                <h:commandLink value="#{msgs.frontpagelink}" action="#{frontPageBean.changeBody}">
                    <f:param name="pageViewId" value="0"/>
                    <f:ajax render=":fbody"></f:ajax>
                </h:commandLink>
                <h:commandLink value="#{msgs.contactlink}" action="#{frontPageBean.changeBody}">
                    <f:param name="pageViewId" value="1"/>
                    <f:ajax render=":fbody"></f:ajax>
                </h:commandLink>
            </h:panelGrid>
        </h:form>

Bean contains following method that extracts request parameter and assigns it to bean parameter.

public String changeBody() { FacesContext fc = FacesContext.getCurrentInstance(); String includedPage = fc.getExternalContext().getRequestParameterMap().get("pageViewId"); setFrontpageBody(includedPage); return null; }

In body part is OpenFaces o:layeredPane where are defined all possible o:subPanels

        <ui:define name="body">
              <o:layeredPane id="fbody"
                           selectedIndex="#{frontPageBean.frontPageBody}">
                <o:subPanel>
                    <ui:include src="mainpage.xhtml"></ui:include>
                </o:subPanel>
                <o:subPanel>
                    <ui:include src="contact.xhtml"></ui:include>
                </o:subPanel>
            </o:layeredPane>
        </ui:define>

As a conclusion when clicking menu link then request parameter with page index is sent to server with ajax. Server updates correct page index and when rerendering o:layeredPane then correct page is included into webpage contents.

f:ajax not working in JSF

Wednesday, December 29th, 2010

Problem is that in JavaServer Faces application ajax request are just not working. o:ajax in openfaces nor f:ajax in plain JSF 2.0 is not sending any requests to server. For testing can be used simple echo application.

<h:form>
<h:inputText value="#{ajaxTestBean.testValue}" >
  <f:ajax event="keyup" render="text"/>
</h:inputText>
<h:outputText id="text" value="#{ajaxTestBean.testValue}" />
</h:form>

Normally this should work without problems but there is little catch. <h:head></h:head> tag must be included in order for ajax to work properly. Definind h:head includes some more needed javascripts to complete everything. Try this code below to get it working:
index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<f:view>
<h:head>
  <title>AjaxTest</title>
</h:head>
<h:body>
<h:form>
<h:inputText value="#{ajaxTestBean.testValue}" >
  <f:ajax event="keyup" render="text"/>
</h:inputText>
<h:outputText id="text" value="#{ajaxTestBean.testValue}" />
</h:form>
</h:body>
</f:view>
</html>

AjaxTestBean.java

package com.ajaxtest; 

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped; 

@ManagedBean(name = "ajaxTestBean")
@SessionScoped
public class AjaxTestBean {
private String testValue = "default";

public String getTestValue() {
  return testValue;
} 

public void setTestValue(String testValue) {
   this.testValue = testValue;
 }
}

Proxy java web requests for tomcat6 through apache 2.2

Friday, December 24th, 2010

Tomcat is missing mod_security and a few other useful features. That is not a problem because httpd eg apache2 has all the missing features and these 2 are designed to work together. What creates problems is getting JK connector to work to display Java pages via apache.

For testing was set up default apache2 and tomcat6 on ubuntu server. Goal was to see tomcat example pages from port 80 when tomcat itself was running on 8080 port.

mod_jk needs configuration of workers.properties, apache conf and tomcat conf. Logs related to errors to why requests are not reaching tomcat are hard to find. One clear error from mod_jk logs was.

[Fri Dec 24 13:51:34.147 2010] [1707:2633885456] [debug] jk_translate::mod_jk.c (3419): missing uri map for localhost:/examples/

Actually biggest problem was that mod_jk is obsolete. It can be made to work but these days mpd_proxy_ajp is used instead. Setting it up just works and can be done in a few minutes.

Confgure tomcat, edit edit /var/lib/tomcat6/conf/server.xml and uncomment this line

<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Configure apache enable mod_proxy_ajp

sudo a2enmod proxy_ajp

edit /etc/apache2/sites-available/default and add following to virtual host definition

ProxyPass /examples/ ajp://127.0.0.1:8009/examples/
ProxyPassReverse /examples/ ajp://127.0.0.1:8009/examples/

Restart both servers

sudo service apache2 restart
sudo service tomcat6 restart

Now both links should display same content

http://localhost/examples/
http://localhost:8080/examples/

If you happen to see Forbidden errorpage then proxy-ing is denied. Edit

/etc/apache2/mods-available/proxy.conf

and change Deny to Allow

        <Proxy *>
                AddDefaultCharset off
                Order deny,allow
                Allow from all
        </Proxy>

After getting proxy between apache and tomcat running its possible to start configuring security of tomcat in more finegrained level and performance regarding static pages etc is also improved.