Skip to main content

Posts

Showing posts from 2010

Access multiple Databases in JPA

According to JPA specification we can define multiple "persistence-unit" elements (i.e. like below) in persistence.xml file and can easily refer them inside Dao layers as this. public class PolarDaoImpl {     @PersistenceContext(unitName="PolarPU")     protected EntityManager entityManager; -- } public class BearDaoImpl {     @PersistenceContext(unitName="BearPU")     protected EntityManager entityManager; -- } Checkout sample persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">     <!-- Database 1 -->     <persistence-unit name="PolarPU" transaction-type="RESOURCE_LOCAL">        ...

Two point formula for Apple IPhone to outsell Android ?

Introduce multiple Iphones with a basic one costing around $100 so Carriers can give it for free in US, and in rest of the world most people can afford it, this can be very slim like IPod without any camera and special hardware, so regular user can enjoy web and touch screen. Introduce and Advertise more Geeky themes which young men would like, this is where Android is making inroad. This is for free -- Do something about Java on IPhone like how Google cleverly used it. 

Running Liferay in Development Mode

Liferay speeds up rendering UI pages including Portlets by caching CSS, JS and layout files, this make developing portlets little painful, since every time you make js or css changes in your portlet and deploy. you may have to clear temp, work directoires and clear caches from Liferay control panel. So when using Liferay for development we can switch off the caching by adding few properties to "portal-ext.properties" file, this will save some time and frustation when developing portlets Solution 1 :  Copy all values from portal-developer.properties to portal-ext.properties Solution 2 :  Copy below values to portal-ext.properties, portal-ext.properties location - webapps/ROOT/WEB-INF/classes/portal-ext.properties if not present create a new one theme.css.fast.load=false theme.images.fast.load=false javascript.fast.load=true javascript.log.enabled=true layout.template.cache.enabled=false browser.launcher.url= combo.check.timestamp=true freemarker...

Easy access to Spring ApplicationContext in any non bean class

Checkout the following class import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /**  *  * @author intesar  * Simple bean class which implements ApplicationContextAware interface   */ @Component public class SpringApplicationContextFactory implements ApplicationContextAware {     static ApplicationContext ctx;     @Override     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {         ctx = applicationContext;     }     public static ApplicationContext getContext() {         return ctx;     } } When an ApplicationContext creates a class that implemetns the ApplicationContextAware...

My experience with Adwords profit sharing

This is what I got from G Adwords for putting adds on this blog. Page impr    Clicks      Page CTR        eCPM            Earnings 3119             11            0.35%                0.89                       $2.79 And this is what one of my client paid for promoting his business via adwords. Page impr    Clicks      Page CTR       eCPM            Costs  3537                  2...

Why its not easy to find Good Java Developers.

Recently I came across lots of post trying to unlock why its difficult to find good Java Developers so I wanted to share my view on this topic. I've been training people on Java since 2007 for various consulting companies. First lets consider the time it takes to become an expert in PHP Development. A good php developer is expected to know these technologies (PHP, HTML, CSS, Javascript, SQL, Photoshop), and in 1 month of training he can start coding in php and in an year he will have nice grip over all these technologies. So a guy with 1yr of experience is good enough to be considered for most of the php jobs.  Now lets consider what it takes to become a good Java developer, most of the posts on job portals will look like this Java, SQL, ORM, MVC, HTML, Unit testing, Servlets, JSP, JDBC, AJAX, Design Patterns, Web Services, and IOC. Most of the students coming straight out of the college know quite a bit of Java, They write desktop and web application using very ...

Its Employers who need to be competent to find good Java Developers

Recently I came across lots of post trying to unlock why its difficult to find good Java Developers so I wanted to share my view on this topic. I've been training people on Java since 2007 for various consulting companies. First lets consider the time it takes to become an expert in PHP Development. A good php developer is expected to know these technologies (PHP, HTML, CSS, Javascript, SQL, Photoshop), and in 1 month of training he can start coding in php and in an year he will have nice grip over all these technologies. So a guy with 1yr of experience is good enough to be considered for most of the php jobs.  Now lets consider what it takes to become a good Java developer, most of the posts on job portals will look like this Java, SQL, ORM, MVC, HTML, Unit testing, Servlets, JSP, JDBC, AJAX, Design Patterns, Web Services, and IOC. Most of the students coming straight out of the college know quite a bit of Java, They write desktop and web application using very less standar...

Reuse JPA Entities as DTO

Note : Major design advantages of JPA Entities are they can detached and used across tiers and networks and later can by merged. Checkout this new way of querying entities in JPA 2.0 String ql = " SELECT new prepclass2.Employee (e.firstname, e.lastname) FROM Employee e "; List<Employee> dtos = em.createQuery(ql).getResultList(); The above query loads all Employee entities but with subset of data i.e. firstname, lastname. Employee entity looks like this. @Entity @Table(name="emp") public class Employee implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @Column     private String firstname;     @Column     private String lastname;     @Column     private String username;     @Column ...

Gmail or Google Apps as Liferay SMTP Server

Good thing of this approach is you don't need restart compare to setting inside ROOT.xml or portal-ext.properties Go to  Control Panel -->  Server Administration --> Mail  and enter these values  Note : If you don't see emails coming, enable your pop of your gmail account.

JPA Performance settings Explained

Lets consider this simple Entity, Ignore @SecondaryTables and other annotations if you are not familiar with just focus on @Basic, @OneToOne, @OneToMany annotations and get ready to answer these questions. @Entity @SecondaryTables({     @SecondaryTable(name="Employee_Comments") }) public class Employee implements Serializable {     private static final long serialVersionUID = 1L;     @Id     private Long id;     @Column(name = "name")     private String name;     @Basic(fetch = FetchType.LAZY)     @Column(name = "comments", table = "Employee_Comments")     private String comments;     @OneToMany     private List tags = new ArrayList ();     @OneToOne(fetch=FetchType.LAZY)     private Address address; .. } What happens when we load the above entity using em.find or by exe...

Reading RSS Feed in Java (3 llines of code) Explained

Rome is a very simple Java API for reading RSS Feeds and is available under Apache License 2.0 Rome Home Page https://rome.dev.java.net/ If you are a maven user just add this dependency         <dependency>             <groupId>rome</groupId>             <artifactId>rome</artifactId>             <version>1.0RC2</version>         </dependency> if you are using ant   1. Add Rome jar from https://rome.dev.java.net/dist/rome-1.0.jar   2. Add JDOM jar from http://www.jdom.org/dist/binary/archive/jdom-1.0.zip And here is the code to pull feeds,  import java.net.URL; import java.util.List; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndFe...

JPA 2 new feature @ElementCollection explained

@ElementCollection is new annotation introduced in JPA 2.0, This will help us get rid of One-Many and Many-One shitty syntax. Example 1: Stores list of Strings in an Entity @Entity public class Users implements Serializable {     private static final long serialVersionUID = 1L;     @Id     @GeneratedValue(strategy = GenerationType.AUTO)     private Long id;     @ElementCollection     private List<String> certifications = new ArrayList <String> ();     public Long getId() {         return id;     }     public void setId(Long id) {         this.id = id;     }     public List <String> getCertifications() {         return certifications;     }     pub...

Liferay DWR Session and Security made easy

In my previous article I discussed about using DWR inside Liferay Portlets, I wasn't happy with security this model provides. First lets have a look at what I proposed ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(WebKeys.THEME_DISPLAY);         portletRequest.getPortletSession().setAttribute("THEME_DISPLAY", themeDisplay, PortletSession.APPLICATION_SCOPE); I was executing the above code inside my portlet's doView() and this puts themeDisplay or remoteUser object into portlet session's application scope, that means my DWR classes access the object like this     @RemoteMethod     public String echo(String msg, HttpSession session) {         ThemeDisplay themeDisplay = (ThemeDisplay)  session.getAttribute("THEME_DISPLAY");     } The problems what I see in the above technique is User can access DWR methods even after his portlet sess...

JPA 2.0 enums with custom values

Let's consider we have this enum public enum EmpType { FULL_TIME("e1"), PART_TIME("e2"); private String val; private EmpType(String val) { this.val = val; } @Override public String toString() { return val; } } And the entity @Entity @NamedQueries({ @NamedQuery(name="Employee.findByEmployeeType", query="SELECT e FROM Employee e WHERE e.employeeType = ?1") }) @Access(AccessType.FIELD) public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Transient private EmpType empType; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public EmpType getEmpType() { return empType; } public void setEmpType(EmpType empType) { this.empType = empType; } @Access(AccessType.PROPERTY) @Column(name="employee_type") protected String getEmploy...

JPA Compound Primary Keys Explained

The whole purpose of this article is to explain JPA Compound Primary Keys in a simple way. Some Entities needs to have a primary key based on more than one field (eg Legacy DB), so we don't have much choice here. JPA supports two ways of configuring compound primary keys however we are going to focus on the one which I feel makes Entities and Queries easy to read and understand. Lets take an example of a PhoneDirectory Entity which stores Phone No, Ext and Employee name, many employees can have same phone no but with different ext so our candidate for primary key is Phone No and Ext. We need to follow just couple of steps write this entity Step 1: 1. Create PhoneId class as show below 2. This class should have equals(), hashcode() and should implement Serializable 3. And should be annotated with @Embeddable import java.io.Serializable; import javax.persistence.Embeddable; /** * * @author intesar */ @Embeddable public class PhoneId implements Serializab...

Why Java Web Application UI lags ?

I've worked on more than 2 Dozen Java Web Applications in different companies and with various teams and every time I felt these applications lagged in UI compare to PHP applications. Don't get me wrong I'm trying to understand and find solution to problems what I'm seeing and I could easily learn from your exposure and experience or may be we all can understand whats happening. Though most of the teams I've worked with were extremely talented and we wrote huge large scale applications and in fact we also had UI experts on these projects, then why couldn't we write great UI? I feel there are two reason's for this firstly these teams are dominated by Java guys who mostly like working on server side code and they really don't enjoy working on UI and they spend enormousness time fixing performance, and other server side issues which hardly are issues for some project for an example in one of my project we spend weeks trying to fix application performance...

JPA Lifecycle Callback Events

Typical Entity Life-cycle Persist   - Creating Entity for the first time. Merge   - Updating detached Entity Load     - Loading Entity from Database Delete   - Deleting Entity from Database JPA provides total of 6 Annotations for Life-Cycle Callback events. @PrePersist @PostPersist @PreUpdate @PostUpdate @PreRemove @PostLoad Following two ways to utilize the above annotations. Case 1 : Defining inside Entity class Any method can be annotated with one or all annotations, though they should follow these rules.  Method can have any name  No parameters  Return type of void  Method should not be final or static  No Checked exceptions should be thrown  Any annotation can be only used on one method Example Code Snippet - 1 @Entity public class Employee implements Serializable { ... @PrePersist @PostPersist @PreUpdate @PostUpdate @PreRemove @PostLoad public void updateDate() {    ...

JPA and Enums

There are different ways of configuring enums inside JPA entity which yields different results. Let's consider we have this enum public enum EmpType { FULL_TIME, PART_TIME; } And the entity @Entity public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column private String name; @Enumerated private EmpType empType; .. } To use enum we have to annotate field with @Enumerated Employee e = new Employee(); e.setId(1L); e.setName("na"); e.setEmpType(EmpType.FULL_TIME); em.persist(e); the above code will save entity as follows ID EMPTYPE NAME 1 0 na This is because all the enum's in EmpType are indexed starting from zero, so if we change order or introduce a new enum in middle we lose the context in Employee table. Instead use this @Enumerated(EnumType.STRING) which save the above entity as ID EMPTYPE ...

Spring ApplicationContext inside JSR-168 Portlet

Use following code to get Spring ApplicationContext inside portlet PortletContext portletContext = this.getPortletContext(); ApplicationContext context = PortletApplicationContextUtils.getWebApplicationContext(portletContext); then use context to retrieve beans context.getBean("beanName"); Note : spring-webmvc-portlet.jar is required. Another more generic way of accessing Spring Application Context http://mdshannan1.blogspot.com/2010/11/easy-access-to-spring.html

Writing Secure Ajax Portlets for Liferay using DWR

Liferay PortletSession cannot be shared with DWR Servlet Session however using following technique we can copy required information from Liferay Session to Application Session request.getPortletSession().setAttribute("remoteUser", request.getRemoteUser(), PortletSession.APPLICATION_SCOPE); Access above session data inside DWR public String test(HttpSession session) { /** * s1 == portal session * s2 == DWR session * * s1 expires before s2 --> s2 will also expire (Tested) * s2 expires before s1 --> s2 invalidates and should work after reload (Tested) * s1 & s2 expires --> user reloads and relogins both should work * */ String userId = (String) session.getAttribute("remoteUser"); if (userId == null) { session.invalidate(); return "Page reload is required!"; } return us...

Tomcat Database Connection Pooling (JPA)

Follow these simple steps to setup Database Connection Pooling inside Tomcat 6.x Step 1 Add following element to conf/context.xml file. This Resource will be avaible to all Applications deployed <Resource name="jdbc/SampleDb" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="3" maxWait="10000" username="" password="" driverClassName="" url=""/> provide values for all attributes (username, password, driverClassName, url etc) Step 2 Add following to web.xml of your Application <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/SampleDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> S...

Recreate User Community Layout

This is a simple DB update... Replace  ValidPLID with a valid layout plid from layout table.. update layout set typesettings = (select typesettings from layout where plid = ValidPLID ) where groupid in ( select groupid from group_ where name in (select concat('',userid) from user_ ) ) and privatelayout = 0 and friendlyurl like '/home'; update layout set typesettings = (select typesettings from layout where plid = ValidPLID  ) where groupid in ( select groupid from group_ where name in (select concat('',userid) from user_ ) ) and privatelayout = 1 and friendlyurl like '/home'; Incase if you have dead portlets visible on user public or private pages just delete records from resource_ table. delete from resource_ where resourceid in ( select r.resourceid from resource_  r , (select concat (plid, '%') p from layout where friendlyurl like '/home' and groupid in ( select groupid from group_ where name in ( select concat('',use...

Liferay DWR Integration issues and solution

DWR classes doesn't have access to Liferay request and session attributes. i.e. inside dwr classes this won't work PortalUtil.getUser(req) --- return null Also sharing themeDisplay object using post login hook won't work.. since postlogin-hook's session data is not shared with other portlet applications One way to access themeDisplay object inside DWR classes is do this.. Add these lines to doView().. ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); request.getPortletSession().setAttribute("themeDisplay", themeDisplay, PortletSession.APPLICATION_SCOPE); and inside DWR class access like this public void test(HttpSession session) { ThemeDisplay themeDisplay = (ThemeDisplay) session.getAttribute("themeDisplay"); logger.trace(" community name :" + themeDisplay.getScopeGroupName()); }
How to Access Spring Application Context from JSR-168 Portlet Step 1 : Make sure you have spring-webmvc-portlet.jar in your project classpath Step 2 : Make sure you defined your spring files in web.xml like this <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext-dao.xml classpath:applicationContext-services.xml classpath:applicationContext-schedule.xml classpath:applicationContext-ajax.xml </param-value> </context-param> Optional <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> Step 3 : Access like this. PortletContext pc = this.getPortletContext(); ApplicationContext context = Portle...

Basic Log4j tutorial

Step 1 : create file log4j.properties in $project_home/src/ log4j.appender.portlet = org.apache.log4j.FileAppender # log file will be in tomcat/logs/ log4j.appender.portlet.File = ${catalina.home}/logs/privatemessage.log log4j.appender.portlet.Append = false log4j.appender.portlet.layout = org.apache.log4j.PatternLayout log4j.appender.portlet.layout.ConversionPattern = %d{ABSOLUTE} [%t] %-5p %-30.30c{2} %x - %m %n # only log errors log4j.rootCategory=WARN, portlet # log trace messages from this package and sub packages log4j.logger.com.cisco.project=TRACE Step 2 : add these lines to web.xml <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> Step 3 : Use logger in your java classes, before add log4j library to your project classpath // add imports import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; // define priv...

Liferay 5.2.3 Solr Integration

Liferay Solr Integration Environment: Liferay 5.2.3 or 5.2.5 Solr 1.4 solr-web-5.2.3.1.war Follow these steps Step 1: Add the below line to catalina.sh or catalina.bat, i.e setting the $SOLR_HOME dir (/content/liferay/data/solr) set JAVA_OPTS=%JAVA_OPTS% -Dsolr.solr.home="C:\solr1" Step 2: Copy conf directory from solr downloaded (apache-solr-1.4.0\example\solr\conf) to the $SOLR_HOME (/content/liferay/data/solr) from step 1 Step 3: Replace $SOLR_HOME/conf/schema.xml with solr-web-5.2.3.1/WEB-INF/conf/schema.xml Step 4: Edit $SOLR_HOME/conf/solrconfig.xml change this line with appropriate dir ... to /content/liferay/data/solr/data/ Step 5: Restart Step 6: deploy your solr-web from control panel or deploy dir, also you can download that from here solr-web-5.2.3.1 Step 7: run reindex in liferay control panel->server administration Step 8: Restart

Liferay Jackrabbit Oracle integration

Follow these steps to integrate Liferay, Jackrabbit, and Oracle. Step 1 : Copy the below lines into portal-ext.properties dl.hook.impl=com.liferay.documentlibrary.util.JCRHook jcr.initialize.on.startup=true jcr.workspace.name=liferay jcr.node.documentlibrary=documentlibrary jcr.jackrabbit.repository.root=${liferay.home}/data/jackrabbit jcr.jackrabbit.config.file.path=${jcr.jackrabbit.repository.root}/repository.xml jcr.jackrabbit.repository.home=${jcr.jackrabbit.repository.root}/home jcr.jackrabbit.credentials.username=none jcr.jackrabbit.credentials.password=none Step 2 : Replace the content of liferay-installation/data/jackrabbit/repository.xml with below xml text and then restart <?xml version="1.0"?> <Repository> <!--<FileSystem class="org.apache.jackrabbit.core.fs.local.LocalFileSystem"> <param name="path" value="${rep.home}/repository" /> </FileSystem>--> <!-- Data...

SCEA 5 Step 1

I have prepared from the following materials EJB in Action GOF Design patterns J2EE Design patterns JEE 5 tutorial from Sun.com JavaPassion.com (EJB, JAX-WS) Real exam was different than what I've learned from the above books, SCEA 5 exam was challenging, its an Enterprise Architect Certification so the focus was on solving architectural problems (Scalability, Availability, Maintainability, Picking right technology, & Patterns) So the above materials covered 60-70% of the objectives, rest of the questions I had to answer from my experience, and most of the answer choices were pretty close. Example However i can't post the real question so I'm providing this from my own Question: Pick the right technology for sending XML based reliable message to another system. A: JMS B: JAX-WS C: RMI D: Stateless bean as you can see A, B, C are all correct i.e. we can send an XML message to another system reliably My Advice: However I would cross all those choice which...