Monday, August 8, 2016

Java Code for Converting Speech to Text

Jars Required

1) cmudict04.jar
2) cmulex.jar
3) cmutimelex.jar
4) cmu_time_awb.jar
5) cmu_us_kal.jar
6) en_us.jar
7) reetts-jsapi10.jar
8) freetts.jar
9) mbrola.jar

Code for Text to Speech

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.sun.speech.freetts.Voice;
import com.sun.speech.freetts.VoiceManager;

public class TextToSpeech {
    // Default voice is Kevin16
    private static final String VOICENAME = "kevin16";
  
    public static void main(String[] args) {
    Voice voice;
    // Taking instance of voice from VoiceManager factory.
    VoiceManager voiceManager = VoiceManager.getInstance();
    voice = voiceManager.getVoice(VOICENAME);
    // Allocating voice
    voice.allocate();
    // word per minute
    voice.setRate(120);
    voice.setPitch(100);
    System.out.print("Enter your text: ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
    // Ready to speak
    voice.speak(br.readLine());
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }   
   }

Saturday, July 30, 2016

How to decide whether to use newCachedThreadPool or newFixedThreadPool?

newFixedThreadPool()

Creates a thread pool that reuses a fixed number of threads...
This means that if you ask for 2 threads, it will start 2 threads and never start 3.
A FixedThreadPool does have its advantages when you do in fact want to work with a fixed number of threads, since then you can submit any number of tasks to the executor service while knowing that the number of threads will be maintained at the level you specified. If you explicitly want to grow the number of threads, then this is not the appropriate choice.

This does however mean that the one issue that you may have with the CachedThreadPool is in regards to limiting the number of threads that are running concurrently. The CachedThreadPool will not limit them for you, so you may need to write your own code to ensure that you do not run too many threads. This really depends on the design of your application and how tasks are submitted to the executor service.



On the other hand, the newCachedThreadPool()

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
In your case, if you only have 2 thread to run, either will work fine since you will only be submitting 2 jobs to your pool. However, if you wanted to submit all 20 jobs at once but only have 2 jobs running at one time, you should use a newFixedThreadPool(2). Otherwise all 20 jobs will run at the same time which may not be optimal depending on how many CPUs you have.

Typically  use the newCachedThreadPool() when you need the thread to be spawned immediately, even if all of the threads currently running are busy. I recently used it when I was spawning timer tasks. The number of concurrent jobs are immaterial because I never spawn very many but I want them to run when they are requested and I want them to re-use dormant threads.

Use newFixedThreadPool() when you want to limit the number of concurrent tasks running at any one point to maximize performance and not swamp the server. For example if I am processing 100k lines from a file, one line at a time, I don't want each line to start a new thread but I want some level of concurrency so I allocate (for example) 10 fixed threads to run the tasks until the pool is exhausted.

Saturday, July 9, 2016

Internals of Garbage Collectors 


Garbage collection works by employing several GC algorithm e.g. Mark and Sweep. There are different kinds of garbage collector available in Java to collect different area of heap memory e.g. you have serial, parallel and concurrent garbage collector in Java. A new collector called G1 (Garbage first) are also introduced in JDK 1.7. First step to learn about GC is to understand when an object becomes eligible to garbage collection.
Since JVM provides memory management, Java developers only care about creating object, they don't care about cleaning up, that is done by garbage collector, but it can only collect objects which has no live strong reference or it's not reachable from any thread. If an object, which is suppose to be collected but still live in memory due to unintentional strong reference then it's known as memory leak in Java. ThreadLocal variables in Java web application can easily cause memory leak. 
Coming to Garbage Collection lets know few Important points about Garbage Collector

1) Objects are created on heap in Java irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves Java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory garbage collection thread invokes finalize() method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc() and Runtime.gc() which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.

Now the Question is when does Object becomes eligible for Garbage Collection
An object becomes eligible for Garbage collection or GC if its not reachable from any live threads or by any static references. In other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.

Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

Heap Generations for Garbage Collection in Java
Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap. New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent minor garbage collection if object survives its gets moved to survivor 1 and then survivor 2 before major garbage collection moved that object to old or tenured generation.
Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of Java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java
Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the runtime via JVM command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

Read More 

Java 8 Features
How to Reset Arraylist In Java
How HashMap Work in Java
Why wait (), notify () and notifyAll () must be called from synchronized block or method in Java
XPath to locate Information in XML
Internals of Garbage Collector
Reference Type in Java
Different Ways to Create ObjectClass Loaders in Java
Producer Consumer Problem
Why String is Final in Java
Singleton Class using Enum
JSON tutorial
Exceptional Handling in Java 

Saturday, June 11, 2016

REST and SOAP: When Should I Use Which Web Services

Simple Object Access Protocol (SOAP) and Representational State Transfer (REST) are two answers to the same question: how to access Web services. The choice initially may seem easy, but at times it can be surprisingly difficult.

SOAP is a standards-based Web services access protocol that has been around for a while and enjoys all of the benefits of long-term use. Originally developed by Microsoft, SOAP really isn’t as simple as the acronym would suggest.

REST is the newcomer to the block. It seeks to fix the problems with SOAP and provide a truly simple method of accessing Web services. However, sometimes SOAP is actually easier to use; sometimes REST has problems of its own. Both techniques have issues to consider when deciding which protocol to use.

SOAP is a more rigid set of messaging patterns than REST. The rules in SOAP are important because without these rules, you can’t achieve any level of standardization. REST as an architecture style does not require processing and is naturally more flexible. Both SOAP and REST rely on well-established rules that everyone has agreed to abide by in the interest of exchanging information.


A Quick Overview of SOAP

SOAP relies exclusively on XML to provide messaging services. Microsoft originally developed SOAP to take the place of older technologies that don’t work well on the Internet such as the Distributed Component Object Model (DCOM) and Common Object Request Broker Architecture (CORBA). These technologies fail because they rely on binary messaging; the XML messaging that SOAP employs works better over the Internet.

After an initial release, Microsoft submitted SOAP to the Internet Engineering Task Force (IETF) where it was standardized. SOAP is designed to support expansion, so it has all sorts of other acronyms and abbreviations associated with it, such as WS-Addressing, WS-Policy, WS-Security, WS-Federation, WS-ReliableMessaging, WS-Coordination, WS-AtomicTransaction, and WS-RemotePortlets. In fact, you can find a whole laundry list of these standards on Web Services Standards.

The point is that SOAP is highly extensible, but you only use the pieces you need for a particular task. For example, when using a public Web service that’s freely available to everyone, you really don’t have much need for WS-Security.

The XML used to make requests and receive responses in SOAP can become extremely complex. In some programming languages, you need to build those requests manually, which becomes problematic because SOAP is intolerant of errors. However, other languages can use shortcuts that SOAP provides; that can help you reduce the effort required to create the request and to parse the response. In fact, when working with .NET languages, you never even see the XML.

Part of the magic is the Web Services Description Language (WSDL). This is another file that’s associated with SOAP. It provides a definition of how the Web service works, so that when you create a reference to it, the IDE can completely automate the process. So, the difficulty of using SOAP depends to a large degree on the language you use.

One of the most important SOAP features is built-in error handling. If there’s a problem with your request, the response contains error information that you can use to fix the problem. Given that you might not own the Web service, this particular feature is extremely important; otherwise you would be left guessing as to why things didn’t work. The error reporting even provides standardized codes so that it’s possible to automate some error handling tasks in your code.

An interesting SOAP feature is that you don’t necessarily have to use it with the HyperText Transfer Protocol (HTTP) transport. There’s an actual specification for using SOAP over Simple Mail Transfer Protocol (SMTP) and there isn’t any reason you can’t use it over other transports. In fact, developers in some languages, such as Python and PHP, are doing just that.

A Quick Overview of REST

Many developers found SOAP cumbersome and hard to use. For example, working with SOAP in JavaScript means writing a ton of code to perform extremely simple tasks because you must create the required XML structure absolutely every time.

REST provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. In some situations you must provide additional information in special ways, but most Web services using REST rely exclusively on obtaining the needed information using the URL approach. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.

Unlike SOAP, REST doesn’t have to use XML to provide the response. You can find REST-based Web services that output the data in Command Separated Value (CSV), JavaScript Object Notation (JSON) and Really Simple Syndication (RSS). The point is that you can obtain the output you need in a form that’s easy to parse within the language you need for your application.

Deciding Between SOAP and REST

Before you spend hours fretting over the choice between SOAP and REST, consider that some Web services support one and some the other. Unless you plan to create your own Web service, the decision of which protocol to use may already be made for you. Extremely few Web services, such as Amazon, support both. The focus of your decision often centers on which Web service best meets your needs, rather than which protocol to use.

Soap Vs Rest

SOAP is definitely the heavyweight choice for Web service access. It provides the following advantages when compared to REST:
  • Language, platform, and transport independent (REST requires use of HTTP)
  • Works well in distributed enterprise environments (REST assumes direct point-to-point communication)
  • Standardized
  • Provides significant pre-build extensibility in the form of the WS* standards
  • Built-in error handling
  • Automation when used with certain language products
REST is easier to use for the most part and is more flexible. It has the following advantages when compared to SOAP:
  • No expensive tools require to interact with the Web service
  • Smaller learning curve
  • Efficient (SOAP uses XML for all messages, REST can use smaller message formats)
  • Fast (no extensive processing required)
  • Closer to other Web technologies in design philosophy
For Details about HTTP Methods for Restful Web Services go through  HTTP Methods for RESTful Services

HTTP Methods for RESTful Services

For More details on differences between Rest and Soap go though Rest vs Soap


RESTful web services heavily rely on HTTP by design. They use different HTTP methods to perform their job and uses HTTP response code to inform clients about success or failure of a particular request. REST stands for Representational State transfer and it uses HTTP to allow two systems to communicate via remote calls. RESTFul web services is a collection of REST URI which points to resources. These URI can point to a single resource of a collection of resource.


POSTThe POST verb is most-often utilized to **create** new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource. In other words, when creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent, assigning an ID (new resource URI), etc.
On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.
POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most-likely result in two resources containing the same information.

GET :- The HTTP GET method is used to **read** (or retrieve) a representation of a resource. In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
According to the design of the HTTP specification, GET (along with HEAD) requests are used only to read data and not change it. Therefore, when used this way, they are considered safe. That is, they can be called without risk of data modification or corruption—calling it once has the same effect as calling it 10 times, or none at all. Additionally, GET (and HEAD) is idempotent, which means that making multiple identical requests ends up having the same result as a single request.
Do not expose unsafe operations via GET—it should never modify any resources on the server.

PUT:- PUT is most-often utilized for **update** capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.
However, PUT can also be used to create a resource in the case where the resource ID is chosen by the client instead of by the server. In other words, if the PUT is to a URI that contains the value of a non-existent resource ID. Again, the request body contains a resource representation. Many feel this is convoluted and confusing. Consequently, this method of creation should be used sparingly, if at all.
Alternatively, use POST to create new resources and provide the client-defined ID in the body representation—presumably to a URI that doesn't include the ID of the resource (see POST below).
On successful update, return 200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return HTTP status 201 on successful creation. A body in the response is optional—providing one consumes more bandwidth. It is not necessary to return a link via a Location header in the creation case since the client already set the resource ID.
PUT is not a safe operation, in that it modifies (or creates) state on the server, but it is idempotent. In other words, if you create or update a resource using PUT and then make that same call again, the resource is still there and still has the same state as it did with the first call.
If, for instance, calling PUT on a resource increments a counter within the resource, the call is no longer idempotent. Sometimes that happens and it may be enough to document that the call is not idempotent. However, it's recommended to keep PUT requests idempotent. It is strongly recommended to use POST for non-idempotent requests.

PATCH :- PATCH is used for **modify** capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.
This resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version. This means that the PATCH body should not just be a modified part of the resource, but in some kind of patch language like JSON Patch or XML Patch.
PATCH is neither safe nor idempotent. However, a PATCH request can be issued in such a way as to be idempotent, which also helps prevent bad outcomes from collisions between two PATCH requests on the same resource in a similar time frame. Collisions from multiple PATCH requests may be more dangerous than PUT collisions because some patch formats need to operate from a known base-point or else they will corrupt the resource. Clients using this kind of patch application should use a conditional request such that the request will fail if the resource has been updated since the client last accessed the resource. For example, the client can use a strong ETag in an If-Match header on the PATCH request.
DELETE :- DELETE is pretty easy to understand. It is used to **delete** a resource identified by a URI.
On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.
HTTP-spec-wise, DELETE operations are idempotent. If you DELETE a resource, it's removed. Repeatedly calling DELETE on that resource ends up the same: the resource is gone. If calling DELETE say, decrements a counter (within the resource), the DELETE call is no longer idempotent. As mentioned previously, usage statistics and measurements may be updated while still considering the service idempotent as long as no resource data is changed. Using POST for non-idempotent resource requests is recommended.
There is a caveat about DELETE idempotence, however. Calling DELETE on a resource a second time will often return a 404 (NOT FOUND) since it was already removed and therefore is no longer findable. This, by some opinions, makes DELETE operations no longer idempotent, however, the end-state of the resource is the same. Returning a 404 is acceptable and communicates accurately the status of the call

Wednesday, May 11, 2016

Serialization in Java

Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine; the reverse process of creating object from binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream etc.

Question 1) What is the difference between Serializable and Externalizable interface in Java?
Externalizable provides us writeExternal() and readExternal() method which gives us flexibility to control java serialization mechanism instead of relying on Java's default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.

Question 2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.io package and forms core of java serialization mechanism. It doesn't have any method and also called Marker Interface in Java. When your class implements java.io.Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.

Question 3) What is serialVersionUID? What would happen if you don't define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . SerialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also. Consequence of not specifying serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch

Question 4) While serializing you want some of the members not to serialize? How do you achieve it?
Declare it either static or transient based on your need and it will not be included during Java serialization process.

Question 5) What will happen if one of the members in the class doesn't implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and

Question 6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?
Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed.

Question 7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object ObjectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject() is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization and deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal. I

Question 8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already Serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid Java serialization you need to implement writeObject() and readObject() method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above Serialization interview question and normally it asked as follow-up question as interview progresses.

Question 9) Which methods are used during Serialization and DeSerialization process in Java?
 Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call ObjectOutputStream.writeObject(saveThisobject) and to deserialize that object we call ObjectInputStream.readObject() method. Call to writeObject() method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be type cast to correct type.

Question 10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don't provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hashCode of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.

11) What are the compatible changes and incompatible changes in Java Serialization Mechanism?
The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or UN-implementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading Java serialization specification.

12) Can we transfer a Serialized object vie network?
Yes you can transfer a Serialized object via network because Java serialized object remains in form of bytes which can be transmitter via network. You can also store serialized object in Disk or database as Blob.

Friday, April 1, 2016

Solid Principles in Java

                                   Solid Principles in Java


Classes are the building blocks of your java application. If these blocks are not strong, your building (i.e. application) is going to face the tough time in future. This essentially means that not so well-written can lead to very difficult situations when the application scope goes up or application faces certain design issues either in production or maintenance.

A set of well designed and written classes can speed up the coding process by leaps and bounds, while reducing the number of bugs in comparison.

Solid Definition

S ---->Single Responsibility Principle
0 ---> Open Closed Principle
L ---> Liskov's Substitution Principle
I --->  Interface Segregation Principle
D ---> Dependency Inversion Principle

Single Responsibility Principle :-  "One class should have one and only one responsibility".

In other words, you should write, change and maintain a class for only one purpose. If it is model class then it should strictly represent only one actor/ entity. This will give you the flexibility to make changes in future without worrying the impacts of changes for another entity.

Similarly, If you are writing service/manager class then it should contain only that part of method calls and nothing else. Not even utility global functions related to module. Better separate them in another globally accessible class file. This will help in maintaining the class for that particular purpose, and you can decide the visibility of class to specific module only.

Open Closed Principle :- "Software components should be open for extension, but closed for modification".

your classes should be designed such a way that whenever fellow developers wants to change the flow of control in specific conditions in application, all they need to extend your class and override some functions and that’s it.If other developers are not able to design desired behavior due to constraints put by your class, then you should reconsider changing your class. Other Developers should be able to override the options provided by software in unharmful way permitted by software.

For example, if you take a look into any good framework like struts or spring, you will see that you can not change their core logic and request processing, BUT you modify the desired application flow just by extending some classes and plugin them in configuration files.

Liskov’s Substitution Principle :- "Derived types must be completely substitutable for their base types".

It means that the classes fellow developer created by extending your class should be able to fit in application without failure. I.e. if a fellow developer poorly extended some part of your class and injected into framework/ application then it should not break the application or should not throw fatal exceptions.

This can be insured by using strictly following first rule. If your base class is doing one thing strictly, the fellow developer will override only one feature incorrectly in worst case. This can cause some errors in one area, but whole application will not do down.

Interface Segregation Principle :- "Clients should not be forced to implement unnecessary methods which they will not use"

Take an example. Developer Tiger created an interface Reportable and added two methods generateExcel() and generatedPdf(). Now client ‘A’ wants to use this interface but he intend to use reports only in PDF format and not in excel. Will he achieve the functionality easily.

NO. He will have to implement two methods, out of which one is extra burden put on him by designer of software. Either he will implement another method or leave it blank. So are not desired cases, right??

So what is the solution? Solution is to create two interfaces by breaking the existing one. They should be like PdfReportable and ExcelReportable. This will give the flexibility to user to use only required functionality only.

Dependency Inversion Principle :- "Depend on abstractions, not on concretions"

you should design your software in such a way that various modules can be separated from each other using an abstract layer to bind them together. The classical use of this principle of BeanFactory in spring framework. In spring framework, all modules are provided as separate components which can work together by simply injected dependencies in other module. They are so well closed in their boundaries that you can use them in other software modules apart from spring with same ease.

This has been achieved by dependency inversion and open closed principles. All modules expose only abstraction which is useful in extending the functionality or plugin in another module.

Thursday, March 17, 2016

How to read File into String in Java 7

Before Java 7, you have to write lot of code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some API but it was not so simple like we have in python.

Whenever you convert binary data into text data, you must remember to use correct character encoding. An incorrect choice of character encoding may result in totally different or slightly different content than the original file.

Before JDK 1.7 we used to read file


InputStream inputStream = new FileInputStream("abc.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
      
String line = br.readLine();
StringBuilder sb = new StringBuilder();
      
while(line != null){
   sb.append(line).append("\n");
   line = br.readLine();
}
      
String fileAsString = sb.toString();
System.out.println("File data is : " + fileAsString);

From JDK 1.7

String fileData = new String(Files.readAllBytes(Paths.get("abc.txt")));
System.out.println("FileData  : " + fileData);

The above code uses platform's default character encoding. If you want you can use your own/custom character encoding.

 How to provide a custom character encoding 


 String fileData = new String(Files.readAllBytes(Paths.get("abc.txt")), StandardCharsets.UTF_8);
 System.out.println("FileData  : " + fileData);

Wednesday, February 17, 2016

How to Upload files through your application (Getting rid of fakepath)

Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense  as a client, you don't want the server to know your local machine's filesystem.Now when you browse a file from your local system you get the file name instead of File whole path. This results in many applications giving error as File Not Found.

Just create a Dynamic Web project from your IDE
You can use apache commons-fileupload-1.3.jar and commons-io-2.2.jar, Now create a Index.html

Index.html

Now create a Servlet named FileServlet

FileServlet

public class FileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private ServletFileUpload uploader = null;
  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileServlet () {
    super();
    // TODO Auto-generated constructor stub
    }
   
    @Override
    public void init() throws ServletException{
    DiskFileItemFactory fileFactory = new DiskFileItemFactory();
    File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
    fileFactory.setRepository(filesDir);
    this.uploader = new ServletFileUpload(fileFactory);
    uploadFileAction = new UploadFileAction();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String fileName = request.getParameter("fileName");
    String name = request.getParameter("username");
    if(fileName == null || fileName.equals("")){
    throw new ServletException("File Name can't be null or empty");
     }
    File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
    if(!file.exists()){
    throw new ServletException("File doesn't exists on server.");
    }
    System.out.println("File location on server::"+file.getAbsolutePath());
    }
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("request.getContentType()\t"+request.getContentType());
    if(!ServletFileUpload.isMultipartContent(request)){
    throw new ServletException("Content type is not multipart/form-data");
    }

    //String name = request.getParameter("name");
    String name = request.getParameter("username");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
    List fileItemsList = uploader.parseRequest(request);
    Iterator fileItemsIterator = fileItemsList.iterator();
    File file = null;
    FileItem fileItem = null;
    while(fileItemsIterator.hasNext()){
    fileItem = fileItemsIterator.next();
    if(fileItem.getName() != null){
    System.out.println("FieldName="+fileItem.getFieldName());
    System.out.println("FileName="+fileItem.getName());
    System.out.println("ContentType="+fileItem.getContentType());
    System.out.println("Size in bytes="+fileItem.getSize());

    if(fileItem.getName().contains("/") || fileItem.getName().contains("\\")){
    String fileName = FilenameUtils.getName(fileItem.getName());
    System.out.println(fileName);
    file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileName);
    }
    else{
    file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+fileItem.getName());
    }

    System.out.println("Absolute Path at server="+file.getAbsolutePath());
    fileItem.write(file);
    out.write("File "+fileItem.getName()+ " uploaded successfully.");
    }
    if(fileItem.getName() != null){
    System.out.println("resp\t"+resp);
    System.out.println("File "+fileItem.getName();
    out.println("success");
    }
    }
    } catch (FileUploadException e) {
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }

}
    }


Now create Listener named FileLocationContextListener

FileLocationContextListener

@WebListener
public class FileLocationContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String rootPath = System.getProperty("catalina.home");
        ServletContext ctx = servletContextEvent.getServletContext();
        String relativePath = ctx.getInitParameter("tempfile.dir");
        File file = new File(rootPath + File.separator + relativePath);
        if(!file.exists()) file.mkdirs();
        System.out.println("File Directory created to be used for storing files");
        ctx.setAttribute("FILES_DIR_FILE", file);
        ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //do cleanup if needed
    }
   
}

web.xml




When you run this program a tmpfiles directory is created in your tomcat server and then file that you browsed through your application gets copied to this location.
from your servlet when you do file.getAbsolutePath() you get the full path of your file.
Now you can easily upload it to your Database or read it as per your requirements

Tuesday, January 12, 2016

Codes for Data Type as per BSON Specifications

As we know MongoDb is document oriented Database so what actually means is Mongodb fundamentally record type is kind of nested dictionary of key value associations. We Map the documents that come out of Mongo Db to Objects in the Programming language that can represent these type of key value associations.

In Javascript, the type of Object that represents these kinds of key value associations is called a Javascript Object. MongoDB uses a binary representation for the data inside the document.
The specification for Binary representation can be find out at  http://bsonspec.org/

The Binary format BSON stands for Binary JSON and it is a serialized format that designed to represent a super set of what can be described in JSON syntax

Now for example you have a collection as people which has a column as name and the user has stored some integer values also in that name field. you want to query the people document to find the name but don't want to display the result having name field with value as integer

db.people.find({name:{$type:2}})
This will fetch you the name from people collection  which are of String type. here the value 2 is mapped for String datatype.

Similar for other datatype has been mapped to some integer value. Here is an list of all Datatype which are mapped to a particular Integer type as per BSON specifications