Thursday, January 6, 2011

HTML5 code

1. Doctype
The actual doctype for any HTML5 document is simply
<!DOCTYPE html>
2.Declare charse
<meta charset="utf-8">

http://www.w3schools.com/html5/html5_reference.asp

W3C

Browser support HTML5

semantic:HTML5 do not work with IE 7 or older
video and audio, canvas: depend on codec and must be IE9
geolocation:mobile device ok, IE9 still not yet support

Use Chrome frame like browser plug-in for most browsers (including IE6 and up) so that it is feasible to haveoffline storage, geolocation services, background JavaScript execution, and other HTML5-like features
meta http-equiv="X-UA-Compatible" content="chrome=1"

http://diveintohtml5.org/
http://introducinghtml5.com/

Tuesday, January 4, 2011

Set up mod_jk and apache2

1. Install mod_jk

apt-get install libapache2-mod-jk

2. Under /etc/apache2/mods-enabled, create jk.conf and add the contents below.

# Sample mod_jk configuration
# for Apache 2
#
# for all commands/options available see the manual
# provided in libapache-mod-jk-doc package.

# The location where mod_jk will find the workers definitions
JkWorkersFile /etc/libapache2-mod-jk/workers.properties

# The location where mod_jk is going to place its log file
JkLogFile /var/log/apache2/mod_jk.log

# The log level:
# - info log will contain standard mod_jk activity (default).
# - warn log will contain non fatal error reports.
# - error log will contain also error reports.
# - debug log will contain all information on mod_jk activity
# - trace log will contain all tracing information on mod_jk activity
JkLogLevel info


# Assign specific URLs to Tomcat. In general the structure of a
# JkMount directive is: JkMount [URL prefix] [Worker name]


# send all requests ending in .jsp to ajp13_worker
# send all requests ending /servlet to ajp13_worker
#JkMount /*/servlet/ ajp13_worker

# JkUnmount directive acts as an opposite to JkMount and blocks access
# to a particular URL. The purpose is to be able to filter out the
# particular content types from mounted context.

# do not send requests ending with .gif to ajp13_worker
#JkUnMount /servlet/*.gif ajp13_worker


# JkMount / JkUnMount directives can also be used inside
# sections of your httpd.conf file.

3. Configure workers.
Under /etc/libapache2-mod-jk, create workers.properties and add the contents below. Normally this file already existed there, what you should do is checking the tomcat-home and jvm path correctly or not.


# workers.properties -
#
# This file is a simplified version of the workers.properties supplied
# with the upstream sources. The jni inprocess worker (not build in the
# debian package) section and the ajp12 (deprecated) section are removed.
#
# As a general note, the characters $( and ) are used internally to define
# macros. Do not use them in your own configuration!!!
#
# Whenever you see a set of lines such as:
# x=value
# y=$(x)\something
#
# the final value for y will be value\something
#
# Normaly all you will need to do is un-comment and modify the first three
# properties, i.e. workers.tomcat_home, workers.java_home and ps.
# Most of the configuration is derived from these.
#
# When you are done updating workers.tomcat_home, workers.java_home and ps
# you should have 3 workers configured:
#
# - An ajp13 worker that connects to localhost:8009
# - A load balancer worker
#
#

# OPTIONS ( very important for jni mode )

#
# workers.tomcat_home should point to the location where you
# installed tomcat. This is where you have your conf, webapps and lib
# directories.
#
workers.tomcat_home=/usr/local/tomcat

#
# workers.java_home should point to your Java installation. Normally
# you should have a bin and lib directories beneath it.
#
workers.java_home=/usr/lib/jvm/java-6-sun

#
# You should configure your environment slash... ps=\ on NT and / on UNIX
# and maybe something different elsewhere.
#
ps=/

#
#------ ADVANCED MODE ------------------------------------------------
#---------------------------------------------------------------------
#

#
#------ worker list ------------------------------------------
#---------------------------------------------------------------------
#
#
# The workers that your plugins should create and work with
#
worker.list=ajp13_worker

#
#------ ajp13_worker WORKER DEFINITION ------------------------------
#---------------------------------------------------------------------
#

#
# Defining a worker named ajp13_worker and of type ajp13
# Note that the name and the type do not have to match.
#
worker.ajp13_worker.port=8009
worker.ajp13_worker.host=localhost
worker.ajp13_worker.type=ajp13
#
# Specifies the load balance factor when used with
# a load balancing worker.
# Note:
# ----> lbfactor must be > 0
# ----> Low lbfactor means less work done by the worker.
worker.ajp13_worker.lbfactor=1

#
# Specify the size of the open connection cache.
#worker.ajp13_worker.cachesize

#
#------ DEFAULT LOAD BALANCER WORKER DEFINITION ----------------------
#---------------------------------------------------------------------
#

#
# The loadbalancer (type lb) workers perform wighted round-robin
# load balancing with sticky sessions.
# Note:
# ----> If a worker dies, the load balancer will check its state
# once in a while. Until then all work is redirected to peer
# workers.
worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=ajp13_worker


4.Configure the URI to worker mapping.
for example

ServerAdmin dang@company.net
ServerName example.company.net
DocumentRoot /home/lamp/webroot/nanocycle
JkMount /*.jsp ajp13_worker
JkMount /routecalc* ajp13_worker
JkMount /Logger* ajp13_worker
JkMount /Params* ajp13_worker

Options FollowSymLinks
AllowOverride None


Options FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all


deny from all

DirectoryIndex index.php index.html index.jsp
LogLevel error
CustomLog /var/log/apache2/access.log combined
ServerSignature Off


5.Enable worker in tomcat
Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

config a host for worker, if use localhost, noneed
otherwise need create a new one:

forexample, a virtualhost for nanocylebooking
cause jk port call locally, add a record in host file, to define a local ip for nanocycle, then in worker.properties, connect to nanocycle like locally

nanocycle.cbdweb.net


6. Restart apache,tomcat
# /etc/init.d/apache2 restart

For Alexander cua me

Mai den hom nay me moi co thoi gian ngoi viet vai dong cho Alex cua me. Ky nghi dai da qua va hai me con minh moi sang phai thuc day som di lam, vat va cho con ha nhung Alex ngoan lam ne, moi sang nghe tieng alarm bao thuc cua ba la me thay con cung thuc day trong bung me roi khong giong nhu me phai cho ba keu ha.

Alex cua me da buoc vao tuan thu 21 roi day nhe, hom di sieu am kiem tra suc khoe cua con, moi thu deu ok dong thoi biet duoc con la mot cau be dang yeu, ba con vui mung du lam, me cung vui lay ay nhe. Alex cua me thuc la hieu dong, moving around all the time, con biet tu play o trong bung me nhe, dua mot tay len nam roi nam hai tay lai voi nhau nhe, roi kick me ne, cuon tron lai ne, den noi the doctor cung lac dau quay quay khi sieu am cho con, chac tinh tinh con giong ba nhu duc roi. Me nhin thay khuon mat va doi mat to cua con, me doan se giong daddy day, nhat dinh Alex se dep trai va rat lau ca day. Moi ngay me deu mong cho nhung cai dap va ngung nguay cua Alex trong bung me, me yeu Alex vo cung, ba con cung yeu con lam. Tu ngay me mang bau Alex, ba khong cho me lam gi ca, tu viec di cho, nau an va rua chen, giat do, don dep nha cua mac du tu truoc den gio ba rat it lam may chuyen do. The con moi biet la ba con yeu con den nhuong nao. Ngu ngoan chong lon nhe Alex cua ba me. Cau mong con khoe manh, binh yen suot 1/2 chang duong con lai de den voi ba me.
Yeu con nhieu nhieu nhieu.


Origin and Meaning of the Name Alexander
Gender:Boy
Origin:Greek
Meaning:Defending men
Pronunciation:(ah lek ZAND ur) [Guide]
Form of:Alexandros
Miscellaneous Info for Alexander
Categories:
Biblical Names, Scandinavian Names, Albanian Names, Australian Names, Canadian Names, Austrian Names, Christian Names, American Names, Dutch Names, English Names, German Names, Greek Names, Middle Names
Used in: Dutch, English, German, Hungarian and Slovak speaking countries
Additional info:

Anglicised version of the Greek name Alexandros.

Alexander appears in the Bible as the one who helps Jesus bear the cross on the journey to Calvary.

Alexander the Great was an ancient Macedon king. Greece was unified by his father, Philip II, but Alexander went on to extend the Macedon empire eastwards to the periphery of modern India.

There have also been two kings of Scotland named Alexander, and three emperors of Russia. Eight popes have been named Alexander. It is also the name of the first king of Yugoslavia and the current pretender to the throne.

Alexander Graham Bell was the inventor of the telephone, and Alexander Fleming discovered penicillin. The name was also borne by poet Alexander Pope, Russian author Alexander Pushkin, Russian composer Alexander Scriabin and former US Secretary of State under President Reagan, Alexander Haig.

Thursday, December 16, 2010

Study Link

HTML5
Spring

Wednesday, December 15, 2010

For my baby

Bib: Yem
Scarf: khan choang co
Khan mem lau mat
Khan tam
Khan voan

Wednesday, September 8, 2010

Fraud

Tuesday, August 31, 2010

Convert from mpm_prefork to mpm_worker using php-cgi in Ubuntu

Installation Steps


1.
install php-cgi package and mpm-prefork

apt-get -u install php5-cgi libapache2-mod-fcgid apache2-mpm-worker

2.
mkdir {WEBROOTFOLDER}/fcgi-bin.d
eg /home/lamp/webroot
mkdir {WEBROOTFOLDER}/fcgi-bin.d/php5-default

ln -s /usr/bin/php5-cgi /home/lamp/webroot/fcgi-bin.d/php5-default/php-fcgi-wrapper





Configuration Steps

1.

Remove mod_php4 / mod_php5 if not already done

# a2dismod php4
# a2dismod php5
2.

Enable mod_actions and mod_fcgid

# a2enmod actions
# a2enmod fcgid
3.

Raise the communication timeout (= maximum execution time) for FCGI applications in /etc/apache2/mods-enabled/fcgid.conf by adding the “IPCCommTimeout” directive


AddHandler fcgid-script .fcgi
SocketPath /var/lib/apache2/fcgid/sock

# Communication timeout: Default value is 20 seconds
IPCCommTimeout 60

# Connection timeout: Default value is 3 seconds

#IPCConnectTimeout 3

4.

Create a new file /etc/apache2/conf.d/php-fcgid.conf:










# Path to php.ini – defaults to /etc/phpX/cgi
DefaultInitEnv PHPRC=/etc/php5/cgi

# Number of PHP childs that will be launched. Leave undefined to let PHP decide.
#DefaultInitEnv PHP_FCGI_CHILDREN 3

# Maximum requests before a process is stopped and a new one is launched
#DefaultInitEnv PHP_FCGI_MAX_REQUESTS 5000

# Define a new handler "php-fcgi" for ".php" files, plus the action that must follow
AddHandler php-fcgi .php
Action php-fcgi /fcgi-bin/php-fcgi-wrapper

# Define the MIME-Type for ".php" files
AddType application/x-httpd-php .php

# Define alias "/fcgi-bin/". The action above is using this value, which means that
# you could run another "php5-cgi" command by just changing this alias
Alias /fcgi-bin/ /var/www/fcgi-bin.d/php5-default/

# Turn on the fcgid-script handler for all files within the alias "/fcgi-bin/"

SetHandler fcgid-script
Options +ExecCGI










5.

Next, create the directory which is chosen by the alias, and put in a symlink to the php5-cgi binary

# mkdir /var/www/fcgi-bin.d/php5-default
# ln -s /usr/bin/php5-cgi /var/www/fcgi-bin.d/php5-default/php-fcgi-wrapper
6.

Finally, restart Apache

/etc/init.d/apache2 restart

Hibernate Question

1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?
An ORM solution consists of the followig four pieces:
API for performing basic CRUD operations
API to express queries refering to classes
Facilities to specify metadata
Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?
The ORM levels are:
Pure relational (stored procedure.)
Light objects mapping (JDBC)
Medium object mapping
Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
Improved performance
Sophisticated caching
Lazy loading
Eager loading
Improved maintainability
A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you
6.What Does Hibernate Simplify?
Hibernate simplifies:
Saving and retrieving your domain objects
Making database column and table name changes
Centralizing pre save and post retrieve logic
Complex joins for retrieving related items
Schema creation from object model
7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:


8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
Programmatic configuration
XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?
Following are the important tags of hibernate.cfg.xml:


10.What are the Core interfaces are of Hibernate framework?
People who read this, also read:-
JSF Interview Questions
Core Java Questions
SCEA Certification
iBatis an alternative to Hibernate
Servlets Interview Questions
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces


11.What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();
Session interface role:
Wraps a JDBC connection
Factory for Transaction
Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();


13.What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
Create session factory from configuration object
Get one session from this session factory
Create HQL Query
Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?
First we need to write Java domain objects (beans with setter and getter).
Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :









16.What’s the difference between load() and get()?
load() vs. get() :-
load() get()
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods.
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. get() will hit the database immediately.

17.What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate?
Using tag.
Example:-


SEQUENCE_NAME



19.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

20.What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {emp.name}
FROM Employee EMP WHERE emp.NAME LIKE :name


Invoke Named Query :
List people = session.getNamedQuery("empdetails")
.setString("TomBrady", name)
.setMaxResults(50)
.list();

21.How do you invoke Stored Procedures?







{ ? = call selectAllEmployees() }





22.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();

23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

24.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
Common functions are simplified to single method calls.
Sessions are automatically closed.
Exceptions are automatically caught and converted to runtime exceptions.


25.How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
true

27.What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.
People who read this, also read:-
Spring Interview Questions
Hibernate Tutorial
SCEA Certification
Hibernate Vs iBatis
Tibco Interview Questions



28.What is component mapping in Hibernate?
A component is an object saved as a value, not as a reference
A component can be saved directly without needing to declare interfaces or identifier properties
Required to define an empty constructor
Shared references not supported
Example:


29.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
sorted collection order collection
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.
If your collection is not large, it will be more efficient way to sort it. If your collection is very large, it will be more efficient way to sort it .


31.What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC Hibernate
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.


32.What are the Collection types in Hibernate ?
Bag
Set
List
Array
Map

33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
An implicit association join
An ordinary join in the FROM clause
A fetch join in the FROM clause.
A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.


36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.


40.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

41.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
People who read this, also read:-
JDBC Interview Questions
JDBC Questions
MyFaces Examples
Let Spring Manage JSF Beans
Hibernate Interview Questions

42.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ?
Three types of instance states:
Transient -The instance is not associated with any persistence context
Persistent -The instance is associated with a persistence context
Detached -The instance was associated with a persistence context which has been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :-
Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of work Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented Programming Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships Entity Relationships are bidirectional or unidirectional

45.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
Table per class hierarchy
Table per subclass
Table per concrete class

http://static.springsource.org/docs/Spring-MVC-step-by-step/part6.html

Sunday, August 29, 2010

SSL key gen

Generate key

openssl genrsa -des3 -out /etc/apache2/ssl/sitename.com.key 2048

cp /etc/apache2/ssl/sitename.com.key /etc/apache2/ssl/sitename.com.key.secure

encrypt key

openssl rsa -in /etc/apache2/ssl/sitename.com.key.secure -out /etc/apache2/ssl/sitename.com.key


send encrypt file to client, because don't want apache ask for password


Link

Wednesday, August 25, 2010

SQL Log file

Digital Devices


How to read Database transaction log in SQL Server?

Another frequently asked questions in the forums and newsgroups, I have seen similar ones recently. I believe most of the newbie users ask this question and even more as interview based questions.
So here is the catch in order to accomplish the task, say you need to provide a solution to log and show all Create, read, update and delete (CRUD) transactions for auditing, this is more a mandatory for SOX & HIPPA regulations.
Using the standard SQL Server methods which is an undocumented statement DBCC LOGINFO will get information, but the problem is it cannot be interpreted in simple terms as per the requirement. Hence the rise of third party tools in this area is evident. In order to enable to read SQL Server transaction log files and provide an in-house tool to show the CRUD transactions on a set of databases in a customized manner is a demanding task for a DBA (now a days). The other aspect is to use Server side trace (Profiler) to track the statements on the database (which will impact the performance if the server is already stressed out for resources)
As per the note above using undocumented DBCC command you will get:

DBCC LOG(databasename,{0|1|2|3|4}])
0 - Basic Log Information (default)
1 - Lengthy Info
2 - Very Length Info
3 - Detailed
4 - Full
Example:
DBCC log (Databasename, Type)
And it displays the following transaction log information:
  • Current LSN
  • Operation (string starts with LOP_XXXXX)
  • Context (string starts with LCX_XXXX)
  • Transaction ID
  • Tag Bits (Hex)
  • Log Record Fixed Length (int)
  • Log Record Length (int)
  • Previous LSN
  • Flag Bits (Hex)
  • Description (string)
  • Log Record (Hex)
As it is undocumented on the Microsoft articles its very hard to interpret what lies beneath those HEX values, therefore using third party tools such as APEX-SQL Log Reader and Lumigent's Log Explorer are more helpful to such users that are needed to cater the management needs. I believe Microsoft has to invest something heavy here in order to comply the newest industry regulations for Auditing and monitoring purpose.


SELECT * FROM fn_dblog(NULL, NULL) WHERE AllocUnitName LIKE '%%' 

Wednesday, August 18, 2010

Native dll

http://www.apache.org/dist/tomcat/tomcat-connectors/native/1.1.20/binaries/


 Connector port="8443" maxHttpHeaderSize="8192"
               maxThreads="150"
               enableLookups="false" disableUploadTimeout="true"
               acceptCount="100" scheme="https" secure="true"
               SSLEnabled="true"
               SSLCertificateFile="${catalina.base}/openssl/tomcatcert.pem"
               SSLCertificateKeyFile="${catalina.base}/openssl/tomcatkey.pem"
  SSLPassword="ewgasdgfasfasdf"



SSL debug

I'd suggest using curl to troubleshoot your problems. curl is a unix tool as well as a library, and on Windows is runs well under cygwin. Try the following command:
curl -Iv https://yourhost:9091
You should see some output which looks something like this:
* About to connect() to yourhost port 9091 (#0)
*   Trying 67.207.137.114... connected* Connected to yourhost (67.207.137.114) port 9091 (#0)
* successfully set certificate verify locations:
*   CAfile: none
  CApath: /etc/ssl/certs* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS alert, Server hello (2):
* SSL certificate problem, verify that the CA cert is OK. Details:
From here you should be able to narrow down where to troubleshoot.

Window 32 bit or 64 bit

http://support.microsoft.com/kb/827218


  • Click Start, and then click Run.

  • Type sysdm.cpl, and then click OK.

  • or winmsd, and then click OK
  • Monday, August 16, 2010

    Session Pooling

    http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

    Thursday, August 5, 2010

    Sunday, June 20, 2010

    I've moved this blog to http://www.ericsimmerman.com/ for all future posts. 1/12/09

    Eric's Agile Answers Posts on whatever your host, Eric Simmerman, deems relevant.

    « Hibernate support... | Main | Anonymous access of... »
    20060623 Friday June 23, 2006
    Preventing Java's java.lang.OutOfMemoryError: PermGen space failure

    The "OutOfMemoryError: PermGen space" message is normally encountered during development activites where a long-running JVM is asked to load/unload builds. However it can also be encountered in a recently spawned JVM under the "right" set of conditions.

    The message is a symptom of an incomplete garbage collection sweep where resources are not properly released upon unload/restart. There is no shortage of debate (Hibernate forum, Sun forum, Spring Framework forum ) regarding which codebase is responsible for this symptom, but the finger of blame has been pointed at CGLIB, Hibernate, Tomcat, and even Sun's JVM.

    Generally speaking, this is an interoperability issue and can be resolved by changing one of the components in your software stack. Some users have reported relief by upgrading to the latest Tomcat 5.5 release, others have simply opted for another webcontainer implementation (like Jetty or Resin) with varying degrees of success.

    In my experience, the most pain-free method of resolving this issue is to switch from Sun's JDK implementation to BEA's freely available JRockit implementation.

    On a recent project utilizing Tomcat 5.5.12 with Hibernate, I was plagued with this PermGen error, at times even experiencing it during web-based unit testing. Since making the switch to JRockit, I have not encountered this issue even once. I attribute the "fix" to the differences between JRockit's and Sun's garbage collection implementations, but have no proof that this is indeed the reason that JRockit resolves the issue. In any case, WFM.


    Posted by ets ( Jun 23 2006, 11:23:09 AM EDT ) Permalink Comments [36]

    Comments:

    I also had these annoying Perm Gen Space OOMs when redeploying webapps. I'm using spring 1.2.8, Hibernate 3 (both with CGLIB 2.1_3), tomcat 5.5.17 and - now the problem: jdk1.5.0_06. After upgrading to jdk1.5.0_07 my Perm Gen Space gets gc'ed like it should be - no increase of Perm Gen Space, no code changes.

    There were however some learnings on the way:

    1. Put JDBC driver in common/lib (as tomcat doku says) and never ever in WEB-INF/lib - If you get No suitable driver Exception during redeploy use JNDI DB definition in META-INF/context.xml; not in server.xml and not in conf/Catalina/localhost/.xml. This is how my META-INF/context.xml looks like:






    2. Don't put commons-logging into WEB-INF/lib since tomcat already bootstraps it

    3. If you still run in Perm Gen Space OOM then you may have to increase Perm Gen Space or don't redeploy your webapps so fast! What was most irritating for me after thinking the issue is solved for me was that sometimes i did ran into Perm Gen Space OOM and sometimes not. It seems that gc cleans Perm Gen Space from time to time and not (!) if space is low or app explicitly requests gc. - But this I didn't fully understand (not to say not at all), but still there are reasonable arguments on sun bug database to increase this memory (see post above)

    Now I'm happy again after two (!) days of reading lots of forum threads, learning lots about class loader, tomcat, spring, hibernate, aop and class metadata and knowing that programming still can be very difficult!

    Posted by Yan Hackl-Feldbusch on June 29, 2006 at 04:11 AM EDT #
    The problem is that Tomcat does not garbage collect the Classloader and the classes it loads. Each you reload the webapp context, more copies of these classes are loaded, and as these are stored in the permanent heap generation, it will eventually run out of memory.
    The same issue could affect (and affects) to any container. You just have to restart the container instead of restarting the context.
    It's easy to reproduce this problem by reloading the context over and over again until you get an OutOfMemoryError (10 times was enough for a simple app)

    Cheers

    Posted by Cheng Lee on August 26, 2006 at 04:36 PM EDT #
    JRockit doesn't have generational garbage collection - in other words, it doesn't have permanent generation space. Therefore, it can't have PermGen errors. Ever.

    That's not to say that you won't / haven't got a memory leak, and that eventually it may bring the JVM down, but it isn't reliant on a separate little hived off area like the Sun's JVM.

    Posted by Graham Triggs on November 08, 2006 at 09:13 AM EST #
    These problems are not specific to Tomcat, Hibernate, or Spring. I am using Glassfish on JDK 6.1, and run into this error all too frequently. If there are solutions that don't require swapping out the JDK, then please post them.

    Posted by ITVGuy2000 on August 06, 2007 at 01:02 AM EDT #
    -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

    Posted by orx on October 12, 2007 at 12:45 PM EDT #
    ok

    Posted by 203.197.25.11 on November 02, 2007 at 06:11 AM EDT #
    I've had large apps running on our server for more than a year now. They are built using JPOX for persistence and we've never once experienced an Out of memory, PermGen Space error.

    Just recently we installed a third party app that uses Hibernate for persistence and now we get PermGen errors. I noticed that there are a number of articles pointing to PermGen memory problems/leaks with Hibernate when it is not using reflection as it burns up a bit too much memory via it's iteractions with CGLIB. The suggestion seems to be to run Hibernate in "reflection" mode but reflection is a very slow mode for any ORM to operate in.

    I'm not sure if our particular problem is with Hibernate or the application itself. It's a third party open source project that we use nearly everyday. I don't want to mention it's name in case this issue is related to the Hibernate framework that it ships with and not the application itself.

    It should be fairly quick to change the code to use JPOX like the rest of our apps use to see if the problem goes away. Both JPOX and Hibernate support transparent persistence so there shouldn't be any references to the any specific ORM stuff in the model code.

    Anyone had experience porting between different "transparent" persistence ORMs before?

    Posted by Golfman on February 08, 2008 at 03:55 PM EST #
    >>The problem is that Tomcat does not garbage >>collect the Classloader and the classes it >>loads. Each you reload the webapp context, >>more copies of these classes are loaded, and >>as these are stored in the permanent heap >>generation, it will eventually run out of >>memory.
    >>The same issue could affect (and affects) to >>any container. You just have to restart the >>container instead of restarting the context.
    >>It's easy to reproduce this problem by >>reloading the context over and over again >>until you get an OutOfMemoryError (10 times >>was enough for a simple app)

    >>Cheers
    >>Posted by Cheng Lee on August 26, 2006 at >>04:36 PM EDT #

    Interesting and believing this is true. Question is how to avoid this happening

    Posted by 134.178.63.3 on February 21, 2008 at 05:50 PM EST #
    fjkfk

    Posted by 122.168.26.172 on March 06, 2008 at 11:18 AM EST #
    When I ran a profiler, I noticed that by default you have 96MB of non-heap memory limit. With BEA this raises up to 4GB, so of course you can redeploy thousands of times. But still, with each redeployment, the amount of allocated memory raises again :(

    Posted by Dunkelheit on March 14, 2008 at 10:07 AM EDT #
    I encounter the same problem. I am using BEA Weblogic. I have removed the deployment of my application, and shutdown the managed server relating to the application. I am intending to redeploy the application, hoping to make a new clean start. But i encounter the message below.

    WARNING: The server has decided to close this client connection.
    <27/03/2008 11:48:46 AM EST>

    How to clean up this garbage so that when i redeploy I don't encounter the same problem of OutOfMemoryError:PermGen space failure??

    Posted by Joni on March 26, 2008 at 08:54 PM EDT #
    I came across this error very recently, and I haven't been able to pin point whether this is happening due to only Tomcat, Hibernate or the JVM mainly because we use both Tomcat and Hibernate.

    One sure way of avoiding this problem, I gather, is by restarting the container every time we re-deploy the app. It may not be practical when you have more than one app running on your server, but it works. I'm usually in the habit of restarting the server with each deployment, whereas some of my teammates are not. And until now, I've never experienced this problem, whereas my teammates have.

    All in all, a good thread, with good insights thrown in from some of the readers. Thanks.

    Posted by Satya on April 25, 2008 at 10:31 AM EDT #
    I can confirm the solution by ITVGuy2000 perfectly works for me (1.6.0_05, Apache Tomcat 6.0.16):
    -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

    ITVGuy2000, Great thanks!!!

    Posted by Maxym on June 18, 2008 at 11:29 AM EDT #
    sorry, seems like it was Posted by orx on October 12, 2007 at 12:45 PM EDT

    orx, huge THANK YOU!

    Posted by Maxym on June 18, 2008 at 11:30 AM EDT #
    This error occurs when the JVM runs out of space in the permanent generation heap. Since the defaults for the JVM are quite low, the first step should be to increase the default using -XX:MaxPermSize.

    Put the below VM argument when starting program

    -XX:MaxPermSize=256m

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


    -XX:MaxPermSize=256m


    Posted by xyz on July 03, 2008 at 02:11 AM EDT #
    Your Comment:Your Comment:Your Comment:Your Comment:

    Posted by Your Comment: on July 07, 2008 at 06:51 AM EDT #
    Someone could tell me what exactly do these 2 options?

    -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

    Posted by Marlon Patrick on July 07, 2008 at 09:44 AM EDT #
    Java PermGen space out of memory error :
    Steps to rectify this error :

    Hi Guys This is common error people get when they are using tomcat
    for big web application .so following are the steps to rectify this error :
    1.0 click on tomcat start up
    2.0 click on java tab in tomcat startup
    3.0 Now add the following parameter in java option field :

    -XX:MaxPermSize=512m
    -verbose:gc
    -XX:+PrintClassHistogram

    4.0 assign intial pool memory 256 mb

    5.0 assign maximum memory pool 1024mb

    6.0 restart the server

    This setting is applicable or this is an example when your system RAM is 2GB where the tomcat

    is running .

    for other RAM size please make sure that memory division does not exceed to system

    memory.otherwise tomcat server will not restart.


    after doing aforesaid setting if you still face this issue :

    please look at the tomcat server log file ,Parameter PrintClassHistogram will
    print the time life of each object .so now you have to optimized your code
    where the object life is more .
    Hope aforesadi solution will workout your issue

    Posted by ram sahai on July 17, 2008 at 12:27 AM EDT #
    I am also facing the same issue ([junit] Exception in thread "Thread-0" java.lang.OutOfMemoryError: PermGen space) when I run the junit testcases using ANT utility. Tried to solve the problem setting the JVM aguments ( -XX:PermSize=1024m -XX:MaxPermSize=1024m). But it didn't worked. Finally ran junit testcases with bea JROCKIT and it worked.

    Posted by Susanta Ghosh on August 19, 2008 at 12:23 PM EDT #
    Thanks alot my problem also solved.

    Posted by KranthiGedela on October 03, 2008 at 10:28 AM EDT #
    @ Susanta Ghosh
    how much RAM do you have?

    Posted by mdalangin on October 05, 2008 at 11:34 AM EDT #
    Hi,
    I think this problem can also be due to a Leakage Class Loader.....

    Check Eclipse Memory Analyzer to see the details.......

    Thanks,
    Nirmal

    Posted by Nirmal Kumar on October 15, 2008 at 12:13 PM EDT #
    add the following in Java-option under tomcar configuration and everything will be ok.

    -Xmx256m
    -Xms256m
    -XX:PermSize=512m
    -XX:MaxPermSize=512m
    -verbose:gc

    Posted by muzy on November 04, 2008 at 09:31 AM EST #
    Switched from jrockit to Sun JDK 1.5.0_16b02 on RH5, started getting the PermGen OOM error. Adding -XX:PermSize=256 cleared it up.

    Posted by Mike on November 08, 2008 at 06:51 AM EST #
    F

    Posted by 59.145.67.121 on November 22, 2008 at 05:18 AM EST #
    Hi everyone,

    I've tried with tomcat(6.0.18), glassfish(prelude v3) and hotspot(1.6.0_04-b12) + a simple spring hibernate app.

    I tried -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled as well.

    In both cases after 10 redeploys I get OutOfMemoryError.

    Did someone managed at least to identify the problem? Is there a official bug report for sun guys?

    Posted by Dusan on December 04, 2008 at 08:48 AM EST #
    THIS IS MY ERROR:
    12/17/2008 15:45:17 HTTP JVM: Unexpected error while executing java agent:JavaAgent
    12/17/2008 15:45:17 HTTP JVM: -->java.lang.OutOfMemoryError: PermGen space
    12/17/2008 15:45:17 HTTP JVM: java.lang.OutOfMemoryError: PermGen space

    We have previously extend the mem space but it ended up crashing our domino server. If you have any other suggestions please send them. Kind regards.

    Posted by Adele on December 17, 2008 at 09:54 AM EST #
    Article provides gud information about JVM parameters

    Posted by Arun on March 04, 2009 at 11:52 PM EST #
    The article is good! And so does the comments. I learn a lot from both.

    I happen to "hit" this kind of error in someone else application. It uses

    Hibernate+Spring+WebSphere. It's turn out that the problem is on the creation of application context EVERYTIME the application run several .Java file! Can you imagine how memory-consume it was.

    The solution is using the SingletonBeanFactoryLocator class.

    Posted by pucha on March 12, 2009 at 05:24 AM EDT #
    -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

    These options only work if you are using CMS garbage collection, i.e. you must also have the JVM option:

    -XX:+UseConcMarkSweepGC

    Posted by vlad on September 03, 2009 at 05:25 AM EDT #
    I new to this. I get the same error and I found good solutions and comments. Now I want to try

    Can you guide me that which file should I update with this :
    -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

    Im using Tomcat 5.5

    Many thanks

    Posted by Mike85 on October 08, 2009 at 11:40 PM EDT #
    In the case of Tomcat (Don't know how Glassfish orany other servlet container implements its undeploy) when a webapp is undeployed tomcat simply removes its reference to the WebAppClassLoader

    In theory this makes all objects in the webapp unreachable go the garbage collector will remove them.

    Two things can mess this up (possibly more):

    1: The webapp started a thread and this thread is still running. This becomes a garbage collector root, so anything it references will not be collected

    2: If a class loaded by the webapp classloader is referenced by a parent classloader that class is still reachable. All class objects contain a reference to their classloader, which make the WebAppClassLoader still reachable - and the entire webapp.

    There are known points in the JVM where this can happen. One is creating a subclass of java.util.logging.Level as its constructor will add the instance to a static field of the Level class, which is typically loaded by the bootstrap classloader

    There's more documents places in this class org.apache.catalina.core.JreMemoryLeakPreventionListener

    Posted by Chris on December 08, 2009 at 05:18 PM EST #
    Thanks for ur solution !!
    Had the same problem and it got fixed when I used -XX:MaxPermSize=512m :)

    Posted by tyt on March 08, 2010 at 12:07 PM EST #
    We are using glassfish, jdk 1.5. During redeployment it throws memory out of error.

    Posted by srinivas on March 20, 2010 at 04:12 AM EDT #
    Exception in thread "GroupChannel-Heartbeat-1" java.lang.OutOfMemoryError: PermGen space

    any one know abt this error . i got this error and tomcat is still loading the page for a long time

    Posted by kalasagar on April 06, 2010 at 02:43 AM EDT #
    My problem was fixed by putting libraries in a shared location for the web server rather than the deployed application library.

    Posted by Chris on April 22, 2010 at 03:47 AM EDT #
    Post a Comment:

    Name:
    E-Mail:
    URL:
    Notify me by email of new comments
    Remember Information?

    Your Comment:

    HTML Syntax: NOT allowed

    Please answer this simple math question

    6 + 37 =