Wednesday, September 20, 2017

Monitor Oracle sequence

In Oracle database, sequence is the way to generating unique key for records.
But there is max number limit till you can generate the key. You need to monitor sequence number growth rate. If it reach a threshold you need to do defragmentation in the table.


You can run the below sql from monitoring tool or as a crontab script. It will show utilization percentage of the sequence.
 

SELECT S.SEQUENCE_OWNER,
       S.SEQUENCE_NAME,    
       TO_CHAR( S.LAST_NUMBER,'99999999999999999999')   CURRENT_VALUE, 
      TO_CHAR( (S.LAST_NUMBER +S.INCREMENT_BY),'99999999999999999999')    NEXT_VALUE ,        
       TO_CHAR( S.MAX_VALUE,'99999999999999999999')  MAX_VALUE ,
       TO_CHAR( S.MIN_VALUE,'99999999999999999999')   MIN_VALUE,
       (S.MAX_VALUE - S.LAST_NUMBER) AS AVAILABLE_BAN,
     TRUNC(  (( S.LAST_NUMBER-S.MIN_VALUE)*100)/(S.MAX_VALUE- S.MIN_VALUE),2) 
|| '%' AS UTILIZATION  FROM DBA_SEQUENCES S
WHERE SEQUENCE_NAME IN (''TEST_SEQ1' ,'TEST_SEQ2'  )AND SEQUENCE_OWNER = 'TEST' 
ORDER BY  
TRUNC(  (( S.LAST_NUMBER-S.MIN_VALUE)*100)/(S.MAX_VALUE- S.MIN_VALUE),2) DESC;






Monday, August 8, 2016

Working with Github

Github is most popular  free project hosting site. You can git repository and upload your project with following steps.

  1.   Create Project repository in  in Github and copy the repository http URL 
  2.    Install git client in you local machine.
  3.    Goto directory where you want to checkout  the code. Right click on directory and select 'Git Bash here' from menu. It will open git bash console
  4. In git console run git clone command.  
    $ git clone https://github.com/sujanctg2005/oracle.git
  5.  Change directory to  oracle
    $ cd oracle/
  6. Check  git status
    $ git status
  7. Modify the files you want to push in git hub
  8. Add modified files in local git repository
    $ git add *
  9. Commit modified files in local git repository
    $ git status
    $ git commit -m 'comments' *
  10. Now you can push modified files in git repository
    $ git status
    $ git push https://github.com/sujanctg2005/oracle.git

    This push command will prompt for Github user-name and password. You can verify the push just browsing that git repository in online.

Oracle Dynamic SQL

You can create SQL statement dynamically and make the script more generic to make it work with any table.
  DECLARE
    TYPE COL_TYPE IS TABLE OF VARCHAR2(40);
    COL_NAME COL_TYPE;
    COL_DATA_TYPE COL_TYPE;
    TAB1_NAME VARCHAR2(30) :='A_USERS'; 
  BEGIN
      SQL_STMT := 'SELECT COLUMN_NAME,DATA_TYPE FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '''|| TAB1_NAME ||'''';
       EXECUTE IMMEDIATE SQL_STMT   BULK COLLECT INTO COL_NAME ,COL_DATA_TYPE;
  END;
 /

Oracle 'EXECUTE IMMEDIATE' will help you to run dynamic sql. If   sql command return data  you can store it in a variable. Above example, SQL statement will return  columns name and data type of a table and it will be store in COL_NAME ,COL_DATA_TYPE variable. You can access value from COL_NAME array in following way.
FOR INDX IN 1 .. COL_NAME.COUNT 
   LOOP   
       DBMS_OUTPUT.PUT_LINE ('COL_NAME: ' || COL_NAME(index));
  END LOOP;


Also if you can create separate code block and pass bind variable   P_REC and IN T_REC  value while executing the statement and output will be store in MISS_MATCH variable.
 
 DECLARE
 P_REC  A_USERS%ROWTYPE;
  T_REC  A_USERS%ROWTYPE;
 BEGIN
               SQL_STMT :=  'DECLARE 
                          P_REC  '|| TAB1_NAME ||'%ROWTYPE; 
                          T_REC  '|| TAB2_NAME ||'%ROWTYPE;  
                       BEGIN    P_REC := :P_REC;  T_REC := :T_REC;   
                       SELECT DECODE(P_REC.' || COL_NAME(INDX) || ',T_REC.' || COL_NAME(INDX) || ',0,1)
INTO :MISS_MATCH FROM DUAL;                       
        
           EXECUTE IMMEDIATE SQL_STMT USING IN  P_REC , IN T_REC , OUT MISS_MATCH;
  END;
/



Replication data compare for oracle golden gate

For high availability  we need database replication, so during fail-over we can switch to standby database. Oracle golden gate provide data replication between data-centers. Replication is mainly depend on last updated time stamp. Oracle golden gate will check transaction time-stamp and replay it in another data-center. But sometime replication doesn't happen properly because of  application' defect on updating time stamp.


One or more applications can use same database and they may be locate in different time-zone. If one application is updating data using one time-zone in a active database and another application is updating data with different  time-zone in another database,  such case replication between these two database  will make database in-consistent state.


To find out data in-consistency we can compare one site data table with another site same table. For example  we have table name 'customer' in database and data is replicating for this table on two active database A and B . If we want to compare data for this table, we can export customer table from A and B into a new database schema, so data comparison job will not impact the running database.

If the table contain only some configuration data, number of records might be less. But customer table can contain millions of record, therefore comparing data become very time consuming.
We can overcome this problem using oracle 'DBMS_PARALLEL_EXECUTE' package. This will allow you to logically split table using table rowid and create job for each partition and run them parallel. You can partition table using different columns as well.

Below snapshot is to create job using oracle 'DBMS_PARALLEL_EXECUTE' package.

 
 DECLARE 
  TASK_NAME VARCHAR2(40) :='A_B_DATA_COMPARE';
  UPDATE_STATEMENT CONSTANT VARCHAR2 (200)
      :=  'BEGIN DATA_COMP(:start_id, :end_id); END;';
 BEGIN
         DBMS_PARALLEL_EXECUTE.CREATE_TASK (TASK_NAME);       
         DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID (TASK_NAME => TASK_NAME, TABLE_OWNER => USER , TABLE_NAME => TAB1_NAME , BY_ROW => TRUE , CHUNK_SIZE => 800000  );
         DBMS_PARALLEL_EXECUTE.RUN_TASK (TASK_NAME => TASK_NAME , SQL_STMT => C_UPDATE_STATEMENT  , LANGUAGE_FLAG => DBMS_SQL.NATIVE  , PARALLEL_LEVEL =>64  );
       EXCEPTION
              WHEN OTHERS  THEN 
                  DBMS_OUTPUT.PUT_LINE('FAIL TO RUN  JOBS, ERROR CODE:' ||SQLCODE);
                  RETURN;
 
    
         
 END;


You can pass number concurrent jobs, partition size and more importantly which procedure or function it will call with start rowid and end rowid.  In the above example DBMS_PARALLEL_EXECUTE will partition customer table by rowid and each partition will contain 800000 record. Then it will call DATA_COMP procedure with a partition start rowid and end rowid. You can select record using rowid and loop through them using oracle cursor.

 
      DECLARE 
   TASK_NAME VARCHAR2(40) :='A_B_DATA_COMPARE';
  UPDATE_STATEMENT CONSTANT VARCHAR2 (200)
      :=  'BEGIN DATA_COMP(:start_id, :end_id); END;';
     BEGIN
         DBMS_PARALLEL_EXECUTE.CREATE_TASK (TASK_NAME);       
         DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID (TASK_NAME => TASK_NAME, TABLE_OWNER => USER , TABLE_NAME => TAB1_NAME , BY_ROW => TRUE , CHUNK_SIZE => 800000  );
         DBMS_PARALLEL_EXECUTE.RUN_TASK (TASK_NAME => TASK_NAME , SQL_STMT => C_UPDATE_STATEMENT  , LANGUAGE_FLAG => DBMS_SQL.NATIVE  , PARALLEL_LEVEL =>64  );
       EXCEPTION
              WHEN OTHERS  THEN 
                  DBMS_OUTPUT.PUT_LINE('FAIL TO RUN  JOBS, ERROR CODE:' ||SQLCODE);
                  RETURN;
       END;
    
    


This way you compare data more faster way, since it will parallel.   Inside the cursor loop you can pull record from another table using primary key and compare the record by each column of A and B database customer table.

You can can get complete oracle  PL/SQL example in Github. I make the script dynamic, so only you need to pass compare  two tables  and report  table name.






Wednesday, August 19, 2015

Load balancer using Apache mod_proxy

First install Apache server. You can download it from http://httpd.apache.org/. For  this example  I have used  httpd-2.2.25-win32-x86-openssl-0.9.8. You can get it from Apache archive.


After  Apache installation complete, you might need to change the port 80 to some other port e.g 8000  if 80 port is block. You can change the port in httpd.conf file which located under   conf  folder.

Listen 8000

Bellow is an example how we can use mod_proxy_balancer to provide load balancing for three back-end server. You need to add following snippet at the bottom of the htttpd.conf. Then restart the server.

 
<Proxy balancer://mycluster>
BalancerMember http://localhost:9001
BalancerMember http://10.83.57.247:7001
BalancerMember http://wabothdk0544042:7001
</Proxy>
ProxyPass / balancer://mycluster/
ProxyPassReverse / balancer://mycluster/ 

Now if you open the URL http://localhost:8000 in browser, request will be forward to one of the back-end server. You can test it by looking server logs.

Tuesday, March 25, 2014

Create Proxy Service for secure web service call using Mule ESB

Mule is open source Enterprise Service Bus. You can create proxy service of a web-service easily with mule. You can transform request and response payload using Mule XSLT transformation.

Following figure is showing diagram of Mule proxy service and XSLT transformation.



Below is configuration XML.

 
  
   
  
  
   
  

 

 
  
  


  
  

  

  

   
    
     
     
     
     
     
    
   
   
    
   
   
    
   
  

  


  



  
   
    
     

    
   
   
    
     
    
   
  

 

To set password following code snippet is used for password callback
package lr.mule.security;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class PasswordCallback implements CallbackHandler
{
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
    {
        WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];

       
         
            pc.setPassword("password");
       
       
    }
}

Thursday, March 6, 2014

How to resolve Java SSL certificate error PKIX path building failed

If you found following error while connecting a secure server

"org.apache.axis2.AxisFault: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"

follow the below step to resolve the issue.

Step 1. Go to your Mozilla Firefox and browse the server URL and follow the highlighted steps.


Step 2. Download the certificate by following highlighted steps and save it to location direction with file extension ".crt", e.g: example.crt.

       


Step 3. Now open command prompt with "run as administrator" and run the following command

keytool -import -trustcacerts -file F:\qatoes002.unix.gsm1900.org.crt -alias CA_ALIAS -keystore "%JAVA_HOME%/jre/lib/security/cacerts"

it might ask password if needed then ask server administrator.

Certificate will be store in JDK home. If you are using eclipse IDE for development, make sure you are using same JDK home.




Using Unix Command:


echo -n | openssl s_client -connect HOST:PORT | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

echo -n | openssl s_client -connect localhost:5116 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert


 /opt/msdp/local/jdk1.8.0_51/bin/keytool -importcert -file /tmp/$SERVERNAME.cert  -keystore keystore1.jks -alias "Alias1"

Reference:
https://www.digitalocean.com/community/tutorials/java-keytool-essentials-working-with-java-keystores

Monday, February 24, 2014

Selenium webdriver Junit test example

Selenium is one of the best tool for automating web application testing. If number of pages of web application increase gradually, it is really hard for application tester to test every page after new deployment.

Selenium provide web driver for almost browser including firefox, IE, Google Chrome etc. Even you can integrate selenium web driver with Junit, TestNG or plan Java, .Net code.

Selenium provide two type of web drivers. Browser base driver like FirefoxDriver will open the Firefox browser and perform the test. In this case, Selenium will fill up all fields and click on necessary places, just like an automated robot. But if you want to write test cases that does't require browser then you can use  HtmlUnitDriver. It will create instance of in-memory browser. But browser base driver is important when you want to test your application whether its compatible with all modern browser like Google chrome, Firefox and IE.

You can download Selenium library from  http://docs.seleniumhq.org/download/.

However, you can add it in your project as maven dependency.
   
  
   org.seleniumhq.selenium
   selenium-java
   2.39.0
   
    
     org.seleniumhq.selenium
     selenium-iphone-driver
    
    
     xml-apis
     xml-apis
    
   
  
Following snippet  is showing initialization of Firefox web driver and HtmlUnitDriver.

Create a new instance of the html unit driver
private WebDriver driver= new HtmlUnitDriver();

 // Create a new instance of the Firefox driver
private WebDriver driver= new FirefoxDriver();


Here is an example showing how to perform login before test any secure page. In Junit @BeforeClass annotation method will be called before run any test case.


@BeforeClass
 public static void setUpBeforeClass() throws Exception {

  entity = new Users("moin", "123", "abc@gmail.com", "xyz",
    "");
         // Create a new instance of the html unit driver
  driver = new HtmlUnitDriver();
              
                // And now use this to visit your login URL. e.g 
  driver.get(serverBaseUrl + "/login");
                // set the user name in user id text field
  driver.findElement(By.name("j_username"))
    .sendKeys(entity.getUserName());
                 // set the password in user password text field
  driver.findElement(By.name("j_password"))
    .sendKeys(entity.getPassword());

  driver.findElement(By.className("pull-right")).click();
  System.out.println(driver.getPageSource());
  if (driver.findElement(By.cssSelector(".jumbotron")).getText()
    .contains("Welcome to ScrapperX")) {

   System.out.println("Login Success");
  } else {
   System.out.println("Login fail");
   throw new Exception("Login Require");

  }

  Thread.sleep(1000);
 }

After login you can test any secure page in the same session. Below snippet is showing how to test "update user profile page"
 
       @Test
 public void testUpdateProfile() {
  driver.get(serverBaseUrl + "/users/editprofile");
                // clear the exist first name or else sendKeys will append new text
  driver.findElement(By.name("firstName")).clear();
  driver.findElement(By.name("firstName"))
    .sendKeys(entity.getFirstName());
  driver.findElement(By.name("lastName")).clear();
  driver.findElement(By.name("lastName")).sendKeys(entity.getLastName());
  driver.findElement(By.name("password")).clear();
  driver.findElement(By.name("password")).sendKeys(entity.getPassword());
  driver.findElement(By.name("c_password")).clear();
  driver.findElement(By.name("c_password"))
    .sendKeys(entity.getPassword());
    // in several way you can select a checkbox
                 /*
   * List checkbox =
   * driver.findElements(By.name("paymentActive")); ((WebElement)
   * checkbox.get(0)).click();
   */
                // select paymentActive checkbox
  WebElement checkbox = driver.findElement(By.name("paymentActive"));
             
  if (checkbox.isSelected() == false) {
   checkbox.click();
  }

  driver.findElement(By.className("btn")).click();
  System.out.println(driver.findElement(By.cssSelector(".alert"))
    .getText());
  assertTrue("Update user profile fail",
    driver.findElement(By.cssSelector(".alert")).getText()
      .contains("Update Complete"));
 }


You can access any field or html element by css class name, id and field name. Following example is showing how to select a drop-down option.
   Select cardTypeDropDown = new Select(driver.findElement(By
    .name("cardType")));
   cardTypeDropDown.selectByValue("visa");

Here is an working example of testing Google search.
package com.scrapperx.web.controller;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GoogleSearchTest {

 @Test
 public void testGoogleSearch() throws InterruptedException {
  // Create a new instance of the html unit driver
  // Notice that the remainder of the code relies on the interface,
  // not the implementation.
  System.out.println("http://www.google.com");
  WebDriver driver = new FirefoxDriver();

  // And now use this to visit Google
  driver.get("http://www.google.com");

  // Find the text input element by its name
  WebElement element = driver.findElement(By.name("q"));

  // Enter something to search for
  element.sendKeys("tometo");

  // Now submit the form. WebDriver will find the form for us from the
  // element
  element.submit();

  // Check the title of the page
  System.out.println("Page title is: " + driver.getTitle());
        Thread.sleep(10000);
  driver.quit();

 }
}

Saturday, February 22, 2014

Bootstrap autocomplete using Typeahead JS

Typeahead provide very good solution for auto complete suggestion. Here is an example showing auto suggestion based on user query. When user type a keyword, a json request will be send to server side and response will be appeared right bottom of search field.
  
 

Thursday, February 20, 2014

Java junit lifecycle methods

 JUnit is more popular framework for unit testing in java.  JUnit provide four life cycle methods for each test case class.

 @BeforeClass and @AfterClass anotation used before methods which are called by framework once for all test case.

@Before  and @After are used on methods which are called before and after any test method run.

Here is an example code snippet.



package com.test;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class ExampleTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  
  System.out.println("Before all test case execution");
 }

 @AfterClass
 public static void tearDownAfterClass() throws Exception {
   System.out.println("After all test case execution");
 }

 @Before
 public void setUp() throws Exception {
    System.out.println("Before single test case execution");
 }

 @After
 public void tearDown() throws Exception {
  System.out.println("After single test case execution");
 }

 @Test
 public void testMethod1() {
   System.out.println("a");
 }

 @Test
 public void testMethod2() {
   System.out.println("b");
 }

}


Tuesday, August 27, 2013

Deploy war to WebLogic using Maven

First off you need Maven and Weblogic setup in your computer to start this tutorial.
My Weblogic(10.3.6.0) has setup under : C:\Oracle\Middleware.

Set Middleware home :
 
set MW_HOME=C:\Oracle\Middleware

1. Build the plug-in JAR file using the WebLogic JarBuilder Tool (wljarbuilder) under %MW_HOME%/wlserver_10.3/server/lib/ with the following command:
 
java -jar wljarbuilder.jar -profile weblogic-maven-plugin
The weblogic-maven-plugin.jar contains a Project Object Model (pom.xml) file which specifies the groupId, artifactId, version, and packaging of the weblogic-maven-plugin.jar:
 groupId=com.oracle.weblogic
artifactId=weblogic-maven-plugin
version=10.3.6.0
packaging=maven-plugin

2. Extract the pom.xml file from weblogic-maven-plugin.jar under the %MW_HOME% wlserver_10.3/server/lib directory, and then copy the pom.xml file to %MW_HOME%/wlserver_10.3/server/lib.
 
jar xvf %MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar META-INF/maven/com.oracle.weblogic/weblogic-maven-plugin/pom.xml


copy %MW_HOME%/wlserver_10.3/server/lib/META-INF/maven/com.oracle.weblogic/weblogic-maven-plugin/pom.xml  to %MW_HOME%//wlserver_10.3/server/lib/pom.xml

Add following in your project pom.xml file:


3.Provision the weblogic-maven-plugin.jar in your local Maven repository with the following command. However, for a shortened command-line goal invocation of the plug-in, follow the directions in next step 4 before performing this step.
http://docs.oracle.com/cd/E21764_01/web.1111/e13702/maven_deployer.htm
 
mvn install:install-file -Dfile=%MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar -DpomFile=pom.xml



4.
  you can shorten the full invocation of the plug-in by providing a pom.xml file  and modifying the settings.xml file located in your $HOME/.m2 directory, before you provision the plug-in in your Maven repository
  1. Change the settings.xml file as follows:
    
    
    
       
       com.oracle.weblogic
     

 b. Replace the %MW_HOME%/wlserver_10.3/server/lib/pom.xml file with the following(Use same version that was in the pom.xml):




  4.0.0
  com.oracle.weblogic
  weblogic-maven-plugin
  maven-plugin
  10.3.4
  Maven Mojo Archetype
  http://maven.apache.org
  
    
      org.apache.maven
      maven-plugin-api
      2.0
    
  
 
  
   
      
       maven-plugin-plugin
       2.3
       
         weblogic
       
      
    
  
 


From within MW_HOME/wlserver_10.3/server/lib/, run the mvn install command.

mvn install

From within MW_HOME/wlserver_10.3/server/lib/, provision the weblogic-maven-plugin.jar in your local Maven repository as follows:

mvn install:install-file -Dfile=%MW_HOME%/wlserver_10.3/server/lib/weblogic-maven-plugin.jar -DpomFile=pom.xml

Now, you can use a shortened command-line goal invocation, such as:

mvn weblogic:deploy

Deployment Goals
weblogic.deploy
weblogic:undeploy
weblogic:redeploy
weblogic:start-app
weblogic:stop-app
weblogic:list-apps
weblogic:update-app
weblogic:help


  

Create Oracle Stored Procedure example

Following is a basic oracle store procedure example:

CREATE OR REPLACE PROCEDURE procPrintHelloWorld
IS

 usr_id VARCHAR2(20):=' sujan ';
BEGIN
 
  DBMS_OUTPUT.PUT_LINE('Hello World!'|| usr_id);
 
END;
/
To see output on console you need to run following command.

 set serveroutput on size 30000;

Run store procedure:


 EXEC procPrintHelloWorld;

If you get any compilation error, run following command to display it.

SHOW ERRORS

Friday, August 16, 2013

Add SVN email notification

SVN email notification is important when many programmer involves  in software development. For example, you are working on module and other programmers are using that. So if you check-in updated the classes , you have to notify other developers that module has been updated.

SVN provide post commit hook option, there you can add any script or programme that would be execute after SVN commit. Here I will add email notification in post-commit hook script.

I have create a repository in /apps/subversion/hsolite/.
Using ls command you can see default directories created under repository. There is a directory called hooks where you will put you post-commit script. When any user will commit in SVN, post-commit script will be execute.


To send email notification you need find out "mailer.py" and "mailer.conf"

[root@domU-12-31-39-09-29-13 hsolite]# find / -name "mailer.py"
/usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/mailer.py


[root@domU-12-31-39-09-29-13 hsolite]#  find / -name "mailer.conf"
/usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/tests/mailer.conf

Now copy the mailer.py and mailer.conf  under /apps/subversion/hsolite/hooks and  /apps/subversion/hsolite/ respectively.

[root@domU-12-31-39-09-29-13 hsolite]#  cp /usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/mailer.py   /apps/subversion/hsolite/hooks/mailer.py

[root@domU-12-31-39-09-29-13 hsolite]# cp  /usr/share/doc/subversion-1.6.11/tools/hook-scripts/mailer/tests/mailer.conf   /apps/subversion/hsolite//mailer.conf

Now edit the mailer.conf and override following properties

mail_command = /usr/sbin/sendmail
commit_subject_prefix = [svn-myproject]
from_addr = noreply@mydomain.com
to_addr = commits-myproject@mydomain.com  # this is a mailing list


Under hooks directory you will find "post-commit.tmpl" that you need to rename to "post-commit".

Replace "post-commit" script  contains with the following snippet.
------------------------------------------------
#!/bin/sh

REPOS="$1"
REV="$2"

/apps/subversion/hsolite/hooks/mailer.py commit "$REPOS" "$REV" /apps/subversion/hsolite/mailer.conf

-------------------------------------------------------

Make sure "post-commit" is executable.
[root@domU-12-31-39-09-29-13 hsolite]# chmod +x post-commit


Testing :
Using svnlook  yon can get latest revision number.

[root@domU-12-31-39-09-29-13 ~]# svnlook info /apps/subversion/hsolite/
sujankn
2013-08-16 07:41:29 -0400 (Fri, 16 Aug 2013)
0

[root@domU-12-31-39-09-29-13 ~]# svnlook youngest /apps/subversion/hsolite/
2850

Test the hook script:

[root@domU-12-31-39-09-29-13 ~]# REPOS=/apps/subversion/hsolite/
[root@domU-12-31-39-09-29-13 ~]#  REV=2850
[root@domU-12-31-39-09-29-13 ~]#  "$REPOS"/hooks/mailer.py commit "$REPOS" $REV "$REPOS"/mailer.conf 

After run above command you should receive email notification with revision number 2850

[root@domU-12-31-39-09-29-13 ~]# REPOS=/apps/subversion/hsolite/
[root@domU-12-31-39-09-29-13 ~]#  REV=2850
[root@domU-12-31-39-09-29-13 ~]#   sh $REPOS/hooks/post-commit  $REPOS$REV
If post-commit script run successfully then commit some files in SVN then check your email inbox for notification.

Monday, August 5, 2013

Weblogic JPA 2.0 configuration

If you find following exception in webloginc while running JPA 2.0 web application
Caused By: java.lang.NoSuchMethodError: javax.persistence.spi.PersistenceUnitInfo.getValidationMode()Ljavax/persistence/ValidationMode;

you need to add following line in commEnv.cmd( located at %BEA_HOME%\wlserver_10.3\common\bin\) just after  "set BEA_HOME=C:\Oracle\Middleware"


set PRE_CLASSPATH=%BEA_HOME%\modules\javax.persistence_1.1.0.0_2-0.jar;%BEA_HOME%\modules\com.oracle.jpa2support_1.0.0.0_2-1.jar

Then restart your server again.


Increase Weblogic heap size

Go to your domain bin directory and find setDomainEnv.cmd.
For example:
C:\Oracle\Middleware\user_projects\domains\base_domain1\bin\setDomainEnv.cmd.

Open it in any text editor and find following block.  Change -Xms1G -Xmx1G

if "%JAVA_VENDOR%"=="Sun" (
set WLS_MEM_ARGS_64BIT=-Xms1G -Xmx1G
set WLS_MEM_ARGS_32BIT=-Xms1G -Xmx1G
) else (
set WLS_MEM_ARGS_64BIT=-Xms1G -Xmx1G
set WLS_MEM_ARGS_32BIT=-Xms1G -Xmx1G
)

Wednesday, July 24, 2013

Install SOA suit in Linux from Windows using Reflection X

SOA suite 11g (11.1.1.2) is installed inside the middleware directory structure. Launch Reflection X software on your local workstation and export DISPLAY variable to point to your IP:0.0 before starting the installer. 

  1. Launch Reflection X tool from your workstation 
  2. Export DISPLAY variable to :0.0
  3. cmsfndev@aldapux04b $ export DISPLAY=172.25.26.91:0.0
  4. Add 64-bit JRE installed earlier to PATH
  5. asufndv2@apux206n $ export PATH=$HOME/ jdk/bin: $PATH
  6. Launch installer from Disk1
  7. asufndv2@apux206n $ ./runInstaller -jreLoc /appl/fusn/asufndv2/jdk

Sunday, March 25, 2012

Spring bean scope annotation example

Spring bean instance will be created depend on scope specified on that bean , spring container support five types of scope
  • singleton – Return a single bean instance per Spring IoC container
  • prototype – Return a new bean instance each time when requested
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session.
Spring container default scope is singleton , so you have to be careful before use bean instance . In multi-thread environment , singleton instance must be thread safe to avoid race condition . In that situation you might use prototype scope. Other three scopes are only valid in the context of a web-aware Spring ApplicationContext.
Example
Here is an example to explain difference between singleton and prototype .
1. Singleton Example: Since no bean scope is specified ,default to singleton
package com.example.springscope;

import org.springframework.stereotype.Service;

@Service("userService")
// default scope is Singleton
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}


Configuration XML : component-scan will allow us to use annotation base bean declaration and enable auto component scan. All beans declared in com.example and its child package will be available in spring context.


 
 


Test example :
package com.example.springscope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is singleton , same instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);
 }

}


Output :
 Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : 1 Name :Jeff]


In this example Id and name has been set on the customerA but same value is also showing on customerB , because of singleton scope. Spring container will create only one object for singleton scope , that will be return to caller every time.
Prototype Example
If you want new instance every time , you have to use prototype scope .
 package com.example.springscope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("userService")
@Scope("prototype")
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}

Test Example :
package com.example.springscope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is prototype , new instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);   // all fields value will be null
  
  customerB.setId(2);
  customerB.setUserName("Jhon");
  System.out.println(" Customer Info B:" +customerB);  
  
 }

}


Output :
  Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : null Name :null]
 Customer Info B:[ ID : 2 Name :Jhon]


You can download this example project from github https://github.com/sujanctg2005/Example

Saturday, March 24, 2012

Some Useful Java File Operations and Utility methods

File Modification, Copy, delete and create new file is quite easy in java programming. Here I wrote some java file operation utility method that might be useful for your application.  

Java File Copy Method
public static void copyfile(String srFile, String dtFile) throws Exception {

File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);

// For Append the file.
// OutputStream out = new FileOutputStream(f2,true);

// For Overwrite the file.
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {

 out.write(buf, 0, len);
}
in.close();
out.close();

}

Java Delete File Method
public static void removeFile(String fileName) throws Exception {

File file = new File(fileName);

if (file.exists()) {
 boolean success = file.delete();
 if (!success) {
  throw new Exception("Fail to delete existing file");
 }
}

}

Java Rename File Method
public static void renameFile(String oldName, String newName) throws IOException {
   File srcFile = new File(oldName);
   boolean bSucceeded = false;
   try {
       File destFile = new File(newName);
       if (destFile.exists()) {
           if (!destFile.delete()) {
               throw new IOException(oldName + " was not successfully renamed to " + newName);
           }
       }
       if (!srcFile.renameTo(destFile))        {
           throw new IOException(oldName + " was not successfully renamed to " + newName);
       } else {
               bSucceeded = true;
       }
   } finally {
         if (bSucceeded) {
               srcFile.delete();
         }
   }
}

Java List of files in specified directory with filter option
  
List fileList = FileUtil.dirlist(sourceLocation, "*.csv");

 public static List dirlist(String path, String filter) throws FileNotFoundException {

   File dir = new File(path);
   
   FileFilter fileFilter = new WildcardFilter(filter);
    File[] chld = dir.listFiles(fileFilter);  
   
   List fileList = new ArrayList();
   
   if (chld == null) {
    log.error("Specified directory does not exist or is not a directory.");
    throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
    
    
   } else {
    for (int i = 0; i < chld.length; i++) {
     File file = chld[i];
     
     if(file.isFile()) {
      fileList.add(file);
     }
     
    }
   }
   return fileList;
  }

Java List of files in specified directory
public static List dirlist(String path) throws FileNotFoundException {
  File dir = new File(path);
  File[] chld = dir.listFiles();
  List fileList = new ArrayList();
  
  if (chld == null) {
   log.error("Specified directory does not exist or is not a directory.");
   throw new FileNotFoundException("Specified directory does not exist or is not a directory.");
   
  } else {
   for (int i = 0; i < chld.length; i++) {
    File file = chld[i];
    
    if(file.isFile()) {
     fileList.add(file);
    }
    
   }
  }
  return fileList;
 }

Thursday, March 15, 2012

Bind Oracle Listener with SID

Most of the time when we try to access oracle database from outside of localhost using oracle client or JDBC driver , we will get "ORA-12505, TNS:listener does not currently know of SID given in connect descriptor" error. But database can be accessible from local machine . To avoid this problem we need follow this steps.
  1. Go to Oracle Net Manager from All Program> Oracle> Configuration and Migration Tool> Oracle Net Manager,
  2. In Oracle Net Manager ,change oracle listener host name "Localhost" to database server IP or server full domain name , e.g : 60.84.278.155 or db.acm.com.
  3. Then you need to save change by clicking File>Save Network Configuration.
  4. Do not forget to add listener port into firewall if your firewall is enable.
  5. Next you have to bind your listener with oracle SID. For this you will change listener.ora. You will get this file into Oracle_HOME\NETWOReK\ADMIN . e.g C:\app\Administrator\product\11.2.0\dbhome_2\NETWORK\ADMIN\listener.ora. Add this in your listener.ora
    SID_LIST_LISTENER =
    (SID_LIST =
    (SID_DESC =
    (SID_NAME = orcl)
          (ORACLE_HOME = C:\app\Administrator\product\11.2.0\dbhome_2)
    
    )
    )
    
    
  6. Restart Listener to effect the change. In command prompt type following command to restart listener.
       
      lsnrctl stop
      lsnrctl start
    
Finally you will be to connect to database from outside of localhost successfully .

Monday, November 16, 2009

Maven Hello World(Part 1)

-->
Why Maven with Eclipse
Eclipse is an industry leader in IDE market, it is used very extensively in developing projects all around the world. Similarly, Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management. Maven–Eclipse Integration makes the development, testing, packaging and deployment process easy and fast. Maven Integration for Eclipse provides a tight integration for Maven into the IDE and avails the following
features: · It helps to launch Maven builds from within EclipseIt avails the dependency management for Eclipse build path based on Maven's pom.xml · It resolves Maven dependencies from the Eclipse workspace without installing to local Maven repository · It avails an automatic downloading of the required dependencies from the remote Maven repositories · It provides wizards for creating new Maven projects, pom.xml or to enable Maven support on plain Java project · It helps to search quickly for dependencies in Maven remote repositories · It quickly fixes in the Java editor for looking up required dependencies/jars by the class or package name. What do you Need? 1. Get the Eclipse Development Environment : In this tutorial we are using the SpringSource Tool Suite .This tool based on eclipse and maven is integrate with this , so no need to download or configure maven with eclipse , which can be downloaded from http://www.springsource.com/products/springsource-tool-suite-download Download and Install Eclipse First download and install the SpringSource Tool Suite on your development machine . Steps to create maven web project 1.Open eclipse IDE and go to File->New-> Other.. as shown in Figure 1 below:

1. Select maven ->maven project as shown in Figure 2 below: Click next->next-> in Filter field type 'webapp' and select group id org.apache.maven.archetypes as shown in Figure 3 below: Click next-> give group id name 'com.testmaven' and artifact ' hello' ,other option remain default as shown in Figure 4 below: Click finish . Select Project hello and run on server select springsource dm server and click finish (you can add any server such as tomcat by manually define a new server) Now you can see Hello World out put in the browser