Tuesday 30 December 2014

JavaScript that disables "browser back" functionality

Here the code, note that "addEventListener" works only from IE9, if you need also support of earlier IE, just change "addEventListener" to the "onkeydown" event.

  var handleBackSpace = function handleBackSpaceFunction(evt) {  
    switch (evt.target.tagName.toLowerCase()) {  
       case "input":  
         if (evt.target.type.toLowerCase() == "text" || evt.target.type.toLowerCase() == "password") {  
            disableIfNeeded(evt);  
            break;  
            //case of checkboxes  
         } else {  
            evt.preventDefault();  
         }  
       case "textarea":  
         disableIfNeeded(evt)  
         break;  
       default:  
         disableBackspace(evt)  
         break;  
    }  
  }  
  document.addEventListener('keydown', handleBackSpace, false);  
  function disableIfNeeded(evt) {  
    if (evt.target.readOnly == true) {  
       evt.preventDefault();  
    }  
  }  
  function disableBackspace(evt) {  
    var key;  
    if (typeof evt.keyIdentifier !== "undefined") {  
       key = evt.keyIdentifier;  
    } else if (typeof evt.keyCode !== "undefined") {  
       key = evt.keyCode;  
    }  
    if (key === 'U+0008' ||  
       key === 'Backspace' ||  
       key === 8) {  
       evt.preventDefault();  
    }  
  }  

Monday 15 September 2014

JavaScript waiting message and page blocking

Sometime when submitting the for cause the long operation we need to show some message that user should wait and block all controls. The following html will do it for you:


 <?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">  
      <head>  
           <title>Waiting message</title>  
           <style type="text/css">  
                #loading-div-background {  
                     display: none;  
                     position: fixed;  
                     top: 0;  
                     left: 0;  
                     width: 100%;  
                     height: 100%;  
                     background-color: rgba(255, 255, 255, 0.5);  
                }  
                #loading-div {  
                     width: 300px;  
                     height: 200px;  
                     text-align: center;  
                     position: absolute;  
                     left: 50%;  
                     top: 30%;  
                     margin-left: -150px;  
                     margin-top: -100px;  
                }  
           </style>  
           <script type="text/javascript">  
                function showProgress() {  
                     document.getElementById("loading-div-background").style.display = 'block';  
                     var pb = document.getElementById("loading-div");  
                     <!--We inserting the gif, because of well-know IE bug http://stackoverflow.com/questions/780560/animated-gif-in-ie-stopping-->  
                     pb.innerHTML =  
                               '<img src="https://d13yacurqjgara.cloudfront.net/users/157197/screenshots/968023/framely.gif" width="200" height ="200"/><h2>Please wait.... We are working on the hard task</h2>';  
                     pb.style.display = 'block';  
                }  
           </script>  
      <head>  
      <body>  
      <form>  
           <input type="button" value="start job" id="show" onclick="showProgress();"/>  
      </form>  
      <div id="loading-div-background">  
           <div id="loading-div">  
                <!--Here we will insert inner html by the java script-->  
           </div>  
      </div>  
      </body>  
 </html>  

If the gif is not available just find another in the internet.
And... wait for it... Happy coding.

Thursday 11 September 2014

JSF 2.1 + gralde + Tomcat: "Hello world" application

Here is the example how to write minimal "Hello world" web application using: JSF, gradle as build and dependency management tool, and Tomcat 7 as servlet container.

The project structure you can see on the screenshot:




So you will need to create only 4 files:

    1. The first one: build.gradle that should lie in the <project_root> folder and it's content should be:

 apply plugin: 'java'  
 apply plugin: 'war'  
 sourceCompatibility = 1.7  
 repositories {  
      mavenCentral()  
 }  
 dependencies {  
      testCompile group: 'junit', name: 'junit', version: '4.11'  
      compile 'com.sun.faces:jsf-api:2.2.8'  
      compile 'com.sun.faces:jsf-impl:2.2.8'  
      compile 'javax.servlet:jstl:1.2'  
      //in this project, you don't actually need this dependency, but there is big probability, that if project is  
      //more complex than "Hello world" you will need it  
      providedCompile 'javax.servlet:servlet-api:2.5'  
 }  

    2. The second one: web.xml that should lie in the <project_root>/src/main/webapp/WEB-INF folder and it's content should be:

 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
            xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
            xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
            id="WebApp_ID" version="2.5">  
      <!-- Change to "Production" when you are ready to deploy -->  
      <context-param>  
           <param-name>javax.faces.PROJECT_STAGE</param-name>  
           <param-value>Development</param-value>  
      </context-param>  
      <servlet>  
           <servlet-name>Faces Servlet</servlet-name>  
           <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
           <load-on-startup>1</load-on-startup>  
      </servlet>  
      <!-- Map these files with JSF -->  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>/faces/*</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.jsf</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.faces</url-pattern>  
      </servlet-mapping>  
      <servlet-mapping>  
           <servlet-name>Faces Servlet</servlet-name>  
           <url-pattern>*.xhtml</url-pattern>  
      </servlet-mapping>  
      <!-- Welcome page -->  
      <welcome-file-list>  
           <welcome-file>welcome.xhtml</welcome-file>  
      </welcome-file-list>  
 </web-app>  

    3.  The third one: welcome.xhtml that should lie in the <project_root>/src/main/webapp folder and it's content should be:

 <?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:f="http://java.sun.com/jsf/core"  
       xmlns:h="http://java.sun.com/jsf/html">  
 <h:head>  
      <title>JSF 2.1 Hello World</title>  
 </h:head>  
 <h:body>  
      <h3>JSF 2.1 Hello World Example - welcome.xhtml</h3>  
 </h:body>  
 </html>  

    4. The last one: settings.gradle that should lie in the <project_root> folder and it's content should be:

 rootProject.name = 'HelloWorldApp'  

To build the war file you need to call gradle build in command line in the <project_root> folder. The result of build should be the war file lies in the <project_root>/build/libs

After you deploy the artifact to the Tomcat you can see your results by the: http://localhost:8080/HelloWorldApp/

Should be something like this:


Happy coding)

Monday 28 July 2014

Intelij Idea and the Subversion integration: forbid SVN to lock the files in a repository

If you enable the Subversion in the Intelij Idea, you can face the problem that the every time you edit the file, it became locked in the repository. To avoid it, you can tel the Intelij to lock the file using file system.

To do, according to the http://www.jetbrains.com/idea/webhelp/changing-read-only-status-of-files.html
You can choose the option lock the file "Using file system", and tick the checkbox: "Do not show this dialog in future".
After it the Intelij Idea won't lock any files in a repository

Wednesday 23 July 2014

Get the path to the executed sh with $(dirname $0)

Lets imagine that you have an A.sh file, that uses some relatives path from this file. Something like: "../.."
And some times you run A.sh file directly, ans sometimes you call it from another B.sh. And when you cal it from B.sh all relatives paths in A.sh could not work any more.

To make the A.sh properly works in both cases you can use something like:

 $(dirname $0)/../..  

The $0 command should return the path from the A.sh file to the B.sh concatenated with /B.sh (file name of the .sh that i called from an other .sh file)

And dirname simply truncates everything after the last slash with the last slack itself. I our case it will truncate /B.sh. If B.sh will be called directly, $0 will return ./ and dirname will do nothing, so everything will work in this case, too.

Monday 21 July 2014

Java initialization order

I was interested in what order java initialize objects in the class and its duper class. So, I wrote small program to get it:

 class Super {  
   static {  
     System.out.println("The first Super static init block");  
   }  
   static StaticSuperField staticSuperField = new StaticSuperField();  
   SuperField superField = new SuperField();  
   static {  
     System.out.println("The second Super static init block");  
   }  
   Super() {  
     System.out.println("The Super constructor");  
   }  
   {  
     System.out.println("The Super non-static init block");  
   }  
 }  
 public class Sub extends Super {  
   {  
     System.out.println("The Sub non-static init block");  
   }  
   static {  
     System.out.println("The first Sub static init block");  
   }  
   static StaticSubField staticSubField = new StaticSubField();  
   private SubField subField = new SubField();  
   static {  
     System.out.println("The second Sub static init block");  
   }  
   Sub() {  
     System.out.println("The Sub constructor");  
   }  
   public static void main(String[] args) {  
     new Sub();  
   }  
 }  
 class StaticSubField {  
   public StaticSubField() {  
     System.out.println("The static sub field");  
   }  
 }  
 class SubField {  
   public SubField() {  
     System.out.println("The sub field");  
   }  
 }  
 class StaticSuperField {  
   StaticSuperField() {  
     System.out.println("The static super field");  
   }  
 }  
 class SuperField {  
   SuperField() {  
     System.out.println("The super field");  
   }  
 }  

And got the output:

The first Super static init block
The static super field
The second Super static init block
The first Sub static init block
The static sub field
The second Sub static init block
The super field
The Super non-static init block
The Super constructor
The Sub non-static init block
The sub field
The Sub constructor

So, clear to see that the first class that is loaded to the JVM will be the super class of need Sub.
Also, you can see static members (not important which blocks or field) runs in the order that they appears in the code.
Obvious that the all fields initialized before a constructor finishes, and after the Super constructor runs.

Finally the initialization order of a class is:
  1. Static members (in the order they appeared in a class, not important if it is block or field).
  2. Non-static fields are given their default values
  3. Than the constructor starts and calls super();
  4. After super() is finished, non-static members are initialized, and here the same rule as for statics members(in the order they appeared in a class).
  5. And the last step, a constructor finishes.

Thursday 17 July 2014

Shell script that call stored procedure by the sqlplus

If you want to write the .sh file that will call sqplus that should execute the sql query, you can try something like this:

 sqlplus <db_username>/<db_password>@//<db_host>:<db_port>/<db sid> <<EOF  
 exec <function_package_name>.<function_name>;  
 exit;  

This example shoul call stored procedure. You can change it to execute any sql query.

Tuesday 8 July 2014

Webshere: creating the profile using gradle


This gradle script will create the profile that will be administrative secure with the usename "admin" and the password "admin"

More about passed parameters and the parameter that you could additionalyy pass, you can read here:
http://pic.dhe.ibm.com/infocenter/wxdinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.ops.doc%2Finfo%2Finstall%2Frinstallprofile_silent.html

The webshere ports will be starting from the 13000.

To delete profile, you can use the script simmilar like in the http://b1102.blogspot.de/2014/07/gradle-escaping-spaces-in-arguments-for.html

 import org.apache.tools.ant.taskdefs.condition.Os  
 task createProfile(type: Exec) {  
     description = 'Create WebSphere Application Server profile.'  
     def isWindows = Os.isFamily(Os.FAMILY_WINDOWS)  
     def cmdExtension = isWindows ? 'bat' : 'sh'  
     def manageProfilesFileName = File.separator + "manageprofiles." + cmdExtension  
     //Path to your webshere installation  
     def wasHome = 'C:/IBM/WebSphere/AppServer'  
     def templatePath = wasHome + File.separator + "profileTemplates" + File.separator + "default"  
     //Path to the wsadmin.bat or wsadmin.sh  
     def wsadminLocation = wasHome + File.separator + "bin"  
     def manageProfilesFile = new File(wsadminLocation, manageProfilesFileName)  
     executable = manageProfilesFile  
     def argsList = ["-create", "-profileName", "Profile1", "-templatePath", templatePath,  
                     "-nodeName", "AppSrv01", "-cellName", "AppSrv01Node1",  
                     "-serverName", "AppSrv01Node1Serve1", "-enableAdminSecurity", "true",  
                     "-startingPort", "13000", "-adminUserName", "admin",  
                     "-adminPassword", "admin"]  
     //defines will this profile will be the default one or not  
     def isDefault = true  
     if (isDefault) {  
         args.add("-isDefault")  
     }  
     if (isWindows) {  
         argsList.add("-winserviceCheck")  
         argsList.add("true")  
         argsList.add("-winserviceUserName")  
         argsList.add("Administrator")  
         argsList.add("-winserviceStartupType")  
         argsList.add("automatic")  
     } else {  
         argsList.add("-enableService")  
         argsList.add("true")  
         argsList.add("-serviceUserName")  
         //any desired service user name  
         argsList.add("root")  
     }  
     args = argsList  
 }  

Gradle: escaping spaces in arguments for the task “type:Exec”

Gradle have problems when try to pass many arguments to its task with the type of "Exec".
The more accurate the problem is decribed here: http://stackoverflow.com/questions/20613244/gradle-execute-task-typeexec-with-many-arguments-with-spaces

The solution is simple: path the parameters as arguments list, like this:

 task callProfileDelete(type: Exec) {
      description = 'Delete profile with wsadmin.'
      executable = manageProfilesFile
      args = ["-delete", "-profileName", "My profile name"]
 }

In this case you will path always the correct number of arguments and the "space" will escaped nicely.

Wednesday 7 May 2014

Show Hibernate parameters with nicely formatted query

Sometime for the debugging it is really handy, to do it, you need:

log4j.properties


log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.hql.ast.AST=info
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.cache=info
log4j.logger.org.hibernate.jdbc=debug

log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.layout.ConversionPattern=HibernateLog --> %d{HH:mm:ss} %-5p %c - %m%n
log4j.appender.hb.Threshold=TRACE
hibernate.cfg.xml
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

Thanks Tommaso Taruffi, http://stackoverflow.com/questions/2536829/hibernate-show-real-sql