Some commands that you can play around with in unix
1.ps -ef - This command will list all the running processes. 'e' is for each process, 'f' is for full format display.
2. ps -ef | grep java - This command will list all the running java processes.
3. chmod nnn filename - To change the access rights on the file.
4. pwd - Present working directory.
5. date - current date and time at the location of the server.
6. who - will list all the logged in user.
7. who am i - will list your username and logged in time.
8. tar cf file.tar file1 file2 … fileN - to create a tar file from combination of files.
9. zip filename - To zip a file.
10. unzip filename - To unzip a file.
11. kill -3 PID - to create the dump of the process. PID is process id can be seen using the first command.
12. cd dir-path - change directory.
13. grep pattern filename- search for a pattern in file. Pattern can be any string you need to look into file.
14. ls - to list the dir and file.
15. man command - to see manual for a command.
16. ftp hostname - to ftp file from unix.
17. grep -c pattern filename - Searches and prints only the number of matches to the screen.
18. grep -i pattern filename - Searches without regard to letter case.
19. grep -n pattern filename - Prints to the screen preceded by the line number.
20. grep -v pattern filename - All lines that do not match are printed.
21. grep -x pattern filename - Only exact matches are printed.
Executing shell script - On the command prompt type sh filename.sh
Executing perl script - On the command prompt type ./filename.pl
Java, Struts, Spring, Hibernate, Unix,IT, Software, Jobs, Interview, Aptitude, Learning, Algorithms
Saturday, July 31, 2010
Friday, July 23, 2010
Writing Your Own Struts PlugIn
A plugin is a configuration wrapper for a module-specific resource or service that needs to be notified about application startup and shutdown events." What this means is that you can create a class implementing the PlugIn interface to do something at application startup or shutdown like we want to initialize Hibernate as soon as the application starts up, so that by the time my web application receives the first request, Hibernate is already configured and ready to use. We also want to close down Hibernate when the application is shutting down. We write a plugin for this requirement with as Hibernate PlugIn.
1.Write a class implementing the PlugIn interface
public class HibernatePlugIn implements PlugIn{
private String configFile;
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering HibernatePlugIn.destroy()");
//Put hibernate cleanup code here
System.out.println("Exiting HibernatePlugIn.destroy()");
}
//This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering HibernatePlugIn.init()");
System.out.println("Value of init parameter " +
getConfigFile());
System.out.println("Exiting HibernatePlugIn.init()");
}
public String getConfigFile() {
return name;
}
public void setConfigFile(String string) {
configFile = string;
}
}
1.Write a class implementing the PlugIn interface
public class HibernatePlugIn implements PlugIn{
private String configFile;
// This method will be called at application shutdown time
public void destroy() {
System.out.println("Entering HibernatePlugIn.destroy()");
//Put hibernate cleanup code here
System.out.println("Exiting HibernatePlugIn.destroy()");
}
//This method will be called at application startup time
public void init(ActionServlet actionServlet, ModuleConfig config)
throws ServletException {
System.out.println("Entering HibernatePlugIn.init()");
System.out.println("Value of init parameter " +
getConfigFile());
System.out.println("Exiting HibernatePlugIn.init()");
}
public String getConfigFile() {
return name;
}
public void setConfigFile(String string) {
configFile = string;
}
}
Sunday, July 18, 2010
Creating Your own RequestProcessor in Struts
We will change our sample application in two steps to implement the content type and user login in.
1. Create your own CustomRequestProcessor class, which will extend the RequestProcessor class, like :
public class CustomRequestProcessor extends RequestProcessor {
protected boolean processPreprocess (HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}
In the processPreprocess method of our CustomRequestProcessor class, we are checking for the userName attribute of the session and if it's not found, redirect the user to the login page.
For our requirement of generating images as output from the ContactImageAction class, we have to override the processContent method and first check if the request is for the /contactimage path. If so, we set the contentType to image/gif; otherwise, it's text/html.
1. Create your own CustomRequestProcessor class, which will extend the RequestProcessor class, like :
public class CustomRequestProcessor extends RequestProcessor {
protected boolean processPreprocess (HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
//If user is trying to access login page
// then don't check
if( request.getServletPath().equals("/loginInput.do")
|| request.getServletPath().equals("/login.do") )
return true;
//Check if userName attribute is there is session.
//If so, it means user has allready logged in
if( session != null &&
session.getAttribute("userName") != null)
return true;
else{
try{
//If no redirect user to login Page
request.getRequestDispatcher
("/Login.jsp").forward(request,response);
}catch(Exception ex){
}
}
return false;
}
protected void processContent(HttpServletRequest request, HttpServletResponse response) {
//Check if user is requesting ContactImageAction
// if yes then set image/gif as content type
if( request.getServletPath().equals("/contactimage.do")){
response.setContentType("image/gif");
return;
}
super.processContent(request, response);
}
}
In the processPreprocess method of our CustomRequestProcessor class, we are checking for the userName attribute of the session and if it's not found, redirect the user to the login page.
For our requirement of generating images as output from the ContactImageAction class, we have to override the processContent method and first check if the request is for the /contactimage path. If so, we set the contentType to image/gif; otherwise, it's text/html.
How a Request is Processed in Struts
ActionServlet is the servlet class in Struts which is configured in web.xml and read by the web application server. This is the entry point into struts framework and is responsible for handling all of the requests. Whenever it receives a request, it first tries to find a sub-application for the current request. Once a sub-application is found, it creates a RequestProcessor object for that sub-application and calls its process() method by passing it HttpServletRequest and HttpServletResponse objects.
The RequestProcessor.process() method is where most of the request processing takes place. The process() method is implemented using the Template Method design pattern, in which there is a separate method for performing each step of request processing, and all of those methods are called in sequence from the process() method. The RequestProcessor class in the Struts distribution provides a default implementation for each of the request-processing steps. That means you can override only the methods that interest you, and use default implementations for rest of the methods. For example, by default Struts calls request.isUserInRole() to find out if the user has one of the roles required to execute the current ActionMapping, but if you want to query a database for this, then then all you have to do is override the processRoles() method and return true or false, based whether the user has the required role or not.
Lets have a look at the default implementation of process() method first.
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will
// use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested
processLocale(request, response);
// Set the content type and no-caching headers
// if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
// Identify the mapping for this request
ActionMapping mapping =
processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form =
processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to
// process this request
Action action =
processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}
The RequestProcessor.process() method is where most of the request processing takes place. The process() method is implemented using the Template Method design pattern, in which there is a separate method for performing each step of request processing, and all of those methods are called in sequence from the process() method. The RequestProcessor class in the Struts distribution provides a default implementation for each of the request-processing steps. That means you can override only the methods that interest you, and use default implementations for rest of the methods. For example, by default Struts calls request.isUserInRole() to find out if the user has one of the roles required to execute the current ActionMapping, but if you want to query a database for this, then then all you have to do is override the processRoles() method and return true or false, based whether the user has the required role or not.
Lets have a look at the default implementation of process() method first.
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Wrap multipart requests with a special wrapper
request = processMultipart(request);
// Identify the path component we will
// use to select a mapping
String path = processPath(request, response);
if (path == null) {
return;
}
if (log.isDebugEnabled()) {
log.debug("Processing a '" + request.getMethod() +
"' for path '" + path + "'");
}
// Select a Locale for the current user if requested
processLocale(request, response);
// Set the content type and no-caching headers
// if requested
processContent(request, response);
processNoCache(request, response);
// General purpose preprocessing hook
if (!processPreprocess(request, response)) {
return;
}
// Identify the mapping for this request
ActionMapping mapping =
processMapping(request, response, path);
if (mapping == null) {
return;
}
// Check for any role required to perform this action
if (!processRoles(request, response, mapping)) {
return;
}
// Process any ActionForm bean related to this request
ActionForm form =
processActionForm(request, response, mapping);
processPopulate(request, response, form, mapping);
if (!processValidate(request, response, form, mapping)) {
return;
}
// Process a forward or include specified by this mapping
if (!processForward(request, response, mapping)) {
return;
}
if (!processInclude(request, response, mapping)) {
return;
}
// Create or acquire the Action instance to
// process this request
Action action =
processActionCreate(request, response, mapping);
if (action == null) {
return;
}
// Call the Action instance itself
ActionForward forward =
processActionPerform(request, response,
action, form, mapping);
// Process the returned ActionForward instance
processForwardConfig(request, response, forward);
}
Extending Struts
Struts is a very powerful framework and also very extensible. You can extend Struts in three ways.
1. PlugIn: Create your own PlugIn class if you want to execute some business logic at application startup or shutdown.
2. RequestProcessor: Create your own RequestProcessor if you want to execute some business logic at a particular point during the request-processing phase. For example, you might extend RequestProcessor to check that the user is logged in and he has one of the roles to execute a particular action before executing every request.
3. ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at either application startup or shutdown, or during request processing. But you should use it only in cases where neither PlugIn nor RequestProcessor is able to fulfill your requirement.
1. PlugIn: Create your own PlugIn class if you want to execute some business logic at application startup or shutdown.
2. RequestProcessor: Create your own RequestProcessor if you want to execute some business logic at a particular point during the request-processing phase. For example, you might extend RequestProcessor to check that the user is logged in and he has one of the roles to execute a particular action before executing every request.
3. ActionServlet: You can extend the ActionServlet class if you want to execute your business logic at either application startup or shutdown, or during request processing. But you should use it only in cases where neither PlugIn nor RequestProcessor is able to fulfill your requirement.
Sunday, July 11, 2010
How to find missing elements from the array of consecutive integers?
The problem says that if you have n consecutive integers array and n-x, n-y and n-z values are missing from the array how we can find those numbers.
In case only one number would have been missing, its easier to find by summing the numbers in this array and comparing it with the sum of n consecutive integer array.
Now in case when two or more than two elements are missing, then the solution goes like this. Create another array of n size. Start putting 1 at the index position in new array which is equal to the value of the element in the old array. Example, if the first element value in the old array is 43, put 1 in the new array at the index position of 43. Like this populate the new array for all the elements in old array. Now the indexes with zero values in the new array are the missing values in the old array.
In case only one number would have been missing, its easier to find by summing the numbers in this array and comparing it with the sum of n consecutive integer array.
Now in case when two or more than two elements are missing, then the solution goes like this. Create another array of n size. Start putting 1 at the index position in new array which is equal to the value of the element in the old array. Example, if the first element value in the old array is 43, put 1 in the new array at the index position of 43. Like this populate the new array for all the elements in old array. Now the indexes with zero values in the new array are the missing values in the old array.
Java constant values are resolved at compile time or runtime?
Java constants are basically variables defined as static final in any class or interface. At compile time when java classes are generated constant values are placed at all the places where the constant is referred. At runtime the defined constant or the class in which constant is defined does not come into picture at all. So if at sometime you change some constant in any file and just try to replace the class file in the jar or in production, it will not work because the value need to be replace where that constant is referred which is done at compile time.
Overridding instance variable in java
Always remember, instance variable can not be overridden. Try below example.
public class A{
public int i = 1;
}
public class B{
public int i=2;
}
public class C{
public static void main(String[] arg){
A a = new B();
System.out.println(a.i);//The output will be 1 and not 2
}
}
public class A{
public int i = 1;
}
public class B{
public int i=2;
}
public class C{
public static void main(String[] arg){
A a = new B();
System.out.println(a.i);//The output will be 1 and not 2
}
}
Summing column value in a sql query
To sum value of two columns in a sql query use + operator as shown below
select column1+column2 from tableA
select column1+column2 from tableA
General hibernate configuration - for quick reference
<hibernate-configuration>
<session-factory>
<property name="connection.driver.class">
org.hsqldb.jdbcDriver
 </property>
<property name="connection.url">
url
 </property>
<property name="connection.username">
username
 </property>
<property name="connection.password">
password
 </property>
<property name="connection.dialect">
HSQLDialect
 </property>
<property name="connection.pool_size">
1
 </property>
<property name="connection.show_sql">
true
 </property>
<mapping resource="test.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Do we always normalize database?
One word answer is No. Although most of the time we normalize our tables but there can be scenarios when our query performance is diminished. Normalization in database calls for the joins in the query on the tables which may reduce the performance of queries by increasing the execution time.
Which fields are indexed in reporting databases?
We, mainly, create index on date fields in databases (basically tables) which are frequently used in reporting. This is because most of the time reports are created on the date bases. So because we will be fetching data from the tables mostly on the basis of date field creating index on it will reduce the execution time of the query as index on the date field will help in easily sorting of the rows in the table.
Swapping object in java
In java, when you are trying to swap two objects, it cannot be swapped by creating a temporary variable in a different method as given below.
public static void main (String[] arg){
//creating two objectsto be swapped
ClassA a1 = new ClassA();
ClassA b1 = new ClassA();
.....
swap(a1,b1);
}
public void swap(ClassA a, ClassA b){
ClassA temp = a;
a=b;
b=temp;
}
One line answer to why objects will not get swapped is that java is a pass by value.
public static void main (String[] arg){
//creating two objectsto be swapped
ClassA a1 = new ClassA();
ClassA b1 = new ClassA();
.....
swap(a1,b1);
}
public void swap(ClassA a, ClassA b){
ClassA temp = a;
a=b;
b=temp;
}
One line answer to why objects will not get swapped is that java is a pass by value.
Open a new web browser window without back button
Using javascript we can do that easily.
window.open(url,window title,"status=1,toolbar=0");
There are more options that you can use while writing a javascript to open a new window
window.open(url,window title,"status=1,toolbar=0");
There are more options that you can use while writing a javascript to open a new window
| status | The status bar at the bottom of the window. |
| toolbar | The standard browser toolbar, with buttons such as Back and Forward. |
| location | The Location entry field where you enter the URL. |
| menubar | The menu bar of the window |
| directories | The standard browser directory buttons, such as What's New and What's Cool |
| resizable | Allow/Disallow the user to resize the window. |
| scrollbars | Enable the scrollbars if the document is bigger than the window |
| height | Specifies the height of the window in pixels. (example: height='350') |
| width | Specifies the width of the window in pixels. |
Disable back button functionality on web client (IE)
To disable back functionality on any web page, we can do it using javascript.
window.history.forward();
window.history.forward();
Subscribe to:
Comments (Atom)
