#htmlcaption1 #htmlcaption2 #htmlcaption3 #htmlcaption4

Thursday, April 4, 2013

Apache ant Build files


Apache ant Build files

 Introduction
Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.

How install Apache Ant (on windows)


The Apache Ant distribution package can be downloading as a zip file from the Apache site and extract it to the location that Ant should install. Then, add the environment variables to the system as follow.

ANT_HOME=path to ant extracted folder
PATH=path to ant folder/bin



Open command prompt and type “ant” will give the result shown below. If this result will receive, then the installation is success.

Buildfile: build.xml does not exist!
Build failed


How work with Ant


In order to execute a build process with Ant, need a build script called “build.xml”. The build script is used to define where the library files are located, where the source code are located, how to compile, make directory , delete directory, make jar file, run jar files, run batch files and many more. In order to do this, it is required to know the basic commands in the Apache Ant. Following example shows the sample build script that compile a simple HelloWorld.java file and  run it.

<?xml version="1.0"?>
<project name="HelloWorld" default="run" basedir=".">
                <property name="src" location="src" />
                <property name="bin" location="bin" />
                <property name="build" location="build" />
                <target name="clean">
                                <delete dir="${bin}" />
                                <delete dir="${build}"/>
                </target>
                <target name="compile" depends="clean" >
<mkdir dir="${bin}" />
                                <javac destdir="${bin}" srcdir="${src}" debug="true"></javac>
                </target>
                <target name="jar" depends="compile">
                                <mkdir dir="${build}"/>
                                <mkdir dir="${build}/jar"/>
                                 <jar destfile="${build}/jar/HelloWorld.jar" basedir="${bin}">
                                                 <manifest>
                                                                <attribute name="Main-Class" value="HelloWorld"/>
                                                </manifest>
                                </jar>
                   </target>
<target name="run">
                                 <java jar="${build}/jar/HelloWorld.jar" fork="true"/>
                </target>
</project> 


 The steps of the build process (methods) can be defined inside the tag “target”. It is possible to give a name for each target and dependency. The dependency means, before run that target the dependent target will be run by the Ant. For an example, if execute compile target, since it depends on the clean target, the clean target will run first. Inside the “property” tag, the source directory, bin directory and other required paths with a logical name can be defined. The name of the project can be defined inside the “project” tag and also the default method that run, if required method does not specify when run the build script. The basedir is defined, from where the relative path should consider. For an example, the folder structure of the “HelloWorld” is as below.

 
                      Folder structure of the “HelloWorld” project

When executing clean target, if there is a directory called “bin” or “build”, that directory will be delete. When executing compile target, a directory will be created called “bin” and java file that inside the “src” folder, will be compiled and class files will be copied in to the bin folder. When executing “jar” target, a directory will be created called “build” and another directory will be created inside that called “jar”. Then the jar file will be created and the main class attribute will be added to the Manifest file of the jar. When executing “jar” target, the jar file will be run and print the result “Hello World”.

String Templates


StringTemplate is a template engine library used for generating text from data structures. StringTemplate's distinguishing characteristic is that it strictly enforces model-view separation unlike other comparable template engines. It is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization. It is also developed for multiple languages, such as Java, C#, Python. Following code show the steps of a simple “Hello World” printing using StringTemplates.

import org.antlr.stringtemplate.*;

StringTemplate hello = new StringTemplate("Hello, $name$");
hello.setAttribute("name", "World");
System.out.println(hello.toString());

Friday, March 29, 2013

disable cache on html5 application

I have developed an android application which continuously get update from a server through AJAX call and there is a PHP file on the server which respond to the AJAX request. My application working properly in localhost. But after i install the application on my android phone, First two or three updates are successfully happens and then after it gives me the historical value( not update).

The problem is the cache. Application hold values on cache and give the cache data when request through AJAX.

I fixed this problem by simply added few codes on the top of my server side PHP file fro disabling the cache. Below is the code.


header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

Wednesday, March 27, 2013

XmlHTTPRequest: “XML Parsing Error: no element found”

I have an html5 application which get details from database through javascript. It is working properly on localhost. But after i move the database to hosting place i get the error XmlHTTPRequest: “XML Parsing Error: no element found”.

This error come because of same origin policy. That mean in my case, database in one host and my application in an another host.

I fix this issue by following steps.(i call database hosting is hostA and my application hosting hostB)

* I have php file on hostA. I add below code to the top of the file.
header('Access-Control-Allow-Origin: *');


Wednesday, February 13, 2013

Reorder/Reset auto increment primary key?


Following query can be used for reorder auto increment of a table.In this example reorder the id column of users table. If there are foreign key, make sure the action is cascade.

SET @count = 0;
UPDATE `users` SET `users`.`id` = @count:= @count + 1;

Tuesday, February 12, 2013

locks in python thread

When doing multi threading program in any language, it is a big problem when having shared variables or some shared objects. In this kind of situation, it is required to lock some variables until finish the some process of one thread. In order to do this we can use locks. In python there is a library for import in order to do this.

ex:

from threading import  Lock

......
....

#initialize lock
lock=Lock()

.....

#when needed to add lock
lock.acquire()
#do the stuff
#remove lock
lock.release()

copy object to another object using python

it is really easy to copy object with all attributes to another object in python. All you need to import copy library.

ex:

import copy

class Test:
       def __init__(self,name):
              self.name=name

def main():
       a=Test('madura')
       b=copy.deepcopy(a)

This will copy Test class object a, to Test class object b with the attribute values

Monday, February 11, 2013

Thursday, January 17, 2013

generate number of random numbers that have not repeat in a given range in python


random.sample(range(1, 16), 3)
[11, 10, 2]

get element, sublist and length of a list using python


d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> d[9]
9


>>> d[-1]
9


>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]


>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]


>>> len(d)
10

Matrix in python

There are no inbuilt function for define matrix. You can define the matrix as a list of list as follow


table= [ [ 0 for i in range(6) ] for j in range(6) ]
print table


result

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

make a list of class objects


class Person(object):
    """__init__() functions as the class constructor"""
    def __init__(self, name=None, job=None, quote=None):
        self.name = name
        self.job = job
        self.quote = quote
       
print
# make a list of class Person(s)
personList = []
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))
personList.append(Person("Don B. Sanosi", "teacher", "Work real hard while you wait and good things will come to you!"))
personList.append(Person("Hugh Jorgan", "organist", "Age is a very high price to pay for maturity."))
personList.append(Person("Herasmus B. Dragon", "dentist", "Enough people can't find work in America!"))
personList.append(Person("Adolph Koors", "master-brewer", "Wish you were beer!"))
personList.append(Person("Zucker Zahn", "dentist", "If you drink from the fountain of knowledge, quench your thirst slowly."))



print "Show one particular item:"
print personList[0].name
print
print "Sort the personList in place by job ..."
import operator
personList.sort(key=operator.attrgetter('job'))
print "... then show all quotes and who said so:"
for person in personList:
    print "\"%s\"  %s (%s)" % (person.quote, person.name, person.job)
   
print
print "Show the quote(s) from any dentist:"
look = 'dentist'
for person in personList:
    if look in person.job:
        # title() capitalizes the job's first letter
        print "%s %s: \"%s\"" % (person.job.title(), person.name, person.quote)
       
print
print "What the heck did the person named Sanosi say?"
look = "Sanosi"
for person in personList:
    if look in person.name:
        print "%s: \"%s\"" % (person.name, person.quote)

for loops in python


for num in range(10,20):  #to iterate between 10 to 20
   for i in range(2,num): #to iterate on the factors of the number
      if num%i == 0:      #to determine the first factor
         j=num/i          #to calculate the second factor
         print '%d equals %d * %d' % (num,i,j)
         break #to move to the next number, the #first FOR
   else:                  # else part of the loop
      print num, 'is a prime number'

Friday, December 7, 2012

configure ssl for apache tomcat in EC2 server

To launch an AWS/EC2 instance, at first setting up a security group to specify what network traffic is allowed to reach the instance. Then select an AMI and launch an instance from it. And create a volume in the same zone of the instance and attach with it. Format the device and mount it to a directory. After that follow the steps to create SSL for Tomcat: (If any of this command say permission denied , then try to execute command with sudo)

1. For the tomcat we need java, so create a directory to save the Java Binary file.

mkdir /usr/java
cd /usr/java

2. Download jdk binary file (jdk-x-linux-ix.bin) here

Use URL http://www.oracle.com/technetwork/java/archive-139210.html
3. Execute the Binary file

/usr/java/jdk-x-linux-ix.bin


Now we have the Java in our device. Then Download the Tomcat and install it followed by the instructions:-


1. Create a directory to save the tomcat

mkdir /usr/tomcat
cd /usr/tomcat


2. Download tomcat source file (apache-tomcat-x.tar.gz) here 

Use URL http://apache.hoxt.com/tomcat/tomcat-6/v6.0.32/bin/


3. Extract that file

tar -zxvf apache-tomcat-x.tar.gz


4. Edit the catalina.sh file

vim /usr/tomcat/apache-tomcat-x/bin/catalina.sh

#** Add at the top **

JAVA_HOME=/usr/java/jdk1.x.x_x

save and exit


5. Start the tomcat

/usr/tomcat/apache-tomcat-x/bin/startup.sh


6. We can see the logs by using the given command

tail -f /usr/tomcat/apache-tomcat-x/logs/catalina.out


7. Take the browser and enter the URL http://localhost

Now we can see the tomcat index page


8. To stop the tomcat

/usr/tomcat/apache-tomcat-x/bin/shutdown.sh


Now configure the SSL Certificate for tomcat. When you choose to activate SSL on your web server you will be prompted to complete a number of questions about the identity of your website and your company. Your web server then creates two cryptographic keys – a Private Key and a Public Key. The Public Key does not need to be secret and is placed into a Certificate Signing Request (CSR) – a data file also containing your details.
 
Create a self signed certificate authority (CA) and keystore.

1. Make a directory to hold the certs and keystore. This might be something like:

mkdir /usr/tomcat/ssl
cd /usr/tomcat/ssl


2. Generate a private key for the server and remember it for the next steps

openssl genrsa -des3 -out server.key 1024

Generating RSA private key, 1024 bit long modulus

…………………..++++++

…++++++

e is 65537 (0×10001)

Enter pass phrase for server.key:

Verifying – Enter pass phrase for server.key:


3. Generate a CSR (Certificate Signing Request). Give the data after executing this command

openssl req -new -key server.key -out server.csr


Enter pass phrase for server.key:

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter ‘.’, the field will be left blank.

—–

Country Name (2 letter code) [GB]:

State or Province Name (full name) [Berkshire]:

Locality Name (eg, city) [Newbury]:

Organization Name (eg, company) [My Company Ltd]:

Organizational Unit Name (eg, section) []:

Common Name (eg, your name or your server’s hostname) []:

Email Address []:

Please enter the following ‘extra’ attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:


4. Remove the passphrasse from the key

cp server.key server.key.org

openssl rsa -in server.key.org -out server.key

Enter pass phrase for server.key.org:

writing RSA key


5. Generate the self signed certificate

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Signature ok

subject=/C=GB/ST=Berkshire/L=Newbury/O=My Company Ltd

Getting Private key

You should then submit the CSR. During the SSL Certificate application process, the Certification Authority will validate your details and issue an SSL Certificate containing your details and allowing you to use SSL. Typically an SSL Certificate will contain your domain name, your company name, your address, your city, your state and your country. It will also contain the expiration date of the Certificate and details of the Certification Authority responsible for the issuance of the Certificate.

Create a certificate for tomcat and add both to the keystore

1. Change the path to ssl

cd /usr/tomcat/ssl


2. Create a keypair for ‘tomcat’


keytool -genkey -alias tom -keyalg RSA -keystore tom.ks


Enter keystore password:

Re-enter new password:

What is your first and last name?

[Unknown]:

What is the name of your organizational unit?

[Unknown]:

What is the name of your organization?

[Unknown]:

What is the name of your City or Locality?

[Unknown]:

What is the name of your State or Province?

[Unknown]:

What is the two-letter country code for this unit?

[Unknown]:

Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?

[no]: yes

Enter key password for <tom>

(RETURN if same as keystore password):

Re-enter new password:


3. Generate a CSR (Certificate Signing Request) for tomcat

keytool -keystore tom.ks -alias tom -certreq -file tom.csr

Enter keystore password:

4. create unique serial number


echo 02 > serial.txt
(If this say permission denied then, mkfile call serial.txt and chmod of it -> then try)


5. Sign the tomcat CSR


openssl x509 -CA server.crt -CAkey server.key -CAserial serial.txt -req -in tom.csr -out tom.cer -days 365


Signature ok

subject=/C=Unknown/ST=Unknown/L=Unknown/O=Unknown/OU=Unknown/CN=Unknown

Getting CA Private Key


6. Import the server CA certificate into the keystore

keytool -import -alias serverCA -file server.crt -keystore tom.ks


Enter keystore password:

Owner: O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB

Issuer: O=My Company Ltd, L=Newbury, ST=Berkshire, C=GB

Serial number: ee13c90cb351968b

Valid from: Thu May 19 02:12:51 EDT 2011 until: Fri May 18 02:12:51 EDT 2012

Certificate fingerprints:

MD5: EE:F0:69:01:4D:D2:DA:A2:4E:88:EF:DC:A8:3F:A9:00

SHA1: 47:97:72:EF:30:02:F7:82:BE:CD:CA:F5:CE:4E:ED:89:73:23:4E:24

Signature algorithm name: SHA1withRSA

Version: 1

Trust this certificate? [no]: yes

Certificate was added to keystore


7. Add the tomcat certificate to the keystore

keytool -import -alias tom -file tom.cer -keystore tom.ks


Enter keystore password:

Certificate reply was installed in keystore

To configure a secure (SSL) HTTP connector for Tomcat, verify that it is activated in the $TOMCAT_HOME/conf/server.xml file. Edit this file and add the following lines.


Tomcat configuration

1. Edit the given portion of tomcat configuretion file and change the port as 80


vim /usr/tomcat/apache-tomcat-6.0.13/conf/server.xml

“””””” <Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" /> “”””””



<Connector port="80" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />


2. Add the given portion to server.xml and give your password in the password portion


<Connector port="443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="tom.ks"
keystorePass="password"
clientAuth="false" sslProtocol="TLS" />


When you start the Tomcat Your web server will match your issued SSL Certificate to your Private Key. Your web server will then be able to establish an encrypted link between the website and your customer’s web browser.

Start the tomcat with SSL Certificate


1. Restart tomcat


/usr/tomcat/apache-tomcat-6.0.13/bin/shutdown.sh


/usr/tomcat/apache-tomcat-6.0.13/bin/startup.sh


2. Go to https://Public DNS name:443/

Then your browser shows a security issue. Click the Approve button. Then you can enter to the tomcat with your certificate. When a browser connects to a secure site it will retrieve the site’s SSL Certificate and check that it has not expired, it has been issued by a Certification Authority the browser trusts, and that it is being used by the website for which it has been issued. If it fails on any one of these checks the browser will display a warning to the end user letting them know that the site is not secured by SSL.

You are Done !!!




Refer from: http://www.migrate2cloud.com/blog/ssl-for-tomcat-on-awsec2