Wednesday, December 7, 2016

Java script regex for different value formats


Regex- ^(\d+|\d+-\d+)((,?\d+)*)$ 

Allowed number formats
9
1-18,6,3,6767,343
34,34,565,6767,122323


Decimal Number Regex : ^\d*[0-9](\.\d*[0-9])?$     
Allowed Format : 119.170 

Date Format Regex (m/d/y): ^([\d]|1[0,1,2])/([0-9]|[0,1,2][0-9]|3[0,1])/\d{4}$ 
Allowed Format : m/d/y

File Names Regex : ^[a-zA-Z0-9-_\.]+\.(pdf|txt|doc|csv)$
Allowed file name format :  
hi-file.pdf
hello1-file.txt
hello3-file.doc
hello44-file.csv

E-mail Address validation regex: ^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$
Allowed format : javafarms@india.com

HTML Color Codes regex : ^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$
Allowed Format : #8877ff

Image Filenames Regex : ^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$
Allowed format : hi-image_file.jpg


IP Address Regex : ^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$
Allowed Format : 10.121.21.111

Multimedia Filenames Regex : ^[a-zA-Z0-9-_\.]+\.(swf|mov|wma|mpg|mp3|wav)$
Allowed Format : hi-multimedia.swf

MySQL Date Format Regex : ^\d{4}-(0[0-9]|1[0,1,2])-([0,1,2][0-9]|3[0,1])$
Allowed Format : 2016-12-07

Time Format (HH:MM) Regex : ^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$
Allowed Format : 11:29


URL regex : ^(http[s]?://|ftp://)?(www\.)?[a-zA-Z0-9-\.]+\.(com|org|net|mil|edu|ca|co.uk|com.au|gov)$
https://www.myjavafarms.com



Wednesday, November 30, 2016

Array subtyping is covariant means

It means array DOVE[] is considered to be subtype of BIRD[] if DOVE is a subclass of BIRD.
example
Integer[] ints = new Integer[]{9,99};
Number[] nums =  ints;
nums[1] = 1.9; // here it will throw array store exception
According to the substitution principle the assignment on the second line is legal
but the exception will be throws at the run time on the third line.
Because whenever an array is created then it tagged with its reified type. here it is integer.
eventhough it is assigned to the Number (super type)  type here internally it points to it
Integer type so it throws exception at run time when it detects a float value assigned.

While in contrats for generics the subtype relation is invariant, means
List<DOVE> is not considered to be subtype of List<BIRD>.

example
List<Integer> intList =  Arrays.asList(1,2,3,4,5,6,7,8,9);
List<Number>  numList = intList; // here it will show compile time error


But here with wild card we can achieve the covariant
in that case here List<DOVE> is considered to be subtype of List<? extends BIRD>.

Thursday, September 29, 2016

What is Filter ? and When to use Filter Web App ?

 A filter is an object than perform filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.

Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
Filters are configured in the deployment descriptor of a web application

Examples that have been identified for this design are
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Tokenizing Filters
7) Filters that trigger resource access events
8) XSL/T filters
9) Mime-type chain Filter

Thursday, August 4, 2016

EVERYTHING ABOUT FILTER

The Java Servlet specification version 2.3 introduces a new component type, called a filter. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.
Filters are important for a number of reasons. First, they provide the ability to encapsulate recurring tasks in reusable units. Organized developers are constantly on the lookout for ways to modularize their code. Modular code is more manageable and documentable, is easier to debug, and if done well, can be reused in another setting.
Second, filters can be used to transform the response from a servlet or a JSP page. A common task for the web application is to format data sent back to the client. Increasingly the clients require formats (for example, WML) other than just HTML. To accommodate these clients, there is usually a strong component of transformation or filtering in a fully featured web application. Many servlet and JSP containers have introduced proprietary filter mechanisms, resulting in a gain for the developer that deploys on that container, but reducing the reusability of such code. With the introduction of filters as part of the Java Servlet specification, developers now have the opportunity to write reusable transformation components that are portable across containers.
Filters can perform many different types of functions. We'll discuss examples of the italicized items in this paper:
  •  
  • Authentication-Blocking requests based on user identity.
  • Logging and auditing-Tracking users of a web application.
  • Image conversion-Scaling maps, and so on.
  • Data compression-Making downloads smaller.
  • Localization-Targeting the request and response to a particular locale.
  • XSL/T transformations of XML content-Targeting web application responses to more that one type of client.
These are just a few of the applications of filters. There are many more, such as encryption, tokenizing, triggering resource access events, mime-type chaining, and caching.
In this paper we'll first discuss how to program filters to perform the following types of tasks:
  •  
  • Querying the request and acting accordingly
  • Blocking the request and response pair from passing any further.
  • Modifying the request headers and data. You do this by providing a customized version of the request.
  • Modifying the response headers and data. You do this by providing a customized version of the response.
We'll outline the filter API, and describe how to develop customized requests and responses.
Programming the filter is only half the job of using filters-you also need to configure how they are mapped to servlets when the application is deployed in a web container. This decoupling of programming and configuration is a prime benefit of the filter mechanism:
  •  
  • You don't have to recompile anything to change the input or output of your web application. You just edit a text file or use a tool to change the configuration. For example, adding compression to a PDF download is just a matter of mapping a compression filter to the download servlet.
  • You can experiment with filters easily because they are so easy to configure.
The last section of this paper shows how to use the very flexible filter configuration mechanism. Once you have read this paper, you will be armed with the knowledge to implement your own filters and have a handy bag of tricks based on some common filter types.

Programming Filters

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. A filter config contains initialization data.
The most important method in the Filter interface is the doFilter method, which is the heart of the filter. This method usually performs some of the following actions:
  •  
  • Examines the request headers
  • Customizes the request object if it wishes to modify request headers or data or block the request entirely
  • Customizes the response object if it wishes to modify response headers or data
  • Invokes the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target servlet, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. It invokes the next entity by calling the doFilter method on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response.
  • Examines response headers after it has invoked the next filter in the chain
  • Throws an exception to indicate an error in processing
In addition to doFilter, you must implement the init and destroy methods. The in it method is called by the container when the filter is instantiated. If you wish to pass initialization parameters to the filter you retrieve them from the FilterConfig object passed to init.

Reference Link for Detail and Examples

Tuesday, August 2, 2016

Everything about SNMP

Simple Network Management Protocol

It has mainly three components
1) Managed Devises
2) Agents
3) Network Management Systems

Managed Devises
---------------
It can be computer, routers, switches, printers, hub etc

Agent
-----
Agent is a softwares program residing inside the devices.
It translates the information into the format compatible with SNMP.

Network Management System (NMS)
-------------------------------
NMS runs monitoring applications.It provides bulk processing and memory resources required for the
network management.

SNMP VERSION1 was the first development of the SNMP protocol.
Its description can be found in RFC 1157.
It works within the specification of SMI (Structure of management of Information).
It works on the UDP, IP, CLNS, AppleTalk Datagram Delivery Protocol (DDP) and Novell IPX(Internet Packet Exchange).

Monday, August 1, 2016

JAVA COMMAND TO EXECUTE JAR FILE

1) java -jar <jar-file-name>.jar
 
2) if you dont have a manifest:Use this command 
       java -cp foo.jar full.package.name.ClassName

3) java -jar NameOfJARFile.jar

Friday, July 29, 2016

Everything About Servlet

Basic meaning of Servlet is Let Serv. 
It a technology to receive a user's Request and Serv back a Response.

In java Servlet is an Interface.
It contains four methods declaration.

public interface Servlet{
    void     destroy();
    ServletConfig     getServletConfig();
    java.lang.String     getServletInfo();
    void     init(ServletConfig config);
    void     service(ServletRequest req, ServletResponse res);
}


Usually developers prepare servlet classes to receive HTTP request and send back HTTP Response.
Servlet works on the HTTP (Hyper Text Transfer Protocol) protocol.

The servlet interface contains method to Inititlize a servlet, to serv the request, and to provide back response.
and to destroy or remove servlet from the server.

To use this servlet interface or to implement this servlet interface, developer can prepare a class which extends the GenericServlet (javax.servlet.GenericServlet) class OR developer can extends the
HttpServlet(javax.servlet.http.HttpServlet) class.

All the servlet classes have their servlet life cycle.
First the Servlet is Initialized by the container using the init(ServletConfig config) method.


Then all the clients requests are handled using the service(ServletRequest req, ServletResponse res) method and finally servlet is destroyed by the container.
(Note: All the Servlet instances are destroyed when server is shutting down )


The init(ServletConfig config) method is called exactly once in the life cycle of a servlet. It is called by Container.


Before serving any request the servlet's init methos's execution must be successfully complete.

All servlets have their configuration information in the ServletConfig object.
ServletConfig object are servlet specific.

Servlet is initialized on the applications startup or on the first request received to that servlet.


There is always one instance of each servlet in webapp.
Developer cannot destroy servlet on their need base. Only container can destroy the servlet.

ServletConfig (Servlet Configuration)

public interface ServletConfig{
    java.lang.String     getInitParameter(java.lang.String name);
    java.util.Enumeration<java.lang.String>     getInitParameterNames();
    ServletContext     getServletContext();
    java.lang.String     getServletName();
}

ServletConfig is an Interface


When the Web Container initializes the Servlet then it container creates the ServletConfig object by reading servlet specific information from the web.xml file and passes the ServletConfig object to the Servlet's init method.

There is always one ServletConfig object per servlet instance.
Developer can get the ServletConfig object using the getServletConfig() method.
i.e.


ServletConfig sc = getServletConfig();
out.println(sc.getInitParameter("dbUrl"));

ServletConfig object provides the ServletContext object using the getServletContext() method.
It provides the Init Parameters values configured into web.xml file, using the getInitParameter(java.lang.String name) method.
It provides the Servlet Instance name using the getServletName() method.
It provides its own Init Parameters names using the getInitParameterNames() method.

ServletContext (Servlet Context)

ServletContext is an Interface


public interface ServletContext{
    .......
    java.lang.Object     getAttribute(java.lang.String name);
    java.util.Enumeration<java.lang.String>     getAttributeNames();
    java.lang.String     getContextPath();
    java.lang.String     getInitParameter(java.lang.String name);
    .......
}


It has lots of more  methods.
There is one ServletContext object "per application" per JVM(Java Virtual Machine).


Container created the ServletContext object when it created the servlet config object.


It passed the ServletContext object to the servlet config. so developer can have the servlet context object using the ServletConfig object.


Developer can put all the application specific informtion into the servlet context object. So, the information will be accessible to whole application.


It means to share the information between multiple servlets in a web app, servlet context can be used.

Thursday, July 7, 2016

Android N Features List


Android N Features
Android N

1) Android N will allow users to open two apps in split-screen mode on Nexus devices.
i.e. This means, for example, users can keep tweeting while watching a video on YouTube.

2) Android N brings with it more Quick Settings when you slide the notifications pane down. 

3) Android N may help solve this, courtesy the new feature called 'Bundled notifications'. With this feature, users can group together notifications from each app in the menu and one will just need to tap the bundle to read individual alerts.

4) Android 7.0, Doze will work not only when your phone is not in use, but also when the screen is turned off. This is expected to improve the battery life.

5) In Android N double-tapping the Recent Apps button from homescreeen will open the last-used app, while double-tapping the button when an app is already open will take you to the app you had open just before.

6) Android N native file browser are: hamburger menus, searchability by file types and folders, the option to move and share files, and Google Drive integration. You can even have multiple instances of the file browser open at the same time.

7) Android N allows users to block phone numbers at the system level, directly from apps like Dialler, Hangouts or Messenger.

8) Android N provides the ability to add your medical information on the lockscreen itself in case of an emergency. You can go to Users in Settings and select the Emergency Information option; fill the details you want to reveal and add an emergency contact for good measure.

9) Android N brings a few changes that can be found in the Settings app under different menus. These include a new night theme, data saver that blocks background data consumption, and provision for display calibration as well as screen zooming, among others.

Wednesday, July 6, 2016

What is HashTable initial capacity and load factor ?

HashTable instance has two main parameters which affect it performance.
Initial Capacity and the Load Factor. 
Initial Capacity is the capacity of the hashtable instance when it is created. 
Load Factor is used to measure how full the hashtable instance is allowed to be before its initial capacity is automatically increased. when the number of entries into the hashtable is exceeds the product of current capacity and load factor, the hashtable is rehashed. It means its internal data structures are rebuild. so that the has table has new free number of buckets. 

Java List Interview Questions Answers

When the contains() method of list throws NullPointerException ?
Ans : if the specified element is null and this list does not permit null elements.

Is it safe to modify the array of object returned by the toArray() method of list ?
Ans : The returned array will be "safe" in that no references to it are maintained by this list.  (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.

Explain Remove method of list
Ans: Removes the first occurrence of the specified element from this list,  if it is present (optional operation).  If this list does not contain the element, it is unchanged.  More formally, removes the element with the lowest index  if this list contained the specified element (or equivalently, if this list changed  as a result of the call).
     
This method throws ClassCastException if the type of the specified element is incompatible with this list (optional)

This method throws NullPointerException if the specified element is null and this list does not permit null elements
This method throws UnsupportedOperationException if the operation   is not supported by this list

Is it possible to get some number of elements sequence from the List ?
Ans: Yes it is possible using the ListIterator<E> listIterator(int index) method.
This method will return all the elements from the list from the specified index position to the size of the list. 

Also you can get some specifi range of elements from list using the 
List<E> subList(int fromIndex, int toIndex) method. here the elements at the fromIdex will be inclusive and toIndex is exclusive. If both of the specified index values are same then the returned list will be empty.
And any non structural changes made into the returned list will be reflected into the original list. (Structural modifications are those that changes the size of the this list)

How can you remove five elements in one shot from the list without using the remove(int index) method ?
Ans: using the subList(int fromIndex, int toIndex) method you can remove multiple elements simultaneously from 'this' list. 
exmple : subList(4,6).clear();
Here the 4th and 5th element will be removed from the list.





Thursday, June 30, 2016

Benefits of Generics

One beneit of using generic classes should now be obvious:
improved correctness. Incorrect types of objects can no longer
be entered into a list. While erroneous attempts to insert
an element could previously be detected only during testing
(and testing can never be complete), they are now detected at
compile time, and type correctness is guaranteed. In addition,
if there is such an error, it will be reported at the point of the
incorrect insertion—not at the
point of retrieving the element,
which is far removed from the
actual error location.
There is, however, a second
beneit: readability. By
explicitly specifying the element
type of collections,
you are providing useful information to human readers of
your program as well. Explicitly saying what type of element
a collection is intended for can make life easier for a
maintenance programmer.

Tuesday, June 21, 2016

Struts2 Points to remember about “field-validator” nodes

Each field can have one or more “field-validator” nodes

Each fields validators are executed in the order they are defined

Each field validator has a “short-circuit” attribute; if this
is true and the validation fails, all further validations are
skipped and a failed result returned for the field

The message node can include a “key” attribute which
looks up the message to display to the user from a
message bundle; the value of the node is then used if no
message bundle key exists

Validator configuration information (such as min and
max) as well as values from the value stack can be used
in the validation message by placing the value between
the tokens “${“ and “}”

Validators can have a scope of either “field” or
“expression”; expression validators can work across
multiple fields

Wednesday, June 8, 2016

BENEFITS OF GENERICS


One beneit of using generic classes should now be obvious:
improved correctness. Incorrect types of objects can no longer
be entered into a list. While erroneous attempts to insert
an element could previously be detected only during testing
(and testing can never be complete), they are now detected at
compile time, and type correctness is guaranteed. In addition,
if there is such an error, it will be reported at the point of the
incorrect insertion—not at the
point of retrieving the element,
which is far removed from the
actual error location.
There is, however, a second
beneit: readability. By
explicitly specifying the element
type of collections,
you are providing useful information to human readers of
your program as well. Explicitly saying what type of element
a collection is intended for can make life easier for a
maintenance programmer.

Monday, April 18, 2016

Fibonacci Series and Palindrome Number programs

class Fibonacci {
public static void main(String[] dataBag){
int ans = 0 ;
int prev = ans;
int next = 1;

do{

System.out.println(prev);
ans = prev + next;
prev = next;
next = ans;
}while(prev<=25);
}
}


class Palindrom{
public static void main(String[] dataBag){
int number = 12121;
int palindrom = 0;
int temp = number;

while(temp>0){
palindrom = palindrom*10;
int digit = temp%10;
palindrom += digit;
temp = temp / 10;
}

if(number == palindrom){
System.out.println(number+" is a palindrom number");
}else{
System.out.println(number+" is not palindrom number");
}
}
}

Tuesday, March 8, 2016

Java HashMap Useful information

HashMap permits null values and the null key.  
The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls.
This class makes no guarantees as to the order of the map.
In particular, it does not guarantee that the order will remain constant over time.

HashTable has two important parameters which affects its performance
one is initial capacity and load factor.
Capacity is the number of buckets in the Hash Table.
Initial capacity is the capacity of hash table as the time of creation.

LoadFactor is the a measure of how full the hash table to be allowed before its capacity automatically increased.
Hash table rehashed when the number of entries in to the hash table exceeds the product of load factor and current capacity. Rehashed means internal data struture rebuilt.
So the hash table will have twice the number of buckets.

If many key-value mappings are to be stored in hashmap then creating it with a sufficient large capacity
will allow the mapping to be stored more efficiently than letting it perform automatic rehashing.

If many threads access the HashMap object at a single time then its a good practice to wrapp it using the Collections.synchronizedMap at the creating time.
Map mapObject = Collections.synchronizedMap(new HashMap(...));

Friday, March 4, 2016

FACTORY DESIGN PATTERN EXAMPLE

/*
Creational Patterns - Factory Pattern
Factory of what? Of classes.
In simple words, if we have a super class and n sub-classes,
and based on data provided,
we have to return the object of one of the sub-classes,
we use a factory pattern.
*/
class Person {

public String name;
private String gender;

public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}

public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}

}


class Male extends Person {
  public Male(String fullName) {
setName(fullName);
setGender("Male");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Mr. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}
}


class Female extends Person {
  public Female(String fullName) {
setName(fullName);
setGender("Female");
}
public String toString(){
System.out.println("----Person Detail----- ");
System.out.println("Ms. "+getName());
System.out.println("Name : "+getName());
System.out.println("Gender : "+getGender());
return "";
}

}

class DPFactory{
  public static void main(String args[]) {

DPFactory factory = new DPFactory();
Person  person = factory.getPerson(args[0], args[1]);
System.out.println(person);

}
public Person getPerson(String name, String gender) {
if (gender.equals("M")){
return new Male(name);
}else if(gender.equals("F")){
return new Female(name);
}else{
return null;
}
}
}

Wednesday, February 24, 2016

What is Serialization in java ?

Serialization is a type of mechanish or process in java using which an object state can be saved in a stream of bytes and its a platform independent so object serialized in one platform can be deririalize in anothe platform.

UseCase
When an object is converted into Bytes Stream then that object can be 
Serialized object can be Stored into database
Serialized object can be stored/write into file
that object can be send over the network
that object can be stored into memory

In java serializable interface is a marker interface there is no method in that interface.
When you want any class object to be serialized then you need to implement the serializable interface.
whenever any object is being serialized then all the member of the object is serialzed except transient and static variables.

also take a look at when to use Volatile ? and  when to use transient ? in java



What is transient in Java ?

About transient 
transient is a keyword which is used with the member variable of a class to exclude a particular variable from the serialization process (In serialization an object state is saved in bytestream by JVM).

One cannot use the transient keyword with the static variable.

transient variable initialized with the default value during de-serialization
(In Deserialization process object state is recovered by JVM except the static and transient variablers)

also take a look at the what is volatile keyword in java

Advantage
many times as a developer we do not want to serialize some members of object at that one can use the transient keyword and it gives us flexibility in this case as per our requirement.

UseCase
may times some variables value is dependent on other variable, means we can gain value of particular variable from other variables value at that time we can exclude particular variable from being serialization process.
sometimes we use some members of class just for logs purpose those variables also no need to be serialize.

What is volatile keyword in java ?

volatile is a keyword in java it is used to indicate java compiler and java thread that do not cache the value of the variable preceded with the volatile keyword and all time read the volatile variable's value from the main memory. 

So whenever you want read and write operation to be atomic on any variable then declare that variable with volatile keyword.

also take a look at what is transient in java

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...