Friday, December 4, 2009

Take backup - but without Stupidity !!!

Please take backup ur code on regular basis otherwise.... :( I got bad sector on my HDD drive ( that contained the OS and my coding folders too... ) suddenly and i discover me that i took my backup on Desktop - as a result guess what happened? All of my codes with my backup turns into my bad dreams :( I tried with several recovery utilities for more than a week but no positive results... and i found some of my important task was in jar formatted - i needed to recover the class files to code - so i download DJ Decompiler - ( i used it before ... one good tool....) but after downloading.... i could not use it any more ..... ( of course for free ) - However i download and this simply saved my time and make me :)

If you need to convert your class files to source (.java) file simply download and enjoy.

Happy Coding..... :)

Monday, August 17, 2009

Tasks....

Search for handsets support AT commands
http://www.allthemobile.com/search/?qr=nokia+AT+command+support+sets

http://www.developershome.com/sms/freeLibForSMS.asp

Check compatibility
http://www.developershome.com/sms/cpmsCommand.asp




Responsibilities:
Lead and oversee the design of new, Java / J2EE / Java EE and SOA based solutions.
Perform Research and Development into the very latest in Internet-based technologies, methodologies, architectures and industry trends.
Analyze code to find causes of errors and revise code. Test code using structured testing methodology and confirms programs meet specification.
Convert designs and specifications into code.
Write and maintain technical specifications, documentation to describe program development, coding, testing, changes, and corrections, installation and operation of developed software.
Provide technical assistance by responding to inquiries from other stakeholders.

Requirements:

A strong interest in researching, making recommendations and implementing new web related tools/technologies is highly preferred. The candidate must be able to code, debug and test application programs utilizing JAVA and web-based programming tools. Having hands on experience in HTML, CSS etc i.e. web technologies will be an advantage. Candidates must be committed to exacting quality standards; extensive unit and integration test experience. Candidates must have experience working successfully in a close team environment.
2+ years experience designing and deploying Java / J2EE / Java EE-based solutions on behalf of complex, integrated, business environments.
Experience designing and exposing re-usable Service Orientated Architecture (SOA) based solutions.
Deep knowledge of XML, Apache Tomcat, JBoss, Java Server Pages (JSP), HTTP, and Servlets.
Proven and extensive experience designing solutions using the Apache Struts Framework (for Java EE) and Apache Axis Framework (for Web Services).
Possesses a strong background in Object-Oriented (OO) system design.
Experience with iterative software design, prototyping and methodologies.
Demonstrable experience with Intellij IDEA or similar product.
Experience with software build/deployment frameworks (such as MAKE, ANT, MAVEN, etc.) and unit test frameworks (such as JUNIT).
Experience performing source control with Perforce or similar product.
Excellent written and verbal communication skills. Presentation skills and the demonstrable ability to discuss technical subjects with personnel - at all levels - is a must.
Highly analytical, pro-active and detail oriented.

Tuesday, June 23, 2009

Oracle Driver Missing for Reports

Check Oracle Driver Missing Info

1. java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Hi everybody

I'm new in java Platform and i have problems trying to load a JDBC driver using Class.forname, but JVM can not find it. I configured classpath enviroment path pointig to libraries

OS: Windows XP
Java Version 1.6
IDE Eclipse 3.2.2

classpath = .;C:\Program Files\Altova\xmlspy\XMLSpyInterface.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msbase.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msutil.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\mssqlserver.jar;D:\oracle\ora92\jdbc\lib\ classes12.zip


java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at bpos.Db.Conectar(Db.java:20)
at bpos.Process.main(Process.java:19)


Can anybody help me about this? It will appreciate.

Leo


2. Hello Leo,

Try putting the full path to the Oracle classes12.zip file at the front of the CLASSPATH. Also remove the extra space between the \ and classes12.zip.

Before you test with an app, ensure the driver returns version information by running this command on the command line:

java oracle.jdbc.driver.OracleDriver

If that command does not work, you still have environment problems and need to revisit before you test with the app.

Best regards,
Netrista Khatam
Technical Services Manager
OpenLink Product Support


3. Hi Netrista.. thank you for your help.. I checked my enviroment variables and i didn't find problems. I think that was copy paste mistake. I put first the oracle driver library reference into the classpath enviroment variable

C:\>echo %classpath%
.;D:\oracle\ora92\jdbc\lib\classes12.zip;C:\Progra m Files\Altova\xmlspy\XMLSpyInterface.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msbase.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\msutil.jar;c:\program files\Microsoft SQL Server 2000 Driver for JDBC\lib\mssqlserver.jar

I performed your suggested command and i couldn't get the version of each class i'm trying to use

C:\>java oracle.jdbc.driver.OracleDriver
Exception in thread "main" java.lang.NoSuchMethodError: main

C:\>java com.microsoft.jdbc.sqlserver.SQLServerDriver
null

any other thing that it could be used? thanks!

Leo


4. Hello Leo,

This is what I would recommend:

1. Verify that the following path is correct:

D:\oracle\ora92\jdbc\lib\classes12.zip

2. Insure no permissions issues exist on that file or directory structure, which is unlikely since it is Windows.

3. Run this command to get your java version:

java -version

4. Insure that the java version of the JVM/JDK that you have installed on Windows is compatible with the requirements of the driver.

Can you state whether or not you can use the other JDBC drivers to get a connection using the application, even though they error on the commandline with DOS. I've seen that before, so it's important to ascertain whether the app connectivity issue is specific to Oracle or generalized to all JDBC connections.


Best regards,
Netrista Khatam
Technical Services Manager
OpenLink Product Support

5. Fixed!
Thank you very much.

The classpath was correct. I proved on command line and it worked correctly. So i have to change my approach looking for into my IDE project definition parameters. I' m using Eclipse and i found that i have to define a classpath for the project.

Ups! I'm new in Eclipse too.. and i forgot mention it. Your description of the solution helped me to find the final solution. Thank you!

Leo


Quote:

Try putting the full path to the Oracle classes12.zip file at the front of the CLASSPATH. Also remove the extra space between the \ and classes12.zip.

Before you test with an app, ensure the driver returns version information by running this command on the command line:

java oracle.jdbc.driver.OracleDriver

If that command does not work, you still have environment problems and need to revisit before you test with the app.

Best regards,
Netrista Khatam
Technical Services Manager
OpenLink Product Support

Tuesday, June 9, 2009

Customize JBoss log file size

Customize JBoss log file size


Some of the logging configuration changes that you might want to make include:
• Specifying a rolling log file.
• Limiting the amount of logging produced.
• Adding logging for your application.
• Defining a new log file.


Each of these topics is covered in the following text.

Rolling the server log file
The server.log file is created new each time the server is launched, and grows until the server is stopped, or until midnight. This behavior, while appropriate for a development environment, is not optimal for a production environment. In production you should specify a rolling log file, which when it reaches a certain size creates a new log file. Listing 1 shows how you can change the appender for the server.log file to create at most 20 log files of 10 megabytes (MB) in size each. All of the changes are highlighted.

Listing 1 Defining a rolling log appender

01.<log4j:...>
02. <appender name="FILE"
03. class="org.jboss.logging.appender.RollingFileAppender"> #1
04. <errorHandler .../>
05. <param name="File" value="${jboss.server.log.dir}/server.log"/> #2
06. <param name="Append" value="true"/> #3
07. <param name="MaxFileSize" value="10MB"/> #4
08. <param name="MaxBackupIndex" value="20"/> #5
09. <layout .../>
10. appender>
11. ...
12.log4j>

#1: Changed to use the rolling appender
#2: Location of log file
#3: Append to existing file on startup
#4: Limit log file size to 10MB
#5: Keep only the last 20 log files

We did not change the errorHandler or layout settings from the default. By the way, the various appenders defined in the org.jboss.logging.appender package are simple subclasses of the Log4J appenders defined in the org.apache.log4j package that automatically create the server/xxx/log directory.
The system property jboss.server.log.dir defines the location of the log file (#2).


Tuesday, May 26, 2009

Generic Data Access Objects


Generic Data Access Objects

This is a pattern for Data Access Objects with JDK 5.0, from the CaveatEmptor example application. It is also explained in the book Java Persistence with Hibernate. Two links you might find useful: Sessions and transactions and Open Session in View.

This time I based the DAO example on interfaces. Tools like Hibernate already provide database portability, so persistence layer portability shouldn't be a driving motivation for interfaces. However, DAO interfaces make sense in more complex applications, when several persistence services are encapsulate in one persistence layer. I'd say that you should use Hibernate (or Java Persistence APIs) directly in most cases, the best reason to use an additional DAO layer is higher abstraction (e.g. methods like getMaximumBid() instead of session.createQuery(...) repeated a dozen times).

The DAO interfaces

I use one interface per persistent entity, with a super interface for common CRUD functionality:

public interface GenericDAO {

T findById(ID id, boolean lock);

List findAll();

List findByExample(T exampleInstance);

T makePersistent(T entity);

void makeTransient(T entity);
}

You can already see that this is going to be a pattern for a state-oriented data access API, with methods such as makePersistent() and makeTransient(). Furthermore, to implement a DAO you have to provide a type and an identifier argument. As for most ORM solutions, identifier types have to be serializable.

The DAO interface for a particular entity extends the generic interface and provides the type arguments:

public interface ItemDAO extends GenericDAO {

public static final String QUERY_MAXBID = "ItemDAO.QUERY_MAXBID";
public static final String QUERY_MINBID = "ItemDAO.QUERY_MINBID";

Bid getMaxBid(Long itemId);
Bid getMinBid(Long itemId);

}

We basically separate generic CRUD operations and actual business-related data access operations from each other. (Ignore the named query constants for now, they are convenient if you use annotations.) However, even if only CRUD operations are needed for a particular entity, you should still write an interface for it, even it it is going to be empty. It is important to use a concrete DAO in your controller code, otherwise you will face some refactoring once you have to introduce specific data access operations for this entity.

An implementation with Hibernate

An implementation of the interfaces could be done with any state-management capable persistence service. First, the generic CRUD implementation with Hibernate:

public abstract class GenericHibernateDAO
implements GenericDAO {

private Class persistentClass;
private Session session;

public GenericHibernateDAO() {
this.persistentClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}

@SuppressWarnings("unchecked")
public void setSession(Session s) {
this.session = s;
}

protected Session getSession() {
if (session == null)
throw new IllegalStateException("Session has not been set on DAO before usage");
return session;
}

public Class getPersistentClass() {
return persistentClass;
}

@SuppressWarnings("unchecked")
public T findById(ID id, boolean lock) {
T entity;
if (lock)
entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
else
entity = (T) getSession().load(getPersistentClass(), id);

return entity;
}

@SuppressWarnings("unchecked")
public List findAll() {
return findByCriteria();
}

@SuppressWarnings("unchecked")
public List findByExample(T exampleInstance, String[] excludeProperty) {
Criteria crit = getSession().createCriteria(getPersistentClass());
Example example = Example.create(exampleInstance);
for (String exclude : excludeProperty) {
example.excludeProperty(exclude);
}
crit.add(example);
return crit.list();
}

@SuppressWarnings("unchecked")
public T makePersistent(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}

public void makeTransient(T entity) {
getSession().delete(entity);
}

public void flush() {
getSession().flush();
}

public void clear() {
getSession().clear();
}

/**
* Use this inside subclasses as a convenience method.
*/
@SuppressWarnings("unchecked")
protected List findByCriteria(Criterion... criterion) {
Criteria crit = getSession().createCriteria(getPersistentClass());
for (Criterion c : criterion) {
crit.add(c);
}
return crit.list();
}

}

There are some interesting things in this implementation. First, it clearly needs a Session to work, provided with setter injection. You could also use constructor injection. How you set the Session and what scope this Session has is of no concern to the actual DAO implementation. A DAO should not control transactions or the Session scope.

We need to suppress a few compile-time warnings about unchecked casts, because Hibernate's interfaces are JDK 1.4 only. What follows are the implementations of the generic CRUD operations, quite straightforward. The last method is quite nice, using another JDK 5.0 feature, varargs. It helps us to build Criteria queries in concrete entity DAOs. This is an example of a concrete DAO that extends the generic DAO implementation for Hibernate:

public class ItemDAOHibernate
extends GenericHibernateDAO
implements ItemDAO {

public Bid getMaxBid(Long itemId) {
Query q = getSession().getNamedQuery(ItemDAO.QUERY_MAXBID);
q.setParameter("itemid", itemId);
return (Bid) q.uniqueResult();
}

public Bid getMinBid(Long itemId) {
Query q = getSession().getNamedQuery(ItemDAO.QUERY_MINBID);
q.setParameter("itemid", itemId);
return (Bid) q.uniqueResult();
}

}

Another example which uses the findByCriteria() method of the superclass with variable arguments:

public class CategoryDAOHibernate
extends GenericHibernateDAO
implements CategoryDAO {

public Collection findAll(boolean onlyRootCategories) {
if (onlyRootCategories)
return findByCriteria( Expression.isNull("parent") );
else
return findAll();
}
}

Preparing DAOs with factories

We could bring it all together in a DAO factory, which not only sets the Session when a DAO is constructed but also contains nested classes to implement CRUD-only DAOs with no business-related operations:

public class HibernateDAOFactory extends DAOFactory {

public ItemDAO getItemDAO() {
return (ItemDAO)instantiateDAO(ItemDAOHibernate.class);
}

public CategoryDAO getCategoryDAO() {
return (CategoryDAO)instantiateDAO(CategoryDAOHibernate.class);
}

public CommentDAO getCommentDAO() {
return (CommentDAO)instantiateDAO(CommentDAOHibernate.class);
}

public ShipmentDAO getShipmentDAO() {
return (ShipmentDAO)instantiateDAO(ShipmentDAOHibernate.class);
}

private GenericHibernateDAO instantiateDAO(Class daoClass) {
try {
GenericHibernateDAO dao = (GenericHibernateDAO)daoClass.newInstance();
dao.setSession(getCurrentSession());
return dao;
} catch (Exception ex) {
throw new RuntimeException("Can not instantiate DAO: " + daoClass, ex);
}
}

// You could override this if you don't want HibernateUtil for lookup
protected Session getCurrentSession() {
return HibernateUtil.getSessionFactory().getCurrentSession();
}

// Inline concrete DAO implementations with no business-related data access methods.
// If we use public static nested classes, we can centralize all of them in one source file.

public static class CommentDAOHibernate
extends GenericHibernateDAO
implements CommentDAO {}

public static class ShipmentDAOHibernate
extends GenericHibernateDAO
implements ShipmentDAO {}

}

This concrete factory for Hibernate DAOs extends the abstract factory, which is the interface we'll use in application code:

public abstract class DAOFactory {

/**
* Creates a standalone DAOFactory that returns unmanaged DAO
* beans for use in any environment Hibernate has been configured
* for. Uses HibernateUtil/SessionFactory and Hibernate context
* propagation (CurrentSessionContext), thread-bound or transaction-bound,
* and transaction scoped.
*/
public static final Class HIBERNATE = org.hibernate.ce.auction.dao.hibernate.HibernateDAOFactory.class;

/**
* Factory method for instantiation of concrete factories.
*/
public static DAOFactory instance(Class factory) {
try {
return (DAOFactory)factory.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Couldn't create DAOFactory: " + factory);
}
}

// Add your DAO interfaces here
public abstract ItemDAO getItemDAO();
public abstract CategoryDAO getCategoryDAO();
public abstract CommentDAO getCommentDAO();
public abstract ShipmentDAO getShipmentDAO();

}

Note that this factory example is suitable for persistence layers which are primarily implemented with a single persistence service, such as Hibernate or EJB 3.0 persistence. If you have to mix persistence APIs, for example, Hibernate and plain JDBC, the pattern changes slightly. Keep in mind that you can also call session.connection() inside a Hibernate-specific DAO, or use one of the many bulk operation/SQL support options in Hibernate 3.1 to avoid plain JDBC.

Finally, this is how data access now looks like in controller/command handler code (pick whatever transaction demarcation strategy you like, the DAO code doesn't change):

// EJB3 CMT: @TransactionAttribute(TransactionAttributeType.REQUIRED)
public void execute() {

// JTA: UserTransaction utx = jndiContext.lookup("UserTransaction");
// JTA: utx.begin();

// Plain JDBC: HibernateUtil.getCurrentSession().beginTransaction();

DAOFactory factory = DAOFactory.instance(DAOFactory.HIBERNATE);
ItemDAO itemDAO = factory.getItemDAO();
UserDAO userDAO = factory.getUserDAO();

Bid currentMaxBid = itemDAO.getMaxBid(itemId);
Bid currentMinBid = itemDAO.getMinBid(itemId);

Item item = itemDAO.findById(itemId, true);

newBid = item.placeBid(userDAO.findById(userId, false),
bidAmount,
currentMaxBid,
currentMinBid);

// JTA: utx.commit(); // Don't forget exception handling

// Plain JDBC: HibernateUtil.getCurrentSession().getTransaction().commit(); // Don't forget exception handling

}

The database transaction, either JTA or direct JDBC, is started and committed in an interceptor that runs for every execute(), following the Open Session in View pattern. You can use AOP for this or any kind of interceptor that can be wrapped around a method call, see Session handling with AOP.

Preparing DAOs with manual dependency injection

You don't need to write the factories. You can as well just do this:

// EJB3 CMT: @TransactionAttribute(TransactionAttributeType.REQUIRED)
public void execute() {

// JTA: UserTransaction utx = jndiContext.lookup("UserTransaction");
// JTA: utx.begin();

// Plain JDBC: HibernateUtil.getCurrentSession().beginTransaction();

ItemDAOHibernate itemDAO = new ItemDAOHibernate();
itemDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());

UserDAOHibernate userDAO = new UserDAOHibernate();
userDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());

Bid currentMaxBid = itemDAO.getMaxBid(itemId);
Bid currentMinBid = itemDAO.getMinBid(itemId);

Item item = itemDAO.findById(itemId, true);

newBid = item.placeBid(userDAO.findById(userId, false),
bidAmount,
currentMaxBid,
currentMinBid);

// JTA: utx.commit(); // Don't forget exception handling

// Plain JDBC: HibernateUtil.getCurrentSession().getTransaction().commit(); // Don't forget exception handling

}

The disadvantage here is that the implementation classes (i.e. ItemDAOHibernate and UserDAOHibernate) of the persistence layer are exposed to the client, the controller. Also, constructor injection of the current Session might be more appropriate.

Preparing DAOs with lookup

Alternatively, call HibernateUtil.getSessionFactory().getCurrentSession() as a fallback, if the client didn't provide a Session when the DAO was constructed:

public abstract class GenericHibernateDAO
implements GenericDAO {

private Class persistentClass;
private Session session;

public GenericHibernateDAO() {
this.persistentClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}

public void setSession(Session session) {
this.session = session;
}

protected void getSession() {
if (session == null)
session = HibernateUtil.getSessionFactory().getCurrentSession();
return session;
}

...

The controller now uses these stateless data access objects through direct instantiation:

// EJB3 CMT: @TransactionAttribute(TransactionAttributeType.REQUIRED)
public void execute() {

// JTA: UserTransaction utx = jndiContext.lookup("UserTransaction");
// JTA: utx.begin();

// Plain JDBC: HibernateUtil.getCurrentSession().beginTransaction();

ItemDAO itemDAO = new ItemDAOHibernate();
UserDAO userDAO = new UserDAOHibernate();

Bid currentMaxBid = itemDAO.getMaxBid(itemId);
Bid currentMinBid = itemDAO.getMinBid(itemId);

Item item = itemDAO.findById(itemId, true);

newBid = item.placeBid(userDAO.findById(userId, false),
bidAmount,
currentMaxBid,
currentMinBid);

// JTA: utx.commit(); // Don't forget exception handling

// Plain JDBC: HibernateUtil.getCurrentSession().getTransaction().commit(); // Don't forget exception handling

}

The only disadvantage of this very simple strategy is that the implementation classes (i.e. ItemDAOHibernate and UserDAOHibernate) of the persistence layer are again exposed to the client, the controller. You can still supply a custom Session if needed (integration test, etc).

Each of these methods (factories, manual injection, lookup) for setting the current Session and creating a DAO instance has advantages and drawbacks, use whatever you feel most comfortable with.

Naturally, the cleanest way is managed components and EJB 3.0 session beans:

Writing DAOs as managed EJB 3.0 components

Turn your DAO superclass into a base class for stateless session beans (all your concrete DAOs are then stateless EJBs, they already have a business interface). This is basically a single annotation which you could even move into an XML deployment descriptor if you like. You can then use dependency injection and get the "current" persistence context provided by the container:

@Stateless
public abstract class GenericHibernateDAO
implements GenericDAO {

private Class persistentClass;

@PersistenceContext
private EntityManager em;

public GenericHibernateDAO() {
setSession( (Session)em.getDelegate() );
}

...

You can then cast the delegate of an EntityManager to a Hibernate Session.

This only works if you use Hibernate as a Java Persistence provider, because the delegate is the Session API. In JBoss AS you could even get a Session injected directly. If you use a different Java Persistence provider, rely on the EntityManager API instead of Session. Now wire your DAOs into the controller, which is also a managed component:

@Stateless
public class ManageAuctionController implements ManageAuction {

@EJB ItemDAO itemDAO;
@EJB UserDAO userDAO;

@TransactionAttribute(TransactionAttributeType.REQUIRED) // This is even the default
public void execute() {

Bid currentMaxBid = itemDAO.getMaxBid(itemId);
Bid currentMinBid = itemDAO.getMinBid(itemId);

Item item = itemDAO.findById(itemId, true);

newBid = item.placeBid(userDAO.findById(userId, false),
bidAmount,
currentMaxBid,
currentMinBid);

}
}

P.S. Credit has to be given to Eric Burke, who first posted the basics for this pattern on his blog. Unfortunately, not even the Google cache is available anymore.

A Better typed Generic DAO? You decide!

We are missing something on end, since T allows you to "domain-ify" everything! and the Identifier type should ideally match the identifier type of T, but there's no way to do that on the code above. You decide which approach is better.

// Our common Model interface that an abstract Domain model will implement and all domain // models will extend.
public interface IModel {
public abstract ID getId();
public abstract void setId(final ID pId);
}
// Our generic DAO, NOTE: MODEL's ID type is the same as ID now, which makes sense.
// Also model type is more restrictive, dis-allowing all kinds of funky stuff to go in.
public abstract class GenericHibernateDAO, ID extends Serializable> implements GenericDAO {

private Class persistentClass;
private Session session;

public GenericHibernateDAO() {
// FIXME : I don't like magic number in the code, is there any way to fix 0 to something dynamic?
this.persistentClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}

public final void setSession(final Session pSession) {
this.session = session;
}

protected void getSession() {
if (session == null)
session = HibernateUtil.getSessionFactory().getCurrentSession();
return session;
}
...

In addition, we could add things like:

public final String getRootAlias(){
this.getPersistentClass().getSimpleName() + String.valueOf('_');
}

Alhough this is not necessary or part of the enhanced version, but when criteria API is in use, this comes in handy.


Reference : https://www.hibernate.org/328.html



Wednesday, May 20, 2009

Tuesday, April 28, 2009

DAO Links

DAO (Data Access Object) from sun

p4j very useful link

DataAccessObject

The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. The BusinessObject also delegates data load and store operations to the DataAccessObject.

DataSource

This represents a data source implementation. A data source could be a database such as an RDBMS, OODBMS, XML repository, flat file system, and so forth. A data source can also be another system (legacy/mainframe), service (B2B service or credit card bureau), or some kind of repository (LDAP).

TransferObject

This represents a Transfer Object used as a data carrier. The DataAccessObject may use a Transfer Object to return data to the client. The DataAccessObject may also receive the data from the client in a Transfer Object to update the data in the data source.


Here we go for some useful links....

Issues in calling DAO from Sateless session bean

From JavaWorld

Core J2EE Patterns - Session Facade


Don't repeat the DAO!

jpa-ejb killed dao

JPA/EJB3 killed the DAO

Regarding to the abstract of the DAO-Pattern: "Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation." the DAO tries to decouple the business logic from the proprietary resource. The solution to the problem is the following: "...The DataAccessObject is the primary object of this pattern. The DataAccessObject abstracts the underlying data access implementation for the BusinessObject to enable transparent access to the data source. The BusinessObject also delegates data load and store operations to the DataAccessObject..." [Core J2EE Patterns].

In the practise the DAO-Pattern was often realized by the following items:

  • DAO-Interface (provided a datasource-neutral interface)
  • DAO-Implementation (=access to the datasource implementation)
  • DAO-Factory (the creation of the implementation)
  • Optional: ServiceLocator (location of resources in JNDI)
The main problem in J2EE was the insufficient power of CMP 2.0. The limited query capabilities, no access to native SQL and lack of dynamic queries forced the developers to access the database using plain-JDBC. It was a very good idea to encapsulate the database access behind a replaceable and mockable implementation.
In EJB 3/Java EE 5 environment there is no need to use the low level JDBC to access the database any more. Actually you can use generic, but powerful Query Lanaguae, as well as Native SQL to fetch not only the persistent objects, but also data transfer objects and even primitive data types as well. It is even possible to execute update and delete statements. The JPA comes already with the EntityManager which provides already generic data access functionality. The usage cannot be simpler. The EntityManager will be just injected to the bean-class:

@Stateless
public class CustomerMgrBean implements CustomerMgr{

@PersistenceContext
private EntityManager em;

It's just one liner. The DAO pattern is actually no more interesting for general data access, but is still needed to access data from stored procedures, flat files etc. However the bean above can be considered as a "DAO", but very streamlined one...
You will find some examples in p4j5 - feel free to participate.



Faking css position: fixed in Internet Explorer 6

Useful link for IE6 css hack

Try at last

Another How to fix div position using javascript in IE 6.0

This is a trick that I have been doing for some time, but now that Internet Explorer 7 is out and it supports position fixed in css; I think this trick will been even more useful now that it will allow web developers to take better advantage of css and at the same time not leave out the Internet Explorer 6 user base. I am posting this here because I sent this to a friend a couple days ago and thought others might be able to use it as well.



The trick is really quite basic. For simplicity I am just putting this example inline, but you can put it where you want.


First your declare your intended style for IE7 (and basically every other browser):



<style type="text/css">
#fixed_div {
position: fixed;
top: 0px; /* tweak this according to placement */
left: 0px; /* tweak this according to placement */
/* add additional styling, etc. */
}
</style>

Second add in your Javascript function which is going to be doing your movement for IE6:



<script type="text/javascript">

function move_box() {
var offset = 0; // set offset (likely equal to your css top)
var element = document.getElementById('fixed_div');

element.style.top = (document.documentElement.scrollTop + offset) + 'px';
}
</script>

Then declare the element itself:



<div id="fixed_div">I am fixed, even in IE6</div>

Lastly, implement your fix for IE6 only:



<!--[if lt IE 7]>

<style type="text/css">
#fixed_div {
position: absolute;
top: 0px; /* tweak this according to placement */
left: 0px; /* tweak this according to placement */
}
</style>
<script type="text/javascript">
window.setInterval(move_box, 100);
</script>
<![endif]-->

I usually put this last part right before the end of the body (I guess you could just put the whole script there). This is because you don't want the window.setInterval to fire before your fixed div is declared. You could use the body onload but I try to stay away from that because I know it is popular for other uses on more advanced pages and I don't want to run the risk of interfering.


Here is the whole script put together:




<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
. . .
<style type="text/css">
#fixed_div {
position: fixed;
top: 0px; /* tweak this according to placement */
left: 0px; /* tweak this according to placement */
/* add additional styling, etc. */
}
</style>
<script type="text/javascript">

function move_box() {
var offset = 0; // set offset (likely equal to your css top)
var element = document.getElementById('fixed_div');

element.style.top = (document.documentElement.scrollTop + offset) + 'px';
}
</script>
. . .
</head>
<body>
. . .
<div id="fixed_div">I am fixed, even in IE6</div>
. . .

<!--[if lt IE 7]>
<style type="text/css">
#fixed_div {
position: absolute;
top: 0px; /* tweak this according to placement */
left: 0px; /* tweak this according to placement */
}
</style>
<script type="text/javascript">
window.setInterval(move_box, 100);
</script>
<![endif]-->
</body>

</html>

NOTE: This will only work properly on pages that have a valid doctype definition. If you don't use one [you should start or] you need to change document.documentElement.scrollTop to document.body.scrollTop in the move_box function.


You can also modify this script to apply to multiple elements by passing arguments to the function or something similar. If you are doing multiple elements on a single page, you may want to consider setting up some kind of Javascript array that tracks what elements need to be corrected, this could save you from having multiple window.setInterval instances running.

http://www.finefrog.com/_code/59.html

http://www.howtocreate.co.uk/fixedPosition.html

Wednesday, April 22, 2009

Fluid Layout Template - Fixed Buttons Div

Reference : http://www.howtocreate.co.uk/fixedPosition.html

http://en.allexperts.com/q/Javascript-1520/position-fixed.htm

http://www.jtricks.com/javascript/navigation/fixed_menu.html

Put in head tag: 

Within body tag:





Deprecated



This fix is deprecated and is no longer supported (meaning that I will not help you to get it working with your pages). It was only written to fill the gap while waiting for Internet Explorer to implement fixed positioning. That has now happened in IE 7. Although this fix can make it work in IE 6 as well, that is counter productive for the future of the Web. IE 6 is a major problem to Web developers (IE 7 is a problem as well, but for now, let's overlook that, since it does at least implement fixed positioning), and the sooner it stops being used, the better.



Instead of using this hack, users of IE 6 should be encouraged to upgrade to IE 7. Users who cannot upgrade to IE 7 (because IE 7 is not being released for most Windows operating systems) should use a better browser, such as Opera or Firefox. They have been abandoned by Microsoft.



What is position: fixed;?


position: fixed; is an alternative to position: absolute; position: relative; and position: static;.


position: fixed; is basically the same as position: absolute; except that when the user scrolls the page, the element
does not scroll with it, it just says exactly where it was. There are many pages that want to use this in order to position
logos or menus.


What is wrong with position: fixed;?


Well, ... nothing. The problem is that the most popular browser - Internet Explorer for Windows - does not understand
it, and instead of reverting to position: absolute; which would be better than nothing, it reverts to position: static; as
specified by the CSS standard. This has the same effect as having no positioning at all. Note that IE 7 from beta 2 upwards
does support position: fixed; (if you use a document type declaration that triggers strict mode) so I will exclude IE 7 from this fix.


As a result, serveral people write scripts that use setInterval to reposition an absolutely positioned element every few
miliseconds, or (ignoring Netscape 4) when the onscroll event is detected. This produces a slightly jerky effect. It would
be better if the position: fixed; style could be applied in browsers that supported it, and browsers that didn't could use
position: absolute; and JavaScript. Some authors use the > CSS selector to isolate Internet Explorer and leave the element
positioned absolutely in that browser, without the scrolling effect.


div#fixme { position: absolute; left: 0px; top: 0px; }
body > div#fixme { position: fixed; }

It produces a reasonably nice effect, but it is even better when coupled with a JavaScript that checks if the position is
'absolute' using the currentStyle property, and then repositioning the element when the onscroll event is detected.




F
i
x

M
e




F
i
x

M
e

T
o
o








Friday, April 17, 2009

Send mail using javamail and gmail

This is my fully tested code. You need javamail 1.4 api to run this. If u find any kind of exception check ur system firewall that is blocking to send mail.

Add mail.jar and activation.jar in ur buildpath and run the code:


import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleSSLMail {

  private static final String SMTP_HOST_NAME = "smtp.gmail.com";
  private static final int SMTP_HOST_PORT = 465;
  private static final String SMTP_AUTH_USER = "xxxxx@gmail.com";
  private static final String SMTP_AUTH_PWD = "xxxx";

  public static void main(String[] args) throws Exception{
  new SimpleSSLMail().test();
  }

  public void test() throws Exception{
  Properties props = new Properties();

  props.put("mail.transport.protocol", "smtps");
  props.put("mail.smtps.host", SMTP_HOST_NAME);
  props.put("mail.smtps.auth", "true");
  // props.put("mail.smtps.quitwait", "false");

  Session mailSession = Session.getDefaultInstance(props);
   
  mailSession.setDebug(true);
   
  Transport transport = mailSession.getTransport();

  MimeMessage message = new MimeMessage(mailSession);
  message.setSubject("Hello Attatched world");
   
  //message.setContent("This is a test", "text/plain");
   
  // content
  MimeBodyPart mimeBodyPart = new MimeBodyPart();
   
  //mimeBodyPart.setText("Link goes here:");  
  String strLink = " Link goes here : http://www.google.com";
  mimeBodyPart.setText(strLink);
   
  // multipart is the main content holder
  Multipart multipart = new MimeMultipart();
  multipart.addBodyPart(mimeBodyPart);
   
  // Part two is attachment
  File f = new File("F:\\angel.JPG");
  if(f.exists() && f.isFile())
  {
  System.out.println("attatching file......."+f.getName());
  mimeBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(f);  
  DataHandler handler = new DataHandler(source);
  mimeBodyPart.setDataHandler(handler);
   
  mimeBodyPart.setFileName(f.getName());
   
  multipart.addBodyPart(mimeBodyPart);
   
  }
   
  // add multipart data to message
  message.setContent(multipart);
   
   
  message.addRecipient(Message.RecipientType.TO,
  new InternetAddress("xxxx@yahoo.com"));

  transport.connect
  (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

   
  transport.sendMessage(message,
  message.getRecipients(Message.RecipientType.TO));
  transport.close();
  }
}


Wednesday, March 18, 2009

ORA-1017: invalid username/password; logon denied

This problem occur in oracle 11g. This is because login information case sensitivity. By default in oracle 11g, 10 versions have login case sensitivity value set true - you have to change it to false to resolve it. Just execute the following command in oracle :

ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE

Hope it will help you cause it really helped me a lot!!!

For further information visit following links:

Friday, February 6, 2009

Pagination in Hibernate and EJB3

This class with SQL Server 2000 and jTDS 0.8.1 and it works very well.

Enjoy!


/*
* Created on Oct 27, 2004
*/
package com.ugs.it.salescentre.navigation;

import java.util.List;

import org.apache.log4j.Logger;

import com.ugs.it.salescentre.logger.SalesCentreLogger;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.ScrollableResults;

/**
* This class provides pagination for displaying results from a large result set
* over a number of pages (i.e. with a given number of results per page).
*
* Taken from http://blog.hibernate.org/cgi-bin/blosxom.cgi/2004/08/14#fn.html.
*
* @author Gavin King
* @author Eric Broyles
*/
public class Page
{

private List results;
private int pageSize;
private int page;
private ScrollableResults scrollableResults;
private int totalResults = 0;

/**
* Construct a new Page. Page numbers are zero-based, so the
* first page is page 0.
*
* @param query
* the Hibernate Query
* @param page
* the page number (zero-based)
* @param pageSize
* the number of results to display on the page
*/
public Page(Query query, int page, int pageSize)
{
this.page = page;
this.pageSize = pageSize;
try
{
scrollableResults = query.scroll();
/*
* We set the max results to one more than the specfied pageSize to
* determine if any more results exist (i.e. if there is a next page
* to display). The result set is trimmed down to just the pageSize
* before being displayed later (in getList()).
*/
results = query.setFirstResult(page * pageSize).setMaxResults(
pageSize + 1).list();
}
catch (HibernateException e)
{
getLogger().error(
"Failed to get paginated results: " + e.getMessage());
}

}

public boolean isFirstPage()
{
return page == 0;
}

public boolean isLastPage()
{
return page >= getLastPageNumber();
}

public boolean hasNextPage()
{
return results.size() > pageSize;
}

public boolean hasPreviousPage()
{
return page > 0;
}

public int getLastPageNumber()
{
/*
* We use the Math.floor() method because page numbers are zero-based
* (i.e. the first page is page 0).
*/
double totalResults = new Integer(getTotalResults()).doubleValue();
return new Double(Math.floor(totalResults / pageSize)).intValue();
}

public List getList()
{
/*
* Since we retrieved one more than the specified pageSize when the
* class was constructed, we now trim it down to the pageSize if a next
* page exists.
*/
return hasNextPage() ? results.subList(0, pageSize) : results;
}

public Logger getLogger()
{
return SalesCentreLogger.getStaticLogger(this);
}

public int getTotalResults()
{
try
{
getScrollableResults().last();
totalResults = getScrollableResults().getRowNumber();
}
catch (HibernateException e)
{
getLogger().error(
"Failed to get last row number from scollable results: "
+ e.getMessage());
}
return totalResults;
}

public int getFirstResultNumber()
{
return page * pageSize + 1;
}

public int getLastResultNumber()
{
int fullPage = getFirstResultNumber() + pageSize - 1;
return getTotalResults() < fullPage ? getTotalResults() : fullPage;
}

public int getNextPageNumber()
{
return page + 1;
}

public int getPreviousPageNumber()
{
return page - 1;
}

protected ScrollableResults getScrollableResults()
{
return scrollableResults;
}

}



Reference

Wednesday, January 7, 2009

Java Important Tips

Hibernate Collection Sorting

Java Jobs

Java Papers

Servlet

Servlet Interview Questions


RoseIndia's Java


Sort Java (for sql query generated / except hibernate relational data) Collections


Full Example to sort Collection

Generic Sorts

If you write a sort for a List, e.g. ArrayList, with proper generics, it will work on collections of any type that supports Comparable or Comparator. To see how to pull it off, have a look at the source for any of my sorts, or Sun’s sort.

However, because of Java’s lack of orthogonality, your List sort won’t work for arrays of such Objects. You need to write very similar code to do that. Even that array version won’t sort an array of primitives such as long, int or byte. You have to write yet another slightly different version of the sort to handle each type of primitive.

Complete Example:

package com.mindprod.example;

import com.mindprod.palette.NamedColor.Alphabetically;
import com.mindprod.palette.NamedColor.ByRGB;

import java.awt.Color;
import static java.lang.System.out;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
* Demonstrate how to sort a Collection in Various orders using Sun's Collections.sort
* Created by IntelliJ IDEA.
*
* @author Roedy Green
*/
public class TestSort
{
// --------------------------- main() method ---------------------------

public static void main( String[] args )
{
// build ArrayList of Animals
ArrayList<Animal> animals = new ArrayList<Animal>( 5 );
animals.add( new Animal( "panther", Color.BLACK, 4 ) );
animals.add( new Animal( "frog", Color.GREEN, 4 ) );
animals.add( new Animal( "crab", Color.RED, 10 ) );
animals.add( new Animal( "elephant", Color.GRAY, 2 ) );
animals.add( new Animal( "spider", Color.BLACK, 8 ) );

out.println( "sort in Natural Order (by legs)" );
Collections.sort( animals );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort in Reverse Natural Order (by legs)" );
Collections.sort( animals, Collections.reverseOrder() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort alphabetically" );
Collections.sort( animals, new Animal.Alphabetically() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort reverse alphabetically" );
Collections.sort( animals, Collections.reverseOrder( new Animal.Alphabetically() ) );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}

out.println( "sort by color" );
Collections.sort( animals, new Animal.ByRGB() );
for ( Animal animal : animals )
{
out.println( animal.toString() );
}
// end main
}
}

/**
* objects we will sort, represent animals, not nested
*/
class Animal implements Comparable<Animal>
{

/**
* what color this animal is.
*/
final Color color;

/**
* name of the animal
*/
final String name;

/**
* how many legs this animal has
*/
final int legs;
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare by legs then by colour (numerically).
*
* @param o other animal to compare with
* @return +ve if this animal is bigger, -ve if smaller, 0 if equal
*/
public int compareTo( Animal o )
{
int diff = legs - o.legs;
if ( diff != 0 )
{
return diff;
}
return ( color.getRGB() & 0xffffff ) - ( o.color.getRGB() & 0xffffff );
}

/**
* what colour is the animal
*
* @return colour
*/
public Color getColor()
{
return color;
}

/**
* how many legs has this animal?
*
* @return number of legs
*/
public int getLegs()
{
return legs;
}

/**
* override usual ToString to give a debugging represenation.
*
* @return name, color, legs as a string.
*/
public String toString()
{
return name + " " + color + " " + legs;
}

// --------------------------- CONSTRUCTORS ---------------------------

/**
* constructor
*
* @param name name of the animal.
* @param color what colonr the animal is
* @param legs howw many legs the animal has
*/
Animal( String name, Color color, int legs )
{
this.name = name;
this.color = color;
this.legs = legs;
}


/**
* Comparator for sorting Animals by alphabetically, case insensitive
*/
static class Alphabetically implements Comparator<Animal>
{
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare two animal objects
*
* @param o1 first object
* @param o2 second object
* @return +ve if o1 is biggern, -ve if smaller, 0 if equal
*/
public int compare( Animal o1, Animal o2 )
{
return o1.name.compareToIgnoreCase( o2.name );
}
}

/**
* Comparator for sorting Animals by Color then legs
*/
static class ByRGB implements Comparator<Animal>
{
// -------------------------- PUBLIC INSTANCE METHODS --------------------------
/**
* compare two animal objects
*
* @param o1 first object
* @param o2 second object
* @return +ve if o1 is biggern, -ve if smaller, 0 if equal
*/
public int compare( Animal o1, Animal o2 )
{
int diff = ( o1.color.getRGB() & 0xffffff ) - ( o2.color.getRGB() & 0xffffff );
if ( diff != 0 )
{
return diff;
}
return o1.legs - o2.legs;
}
}
}

Tuesday, January 6, 2009

Software Site Links

Dreamweaver Extensions

Css Validator

Cross Browser Compatible Useful Article

Make your site cross browser compatible in 5 steps

Make your site cross browser compatible in 5 steps

Make your site cross browser compatible in 5 steps

Making your site cross browser compatible is not easy, but with this tutorial you can make your site cross browser compatible in 5 simple steps.

Step 1: Validate

Lots of bugs are caused by invalid (X)HTML or CSS. If you have your site validated, it will be a lot easier to make it cross browser compatible. Validate your (X)HTML code with the W3C validator and your CSS file with the W3C CSS validator.

validhtml

Step 2: Check your Website

Now you have to check your website in all browsers. I always check my site in the browsers, I’ve installed on my computer (Opera, Safari, Internet Explorer and Firefox). Do it and make a note of the bugs.

Of course, checking your website in the browsers installed on your computer is not enough. You have to check the website in different browser versions on different operating systems. The solution is Browsershots.org. With this website you can take full-length screen shots of your website in a lot of browsers. Just type in your url, bookmark the page and come back 20 minutes later to view the screen shots.

browsers

Analyse the screen shots and look for bugs. Be sure to write them down.

Step 3: Is it worth my time?

If you notice bugs in very old or uncommon used browsers, ask yourself if it’s worth your time to fix the problems. Look at the browser statistics of w3schools.com, but don’t forget to look to your own stats (I recommend AWstats). If you have one or two visitors every month still browsing with IE5.5, you should really ask yourself if it’s necessary to make the changes.

browserstats

Step 4: Search the cause

Now you know about the bugs, you’ll have to look for the CSS attribute or HTML code that is causing this problem. This is often obvious. A good reference can be found on westciv.com. There is a complete list of css attributes with their support in different browsers. Too bad Firefox isn’t in the tables.

If you still cannot find the cause of the issue, search for topics on webmaster forums or post a topic yourself, with a screen shot and (a part of) your CSS and HTML code. A forum I visit often is Ozzu.

ozzu

Step 5: Fix the issues

Now we’re at the essential part of making your website cross browser compatible: fixing the issues. If you know the code that is causing the trouble, find a way to rewrite the code for the specific browser. There are loads of CSS hacks to do that, but I recommend the use of conditional comments. There is an article on 456 Berea St. explaining why you should use conditional comments instead of CSS hacks.

Conditional Comments.
With conditional comments you can link to separate style sheets for all versions of Internet Explorer. A complete reference can be found on quirksmode. For example: