Monday, 10 March 2014

Starting Apache Velocity with struts

What is Velocity?

Ans: Velocity is a Java-based template engine. It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.
When Velocity is used for web development, Web designers can work in parallel with Java programmers to develop web sites according to the Model-View-Controller (MVC) model, meaning that web page designers can focus solely on creating a site that looks good, and programmers can focus solely on writing top-notch code. Velocity separates Java code from the web pages, making the web site more maintainable over its lifespan and providing a viable alternative to Java Server Pages (JSPs) or PHP.
Check (http://velocity.apache.org/) for details.

For first App you need jars required for velocity.


  1.       Create a Dynamic web application.
  2.       Put all the required jars in /WEB-INF/lib  directory of your application

antlr-2.7.5.jar
avalon-logkit-2.1.jar
commons-collections-3.2.1.jar
commons-lang-2.4.jar
commons-logging-1.1.jar
jdom-1.0.jar
log4j-1.2.12.jar
maven-ant-tasks-2.0.9.jar
oro-2.0.8.jar
servletapi-2.3.jar
werken-xpath-0.9.4.jar

Note: you can find all these jars in lib folder of downloaded zip of Velocity (Ex. velocity-1.7.zip).

  3.       Map a servlet in your web.xml

<servlet>
    <servlet-name>velocity</servlet-name>
    <servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
  </servlet>
  <servlet-mapping>
       <servlet-name>velocity</servlet-name>
       <url-pattern>*.vm</url-pattern>
  </servlet-mapping>


  4.       In case of Struts 2.x map struts filter

<filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>*</url-pattern> 
</filter-mapping>


  5.  Create a UserAction


package com.ankit.web;

import com.opensymphony.xwork2.ActionSupport;

public class UserLogin extends ActionSupport {

       private String name;
       private String email;
       private int random;
      
       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public String getEmail() {
              return email;
       }

       public void setEmail(String email) {
              this.email = email;
       }

       public int getRandom() {
              return random;
       }

       public void setRandom(int random) {
              this.random = random;
       }

       public  String login() {
             
              random=(int)( Math.random()*10);
              System.out.println("Name->"+name+" random->"+random);
              return SUCCESS;
       }
}

  6.  Struts.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default" >
       <action name="login" class="com.ankit.web.UserLogin" method="login" >
              <result>index.vm</result>
       </action>
</package>
</struts>

  7.  index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib uri="/struts-tags"  prefix="s" %>
    <%@taglib uri="http://velocity.apache.org/velocity-view"  prefix="velocity" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="login" >
<s:textfield  name="name" label="Name" labelSeparator=":-" ></s:textfield>
<s:textfield  name="Email" label="Email" labelSeparator=":-" ></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>

  8.  index.vm

#set($a="Welcome")
$a
<b>$name</b> <br>
Your Email is <b>$email</b>
<br>
Generated Random Number is in RED
#set($i=10)
#foreach($i in [1..10])
<b
#if($i==$random)
style="color:red;"
#else
style="color:green;"
#end >$i</b>&nbsp;
#set($i=$i+1)
#end
<br>Check if user is  Admin
#if($name=="Admin")
<b>User is Admin</b>
#end

Output:- 

Page1

   

        Page2

 


Download:-



Tuesday, 11 February 2014

Date Converter for Different Timezone and Formats

Convert Date from one timezone to another without hassle. Covert a different format to different format.

Features:-
1. Easy to use.
2. Free of cost.
3. Light weight.
4. Pure Java tool.

If you want to calculate your age or want to know how much younger or older your friend than you, Have a date in different timezone and want to know time in your timezone or whats time in different timezone now. All this is just one download and one click away. May be you don't have internet next time just download it once and use it. Any platform and place just you need Java enabled (Today most of the systems have Java).

Download

Want to explore more looking for source code Download Source

Can't find your desired format write to me.

Thanks.

Monday, 19 August 2013

Not In query In Liferay Dynamic Query


In liferay dynamic query you can create a query for not in condition like
"SELECT * FROM traders WHERE traderId NOT IN(455,466)"


Thursday, 8 November 2012

Convert Amount In Words

A simple problem is to convert the given amount in words for receipt or other bills related usage.


Thursday, 25 October 2012

Environment Variables In Java


Environment Variables  are variables that are added in any Operating system that can be accessed from anywhere in OS without using the complete(Real) location.

In a java Application System.getenv(); is used to find out the system environment variables

Example:-

import java.util.Map;

public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}

The Security Manager

The security manager is an object that is used to check whether the operation we want to perform is not violating security policy of the operation system.
Sometime we want to perform any operation and got a exception


Exception in thread "AWT-EventQueue-1" java.security.AccessControlException: access denied (java.io.FilePermission characteroutput.txt write)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
        at java.security.AccessController.checkPermission(AccessController.java:546)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
        at java.lang.SecurityManager.checkWrite(SecurityManager.java:962)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
        at java.io.FileWriter.<init>(FileWriter.java:46)
...

To Prevent from this exception we can use SecurityManager class to check for the permission before performing operation.

The security manager is an object of type SecurityManager; to obtain a reference to this object, invoke System.getSecurityManager.

SecurityManager appsm = System.getSecurityManager();

If there is no security manager, this method returns null.


The SecurityManager class defines many other methods used to verify other kinds of operations. For example, SecurityManager.checkAccess verifies thread accesses, and SecurityManager.checkPropertyAccess verifies access to the specified property. Each operation or group of operations has its owncheckXXX() method.
In addition, the set of checkXXX() methods represents the set of operations that are already subject to the protection of the security manager. Typically, an application does not have to directly invoke any checkXXX() methods.

System Properties in java

There are various system properties that we need to use during our programs to perform some action or access some file.
There are some commonly used properties.


KeyMeaning
"file.separator"Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
"java.class.path"Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home"Installation directory for Java Runtime Environment (JRE)
"java.vendor"JRE vendor name
"java.vendor.url"JRE vendor URL
"java.version"JRE version number
"line.separator"Sequence used by operating system to separate lines in text files
"os.arch"Operating system architecture
"os.name"Operating system name
"os.version"Operating system version
"path.separator"Path separator character used in java.class.path
"user.dir"User working directory
"user.home"User home directory
"user.name"User account name

These are following keys that can be used to find out the property.
"System"  class has a properties Object associated with it that is used to find out those properties.

Example:-