Thursday, February 17, 2011

Hibernate Interview Questions

1.What is ORM ?

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


2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

  • API for performing basic CRUD operations
  • API to express queries refering to classes
  • Facilities to specify metadata
  • Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

  • Pure relational (stored procedure.)
  • Light objects mapping (JDBC)
  • Medium object mapping
  • Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.


5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

  • Improved productivity
    • High-level object-oriented API
    • Less Java code to write
    • No SQL to write
  • Improved performance
    • Sophisticated caching
    • Lazy loading
    • Eager loading
  • Improved maintainability
    • A lot less code to write
  • Improved portability
    • ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

  • Saving and retrieving your domain objects
  • Making database column and table name changes
  • Centralizing pre save and post retrieve logic
  • Complex joins for retrieving related items
  • Schema creation from object model

7.What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects


8.What are the most common methods of Hibernate configuration?

The most common methods of Hibernate configuration are:

  • Programmatic configuration
  • XML configuration (hibernate.cfg.xml)

9.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

  • Session interface
  • SessionFactory interface
  • Configuration interface
  • Transaction interface
  • Query and Criteria interfaces

10. What role does the Session interface play in Hibernate?

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

Session session = sessionFactory.openSession();

Session interface role:

  • Wraps a JDBC connection
  • Factory for Transaction
  • Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

11. What role does the SessionFactory interface play in Hibernate?

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

SessionFactory sessionFactory = configuration.buildSessionFactory();


Monday, February 14, 2011

Struts Interview Questions

1. What is MVC?

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

Model: The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.

View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.

Controller: The controller reacts to the user input. It creates and sets the model.

2.What is a framework?

A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

3.What is Struts framework?

Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

4.What are the components of Struts?

Struts components can be categorized into Model, View and Controller:
Model: Components like business logic /business processes and data, are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

5.What are the core classes of the Struts Framework?

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.

JavaBeans components for managing application state and behavior.
Event-driven development (via listeners as in traditional GUI development).
Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

6.What is ActionServlet?

ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.

7.What is role of ActionServlet?

ActionServlet performs the role of Controller:
Processes user requests
Determine what the user is trying to achieve according to the request
Pull data from the model (if necessary) to be given to the appropriate view,
Select the proper view to respond to the user
Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources

8.What is the ActionForm?

ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().

10.Describe validate() and reset() methods ?

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

public void reset() {}

11.What is ActionMapping?

Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

12.How is the Action Mapping specified ?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file

<action-mappings>
<action path="/submit" type="submit.SubmitAction" name="submitForm" input="/submit.jsp" scope="request" validate="true">
<forward name="success" path="/success.jsp">
<forward name="failure" path="/error.jsp">
</forward></forward></action>
</action-mappings>

13.What is role of Action Class?

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

14.In which method of Action class the business logic is executed ?

In the execute() method of Action class the business logic is executed.

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;

execute() method of Action class:
Perform the processing required to deal with this request
Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
Return an appropriate ActionForward object

15.What design patterns are used in Struts?

Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token

16.Can we have more than one struts-config.xml file for a single Struts application?

Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>

18.What is the difference between session scope and request scope when saving formbean ?

when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.

20.What are the different kinds of actions in Struts?

The different kinds of actions in Struts are:
ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction

21.What is DispatchAction?

The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

22.How to use DispatchAction?

To use the DispatchAction, follow these steps :
Create a class that extends DispatchAction (instead of Action)
In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
Do not override execute() method – Because DispatchAction class itself provides execute() method.
Add an entry to struts-config.xml

23.What is the use of ForwardAction?

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

24.What is IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

25.What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

26.What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?

LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

28.What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

29.What is SwitchAction?

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

30.What if element has declaration with same name as global forward?

In this case the global forward is not used. Instead the element’s takes precendence.

31.What is DynaActionForm?

A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.

32.What are the steps need to use DynaActionForm?

Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:
In struts-config.xml: change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm





In your Action subclass that uses your form bean:
import org.apache.struts.action.DynaActionForm
downcast the ActionForm parameter in execute() to a DynaActionForm
access the form fields with get(field) rather than getField()

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;


import org.apache.struts.action.DynaActionForm;

public class DynaActionFormExample extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........

33.How to display validation errors on jsp page?

tag displays all the errors. iterates over ActionErrors request attribute.

34.What are the various Struts tag libraries?
The various Struts tag libraries are:
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags

35.What is the use of ?

repeats the nested body content of this tag over a specified collection.











36.What are differences between and

: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.

: is used to retrieve and print the value of the bean property. has no body.


37.How the exceptions are handled in struts?

Exceptions in Struts are handled in two ways:
Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.

Declarative exception handling :You can either define handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.

type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>

or
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>

38.What is difference between ActionForm and DynaActionForm?

An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml
The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

Tuesday, December 7, 2010

Spring MVC Architechture









Spring FORM Tag Library

Spring MVC provides a JSP tag library (Spring Form) for making it easier to bind form elements to Model data. Spring Framework also provides you with some tags for evaluating errors, setting themes and outputting internationalized messages.



Syntax to use Spring Form tag library

	<%@taglib  uri="http://www.springframework.org/tags/form" prefix="form">

Form tags used in this example

-Renders an HTML 'form' tag and exposes a binding path to inner tags for binding.

-Renders an HTML 'input' tag with type 'text' using the bound value.

-Renders field errors in an HTML 'span' tag.

-Renders an HTML 'input' tag with type 'password' using the bound value.

-Renders an HTML 'input' tag with type 'radio'.

-Renders an HTML 'select' element. Supports databinding to the selected option.

-Renders a single HTML 'option'. Sets 'selected' as appropriate based on bound value.

-Renders an HTML 'textarea'.

-Renders an HTML 'input' tag with type 'checkbox'.

Simple Registration Form Example

1.Modify the web.xml to configure the Dispatcher Servlet.

web.xml













































false



registration">









index



success























3.Create a Jsp file for taking input from the user index.jsp which contains all the form fields with Spring Form tags.

index.jsp



<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>











Welcome to Spring Web MVC project







Spring Form tags Example







User Name:





Password:





First Name:



Last Name:



Gender: Male

Female



Country :

India

USA

Australia





Address:



Select any :

Check Box1



Check Box2





















4.Create another Jsp file success.jsp which is a View for Spring to display the output. In this file we use Expression Language to display the details.

success.jsp



<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@page import="java.util.Enumeration"%>











Spring Form Tags Example





Spring Form tags examples





User Name: ${uname}



First Name: ${fname}



Last Name: ${lname}



Gender: ${gender}



Country: ${country}



Address: ${addr}



Selected Check box: ${cb}











5.Create a Java class file Registration.java which contains the business logic for registration application. Here this file contains 8 private variables with their respective getter and setter methods to store the details for registration.

Registration.java



public class Registration {



private String username;

private String password;

private String fname;

private String lname;

private String gender;

private String country;

private String addr;

private String cb;



public String getAddr() {

return addr;

}



public void setAddr(String addr) {

this.addr = addr;

}



public String getCb() {

return cb;

}



public void setCb(String cb) {

this.cb = cb;

}



public String getCountry() {

return country;

}



public void setCountry(String country) {

this.country = country;

}



public String getGender() {

return gender;

}



public void setGender(String gender) {

this.gender = gender;

}



public Registration() {

}



public String getFname() {

return fname;

}



public void setFname(String fname) {

this.fname = fname;

}



public String getLname() {

return lname;

}



public void setLname(String lname) {

this.lname = lname;

}



public String getPassword() {

return password;

}



public void setPassword(String password) {

this.password = password;

}



public String getUsername() {

return username;

}



public void setUsername(String username) {

this.username = username;

}



}





6.Create a RegistrationFormController.java file which extends SimpleFormController to control the user request and return respective ModelAndView object.

RegistrationFormController.java





import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;



public class RegistrationFormController extends SimpleFormController {



@Override

protected ModelAndView onSubmit(Object command) throws Exception {



Registration reg=(Registration)command;



String uname=reg.getUsername();

String fname=reg.getFname();

String lname=reg.getLname();



String gender=reg.getGender();

String country=reg.getCountry();

String cb=reg.getCb();

String addr=reg.getAddr();



ModelAndView mv = new ModelAndView(getSuccessView());



mv.addObject("uname",uname);

mv.addObject("fname",fname);

mv.addObject("lname",lname);

mv.addObject("gender",gender);

mv.addObject("country",country);

mv.addObject("cb",cb);

mv.addObject("addr",addr);



return mv;

}



}



7.Create a registrationValidator.java file to validate the form fields like username and password should not be empty.DispatcherServlet is responsible to give property to add Validator to the user request and perform validation.

registrationValidator.java



import org.springframework.validation.Errors;

import org.springframework.validation.Validator;



public class registrationValidator implements Validator

{



public boolean supports(Class cl) {

return Registration.class.isAssignableFrom(cl);



}



public void validate(Object ob, Errors errors) {

Registration reg=(Registration)ob;

if (reg.getUsername() == null || reg.getUsername().length() == 0) {

errors.rejectValue("username", "error.empty.username");

}



else if (reg.getPassword() == null || reg.getPassword().length() == 0) {

errors.rejectValue("password", "error.empty.password");

}



}



}



8.Create or Modify messages.properties file which contains the messages for their respective keys.In this file we write messages for two keys empty username and empty password.

messages.properties



error.empty.username=Please Enter User name

error.empty.password=Please Enter Password

9.Building and running the application





Friday, September 10, 2010

Very Secure File Transfer Protocol Daemon (VSFTPD)

File Transfer Protocol (FTP) is considered as the primary method used to transfer files over a network from computer to computer. FTP uses a client/server model. An FTP client is used to access the FTP server, and as a server, FTP provides access to files or storage.

Very Secure File Transfer Protocol Daemon (vsFTPd) is a fast and secure FTP daemon which is the preferred FTP server for Red Hat Enterprise Linux.

How to Install Very Secure File Transfer Protocol Daemon (vsFTPd)

You can use the rpm command to install vsFTPd as shown below.

[root@RHEL04 ~]# rpm -Uvh vsftpd-2.0.5-10.el5.i386.rpm

OR by using the yum command, if you have configured yum properly.


[root@RHEL04 ~]# yum –y install vsftpd


Once vsFTPd is installed, make sure it starts the next time you boot Linux. You can use the ‘chkconfig’ command to make the vsFTPd start working when you reboot the system.

[root@RHEL04 ~]# chkconfig vsftpd on

Main files and directories Installed with vsftpd

The vsftpd RPM installs the daemon (/usr/sbin/vsftpd), its configuration and related files, as well as FTP directories onto the system.

The following list shows the main files and directories related to vsftpd configuration:

• /etc/rc.d/init.d/vsftpd: The initialization script (initscript) used by the /sbin/service command to start, stop, or reload vsftpd.

• /etc/pam.d/vsftpd: The Pluggable Authentication Modules (PAM) configuration file for vsftpd.

• /etc/vsftpd/vsftpd.conf: The main configuration file for vsftpd.

• /etc/vsftpd/ftpusers: A list of users not allowed to log into vsftpd. By default, this list includes the root, bin, and daemon users, among others, since sending the username and password credentials of sensitive users using clear text is not secure.

• /etc/vsftpd/user_list: This file can be configured to either deny or allow access to the users listed, depending on whether the userlist_deny directive is set to YES (default) or NO in /etc/vsftpd/vsftpd.conf. If /etc/vsftpd.user_list is used to grant access to users, the usernames listed must not appear in /etc/vsftpd.ftpusers.

• /var/ftp/: — The directory containing files served by vsftpd. It also contains the /var/ftp/pub/ directory for anonymous users. Both directories are world-readable, but writable only by the root user.

vsFTPd configuration file /etc/vsftpd/vsftpd.conf

All configuration of vsftpd can be done by its configuration file, /etc/vsftpd/vsftpd.conf. Each directive is on its own line within the file and follows the following format:

=

The lines starting with‘#’ are comments.

vsFTPd daemon Options in /etc/vsftpd/vsftpd.conf

The following is a list of directives which control the overall behavior of the vsftpd daemon.

listen: When enabled, vsftpd runs in standalone mode. This value is set to YES by default. This directive cannot be used in conjunction with the listen_ipv6 directive.

listen_ipv6: When enabled, vsftpd runs in standalone mode, but listen only to IPv6 sockets. This directive cannot be used in conjunction with the listen directive.

The default value is NO.

Log-in Options and Access Controls in /etc/vsftpd/vsftpd.conf

Anonymous access features can be changed for your FTP server by editing the vsftpd.conf file and changing related entries to YES or NO in the file. The main setting related with anonymous access are:

anonymous_enable: Enabled by default. Use a setting of NO, and then restart the server to turn off anonymous access.

anon_mkdir_write_enable: Allows or disallows creating of new directories.

anon_other_write_enable: Allows or disallows deleting or renaming of files and directories.

anon_upload_enable: Controls whether anonymous users can upload files (also depends on the global write_enable setting).

anon_world_readable_only: Allows anonymous users to download only files with world-readable (444) permission

no_anon_password: When enabled, the anonymous user is not asked for a password. The default value is NO.

banner_file: Specifies the file containing text displayed when a connection is established to the server. This option overrides any text specified in the ftpd_banner directive.

cmds_allowed — Specifies a comma-delimited list of FTP commands allowed by the server. All other commands are rejected.

ftpd_banner: When enabled, the string specified within this directive is displayed when a connection is established to the server. This option can be overridden by the banner_file directive. By default vsftpd displays its standard banner.

local_enable: When enabled, local users are allowed to log into the system.

userlist_deny: If userlist_deny=NO, only allow users in userlist_file. If userlist_deny=YES (default), never allow users in userlist_file, and do not even prompt for a password.

userlist_enable: When enabled, the users listed in the file specified by the userlist_file directive are denied access.

userlist_file: Specifies the file referenced by vsftpd when the userlist_enable directive is enabled. This file is created when vsftp is installed and is located in /etc/vsftpd/user_list.

ftp_username: Specifies the local user account (listed in /etc/passwd) used for the anonymous FTP user. The home directory specified in /etc/passwd for the user is the root directory of the anonymous FTP user. The default user is ftp and default home folder is /var/ftp/.

chroot_list_enable: When enabled, the local users listed in the file specified in the chroot_list_file directive are placed in a chroot jail upon log in. If enabled in conjunction with the chroot_local_user directive, the local users listed in the file specified in the chroot_list_file directive are not placed in a chroot jail upon log in. The default value is NO.

chroot_list_file: Specifies the file containing a list of local users referenced when the chroot_list_enable directive is set to YES. The default value is /etc/vsftpd/chroot_list.

chroot_local_user: When enabled, local users are change-rooted to their home directories after logging in. The default value is NO.

Other important options in /etc/vsftpd/vsftpd.conf

dirlist_enable: When enabled, users are allowed to view directory lists.

write_enable: When enabled, FTP commands which can change the file system are allowed.

accept_timeout: Specifies the amount of time for a client using passive mode to establish a connection. The default value is 60.

anon_max_rate: Specifies the maximum data transfer rate for anonymous users in bytes per second. The default value is 0, which does not limit the transfer rate.

connect_timeout: Specifies the maximum amount of time a client using active mode has to respond to a data connection, in seconds. The default value is 60.

idle_session_timeout: Specifies the maximum amount of time between commands from a remote client. Once triggered, the connection to the remote client is closed.

listen_address: Specifies the IP address on which vsftpd listens for network connections. There is no default value for this directive.

listen_address6: Specifies the IPv6 address on which vsftpd listens for network connections when listen_ipv6 is set to YES. There is no default value for this directive.

listen_port: Specifies the port on which vsftpd listens for network connections. The default value is 21.

local_max_rate: Specifies the maximum rate data is transferred for local users logged into the server in bytes per second. The default value is 0, which does not limit the transfer rate.

max_clients: Specifies the maximum number of simultaneous clients allowed to connect to the vsFTPd server when it is running in standalone mode. Any additional client connections to the vsFTPd server would result in an error message. The default value is 0, which does not limit connections.


Wednesday, September 1, 2010

Users and Groups

Although adding users and groups seems like a simple task on the surface, it does require forward planning and preparation for a large user group such as one for a large company or corporation or for an organization that requires users to have access to multiple computers throughout the same building or even a set of worldwide offices.

In addition to a Red Hat Enterprise Linux system having a username for each user allowed access to a system, each system has user groups. A user group is a group of one or more users. A user can be a member of more than one group.

Each user on a Red Hat Enterprise Linux system is assigned a unique user identification number, also known as a UID. UIDs below 500 are reserved for system users such as the root user. System users also include those added for a specific service such as the nfsnobody, rpc and rpcuser users for the NFS service.

By default in Red Hat Enterprise Linux, when a user is added, a private user group is created—meaning that a user group of the same name is created and that the new user is the sole user in that group.

Adding and Modifying Users
Configure the username, full name, and password for the new user. The default login shell for new users is bash. By default, the directory /home// is created as the user’s home directory, and a private group is created for the user.

Adding Users
To add a new user, use the useradd command. The basic syntax is useradd . The username is the only information required to add a new user. The useradd command creates the account, but the account is locked. To unlock the account and create a password for the user, use the command passwd . By default, the user’s home directory is created and the files from /etc/skel/ are copied into it. The two exceptions are if the -M
option is used and if the home directory already exists.



Password Aging
Optionally, password aging can also be configured with the chage command. If the chage
command is immediately followed by a username, the administrator will be interactively
prompted for the password aging

[root@Matrix ~]# chage swathi
Changing the aging information for swathi
Enter the new value, or press ENTER for the default
Minimum Password Age [0]: 15
Maximum Password Age [99999]: 15
Last Password Change (YYYY-MM-DD) [2010-09-01]: 2010-09-02
Password Expiration Warning [7]: 5
Password Inactive [-1]: -1
Account Expiration Date (YYYY-MM-DD) [1969-12-31]: 2010-09-17

[root@Matrix ~]# chage -l swathi
Last password change : Sep 02, 2010
Password expires : Sep 17, 2010
Password inactive : never
Account expires : Sep 17, 2010
Minimum number of days between password change : 15
Maximum number of days between password change : 15
Number of days of warning before password expires : 5

Deleting Users
The userdel command is available for deleting users using the userdel syntax. If no command line options are used, the user is deleted and can no longer log into the system. The private user group for the user is also deleted, and the user is removed from any other groups of which he was a member. However, the user’s home directory and any other files the user owned are not deleted from the system. To remove the user’s home directory and mail spool, use the userdel -r command. All other files owned by the user must be deleted manually if the administrator needs them removed. However, use caution when removing files owned by a removed user, they might be shared files still needed by others in the group.

Any remaining files will still exist with the user’s old UID, so be careful when creating new users.
If the UID is reused for a different user, you might be giving the new user access to the old
user’s files because file permissions are based on the UID and GID associated with the file.


Managing Groups
A new group with the same name as the user is created by default when a new user is added. This new group is referred to as a private user group. Every user has a default group, which is usually the user’s private user group, but every user can also be a member of more than one group. When a file or directory is created by a user, the user’s default group becomes the group associated with the file unless the directory is configured to with the s option to chmod that sets the group ID of files in that directory upon creation. The additional groups a user is a member of allows the user to
have access to files associated with the group and with the proper group file permissions.
A unique integer known as a GID is associated with each group. GIDs below 500 are reserved for system groups just like UIDs below 500 are reserved for system users.

Adding Groups
The groupadd command can be used to add user groups to the system. The basic syntax is
groupadd . If no command-line options are used, the group is created with the next available GID above 499. To specify a GID, use the groupadd -g command. To add a system group, use the groupadd -r command. The first available GID below 500 is used for the system group. To add a system group and specify the GID, use the groupadd -r -g command. Even if you specify a GID for the system group, the GID still needs to be below 500 to follow the numbering convention.

To add users to a group, use the usermod -G command

Modifying Groups
Other than adding users to the group, the name of the group and the GID of the group
can be changed with the groupmod command. To change the GID of a group, use the
groupmod -g command. To change the name of the group, use the
groupmod -n command.
Red Hat Enterprise Linux also includes the gpasswd command for managing groups. It
allows an administrator to configure group administrators, group members, and a group
password. Group administrators can add and delete users as well as set, change, or remove
the group password. A group can have more than one group administrator.
To add group administrators, use the gpasswd -A command, where
is a comma-separated list of existing users you want to be group administrators.
Don’t use any spaces between the commas.
The root user or a group administrator can add users to the group with the gpasswd -a
command. Using this method, only one user can be added at a time.
Similarly, to remove a user from a group, use the gpasswd -d command.
t is also possible for the root user (not a group administrator) to modify the members of a
group with the gpasswd -M command, where is a comma-
separated list of all the users in the group. Notice the word all. When this command is
executed, the group members list changes to the users listed in this command. Any exist
ing members not listed will be removed.
To add or change the password for a group, the root user or a group administrator can use
the gpasswd command. When changing the password, the old password is
not needed. To remove the group password, use the
gpasswd -r command.
If a user is a member of a group, she can use the newgrp command to make
that group her default group for that login session. If the group has a password, the user
must enter the correct password before successfully switching groups. If the group has a
password, users who aren’t members of the group can also make the group their default
group with the newgrp command. If the group doesn’t have a password configured, only
users who are members of the group can use the newgrp command to change groups for
that login session. To disable the use of the newgrp command for a group, use the gpasswd
-R command.

How It All Works
A list of all local users is stored in the /etc/passwd file. This file is in plain text format and
is readable by anyone logged in to the system because it is referenced by user-accessible
utilities such as ls and who to map user and group IDs to usernames and group names.
Each user is listed on a separate line, with the following format:
username:password:uid:gid:real_name:/home/directory:shell

If shadow passwords are used (the default), the encrypted passwords are stored in the
/etc/shadow file, readable only by root for security reasons. This file can also store
optional password expiration data.
All user groups are stored in the /etc/group file, readable by everyone but only writable
by root for the same reason /etc/passwd has these permissions—user utilities need to be
able to map group IDs to group names. Each group is listed on a separate line in the
following format:
groupname:password:gid:users

The group name is the actual name of the user group, the password field contains the x
character if shadow passwords are used or the encrypted password if shadow passwords
are not used. The gid is the unique group ID for the group, and the users field is a
comma-delimited list of users in the group.
If shadow passwords are used for group passwords (the default), they are stored in
/etc/gshadow, a file readable only by the root user.
When a new user is added, files from the /etc/skel/ directory are copied to the user’s
home directory unless the administrator chooses not to create one.

NOTE
By default, a home directory is created when a user is added. If the user’s home direc
tory already exists (for example, the /home/ directory was preserved during reinstalla
tion), the files from /etc/skel/ are not copied to the existing home directory so that
the existing files are not overwritten. This behavior has changed in recent versions of
useradd, so use caution when performing this same operation on older versions of
Red Hat Enterprise Linux.
The default values used when adding a user are stored in the /etc/default/useradd file.
Additional default values for creating users and groups are located in the /etc/login.defs
file. This file is documented with comments above each directive, which should be easy
to follow if modifications are needed. The following can be modified with options from
this file:
. Mail spool directory
. Maximum number of days a password can be used
. Minimum number of days between password changes
. Minimum password length accepted
. Number of days to warn user before password expires
. Maximum UID for automatic selection by useradd
. Minimum UID for automatic selection by useradd
. Maximum GID for automatic selection by groupadd
. Minimum GID for automatic selection by groupadd
. Whether to remove cron and print jobs owned by user when user is removed
. Whether or not to create the home directory by default

Deleting Groups
To delete an existing group, use the groupdel command. The group is removed, and the users in the group are no longer members of the group.

Monday, August 9, 2010

Installing Apache Webserver on Fedora 12

1. Download the latest stable version of Apache webserver from the apache website
2. Create a directory apache2 in your home directory and copy the tar file there
(This is not mandatory, this is just to ease your installation)
[sridhar@Matrix ~]$ mkdir apache2
3. change to root
[sridhar@Matrix ~]$ su Password: [root@Matrix sridhar]#
4. copy the download file to the newly created apache2 folder
in this case
[root@Matrix ~]# cp /home/sridhar/Downloads/httpd-2.2.16.tar.gz /home/sridhar/apache
5. Unzip the file
[root@Matrix ~]# gzip -d httpd-2.2.16.tar.gz
6. Untar the file
[root@Matrix ~]# tar -xvf httpd-2.2.16.tar
7. [root@Matrix ~]# ./configure --prefix=/opt/apache2
This will install apache in /opt/apache2 location, default location is /usr/local/apache2
8. [root@Matrix ~]# make
9. [root@Matrix ~]# make install
10. [root@Matrix ~]# /opt/apache2/bin/apachectl start

Open a webbrowser and type in http://localhost, you must be able to see this

Sunday, August 1, 2010

Cron Job

Cron is a time-based job scheduler utility for automating certain tasks in Unix-like operating systems. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain time or date. It is commonly used to automate system maintenance or administration. For example if you would like to create backups of certain files or directories each night, you can use Cron to automate this.

Cron stores it's enteries in the crontab (cron table) file. This is generally located in the /etc directory. Each user can have their own crontab which would be stored in /var/spool/cron/. To edit a users crontab entry, simply log on to the system for that particular user and type crontab -e. The default editor for the 'crontab -e' command is vi. If you are not familiar with VI you can change the default editor by running the following command export VISUAL='editor'. Of course you must replace editor with your favorite text editor (nano, pico, joe etc). Or you could always learn how to use VI

Each line of a crontab file represents a job and is composed of a CRON expression, followed by a shell command to execute. Cron job has seven fields
1st field denotes Minutes ( 0 - 59 )
2nd field denotes Hours ( 0 - 23 )
3rd field denotes Day of the month ( 1 - 31 )
4th field denotes Month ( 1 - 12 ) or ( Jan, feb, mar, apr, ......)
5th field denotes Day of the week ( 0 - 7 ) or ( sun, mon, tue, wed, ......) Note ( 0 & 7 both denote Sunday)
6th field contains user User who runs the command.
7th field contains command Command that needs to be run. This field may contain multiple words or spaces.

There are several special predefined values which can be used to substitute the CRON expression.

Entry : @yearly (or @annually)
Description : Run once a year
Equivalent To : 0 0 1 1 *

Entry : @monthly
Description : Run once a month
Equivalent To : 0 0 1 * *

Entry : @weekly
Description : Run once a week
Equivalent To : 0 0 * * 0

Entry : @daily
Description : Run once a day
Equivalent To : 0 * * *

Entry : @midnight
Description : (same as @daily)
Equivalent To : 0 0 * * *

Entry : @hourly
Description : Run once an hour
Equivalent To : 0 * * * *

If both the dom and dow are specified, the command will be executed when
either of the events happen.
e.g.
* 12 16 * Mon root cmd
Will run cmd at midday every Monday and every 16th, and will produce the
same result as both of these entries put together would:
* 12 16 * * root cmd
* 12 * * Mon root cmd

Vixie Cron also accepts lists in the fields. Lists can be in the form, 1,2,3
(meaning 1 and 2 and 3) or 1-3 (also meaning 1 and 2 and 3).
e.g.
59 11 * * 1,2,3,4,5 root backup.sh
Will run backup.sh at 11:59 Monday, Tuesday, Wednesday, Thursday and Friday,
as will:
59 11 * * 1-5 root backup.sh

Cron also supports 'step' values.
A value of */2 in the dom field would mean the command runs every two days
and likewise, */5 in the hours field would mean the command runs every
5 hours.
e.g.
* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

*/15 9-17 * * * root connection.test
Will run connection.test every 15 mins between the hours or 9am and 5pm

Lists can also be combined with each other, or with steps:

* 12 1-15,17,20-25 * * root cmd
Will run cmd every midday between the 1st and the 15th as well as the 20th
and 25th (inclusive) and also on the 17th of every month.

* 12 10-16/2 * * root backup.sh
is the same as:
* 12 10,12,14,16 * * root backup.sh

When using the names of weekdays or months, it isn't case sensitive, but only
the first three letters should be used, e.g. Mon, sun or Mar, jul.

Comments are allowed in crontabs, but they must be preceded with a '#', and
must be on a line by them self.

Controlling Access to cron

Cron has a built in feature of allowing you to specify who may, and who
may not use it. It does this by the use of /etc/cron.allow and /etc/cron.deny
files. These files work the same way as the allow/deny files for other
daemons do. To stop a user using cron, just put their name in cron.deny, to
allow a user put their name in the cron.allow. If you wanted to prevent all
users from using cron, you could add the line ALL to the cron.deny file:

root@Matrix # echo ALL >>/etc/cron.deny

If you want user cog to be able to use cron, you would add the line cog
to the cron.allow file:

root@Matrix # echo cog >>/etc/cron.allow

If there is neither a cron.allow nor a cron.deny file, then the use of cron
is unrestricted (i.e. every user can use it). If you were to put the name of
some users into the cron.allow file, without creating a cron.deny file, it
would have the same effect as creating a cron.deny file with ALL in it.
This means that any subsequent users that require cron access should be
put in to the cron.allow file.