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 =

    Wednesday, May 26, 2010

    Hibernate call store procedure

    Hibernate call store procedure

    In Hibernate, there are three approaches to call a database store procedure.

    1. Native SQL – createSQLQuery

    You can use createSQLQuery() to call a store procedure directly.
    Query query = session.createSQLQuery(
     "CALL GetStocks(:stockCode)")
     .addEntity(Stock.class)
     .setParameter("stockCode", "7277");
     
    List result = query.list();
    for(int i=0; i<result.size(); i++){
     Stock stock = (Stock)result.get(i);
     System.out.println(stock.getStockCode());
    }

    2. NamedNativeQuery in annotation

    Declare your store procedure inside the @NamedNativeQueries annotation.
    //Stock.java
    ...
    @NamedNativeQueries({
     @NamedNativeQuery(
     name = "callStockStoreProcedure",
     query = "CALL GetStocks(:stockCode)",
     resultClass = Stock.class
     )
    })
    @Entity
    @Table(name = "stock")
    public class Stock implements java.io.Serializable {
    ...
    Call it with getNamedQuery().
    Query query = session.getNamedQuery("callStockStoreProcedure")
     .setParameter("stockCode", "7277");
    List result = query.list();
    for(int i=0; i<result.size(); i++){
     Stock stock = (Stock)result.get(i);
     System.out.println(stock.getStockCode());
    }

    3. sql-query in XML mapping file

    Declare your store procedure inside the “sql-query” tag.
    
    ...
    >
         name="com.mkyong.common.Stock" table="stock" ...>
             name="stockId" type="java.lang.Integer">
                 name="STOCK_ID" />
                <generator class="identity" />
            >
             name="stockCode" type="string">
                 name="STOCK_CODE" length="10" not-null="true" unique="true" />
            >
            ...
        >
     
         name="callStockStoreProcedure">
      alias="stock" class="com.mkyong.common.Stock"/>
     
        >
     
    >
    Call it with getNamedQuery().
    Query query = session.getNamedQuery("callStockStoreProcedure")
     .setParameter("stockCode", "7277");
    List result = query.list();
    for(int i=0; i<result.size(); i++){
     Stock stock = (Stock)result.get(i);
     System.out.println(stock.getStockCode());
    }

    Conclusion

    The above three approaches are doing the same thing, call a store procedure in database. There are not much big different between the three approaches, which method you choose is depend on your personal prefer.

    Sunday, April 11, 2010

    Apache test config syntax

    /usr/sbin/apache2ctl -t
    add +Includes for directory required SSI

    CSS

    http://www.alistapart.com/

    http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/

    Wednesday, April 7, 2010

    date 31 for setDate javascript

    Date.setDate(day) day:1-31
    When use setDate, setMonth and setYear in javascript.
    Must be in order setYear, setMonth, setDate
     otherwise setDate(31) will create wrong date

    actually not like this, always do a hack setDate first with hard code value is one

    echo "dspStartDate.setDate(1);\n";
    echo "dspStartDate.setFullYear(" . date("Y", $startstamp) . ");\n";
    echo "dspStartDate.setMonth(" . (date("m", $startstamp) - 1) . ");\n";

    //down here the the date that you would like to set

    echo "dspStartDate.setDate(" . date("d", $startstamp) . ");\n";

    Wednesday, March 17, 2010

    Monday, March 15, 2010

    Checkbox value not changes when submit form to server

    Checkboxes

    The status of a checkbox is reflected in the boolean attribute .checked:

    var ischecked = obj.checked;  // Retrieve value
    obj.checked = true; // Force checked state

    When the form is submitted to the web server, the .checked attribute is sent when the checkbox is in the checked state, and it isn't sent when the checkbox is in the unchecked state. You can retrieve or change this value with the .value attribute, as with text fields.

    An onclick event is triggered when the checkbox is clicked. If your event handler returns false, the state of the checkbox will not change on Internet Explorer or Mozilla (and other Gecko-based browsers). On Safari, however, the event handler's return value is ignored.

    E2C
    http://depfind.sourceforge.net/

    Thursday, March 11, 2010

    What to Do with "The requested operation requires elevation" in Vista

    What to Do with "The requested operation requires elevation" in Vista

    Somehow you get the prompt The requested operation requires elevation sometimes when you try to execute some Windows network programs or run some network commands in command prompt, and you might wonder what is this and not too sure what to do next.

    This is actually part of the User Account Control (UAC) feature of Windows Vista that controls the program execution as normal user, administrator or other user types with different access control. You will get this prompt because that program will need to be run as administrator, so the quick way to fix it is re-run by right clicking the program and select Run as administrator.

    Run-as-Administrator

    This alert message will come out sometimes even you run that program with administrator user id, this is because the Vista won’t tell you sometimes when that program needs to be run as administrator.


    DISABLE UAC feature

    If you don’t like this UAC feature, you can actually disable it, you can follow the following ways to disable it. For a better security, next time only log on as normal user to do routine works and use administrator access if you need to run Windows operation or program with admin privilege.

    1) Go to Start -> Control Panel, then click on User Accounts and Family Safety.

    User Accounts and Family Safety

    2) After that click on User Accounts.

    User Accounts

    3) Click Turn User Account Control on or off in User Accounts window.

    Note: If you are using Control Panel in classic view mode, you can come to this page by going to Start ->Control Panel -> User Accounts.

    Turn User Account Control On or Off

    4) Uncheck Use User Account Control (UAC) to help protect your computer and click OK at last.

    Note: You need to to restart the computer in order to disable the UAC feature successfully.

    Use User Account Control UAC

    Monday, March 8, 2010

    Smart Client Lib for GWT

    www.smartclient.com

    http://fredsa.allen-sauer.com/2009/04/1st-look-at-app-engine-using-jdo.html

    http://fredsa.allen-sauer.com/2009/04/1st-look-at-app-engine-using-jdo.html

    Wednesday, February 17, 2010

    Search Engine Friendly URL

    Search Engine Friendly urls


    This tutorial will guide you through setting up the SEF - Search Engine Friendly Urls for the latest version of Joomla 1.5

    By default Joomla will produce URLs which look like this

    Joomla Search engine friendly url

    As you can see the default URL includes the PHP sting, component name plus a number of parameters which don't look to good to search engines or your visitors.

    Enabling the SEF functionality built into Joomla! offers the following advantages

    • It will make it easier for other web sites to link directly to the SEF article rather than to the default URL generated by Joomla!
    • Visitors are more likely to remember the short easy to read SEF URL
    • Provides the visitor and search engines with useful information about the article title and the section, category the article is associated with.
    • You can include targeted keywords in the URL which reference the section, category and article title which may help improve your search engine position
    • Can resolve the issue where your template is displayed on the front page but not on other pages

    The above are just some of the benifits of using SEF Urls.

    We will now explain how you can setup your Joomla! site to use this functionality.

    What will you need to setup the search engine friendly urls

    • Access to the Joomla Administrator area
    • FTP Access to rename and update the htaccess.txt file included with the default installation of Joomla!
    • Your web site is hosted on a Linix platform, this tutorial does not cover setting up SEF urls for IIS

    Step 1 : Rename Htaccess.txt file

    The first step is to rename the htaccess.txt file located in the root of the public_html directory where you have installed Joomla!. To do this log into the web site using your FTP client and rename the htaccess.txt file to .htaccess

    Please note you must add the dot . before the htaccess file when renaming it from htaccess.txt to .htaccess

    Step 2 : Configuration.php file permissions

    In order to change the SEO settings you will need to ensure the Joomla! configuration.php file is writable.

    To make the configuration.php file writable complete the following

    1. Log into the web site using your FTP client and browse to the Joomla installation
    2. Select the configuration.php file and change the file permissions from CHMOD 644 to CHMOD 777
    After you have updated the SEO settings ALWAYS change the file permissions for the configuration.php file back to CHMOD 644

    STEP 3 : Setup Joomla SEO settings

    1. Log into the Joomla! administrator area
    2. Select the Global Configuration icon
    3. You will now see the following SEO setting
    4. To save the SEO settings select the APPLY button

    4. Each setting you select from the above will produce a different result.

    5. If you enable the " Search Engine Friendly URLs" option

    6. The URL will look like this and include the .index.php name in the URL

    7. Using the above method may break the template layout "your design displays ok on the front page but not on other pages"

    8 . If you enable both the "search engine friendly URLs" plus "Use Apache mod_rewrite"

    9. The URL will look like this and produce a clean easy to read URL.

    10. If you enable all 3 of the above settings

    11. The URL will display a .html suffix

    If you want search engine and human freindly URLs we recommend you choose both the "search engine friendly URLs" plus "Use Apache mod_rewrite" seo options.

    From http://www.joomladesigns.co.uk/Tutorials/Joomla/Search-Engine-Friendly-urls.html

    Store Procedure and Function

    The main different between store procedure and function is that
    - Function can return only one value and must return a value
    - Store procedure can have many IN or OUT parameters and no return value
    - Function can be called in a select statement but store procedure can not be called in a select, it must be executed by 'call storeprocedure name'
    Example
    create function AddA(p_inparam varchar(30)) returns varchar(30)
    return concat('A',p_inparam);

    mysql> select AddA(emp_name) from emps;
    +----------------+
    | AddA(emp_name) |
    +----------------+
    | ARoger |
    | AJohn |
    | AAlan |
    +----------------+
    3 rows in set (0.26 sec)

    create procedure AddB(INOUT p_inparam varchar(30))
    set p_inparam := concat('B',p_inparam);

    mysql> select AddB(emp_name) from emps;
    ERROR 1305 (42000): FUNCTION pers.AddB does not exist

    mysql> select call AddB(emp_name) from emps;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'call AddB(emp_name) from emps' at line 1

    Thursday, January 21, 2010

    • R = runnable
    • S = sleeping
    • D = uninterruptible sleep
    • T = stopped or traced
    • Z = zombie process
    • Second field = W if the process has no resident pages.
    • Third field = N if the process has a positive nice value

    How to enable or clean cache in Joomla 1.5?

    Enabling cache will increase the overall performance of your Joomla application.

    You can enable caching from your Joomla admin area > Site > Global Configuration > System.

    At the right side of the System page, under Cache Settings, next to Cache you should select Yes. Then click Save at the top right menu to enable caching for your Joomla :)


    Sometimes, when you have made a change in your Joomla application and it does not appear on the front end, the only solution is cleaning the cache.

    You can clean your Joomla 1.5 cache from the admin area > Tools > Clean Cache.



    Apache, by default, is set up for worker processes to exit after handling a limited number of requests. This is designed to not allow memory leaks to get out of hand.

    Usually, the main Apache process will reap any of its workers that exit. However, on a heavily-loaded server like you describe, the main process may not have enough time available to it to do this reaping. Unreaped (“zombie”) processes show up as in top. In this case, the processes are normal and are not of concern, unless there are many, many unreaped processes.

    However, an alternative possibility is that your worker processes are dying abnormally. This can happen if your web application (or its engine) has a bug which causes the worker process to crash. You should look in your Apache error log to see if there are any serious error messages in it.

    The below explains what means. If you aren't a Unix system administrator, this may not be of interest to you.

    Normally, when a process exits (normally or abnormally), it enters a state known as “zombie” (which in top appears as Z). Its process ID stays in the process table until its parent waits on (or “reaps”) it. Under normal circumstances, when the parent process fully expects its child processes to exit, it sets up a signal handler for SIGCHLD so that, when the signal is sent (upon a child process's exit), the parent process then reaps it at its convenience.

    If the parent process has hung for some reason, such as if it's suspended, or is too busy, or is deadlocked, then child processes that exit will not be reaped (until the parent process resumes again). This can cause serious problems if there are many child processes, occupying slots in the process table that will not be freed.

    In that case, one solution (if the parent process is unrecoverable, say), is to kill the parent process. Then, the child processes will be reparented to the init process (process ID 1), which will reap them. (If the init process is stalled, then you have much, much bigger problems than child processes not being reaped. In fact, a crashed init process will usually cause a kernel panic.)

    Tuesday, January 19, 2010

    How to config timezone for debian

    How to config timezone for debian
    dpkg-reconfigure tzdata
    Memory Leak Control

    After months frustrated with server crashing due to memory leak of mysql server. I found a way so that we can control how memory increase by date and log it in the system. Here is my way

    First using sysstat to monitor mysql process

    debian : apt-get install sysstat
    or can install from source by download from sysstat page

    Create experiments for testing