Friday, 1 November 2013

CLI (Command Line Program)

Write a CLI program with Tab completation fetures, like linux Shell.

JLine is a Java library for handling console inputs.   
jline CLI offers Command History, Tab completion, Line editing, Custom Keybindings, Character masking features.

URLs:
https://github.com/jline/jline2/tree/jline-2.11
http://jline.sourceforge.net/

Sunday, 20 October 2013

Run MySQL Query in InfiniDB

set infinidb_vtable_mode=2 for run mysql query.


set infinidb_vtable_mode = n
where n is:

0) a generic, highly compatible row-by-row processing mode. Some WHERE clause components can be processed by InfiniDB, but joins are processed entirely by mysqld using a nested-loop join mechanism


1) (Default) query syntax is evaluated by InfiniDB for compatibility with distributed execution and incompatible queries are rejected. Queries executed in this mode take advantage of distributed execution and typically result in higher performance.

2) auto-switch mode: InfiniDB will attempt to process the query internally, if it cannot, it will automatically switch the query to run in row-by-row mode.






With infinidb_vtable_mode=2, the sub select will be handled within the MySQL front end and will not have the full benefit of the MPP architecture. The vtable mode option allows extended syntax support and can be a viable option for certain types of queries. It's very possible that MYSQL will run for hours or even days on a query that involves sub selects against the row counts you posted.

Tuesday, 10 September 2013

Java 7 with Mail API

javax.mail.MessagingException: Could not connect to SMTP host: smtp.exg6.exghost.com, port: 25;

nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)


Using java Mail API with JDK 6 it's work proerly with any changes in code or arguments.

But here in same code with JDK 7 ,it will throe an error... Could not connect..

[Solution]  


Here in JDK 7 brings support for IPv6 on Windows.
When you try to connect to an IPv4 address then it will use an IPv4-mapped IPv6 address.


So we have to add an arguments when run the java program,

like

 

> java -Djava.net.preferIPv4Stack=true package.Sample





[source] http://download.java.net/jdk7/archive/b123/docs/api/java/net/doc-files/net-properties.html

Tuesday, 6 August 2013

Java User Defined Annotation and Reflection

 Annotation is about Metadata of Class.There is no Direct reflection of annotation in your logic.
 But you can add annotation to class for perform some predefined logic to validate your class, let's take an well know example,
 A JPA pojo,which have annotation like @Entity ,@Column etc. Which is used to map pojo's field with Database column name, and while we try to
 persist our pojo with EnntityManager it create some sql query which is exactly map with columnname and pojo's value respectively.

 Let's get more concept of annotation.Before we start an Example let's clear some concept about meta-annotation.

 source(http://docs.oracle.com/javase/tutorial/java/annotations/predefined.html)

 Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation.

@Retention @Retention annotation specifies how the marked annotation is stored:

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

@Documented @Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

@Target @Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:

  • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
  • ElementType.CONSTRUCTOR can be applied to a constructor.
  • ElementType.FIELD can be applied to a field or property.
  • ElementType.LOCAL_VARIABLE can be applied to a local variable.
  • ElementType.METHOD can be applied to a method-level annotation.
  • ElementType.PACKAGE can be applied to a package declaration.
  • ElementType.PARAMETER can be applied to the parameters of a method.
  • ElementType.TYPE can be applied to any element of a class.

 Example.

 We create a annotation which is used to validate Class's Integer type property's Minimum and Maximum value.

 If annotation method haven't any default value, than is a mandatory while you apply annotation.


 1). We create a annotation for a Class level

        package com.test;
      
        import java.lang.annotation.Retention;
        import java.lang.annotation.Target;
        import static java.lang.annotation.ElementType.TYPE;
        import static java.lang.annotation.RetentionPolicy.RUNTIME;
      
        @Retention(RUNTIME) @Target({TYPE})
        public @interface Validation {
        }



 2). create a annotation for Field/Method Level

        package com.test;
      
        import static java.lang.annotation.ElementType.FIELD;
        import static java.lang.annotation.ElementType.METHOD;
        import static java.lang.annotation.RetentionPolicy.RUNTIME;
      
        import java.lang.annotation.Retention;
        import java.lang.annotation.Target;
      
      
        @Retention(RUNTIME) @Target({FIELD, METHOD})
        public @interface ValidInteger {
            String Label();
            int MIN() default 0;
            int MAX() default Integer.MAX_VALUE;
        }

 3). Now we use this annotation in our Class and again read the annotation and perform validation using Java Reflection API.
     for that we create a Test Class with main method and validation our class.
   
   
        package com.test;
      
        import java.lang.reflect.Field;
      
        @Validation
        public class Test  {
      
            @ValidInteger(Label="Height",MIN=10,MAX=100)
            private int a;
          
            public int getA() {
                return a;
            }
          
            public void setA(int a) {
                this.a = a;
            }
          
            public static void main(String[] args) throws ClassNotFoundException {
                Test t = new Test();
                t.a = 200;
              
                System.out.println(Validate(t));
              
            }
      
            // the method validate your class using java reflection.
            private static String Validate(Test t) {
                // find that the class have annotation present.
                boolean annotation =  Test.class.isAnnotationPresent(Validation.class);
                StringBuilder builder = new StringBuilder();
                if(annotation){
                    Field[] fields = Test.class.getDeclaredFields();
                    for (int i = 0; i < fields.length; i++) {
                        Field field = fields[i];
                        // finding of method level annotation is present
                        if(field.isAnnotationPresent(ValidInteger.class)){
                            ValidInteger integer = field.getAnnotation(ValidInteger.class);
                            try {
                                int fieldObject = (Integer) field.get(t);
                              
                                // Validation for integer.
                              
                                if(fieldObject > integer.MAX() || fieldObject < integer.MIN()){
                                    // return UserDefined Exception or Error Message
                                    builder.append(integer.Label()+" should not greter than "+integer.MAX() +" and not less than "+integer.MIN());
                                }
      
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                return builder.toString();
            }
        }
 

         The output of the class is
       
         "Height should not greter than 100 and not less than 10"

Thursday, 25 July 2013

How to get Recent Journal Article in Action Class Liferay6.1 Hook

The Recent Article is stored in PortletSession. And it's a Object of 

java.util.Stack having 20 Objects of JournalArticle.

The Snippet is as below.

PortletSession portletSession = portletRequest.getPortletSession();

        Stack<JournalArticle> recentArticles =
            (Stack<JournalArticle>)portletSession.getAttribute(
                WebKeys.JOURNAL_RECENT_ARTICLES);

Tuesday, 23 July 2013

Hibernate second level cache using Ehcache


Hibernate is compatible with many second-level cache providers. One of the best solution is Ehcache.
We create a sample project and configure second-level cache with hibernate using Maven. Here we use Hibernate 4.1 and Hibernate Ehcache 4.1
So the pom.xml is look like this
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.haresh</groupId>
<artifactId>hibernate-tutorials</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>HibernateTutorial</name>


<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.12.Final</version>
</dependency>

<!-- Hibernate uses jboss-logging for logging, for the tutorials we will
use the sl4fj-simple backend -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.1</version>
</dependency>

<!-- The tutorials use JUnit test cases to illustrate usage -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>

<!-- The tutorials use the H2 in-memory database -->

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>4.1.1.Final</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.2.145</version>
</dependency>
</dependencies>
</project>


Now have to create a Hibernate-configuration File. hibernate.cfg.xml.
the Default configuration of hibernate.cfg.xml is as below,

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>


Here we have to change the configuration to enable second-level cache. I mention that we are using 4.x version of Hibernate.
So, In our case we have to add two more property in configuration file. One is for enable the cache, it's a boolean value, this value tell to hibernate that the second-level cache is enable.
And Second-one is Provider Class, which tell to hibernate that the Second-level cache is used through this provider. Below is the configuration.


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable the second-level cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Names the annotated entity class -->
<mapping class="com.haresh.model.Event"/>

</session-factory>

</hibernate-configuration>
Now we have to create an entity. Which have annotation for ORM. And we add another annotation to this entity for cache.
At the top of Class and below the @Entity annotation we add two more annotation, one is @Cacheable which tell to hibernate that the entity is enable for Cache. And the Second one and Most important thing is to add Cache strategy, Here we add READ-ONLY. The Object is only in read mode while it's a cache-able, there is no insert/update operation perform event after the change of State of Object. Hibernate have no worry to manage Object when it's state change. In READ-WRITE the Object's data is update then the Cache is also update simultaneously.
package com.haresh.model;

import java.util.Date;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;

@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Table( name = "EVENTS" )
public class Event {
private Long id;

private String title;
private Date date;

public Event() {
// this form used by Hibernate
}

public Event(String title, Date date) {
// for application use, to create new events
this.title = title;
this.date = date;
}

@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Long getId() {
return id;
}

private void setId(Long id) {
this.id = id;
}

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "EVENT_DATE")
public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "[id = "+id+", title = "+title+"]";
}
}


Now let's test the code, We are trying to fetch a Record from Database of Event having ID equal 1. In a normal case when we are trying to fetch record from Hibernate Session, it's traverse to the database for each new query in a every new open session.
Here It's traverse once to database and in second query it's look in to cache and get data immediatly. For ex.


Session session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
session.get(Event.class, 1l);
session.getTransaction().commit();
session.close();
// Again try to fatch data for the same Event Id,It retrive from Cache
session = HibernateUtil.getSessionFactory().openSession();
session.getTransaction().begin();
session.get(Event.class, 1l);
session.getTransaction().commit();
session.close();


In console it print only one select query rather than two select query. The Second fetch was from Cache.
Hibernate: select event0_.id as id1_0_0_, event0_.EVENT_DATE as EVENT2_0_0_, event0_.title as title3_0_0_ from EVENTS event0_ where event0_.id=?


Hibernate Cache Strategy.(http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e1364)
read-only
A read-only cache is good for data that needs to be read often but not modified. It is simple, performs well, and is safe to use in a clustered environment.
nonstrict read-write
Some applications only rarely need to modify data. This is the case if two transactions are unlikely to try to update the same item simultaneously. In this case, you do not need strict transaction isolation, and a nonstrict-read-write cache might be appropriate. If the cache is used in a JTA environment, you must specify hibernate.transaction.manager_lookup_class. In other environments, ensore that the transaction is complete before you call Session.close() or Session.disconnect().
read-write
A read-write cache is appropriate for an application which needs to update data regularly. Do not use a read-write strategy if you need serializable transaction isolation. In a JTA environment, specify a strategy for obtaining the JTA TransactionManager by setting the property hibernate.transaction.manager_lookup_class. In non-JTA environments, be sure the transaction is complete before you call Session.close() or Session.disconnect().
transactional
The transactional cache strategy provides support for transactional cache providers such as JBoss TreeCache. You can only use such a cache in a JTA environment, and you must first specify hibernate.transaction.manager_lookup_class.

Monday, 15 July 2013

Liferay SSO with Facebook



From Liferay 6.0 Facebook SSO Single Sign-On is introduced.
Facebook SSO using OAuth 2.0. 

It's a very easy steps to do configure Facebook SSO with Liferay.




  • To create Facebook SSO, you first have to have a Facebook application account, and than go to facebook developer site ,create a new Facebook application account.You have to set Site URL.From facebook application account you can get Application ID and Secret Key.




 
  • Go to your Liferay Portal Site, In control Panel click on 'Portal Setting' under Portal tab.
  • Now Go in Portal setting > Authentication > General. here you must have to enble 'Allow stranger to create account'.







  • Go to Authentication > Facebook. Enable facebook SSO. Set Application ID and Key you get from Facebook application account.
    Also you need to set "Redirect URL". http://mydomain.com/c/login/facebook_connect_oauth.
    if you are doing all this in local than you must have to map a domain name (127.0.0.1  -- mydomain.com) and also have to set in Community Virtual host as well.



  • Now go to Sign In Portlet, You can see a Facebook logo with link in the portlet.Click on the link and login in facebook.After login in facebook you redirect to Liferay Portal Page with a following Screen to add new user in Liferay,if you are alredy a member/User of Portal than user forced to automatic logged in using the SSO.






Liferay Portlet as facebook application



The easy step to configure your portlet as facebook app.

  • Goto facebook create a sample application. for example we create a 'hareshliferay' application.


  • Create a Portlet and drop it on a Portal Page.  
  • Now goto right top corner 'Configuration' menu.
  • Click on 'Sharing' tab, and than click on child tab 'Facebook' , copy and paste API Key from Facebook application.And add canvas page URL and click on 'save'   button. It generate a Callback URL, And Save.


  • Copy the callback URL and specify in facebook application,in Canvas URL under the app on facebook tab, And Save
.


  • Click on 'App Details' Menu.fill mandatory information and save than go for 'Submit App Detail Page' , if successfully done than it's showing approval status as 'Live'. Click on 'Web Preview' , it show a Facebook application page.






  • Now click on 'Go to App'.your Liferay portlet is rendered as facebook app. Simply you can add "Facebook Api" in your portlet to do some facebook specific function.



Tuesday, 9 July 2013

Create your own Portlet Container

Create your own Portlet Container

1. Download portlet-container-configurator.jar from
2. Get fresh Copy of Tomcat6.0

Configuration

Now from the jar you can configure your server to Portlet-containter in two way
  1. Using GUI
  2. From Command Line

1. From GUI

java -jar portlet-container-configurator.jar


  • You can choose container from select menu, select Tomcat6. (you can select GlassFish, Tomcat5, etc ,as shown in screen)
  • Set the Ant Home path
  • Same as Set Container Home Directory for Tomcat
    • C:\Apache-tomcat-6.0.35\
  • Domain Directory
    • C:\Apache-tomcat-6.0.35\webapps

Click on the “Ok” button.


2. From Command Line

java -jar portlet-container-configurator.jar <webcontainer-install-dir> <domain-dir/webapps> <ContainerName> <ANT_HMOE>




<webcontainer-install-dir>
  • location of installed WebContainer, ex: C:\Apache-tomcat-6.0.35\

<domain-dir/webapps>
  • path upto webapps folder, ex: C:\Apache-tomcat-6.0.35\webapps

<ContainerName>
  • container can be one of tomcat, tomcat6, jetty, weblogic. Here in our case it is tomcat6.
java -jar portlet-container-configurator.jar C:\Apache-tomcat-6.0.35 C:\Apache-tomcat-6.0.35\webapps tomcat6 C:\ANT\


Now Goto the WebContainer(tomcat6/bin) and restart/start the server.

Hit the URL in Browser

You can see two tab in portlet container driver. Portles and Admin







From Admin tab User can deploy Portlet as well configure the portles and create a New portlet window.
One can also assing role to portlets.

By Default portlet container store the data in file system, you can configure Database for saving data.

Just change the configuration file 'DriverConfig.properties' located at

C:\apache-tomcat-6.0.35\portlet-container\config\ DriverConfig.properties


The Default configuration is


persistenceType=file


# Specify the properties if the persistence type is database


jdbc.url=jdbc:derby:portletdriver;create=true
jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver
jdbc.user=
jdbc.password=
change to

persistenceType=database
# For MySQL
jdbc.url=jdbc:mysql://localhost/portletdriver
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

Infinidb _CpNoTf_ problem

infinidb table with a varchar column insert string as a '_CpNoTf_' while using Cpimport. The Problem is occured if inserted string ...