Wednesday, 23 March 2016

PowerMock and TestNG mock static methods example

import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@PrepareForTest(ClassStatic.class)
public class ClassStaticMockTest extends PowerMockTestCase {

    @Mock    
    public ClassStatic classStatic;

    @Test    
    public void mockGetValueVoid() throws Exception {
        mockStatic(ClassStatic.class);
        when(ClassStatic.getValue()).thenReturn("newValue");
        Assert.assertEquals(ClassStatic.getValue(), "newValue");
    }
}

class ClassStatic {
    static String getValue() {
        return "value";
    }
}

Thursday, 18 June 2015

JTA bean-managed transaction. Why?

Bean-managed transaction (BMT), also known as programatic transactions are implemented with the
help of javax.transaction.UserTransaction inteface, which have the commit(), the begin(), the rollback() methods, Why we need it? There are 3 possible reasons:

  1. We want to use a transaction not in EJB beans (we can use it in POJO or CDI bean)
  2. We want a one transaction during several request.
  3. We want client-initiated Transactions: a client, such as an applet, can obtain a reference to the UserTransaction and TransactionManager objects using JNDI. A client can begin a transaction using either object reference

Sunday, 11 January 2015

SCJP notes: Strings, StringBuffer and StringBuilder

Strings
  • String are immutable objects, so when you trying to change it like: "s.concat("bla")" - you not changing the current object, you creating the new one
  • This statement String s = "dsfsf" creates new String literal in the run time constant pool and even if the reference for this literal is lost it still will exist (the most likely) in memory
  • This statement String s = new String ("dsfsf") will create two objects: one on the heap and second in the run time constant pool there is such String. And the variable will be reference to the String in the heap
  • If call the intern() method it will return the reference to the same String in  the run time constant pool, if there is no such string there it will create it
  • For Strings we can use the +=  operator to concatenation and assign in a one line
  • Important String methods: charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), trim() 
  • If you ask charAt() with the index more than letters in the word-1(indexes starts with 0), you will get StringIndexOutOfBoundsException
  • If you ask substring() with the index more than letters in the word-1(indexes starts with 0), you won't get an exception, you will get an empty String
StringBuffer and StringBuilder

  • StringBuffer is StringBuilder
  • Important StringBuffer and StringBuilder methods: append(), delete(), insert(), reverse(), toString()
  • Almost all mentioned methods(except toString) returns the modified StringBuffer and StringBuilder object, but in comparison with String this methods change the object on which this methods will be called

Saturday, 10 January 2015

SCJP notes: multithreading


Miscelanious
  • If you want to write the code that will be started in its own thread, you can: or implement the Runnable interface; or extend the Thread object
  • To start the code to run its own thread, just call the start() method (not the run())
  • Thread itself implements Runnable
  • If you will to start already started Thread you will get IllegalThreadStateException
  • There is now way to pass the Thread priority, to the Threads constructor, you can pass only the thread name
  • To pass the priority to the thread just use the setPriority() method
  • Thread priority could be from 1 to 10
  • Priorities could be ignored by JVM
  • If priority of started Thread wasn't specified, the priority would be inherited from the priority of the Thread that stated Thread
java.lang.Thread important methods
  • To get the current thread instance you should call the Thread.getCurrentThread() method
  • The static Thread.sleep() method throws checked InterruptedException when thread encounters sleep it must go to sleep for at least to the number of specified milliseconds
  • The static Thread.yeld() method could be used as the hint to the scheduler that the current thread is willing to yield its current use of a processor and if it was successful in it other thread will run. But it is absolutely not guarunteed
  • The non-static join() method  throws checked InterruptedException makes the current thread wait until the Thread on which instance it was called will finish its work. If Thread on which instance it was called wasn't started or already dead nothing happens
  • The non-static interrupt() method if interrupted thread in the sleeping or waiting state cause the sleeping thread throw InterruptedException. Else just change the flag isInterrupted() to true. . Possible to interrupt not started thread and then start it. The isInterrupted() method will return false
  • The non-static setDaemon() method, sets the method as daemon. Program won't wait this thread to be finished
Synchronization
  • The method or the block of code could be synchronized and you need to synchronize when there is more than two thread in your application trying to access the same the data and at least one thread modifies this data
  • Synchronizing the instance method will cause the synchronization only for this one instance
  • The static method or the block of code could be synchronized on the static variable, so only one thread for the all application could execute such code at once
  • Synchronization of the non-static getter or setter for the static field will ensure you from race condition only when you use only one instance. When there is two or more instances synchronization could be broken
  • Synchronization of the static and non-methods doesn’t block each other
  • Sleep doesn't release the synchronization lock
  • The all run() method could be syncromized
 java.lang.Object important methods
  • wait(), notify(), notifyAll() must be called from within a synchronized context! A thread can't invoke this method on an object unless its own that object's lock. You will get the IllegalMonitorStateException if you will try it
  • The non-static wait() method  throws checked InterruptedException release the lock of synchronization and makes the thread to waits until it will notified or interrupted, or until timeout is passed if it is specified
  • There is  possibility that the thread will spontaneously wakes up it is so called "spurious wake ups"
  • The non-static method notify() wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is randomly chosen to be awakened. If nobody waits this monitor - nothing happens

Tuesday, 6 January 2015

SCJP notes: innner classes

"Regular" inner classes
  • The inner class couldn't have anything static, except compile-time constants
  • The inner class doesn't initialized when the outer is initialized
  • The inner class could have every possible access modifiers
  • Actually, inner class could have all modifiers (like: strictfp, final, abstract)
  • The only way you can access the inner class is through a live instance of the outer class
  • So you couldn't instantiate the inner class in static method of the outer class(unless you create there an instance of the outer class)
  • The inner class as a member of the outer class has the access to all other members of the outer class
  • To instantiate the inner class inside outer, just write new Inner()
  • To instantiate the inner class outside outer, you need to write something like: new Outer().new Inner()
  • You can get the link to the outer class that corresponds to the inner by Outer.this
  • You can get the link to the inner class inside inner by this or Outer.Inner.this
  • You couldn't instantiate static member in the inner class
  • But you could inherit them from other class
Method-local inner class
  • The instantiation of the method-local inner class should go after its declaration
  • The instantiation of the method-local inner class could be done only inside the method where it is declared
  • As "regular" inner class has access to all outer class members
  • The method-local inner class could use only final local variables
  • The method-local inner class could have the following modifiers: strictfp, final, abstract
  • The method-local inner class could be declared in the static method, but in this case it will have access only to the static members of the outer class, and no any "this" will be available
  • As "regular" inner classes method-local inner class couldn't declare static content
Anonymous inner class
  • There could be new methods in the anonymous inner class, but there will be no way (except reflection) to call them
  • You couldn't define new constructor within the anonymous inner class
  • You could use the proper constructor by the anonymous inner class
  • As "regular" inner classes method-local inner class couldn't declare static content
  • As the method-local inner class could use only final local variables, so it is just method-local inner class
  • As "regular" inner class has access to all outer class members
  • Anonymous inner class allows you to create the interface implementer
  • You can pass the anonymous inner class as the method parameter
Static nested classes
  • The static nested class has the access only to the static members of the outer class
  • Could declare the own static members
  • You do not need the instance of the outer class, actually even when you have you couldn't create the instance of the static inner with the instance of the outer class. The only way to create instance of staitc nested class looks like: Outer.Inner inner = new Outer.Inner();




Monday, 5 January 2015

SCJP notes: collections and generics

Miscellaneous

  • Most of collections classes are not final, so they could be subclassed

Maps:
  • Map doesn't implement Collection
  • Map doesn't have the contains() as all collections, but it has containsKey() and containsValue()  methods
  • Map implementations: TreeMap, Hashtable, HashMap. LinkedHashMap
  • LinkedHashMap extends HashMap is ordered Map
  • Hashtable is HashMap with synchronized methods
  • Hashtable, HashMap  not sorted and not ordered
  • HashMap allows null as key, all other implementation will throw nullpointer, when you try to add it
  • When you add duplicate in map, it replace previous value
  • For Map sometimes it is critical to override equals and hashcode to get your value back from Map
  • If you will try to add to the TreeMap something that is not Comparable, you will get at this time ClassCastException
  • Or you can supply to the TreeMap constructor the comparator, to avoid previously mentioned exception.
  • If you want to iterate throw Map, you need to call the entrySet() method, and then can call iterator from it. Map itself doesn't have the iterator
Sets:
  • Set implementations: TreeSet, HashSet, LinkedHashSet
  • Couldn't get element by index, need iterator or for-each construction
Navigating TreeMaps and TreeSets:
  • TreeMaps and TreeSets are sorted in natural ascending order 
  • TreeMap has methods like: higherKey(), lowerKey(), floorKey(), ceilingKey()
  • TreeSet has methods like: higher(), lower(), floor(), ceiling()
  • higherXXX() returns the element is smaller than the asked one
  • ceilingKeyXXX()  returns the element is smaller or equals that the asked one
  • TreeMap and TreeSet has descendingXXX() method
  • TreeSet hass pollFirst() and pollLast() methods that returnas and removes from the collection the first or last items
  • For TreeMap the same, but just pollFirstEntry() or pollLastEntry() 
Lists:
  • List implementations: ArrayList, LinkedList, Vector
  • LinkedList implemenst the Queue inteface
  • The add(<something to add>) method adds to the end of the list 
  • Or the add(int index, <something to add>) method  adds to the specified index position and moves all element with index higher or equals of specified index.
  • The set(int index, <something to add>) method replace existing value by index, could get IndexOutOfBoundsException if there is no such value by index that should be replaced
  • The sublist method returns the baked sublist with left borde inclusive and right border exclusive, you can also specify both borders with the same value, it will return empty list
Queues:
  • Queue implementations: LinkedList, PriorityQueue
  • PriorityQueue just sorted queue
  • Queue inteface and so on PriorityQueue has method offer() that is used to add something to the queue, and no methods as offerFirst() and offerLast() 
  • LinkedList has the offerFirst() and offerLast() methods
Backed collections
  • Everything that implements collection (everything except maps) has toArray() methods
  • The first of toArray() takes nothing and returns the array of Object
  • The second of toArray() takes the array of the type of the generics Collection, returns this array populated with the Collection items if the capacity of this array is enough, and new array of the same type if no.
  • This array is not backed with the Collection from which it was derived
  • If you will try to derive the list from the array of primitives you will get the list of arrays of these primitives.
  • Arrays.asList() return the generic list of the type of the passed array, backed together. Backed means that the list will be fixed size (you will get exception trying to add something), but if you change something in this collection the array will know about it, and the vice versa.
Sorting and searching throw collections and arrays
  • Collections (only for Lists) and Arrays classes has the sort() method that has two flavors: the first takes Comparable Collection; the second takes Collection and Comparator
  • Both Comparable and Comparator could be parameterized by generics
  • Collections (only for Lists) and Arrays classes has the binarySearch() method, this method searches throw sorted List or array and returns the index of the element if it was found
  • If the searched List or array wasn’t sorted the result of the search in unpredictable
  • If the searched List or array doesn't contains the searched element it will return the index where this element could be added with no braking sort - 1
  • Collections has the reverseOrder() method which takes Comparator and returns the reverse order Comparator
  • Collections has the reverseOrder() method which takes nothing and returns the reverse order Comparator for all Comparable objects, but if you try to sort or search with this Comparator something that is not Comparable you will get ClassCastException
  • During binary search, if one object equals another one will be taken not from equals() method, but from Comparator or compareTo(). So if Comparator or compareTo() contradict the equals() method you could find sometimes something unexpected 
  • Emty String is the first String after sorting
Generics
  • Generics doesn't exist in runtime
  • To the List<Object> you can add everything of Object's subclass 
  • You can always pass the generic Collection to the method that take non-generic ones, but you will get compiler warning for it
  • If you will try to add something to the Collection in such method that is not the type of what the Collection is generified, you won't get any exception until you will try to get something from this Collection there you can get ClassCastException. The same exception you will get trying to sort such List.
  • This wildcard <? extends Object> means that the Collection could be parameterized by all subclasses of the Object class and by the Object class itself
  • You couldn't use wildcards in the new instance instantiation (this will give compile error: new ArrayList<? extends Object>())
  • You could use the wildcards in variable declaration: List <? extends Object> list, the same as declaration of method variables
  • You could use wild cards when declaring the returning type of the method
  •  If variable is using: <? extends Object> this means that you won't add (or set) anything to this Collection
  •  If variable is using: <? super Object> you still could add to this Collection
  •  If you are writting <? super Number> it includes all super classer of number (here only Object class), but doesn't include the Number class itself
  • <? extends Object> is absolutely the same as <?>
  • To generify class you can write: class Foo T, and the use T as the generics type
  • You can use wildcards in class creation generics, but you can use question mark, the usage should look like class Foo<X extends Object>
  • If you create class like: class X <X> than the mentioned in the class X will be considered as the generic type
  • It is possible to use few generic types in one class, like: class Foo <X, Y>
  • You can generify the method will look like: <T> void T(){}. So the generic type should go exactly before the method return type
  • During overriding you could override the method that using generic return or input values with concrete classes, but the generic of child class should correctly set up with these concrete classes





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