Thursday, December 16, 2010

Mysql Triggers Example

Mysql triggers are like schedulers run on table changes.  When INSERT, DELETE, UPDATE command executions, these triggers are executed automatically.

Below is a sample of SQL commands to create and test Triggers when insert happens to "test1" table.

Create below four tables and insert values into "test3" & "test4" tables.

Trigger

This Trigger is executed when insert happens into "test1" table. It gets "test1.a1" value and insert it into "test2" table. And, delete it from "test3" table. Update  "test4" b4 value.

Create Tables

CREATE TABLE test1(a1 INT);
CREATE TABLE test2(a2 INT);
CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE test4(
a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
b4 INT DEFAULT 0
);

Create Trigger

delimiter |
CREATE TRIGGER testref BEFORE INSERT ON test1
FOR EACH ROW BEGIN
INSERT INTO test2 SET a2 = NEW.a1;
DELETE FROM test3 WHERE a3 = NEW.a1;
UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
END;
|

Insertions

delimiter ;
INSERT INTO test3 (a3) VALUES
(NULL), (NULL), (NULL), (NULL), (NULL),
(NULL), (NULL), (NULL), (NULL), (NULL);

INSERT INTO test4 (a4) VALUES
(0), (0), (0), (0), (0), (0), (0), (0), (0), (0);

Executes following SQL to run the Trigger.
INSERT INTO test1 VALUES (1), (3), (1), (7), (1), (8), (4), (4);

Monday, November 15, 2010

IReport dynamic table sql

In IReport tool, you can dynamically generate SQL by changing table name.

1) Create parameter for table name. Ex :- $P{tableName}
2) Change IReport SQL as following.

      SELECT * FROM $P!{tableName}

Wednesday, November 10, 2010

limit Resultset size in informix

Use the following SQL to limit the size of the result set in informix. 

SELECT FIRST 1 * FROM orders

Tuesday, October 26, 2010

Get map for latitude & longitude using Google Maps API

Google provides a FREE Java Script map API for longitude & latitude. Simple demonstration is given below. Position marker, mouse wheel zooming, Map view/Satelite view/Hybrid view controls are enabled in the example.

NOTE :- Map searching is commented.

<html>
<head>
<script type="text/javascript"
src="http://www.google.com/jsapi?key=ABCDEFG"></script>
<script type="text/javascript">
google.load("maps", "2");
// google.load("search", "1");
// Call this function when the page has been loaded

function initialize() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(7, 80), 13);
map.enableRotation();
map.addControl(new GOverviewMapControl());
map.enableDoubleClickZoom();
map.enableScrollWheelZoom();
map.addControl(new GMapTypeControl());

map.addControl(new GSmallMapControl());

var marker = new GMarker(new GLatLng(7, 80));
map.addOverlay(marker);
map.setMapType(G_SATELLITE_MAP);

// var searchControl = new google.search.SearchControl();
// searchControl.addSearcher(new google.search.WebSearch());
// searchControl.addSearcher(new google.search.NewsSearch());
// searchControl.draw(document.getElementById("searchcontrol"));
}

google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="map" style="width: 500px; height: 500px"></div>
<!-- <div id="searchcontrol"></div> -->
</body>
</html>

Reference :- http://code.google.com/apis/ajax/documentation/ 

Tuesday, October 12, 2010

Shell Script to load data from a TableA to TableB in mysql

Suppose you have to select custom fields in TableA and insert those fields into TableB in mysql, then the following shell script command would be appropriate.

mysql -u user -p -D database -e 'insert into TableB select id, addr from TableA;'

Insert above code in a file and save it as ".sh" file extension. Then run it as "./Test.sh".

NOTE :- Test.sh must be stored in the server that mysql db server is running.

Thursday, October 7, 2010

Remove non empty directory in linux

Use the below command to remove non empty directory in Linux without prompting for verification "yes" or "no".

rm -rf directory

This will remove all the contents in the directory without asking further verifications for files deletion.

Monday, August 30, 2010

File download using Struts

In some developments, you have to prompt "OPEN/SAVE" dialog for file viewing.
Here is a sample code for file download with the support of the "DownloadAction".

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;


public class ExampleByteArrayDownload extends DownloadAction {

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
   
        String fileName = httpServletRequest.getParameter("fileName");

        String fileExtension =
            fileName.substring(fileName.lastIndexOf("."), fileName.length());

        httpServletResponse.setHeader("Content-Disposition",
                                      "attachment;filename=\"" + fileName +
                                      "\"");
        
        // Download a "pdf" file
        String contentType = "application/pdf";
        byte[] myPdfBytes  = null;              // Get the bytes from somewhere

        return new ByteArrayStreamInfo(contentType, myPdfBytes);
        
    }

    protected class ByteArrayStreamInfo implements StreamInfo {
        
        protected String contentType;
        protected byte[] bytes;
        
        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }
        
        public String getContentType() {
            return contentType;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }
}

Reference
http://wiki.apache.org/struts/StrutsFileDownload

Wednesday, July 28, 2010

Replace String pattern in "Vi"

1) Open the TEXT file using "vi" editor in linux.
2) Press ESC
3) Following command will replace "tab" character by "|".

    :%s/    /|/g

4) Save & quit file using following command.

    :wq!

Monday, July 19, 2010

Java property file usage

Use the below code to read the java property file and retrieve the property value.
 
      Properties properties = new Properties();
        FileInputStream in;
        try {
            in = new FileInputStream("app.properties");
            properties.load(in);
            in.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return properties.getProperty("appcode");

Sample "app.properties" file is shown below.

appcode=50
email=admin@yahoo.com

Tuesday, July 6, 2010

From date < To date validate using js

Use the below js code to validate date "From date < To date"

         var frmDate = document.getElementById("frmDate").value;
         var toDate = document.getElementById("toDate").value;

         if (frmDate < toDate) {
               alert("Invalid Date Range!\nStart Date cannot be after End Date!")
               return false;
           }

Wednesday, June 23, 2010

Solution to dwr session error

Edit your web.xml file and and the following code.

<init-param>
<param-name>crossDomainSessionSecurity</param-name>
<param-value>false</param-value>
</init-param>

Sunday, May 9, 2010

Move large number of files in solaris using "awk"

  • Change directory where your files are located.
  • Use the following "awk" script to move files from one location to another.
  for k in `ls | awk '{print $1}'`; 
  do 
  mv $k destination;
  done

Monday, May 3, 2010

Use java 64 bit version

You have to use 64bit version of java when your memory allocation is larger than 4Gb.

Use -d64 parameter when running the application.

java -d64 -jar -Xms1024m -Xmx4096m Test.jar

Sunday, May 2, 2010

Type Cast in Java Script

In js, variables are created as var type. That means, js engine can cast it to the original type by itself.

parseInt(12) will be converted 12 to an Integer value.

           Example                           Result 
parseInt("12")                          12
parseInt("12.657")                    12
parseInt("12aaaa")                   12
parseInt("aaaa")                NaN (means "Not a Number")

Friday, April 23, 2010

Encrypt, Decrypt password in Mysql

Inserting password encrypted to database using the following sql.

INSERT INTO PASSWORD(pass) VALUES(DES_ENCRYPT('user password')); 

This SQL will encrypt the user inserted password to a encrypted text. In table level, password is unreadable.
Instead of DES_ENCRYPT() method you can come up with your own function.

Selecting password from database to a string.

SELECT DES_DECRYPT(pass) FROM PASSWORD ;

This SQL will return user password as user inserted.



Monday, March 29, 2010

weblogic.xml to use on memory session replication

<?xml version="1.0" encoding="UTF-8" ?>
<weblogic-web-app xmlns="http://www.bea.com/ns/weblogic/90"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-descriptor>
<timeout-secs>300</timeout-secs>
<invalidation-interval-secs>60</invalidation-interval-secs>
<persistent-store-type>jdbc</persistent-store-type>
<persistent-store-pool>SessionDS</persistent-store-pool>
<persistent-store-table>WL_SERVLET_SESSIONS</persistent-store-table>
</session-descriptor>
</weblogic-web-app>

Use the above code for weblogic.xml. Your weblogic cluster MUST be configured to use jdbc persistence store to capture web-browsers and nodes sessions. WL_SERVLET_SESSIONS is the table for session store.

Add this weblogic.xml file to your WEB-INF directory and deploy your application to the weblogic cluster. When a cluster node down, it will replicate all the JSP sessions associates with the clients.

Sunday, March 14, 2010

Add your own jars to weblogic application

Sometimes weblogic server uses its server lib .jars. If you want your application to use your own versions of .jar files, add following code to your weblogic.xml file located in WEB-INF directory.

<container-descriptor>
<prefer-web-inf-classes>true</prefer-web-inf-classes>
</container-descriptor>

This will use libraries in your application.

Thursday, February 25, 2010

Java Application Memory utilization

java -jar -Xms64m -Xmx128m Test.jar

When running your java application, use above arguments. This will allocate 64MB minimum for your application and 128MB maximum. If 128MB exceeds, java will call the garbage collector.

Wednesday, February 10, 2010

Writing console output to a file in java

Use this code to write your console outputs to a file using java.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectIO {

public static void main(String[] args) {

PrintStream orgStream = null;
PrintStream fileStream = null;

try {

// Saving the orginal stream
orgStream = System.out;
fileStream = new PrintStream(new FileOutputStream("d:/123.txt",true));

// Redirecting console output to file
System.setOut(fileStream);

// Redirecting runtime exceptions to file
System.setErr(fileStream);

throw new Exception("Test Exception");

}catch (FileNotFoundException fnfEx){
System.out.println("Error in IO Redirection");
fnfEx.printStackTrace();
}catch (Exception ex){
ex.printStackTrace();
//Gets printed in the file
System.out.println("Redirecting output & exceptions to file");
}finally{
//Restoring back to console
System.setOut(orgStream);
//Gets printed in the console
System.out.println("Redirecting file output back to console");
}
}
}

Saturday, February 6, 2010

Stack Trace of the Exception to a String

Use this code inside your catch block. This will return a string.

}catch(Exception e){

StringWriter sWriter = new StringWriter();
e.printStackTrace(new PrintWriter(sWriter));
System.out.println(sWriter.getBuffer().toString()) ;

}

Tuesday, February 2, 2010

Task Manager in Solaris Console

In console type "prstat".

This will show a program looks like windows Task manager.

Sunday, January 17, 2010

Embed fonts for pdf usng itext

Usually, "consola" font family is not used for pdfs, because it is not available in all systems. Using following code sample, you can embed your interested fonts for pdfs.

Registering regular True type "consola" font.
FontFactory.register("D:\\consola.ttf", "Manning");
FontFactory.getFont("Manning", BaseFont.CP1252, BaseFont.EMBEDDED);
Registering bold True type "consola" font.
FontFactory.register("D:\\consolab.ttf","Manning");
FontFactory.getFont("Manning", BaseFont.CP1252, BaseFont.EMBEDDED);