Sunday, February 16, 2014

Sorting Collections

Sorting of Java Objects in Collections is done in two ways.They are:

1)Implementing Comparable interface :

           Comparable Interface in java is used to define the natural sort order of a class.It is defined in lang package.Comparable interface provides one method "compareTo()" to implement in any class so that two instances of that class can be compared. compareTo() method compares the two object of the same type and returns a numerical result based on  the comparison.

In a Student list if we need to sort the list, based on the student roll no, its best  way to implement with Comparable interface.

Example :

public class Student implements Comparable {
private int rollNo;
private String firstName;
private String lastName;
// getter and setter for the properties
@Override
public int compareTo(Student s) {
return this.rollNo- s.rollNo;
}
}

Usage:
   List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList);



2)Implementing Comparator interface :

          Comparator interface is used to order the objects of user-defined class.It is defined in util package.it provides multiple sorting sequence i.e. you can sort the elements based on any data member. Comparators can also be used to control the order of certain structures(such as TreeSet or TreeMap). For instance it may be rollno, name, age or anything else.             

This method is more like generics type if you have to sort with more option.
1) sort based on the firstNamne
2) sort based on the lastName

Example :

Sorting student collection by firstName.

public class FirstNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getFirstName().compareTo(s2.getFirstName());
}

} 

Usage:
List studentList=new ArrayList();
     //add student objects to studentList 
       Collections.sort(studentList, new FirstNameSorter());


Sorting student collection by lastName.

public class LastNameSorter implements Comparator{
@Override
public int compare(Student s1, Student s2) {
return s1.getLastName().compareTo(s2.getLastName());
}
}

Usage:
     List studentList=new ArrayList();
     //add student objects to studentList 
    Collections.sort(studentList, new LastNameSorter());






Wednesday, September 11, 2013

JodaTime

Free, open-source Java library for working with dates and times

Supported Concepts
Instant
 “An instant in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z”
  Within Joda-Time an instant is represented by the ReadableInstant interface.
  There are four implementations of the interface provided.

 Instant - A simple immutable implementation which is restricted to the UTC time zone and is intended for   time zone and calendar neutral data transfer
 DateTime - The most commonly used class in the library, and an immutable representation of a date and time with calendar and time zone
 DateMidnight - Similar to DateTime and also immutable but with the time component forced to be midnight (at the start of a day)
 MutableDateTime - A mutable representation of date and time with calendar and time zone.

• Partial
 a partial date/time representation (subset of fields) with no time zone
• Interval
 “an interval of time from one millisecond instant to another”
• Duration
 “a duration of time measured in milliseconds”
• Period
 “a period of time defined in terms of fields, for example, 3 years 5 months 2 days and 7 hours”
• Chronology “a pluggable calendar system

Friday, October 14, 2011

Java telephonic round for onsite

Mostly onsite and offshore model.
Abstract class vs Interface
about Finally block
will Finally block excutes after return statement
difference between sendRedirct and forward method
use of filters

What is the use of ActionServiclet
wht is the use of ActionFrom

Why do you use joins?
different between inner join and left outer join
What are aggregate functions
having clause and group by.

Monday, September 19, 2011

TIBCO Product Overview

TIBCO products are designed to help organizations pursue and benefit
from initiatives in three key areas: service-oriented architecture (SOA), business
process management (BPM), and business optimization.

SOA and Integration
TIBCO ActiveMatrix® Service Grid: is a distributed platform for assembling, deploying, and managing Java, .NET, and other services as composite applications. This unique approach to service virtualization enables organizations to reduce the complexity of heterogeneous SOA.

TIBCO ActiveMatrix® Registry: is a standards-based system of record for discovering, categorizing, and publishing services. As an integral part of TIBCO’s end-to-end service governance and virtualization platform, TIBCO ActiveMatrix Registry provides the foundation required to improve service reuse and promote services from development through to production.

TIBCO ActiveMatrix® Policy Manager: is a policy management solution that enables IT to define, distribute, and enforce rules for security, auditing, logging, service levels, and other application characteristics across a wide range of services built on Java and .NET, as well as custom and packaged applications.

TIBCO ActiveMatrix BusinessWorks™: is a standards-based service creation, orchestration, and integration product built to run natively with other ActiveMatrix products. It enables companies to expose existing systems as services, build new services, and orchestrate and assemble services into more flexible applications with little or no coding.

TIBCO ActiveMatrix® Service Performance Manager: is an enterprise software platform that monitors and proactively manages the health and performance of IT and business services based on service level agreements.

Enterprise Service Bus

TIBCO ActiveMatrix® Service Bus: is an enterprise service bus that enables IT to mediate services in a flexible and reliable manner in any heterogeneous environment.

Application Integration

TIBCO BusinessWorks™ SmartMapper software lets organizations assemble a more comprehensive and consistent view of their data by providing the cross-referencing and translation rules to harmonize semantically different data sets across multiple applications.

TIBCO Adapter™ software enables packaged applications, databases, and networking technologies to become active participants in the enterprise information flow. With a configuration-based approach to integration, TIBCO Adapters provide simple, automated mapping of incompatible technologies and data formats. TIBCO offers a broad set of adapters, including adapters for packaged applications, adapters for databases, adapters for technologies, and a full-featured TIBCO Adapter Software Development Kit (SDK).

B2B Integration

TIBCO BusinessConnect™ software lets organizations electronically interact and collaborate with trading partners by enabling the secure exchange of documents and automation of transactions across public and private networks. TIBCO BusinessConnect supports a variety of protocols including EDI, SOAP, RosettaNet, HIPAA, HL7, and UCCNet.

Mainframe Integration

TIBCO Mainframe Service Suite™ brings crucial, mainframe-based data and processes to SOA environments. The suite enables organizations to develop and deploy native mainframe services and events – without having to modify mainframe sources – for true end-to-end enterprise integration solutions.

Messaging
TIBCO Enterprise Message Service™ is standards-based messaging software that can serve as the backbone of an SOA by providing Java Message Service (JMS)-compliant communications across a wide range of platforms and application technologies.

TIBCO Rendezvous® software is the leading messaging product for real-time, broad data distribution. It has been used by thousands of customers for more than a decade and is the backbone for several of the largest mission-critical systems in production today. A common example of broad data distribution is the use of TIBCO Rendezvous for financial market data distribution systems.

TIBCO Messaging Appliance™ P-7500 provides a TIBCO Rendezvous backbone as pure hardware in a single box. By replacing the standard hardware, operating system, and messaging software with special purpose hardware, the TIBCO Messaging Appliance P-7500 delivers up to 10 times the message volumes and performance, one tenth the rack space and power consumption, and greater reliability – all with a lower cost of ownership.

TIBCO SmartSockets® software provides reliable real-time messaging using industry-standard protocols with exceptional performance, scalability, bandwidth efficiency, and fault tolerance. Using the rich TIBCO SmartSockets application programming interfaces (APIs) and class libraries, your organization can ensure that applications distribute and exchange information quickly, reliably, and securely across any platform and any network – LAN, WAN, internet, or satellite.

Business Process Management

TIBCO iProcess™ Suite is an open and standards-based BPM solution that extends from process design to process optimization. TIBCO iProcess™ Engine is the foundation of the suite and provides a powerful platform built to handle the most complex and demanding processes in any organization. It includes complete support for load balancing, multiple background processing, and real-time process monitoring to ensure highly available (24/7) system uptime.

TIBCO Business Studio™ software is the modeling and simulation environment for the iProcess Suite. It unifies key elements of BPM – modeling, management, simulation, and implementation – in one design environment. Different views of the same process model allow business and IT to collaborate seamlessly to create executable business process models.

TIBCO iProcess™ Analytics software is an OLAP-based analytics tool that gives business managers a timely and actionable view of process performance through highly configurable interactive dashboards.

TIBCO iProcess™ Decisions software enables business users to easily define, implement, analyze, and change rules without the aid of IT staff, providing an enterprise with the agility to respond to a constantly changing business environment.

TIBCO iProcess™ Conductor software extends the process management capabilities of the suite to address“goal-oriented BPM.” It packages TIBCO iProcess Engine processes as independent process components that are combined to create an execution plan. Process components can be reused, coordinated, individually monitored, dynamically modified – even completely remodeled – during runtime.

TIBCO iProcess™ Insight software provides business activity monitoring capabilities to BPM suite users. It gives business managers real-time process performance visualization and optimization information through operational dashboards.

Business Intelligence

• TIBCO Spotfire DXP™ Professional software enables business analysts and professionals to perform not only compelling ad hoc analyses, but also to rapidly capture, but also to rapidly capture, author, and share Guided Analytic applications that encapsulate analysis workflows and best practices.
TIBCO Spotfire DecisionSite® software allows engineers, researchers, and analysts to visualize, analyze, and explore attribute-rich data in real time.

TIBCO Spotfire® Analytics Server provides the enterprise with a centralized platform for the integration, deployment, and administration of next-generation business intelligence applications.

Complex Event Processing

TIBCO BusinessEvents™ software enables organizations to identify meaningful patterns among the countless events that occur across their business. By doing so, the software helps organizations recognize and proactively address problems and opportunities sooner than would otherwise be possible.

TIBCO BusinessFactor® software enables the creation of dashboards that let users observe, analyze, and act on operational metrics to fix problems and optimize performance.

Master Data Management
• TIBCO Collaborative Information Manager™ software enables organizations to align enterprise master data (product, customer, vendor, etc.) across multiple business units, departments, and partners and synchronize that information with downstream IT transactional systems.

User Experience
• TIBCO Ajax Message Service™ software provides a scalable and reliable way to deliver real-time information to web applications. With Ajax Message Service software, you can deliver low latency publish/subscribe solutions over HTTP in combination with web pages, Ajax applications, and other client technologies.

TIBCO General Interface™ software is an RIA framework that makes it faster and easier for organizations to build and deploy web-based applications and components that have the rich feel and functionality of desktop software.

TIBCO PortalBuilder® software is a robust, proven enterprise portal platform that enables organizations to effectively and efficiently deliver content and applications to different audiences via secure and fully customizable web-based interfaces.

Monitoring and Management
• TIBCO Hawk® software is distributed monitoring and management software that helps IT staff ensure and improve the performance and availability of the software that supports business processes.

TIBCO Enterprise Management Advisor™ software works with leading enterprise management platforms to help IT staff monitor and manage the performance of applications across their organization.

TIBCO® Enterprise RTView software enables TIBCO users to monitor and receive real-time feedback on the status of their networks without the costs of building and maintaining custom interfaces.













Sunday, June 19, 2011

Android Application Development Setup with Eclipse



Step1: Install Android SDK
Download Android SDK exe file from the below link and install it.
Step2: Install eclipse plugin for Android Development Tools (ADT) using the below link.

Step3: Configuration
Give Android SDK installation path to eclipse:
Window-->Preferences-->Android
Give the path in the SDK Location and click on apply.














Step4: Create Android Emulator Device.

Windows-->Android SDK and AVD Manger.
Select Virtual Devises and click New.
enter the details like below.














click on create AVD.

your done with setup to develop android applications.






Tuesday, February 22, 2011

Coding Convention in Java


1. Proper Names
  • Should give correct spellings
  • All meaningful names should have to give. Method should have to do same or more what they say..
  • Try to Avoid abbreviations.
  • Don't give java keywords as variable and method names
  • Package name should be lower case.
  • Ex: com.challa.action

Wednesday, February 16, 2011

Web Services Interview Questions and Answers


What is Web Services.
Web Services is Type of interaction between the applications helping their features each other.
Ex: Application A performs addition of two numbers and application B performs multiplication of Two Numbers. Application B required the feature of adding two numbers instead of implementing the same feature in Application B send the numbers to application A and get the result.

What is the use of Web Services or Why you should use Web Services
May be these tips can convince the client.
Web Services make use of developed application.
Reduce the cost for development and maintenance of the application.
Web Services can make easy integration.

Thursday, February 10, 2011

Multithreading in Java

Multithreading in Java

Some times we do multple tasks at a particular period of time to complete the unit of work ASAP.
For example: If your working on one issue in the middle you came to know that this issue is dependent on DB. You need help from
DB guy if DB guy is not available at this point of time, you will not keep waiting for him. you will switch to some other task to work on.
ones he come back you can finish the task which is dependent on DB.

Java also perform muti tasking using Multithreading, so that it will improve the performance of the appilication.

We can see how to implement multithreading in java.

In Java We have two types of multi tasking.
1. Thread based multi tasking.
2. Process based multi tasking.

Processed based multi threading:
The best way to remeber is Multiple programs running at a time
ex: adding and subtracting.

Thread based multi tasking.

Multiple tasks in one program.
if we take one example adding numbers 1+2+3+4=9

if one thread is processing this program if we assume for each operation it is taking 1ms it will take 3ms to add this .
if we perform multithreading first two numbers will add by one thread and the last two numbers will add thread this task will in 1 sec by using multi threading
the result of two threads can added in another secong we can complete this in two seconds, so we are able to save 33% of the time.


Java run time environment manages threads, Threads are processed asynchrously this means that one thread can wait while other thread can continue process.
A thread can be in one of four states:
• Running A thread is being executed.
• Suspended Execution is paused and can be resumed where it left off.
• Blocked A resource cannot be accessed because it is being used by
another thread.
• Terminated Execution is stopped and cannot be resumed.

Thread Priority: In a mutlithreaded programing few threads can be dependent on the result of anthor thread so by giving the priority
we can decide which thread have to excute first.





We can see how to implement multithreading in java.

Creating Thread
Multiple Threads in a Program
Synchronization Concept
Thread Communication

Sunday, November 21, 2010

Business Delegate

Use a Business Delegate to reduce coupling between presentation-tier clients and business services. The Business Delegate hides the underlying implementation details of the business service, such as lookup and access details of the EJB architecture.





Front Controlers

Front Controller is responsible for processing all application request.

Ex:
Strut2: Dispatcher FilterDispatcher.
Struts1: ActionServlet.

Wednesday, September 22, 2010

Struts2 Overview

What is Struts2?

Struts2 is a MVC (model-view-controller) web application framework. It has a simple goal – make web development easier for developers. Struts2 aims at providing increased productivity through reduced XML configuration, smart conventions, and a modular and loosely-coupled architecture.

Originally started as WebWork, Struts 2 was designed to address several perceived deficiencies with Struts1. Struts1 was to tightly tied to the servlet specification and contained many Struts 1-specific constructs. Struts 2 takes advantage of the many lessons learned to present a cleaner implementation of MVC.

Features and Benefits of Using Struts2:

  • Action based framework
  • Mature with a vibrant developer and user community
  • Annotation and XML configuration options
  • POJO-based actions that are easy to test
  • Spring, SiteMesh and Tiles integration
  • OGNL expression language integration
  • Themes based tag libraries and Ajax tags
  • Multiple view options (JSP, Freemarker, Velocity and XSLT)
  • Plug-ins to extend and modify framework features

Struts2 Configuration

The majority (if not all) of the struts2 configuration should done using the struts.xml. Another option is to include a struts.properties file. However, it is not recommend when developing new applications. The struts.properties file is provided for backward-compatibility with WebWork. The struts.xml file needs to be located in the root of the classpath

The struts.xml file will contain the configuration for actions, interceptors, packages, namespaces, results and some validation. It can also be used to set Struts2 specific properties like the devMode. The alternative to configuring Struts2 with the struts.xml file is to use annotations. I prefer to the xml file approach over annotations since our entire configuration is kept in a single location not spread across several (maybe hundreds) classes. I also like to keep configuration details out of classes.

When defining configuration elements (like actions) in the struts.xml file it is important to think about grouping them into packages and namespaces. Packages and namespaces help group and classify various configuration elements, delineate areas of responsibility and provide package-specific resources. They help draw destinations between different sections of an application. For example, admin operations should have their own package and namespace separate from the other application operations.

Title, label, error and all other messages that need to be displayed to the end user should be built in the package.properties file (usually located in the action package). Package.properties is simple properties file that holds messages (and keys) in a single, common location for the entire application. Messages can be easily retrieved or throughout the entire application. Maintenance is reduced by having everything in a common location.

Actions

Actions are the basic building block the Struts2 framework (as well many other MVC frameworks). Each URL is mapped to a specific action, which provides the processing logic necessary to service the request from the user. They are the most basic unit of work that can be

associated with a HTTP request coming from a user.

In Struts 2 actions are POJOs (Plain Old Java Objects) and an object instance is created for every new request. This is a different from Struts 1 where actions are singletons and only one instance of the actions class is used to handle all requests. POJOs increases testability, reduces coupling in the framework and HTML form field data is converted to proper types for the action to use.

Much of the functionality that actions need is provided through a combination of interface implementations and interceptors (we’ll get more information on interceptors later). Most (if not all) of our actions should extend the ActionSupport class. ActionSupport is a utility class that implements the most commonly used interfaces (Action, Validateable, ValidationAware, TextProvider, Localprovider and Serializable.)

Since the bulk of the applications functionality should reside in service classes our actions are where the service operations are instantiated and invoked. Generally, actions should be kept highly cohesive. Meaning that each action should serve a single, well focused purpose. They should provide a single unit of work for a request. However, you can have actions with several methods that can be invoked separately.

Several actions may be built as “Model Driven” actions. Model driven actions implement the ModelDriven interface and provide access to domain objects. Struts will then populate the fields of this object with the request parameters, and this object will be placed on top of the stack once the action is executed. Validation will also be performed on this model object, instead of the action. See http://struts.apache.org/2.1.8/docs/model-driven.html for more information.

Interceptors

Interceptors are another of the core components that makes up a Struts2. The bulk of core framework functionally comes from interceptors. They provide common crosscutting functionality and features to be applied to actions in a constant and convenient manner, without the need of adding code in each and every action. Working very similar to Servlet Filters, interceptors provide a simple way to add processing logic around method calls in an action.

Interceptors are grouped into collections called “Interceptor Stacks”. Struts2 provides several pre-configured stacks for performing common application tasks. However, you can also customize and configure your own stacks. Either stacks or individual interceptors can be configured by action or by package. Configuring what interceptor an actor or package should use is done in the struts.xml.

All packages and actions configuration should include the defaultStack or paramPrepareParamsStack provided with Struts 2. The defaultStack contains interceptors for exceptions, servletConfiguration, params, debugging, modelDriven, validation and many others. The paramPrepareParamsStack is very similar to the defaultStack except it does not contain interceptors for debugging and profiling. Another important difference between the two stacks is that the paramPrepareParamsStack includes an additional params interceptor before the prepare interceptor (if action is preparable.) In the defaultStack the params interceptor is called after the prepare interceptor. What does this all mean? If a parameter from the UI is needed for the prepare method to execute properly it will fail if the defaultStack is used because the parameters are set after the prepare call. Just be ware of the difference.

Several other interceptors may be used for specific areas of the application. For example, the roles interceptor may be used for admin type functionality, clearSession interception for logout operation.

Since interceptions are such an important concept in Struts 2 it is important to know what interceptors are available and what they are used for. See http://struts.apache.org/2.x/docs/interceptors.html for a list of all framework interceptors and their functions.

User Interface

Struts2 Tag Library

When developing a UI (User Interface) with JSPs, tag libraries should be used. Tag libraries are nothing new to Java. They provide an easy, uniform way to render information to the user while minimizing the simple, repetitive programming that usually happens with UI development. Tag libraries help with maintainability by keeping the logic encapsulated, and reducing the temptation of cutting and pasting code.

Struts2 provides a rich tag library that is very similar to JSTL (JavaServer Pages Standard Tag Library) except it has a tight integration with the framework. It provides the intersection between actions and views, allowing dynamic information from actions to be rendered as well as making rendering decisions on the information to display at runtime. Tags can also access action methods and can use OGNL to evaluate expressions. See http://www.struts2.net/reference.htm

for more information on Struts2 tags.

OGNL (Object-Graph Navigation Language)

OGNL is open-source EL (Expression Language) that Struts2 uses (In the future Struts2 will allow for other expression languages to be plugged in instead). It provides a mechanism to navigate object graphs using dot notation and evaluate expressions, including calling methods on the objects being retrieved. OGNL can be a very valuable tool in Struts2. See

http://www.opensymphony.com/ognl/ for more information.

SiteMesh

SiteMesh is a templating technology (similar to Apache Tiles) that is used to construct a common look and feel for an entire application. It uses a decorator design pattern to establish HTML with additional HTML provided from a secondary file. In other words, SiteMesh builds an HTML template for a page and then decorates additional HTML to that template. See http://www.opensymphony.com/sitemesh/ for more information.

Struts2 Validation Configuration

Input validation is a very important part of every application. This is no different for Struts2 applications. Validation helps us ensure that only appropriate data is passed to our actions. Like most of the configuration within Struts 2, validation can be done either through XML or annotations. I would recommend taking the XML approach for the same reasons stated in the Struts2 configuration section.

Any action class that extends ActionSupport or implements the ValidationAware interface can easily tie into the Struts2 validation framework. Action validation configuration can either be done in the struts.xml file or in individual action validation XML files (located in the same package as the action). I recommend using the individual action validation files in order to minimize the size and complexity of the struts.xml file. An action validation file has the same name as the action but with “-validation.xml” appended on the end. For example, if we have an action class called ILikeBaconAction.java then we use a validation file called ILikeBaconAction-validation.xml. Within the validation XML file, field and action validation rules are configured by building validators and setting their validation types and properties. See http://struts.apache.org/2.x/docs/validation.html for a full list of validation types and what can be done within Struts2 validation.

The validation XML files can handle the majority of the validation rules for actions. However, there are situations where the business rules are too complex and the XML configuration gets complicated and unreadable. When this situation occurs a no argument validate method can be added to the action. If the action extends ActionSupport or implements the ValidationAware interface the validate method will be automatically invoked when the actions is called. Within the validate method the validation rules can then be coded in pure Java and error messages can be added to the action.

References / Helpful Links:

Struts2 Home: http://struts.apache.org/2.1.8/index.html

Struts2 Wiki: http://cwiki.apache.org/WW/home.html

Struts2 FAQ: http://struts.apache.org/2.0.14/docs/faqs.html

Free Struts2 Book: http://www.infoq.com/minibooks/starting-struts2

Struts 1 vs. Struts2 http://struts.apache.org/2.0.14/docs/comparing-struts-1-and-2.html

Struts2 Tags: http://www.struts2.net/reference.htm

More Struts2 Tags: http://www.roseindia.net/struts/struts2/struts-2-tags.shtml

Model Driven Actions: http://struts.apache.org/2.1.8/docs/model-driven.html

Interceptors: http://struts.apache.org/2.x/docs/interceptors.html

More Interceptors: http://struts.apache.org/2.0.14/docs/interceptors.html

Even More Interceptors: http://jodd.org/doc/madvoc/interceptors.html

Struts2 Validation: http://struts.apache.org/2.x/docs/validation.html

OGNL: http://www.opensymphony.com/ognl/

SiteMesh: http://www.opensymphony.com/sitemesh/

More SiteMesh: http://today.java.net/pub/a/today/2004/03/11/sitemesh.html

Wednesday, August 11, 2010

would you like to become wealthy


Warren Buffet suggested two very simple rules which anyone can follow.

Rule #1: Never lose money
Rule #2: Never forget Rule #1

By following these two rules, he went on to become the worlds 2nd richest man.

How do we lose money?
1. By spending recklessly. I have seen people spending not only their current income recklessly but also their future income though Credit Cards and Personal Loans.
2. By not having any value for the money they have. If you do not have value for money then money will not have any value for you and keep evading you. Show respect to money and it will show respect to you. If you wish to check out this point, show lesser respect to your spouse and / or children for a week and see what happens. They will immediately start showing lesser respect towards you.

3. By investing rashly. I have heard people say "I do not have the time. Tell me in two minutes what you have to say and then I will decide what to do". Well, if you do not have time to learn how to save your hard earned money and invest it in the most efficient manner, you will go into retirement with a lot time in hand and no money to enjoy it.



What can you do about it? Change your attitude !!!

1. Start saving. Save as much as you can while you can.

2. Start showing a lot of value and respect for the money that you already have. By being grateful to what you already have, you will enter an ever growing virtuous spiral of abundance and growth where you will start experiencing abundance of time, money, love, friends and everything else that you need. By not being grateful to what you already have, you will enter a vicious spiral of scarcity where-in you will keep experiencing shortage of time, money, love, friends and everything else.

3. Invest wisely. Devote some time to learn the basics of investing. 

4. Do not get swayed by others. I hope you have heard the story about the "Crab Mentality". An international competition was held to decide which country has the best crabs. Everyone sent their best specimens properly packed. Indians sent their crabs in a open basket. The organizers asked the person who brought them "how did you manage to get so many crabs in an open basket without the fear of losing them". The person answered "Sir these are Indian Crabs. The moment one crab starts climbing out of the basket, the others will pull its leg and make sure that it does not escape !!!"

5. Implement what needs to be done today. Tomorrow never comes.

Monday, May 10, 2010

Hibernate Caching

I found some useful information on internet about hibernate caching.I thought of sharing with everyone.
High-volume database traffic is a frequent cause of performance problems in Web applications. Hibernate is a high-performance, object/relational persistence and query service. In many cases, second-level caching can be just what Hibernate needs to realize its full performance-handling potential.

What is caching – Anything you can do to minimize traffic between a database and an application server is probably a good thing. In theory, an application ought to be able to maintain a cache containing data already loaded from the database, and only hit the database when information has to be updated. When the database is hit, the changes may invalidate the cache.

There are two different cache used in hibernate-
1. First Level cache – This is associated with session. This is default implemented in hibernate on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications
2. Second level cache – This is associated with Session Factory object. It will survive Sessions and can be reused in new Session by same SessionFactory (which usually is one per application). By default the 2nd level cache is not enabled. This ’second-level’ cache exists as long as the session factory is alive. The second-level cache holds on to the ‘data’ for all properties and associations for individual entities that are marked to be cached. The second level cache is responsible for caching objects across sessions.

Cache Type
EHCache (Easy Hibernate Cache) — http://ehcache.sourceforge.net/
OSCache (Open Symphony) — http://www.opensymphony.com/oscache/
SwarmCache — http://swarmcache.sourceforge.net/
JBoss TreeCache — http://jboss.org/wiki/Wiki.jsp?page=JBossCache

• EHCache -s an open source widely used java distributed cache for general purpose caching, Java EE and light-weight containers. It features memory and disk stores, replicate by copy and invalidate, listeners, cache loaders, cache extensions, cache exception handlers, a gzip caching servlet filter, RESTful and SOAP APIs and much more. Ehcache is available under an Apache open source license and is actively developed, maintained and supported.It support read only, Non strict Read/write,Read/write caching.It does not support transactional caching architecture.
• OSCache – is “a Java framework” developed by OpenSymphony that makes it easy to cache content in Web applications.It is a caching solution that includes a JSP tag library and set of classes to perform fine grained dynamic caching of JSP content, servlet responses or arbitrary objects.It provides both in memory and persistent on disk caches.They can allow your site to have graceful error tolerance .It support read only, Non strict Read/write,Read/write caching.It does not support transactional schema caching architecture.
• SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching. This type of cache is appropriate for applications that typically have many more read operations than write operations.It support read only, Non strict Read/write caching.It does not support ,Read/write and transactional caching architecture.It is is a cluster-based caching.
• JBoss TreeCache – is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.


Saturday, May 1, 2010

Bean Scope

Bean scopes

When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-awareApplicationContext).

The scopes supported out of the box are listed below:

Scope Description

singleton Scopes a single bean definition to a single object instance per Spring IoC container.


prototype Scopes a single bean definition to any number of object instances.


request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.


session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.


global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


reference

http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes




Strategies for starting a small business

  • Expand your business horizons by reaching out to different customers
  • Recognize your Unique Selling Point which is uniquely different from your competitors.
  • Formulate an expert and professional team to execute your business plans
  • Create Goodwill, impetus and proper management
  • Recognize and safeguard your Intellectual Property
  • Expand your business through various medium
  • Look forward for tie-ups and meaningful collaborations with other companies
  • Win the faith and reliability of your customers
  • Do not neglect the importance of internet and create your business website
  • Gain from your experience, deploy standard machinery and methodologies
  • Provide money back assurance
Remember, business is all about proper approach, determination and dedication. Strike the perfect balance between vocation, family and leisure to go a long way.

Saturday, February 21, 2009

Interface

We use interface to achieve polymorphism. In simple english, the users of your class will have a reference of the interface rather than the class which actually implement that method. This is an object oriented principle that enforce 'keeping the concerns separate' and 'program to super class/interface rather than sub class'. For example: assuming Calculator is an interface, the users of your controller are allowed to call getCalculator to get it. Now, for users, the point of contact is 'Calculator', they shouldn't be interested which class actually implemented the Calculator interface to provide the logic.
public Calculator getCalculator() {
return new BasicCalculator();
}
In future version, you can change the logic, and your users will not be bothered, for example, in an overridden method:
public Calculator getCalculator()
{return new EnhancedCalculator();}
Take an example of T.V, you will see that the remote control is the Interface to your T.V functions. If some Functions are subjected to change/enhanced there should be no effect on the interface/remote control in this example.
Plus if you don't want to expose your logic to some one, (means you don't some one to share your code) you can give him you interface, a standard way to use your logic.

"Interface is like defining some protocol.
When you start building some module or package you must code it into some proper manner so if someone else wants to update or work on it, its working is clear for them. Means it should be generic code. So instead of starting whole thing into single class, you thing about some generic methods, constants your module needed, without thinking of its implementation. So here comes the concept of Interface and Abstract Classes.
When you start implementing method define in Interface you start working with classes which implementing your interface. "

Tricky Questions

1)Can I get Session object from servlet or jsp to simple java class?
2)What is a singleton class?
3)What is the difference between sendRedirect and forward in servlet ?
4)What happened if i clone a singleton object?
5)What is the difference between PrintWriter and JspWriter class?
6)Can I call a static variable with object?
7)What are the collection framework hibernate supports?
8)How to get variable value from javascript in to jsp page?
9)What is the difference between pageContext and SevletContext?
10)Why java doesnot support multiple inheritance?
11) Can we use a ResultSet object after closing the Connection??
Actually not, but you can use RowSet in connectionless mode
12) By default java will import java.lang
println() is the method of class PrintStream and in the package java.io.*
Why how we are able to use println() without importing java.io.*
we dont use println() directly :P , instead we use System.out.println() where out is a final static member of type PrintStream in System class, and System class imports java.io.* for us so we need not bother to import java.io package.
11) Explain Memory leak in java ?
12) Write a program of Dead Lock condition in java .
13) What is the difference between sleep(1000) and wait(1000) ?
15) What is delegation in Java?

Friday, February 20, 2009

Marker Interface and Reflection Mechanism

Marker Interface
The marker interface is just an empty interface. Its purpose is to "mark". That is, a class is suppose to contain certain capability so it "marks" itself with a marker interface -- for example a class capable of cloning itself marks itself with 'Cloneable' interface. Its just a way of Object Oriented Programming. A certain framework (for example RMI) will only deal with classes which are "mark" with their required interfaces (for example Remote).
Reflection Mechanism
Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions. The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class.
Ex.
import java.lang.reflect.*;
class B
{
private int val=10;
}
class A
{
public static void main(String[] args) throws Exception
{
B bob=new B();
Field fld=bob.getClass().getDeclaredField("val");fld.setAccessible(true);
System.out.println("value:"+fld.getInt(bob));}}

Thursday, February 19, 2009

why EJB is only in appserver

EJB specs are part of Java Enterprise specifications. An App server implements JEE specifications, hence an EJB container is part of an app server. An EJB utilizes several other JEE components hence it usually does not exist as stand alone container.

There were some efforts to implement EJB as standalone container (just like JSP/Servlet container), but it wasn't successful.