Wednesday, December 13, 2017

Some basic JavaScript String concepts

Basic and Best things to know work with JavaScript Strings:

1. String replace

The replace function will help to replace any string operation. It will replace string for the first occurrence only.

So by going with regex its so simple and your quality of code will be good.

let first = " I want to replace first as second , but here first comes in many places";

first.replace(/first/g,"second")

" I want to replace second as second , but here second comes in many places"

2. Template String

In ES6, we have an option to use template string which will give an option to modify the string within it. Example below.


let templateSecond = "I am waiting for you!"
`Hi Monisha ${templateSecond}`
"Hi Monisha I am waiting for you!"

3. Includes

If you want to find whether particular string is available or not in the current string. Use like below

let includeChck ="ABC, DEF, GHI, JKL, MNO"
includeChck.includes("GHI") //Output : true

includeChck.includes("GHIS") //Output : false

4. String to Number


let strToNum = "1234576"
parseInt(strToNum) // Output: 1234576

let str = "123488bcd34"
parseInt(str)    //Output: 123488

Remember if character placed after number it will not consider.

The same thing can apply to parseFloat also.

5. setInterval and setTimeout

While passing function to setInterval and setTimeout do not use string quotes. Use without quotes, so that it can bring better performance.

Else eval function will be executed it makes process time to slow.

//Wrong Format
setInterval('doSomethingPeriodically()', 1000);  
setTimeout('doSomethingAfterFiveSeconds()', 5000);


//Correct Format
setInterval(doSomethingPeriodically, 1000);  
setTimeout(doSomethingAfterFiveSeconds, 5000);

Thursday, November 23, 2017

Builder design pattern simple example

The below is normal simple class with constructor.

public class Computer {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public Computer(String modelname, int ram, String keyboardName, String mouseName) {
		super();
		this.modelname = modelname;
		this.ram = ram;
		this.keyboardName = keyboardName;
		this.mouseName = mouseName;
	}

	@Override
	public String toString() {
		return "Computer [modelname=" + modelname + ", ram=" + ram + ", keyboardName=" + keyboardName + ", mouseName="
				+ mouseName + "]";
	}
}

You have another one main class called JavaTest is below.

public class JavaTest{
public static void main(String args[]){
Computer comp = new Computer("Intel", 6, "Logitech", "dell");
System.out.println("Comp object is: " + comp );
}
}

Output:
Comp object is: Computer [modelname=Intel, ram=6, keyboardName=Logitech, mouseName=dell]


We can change the above code to Builder design pattern. To do this you need to create one additional class called ComputerBuilder.

public class ComputerBuilder {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public ComputerBuilder setModelname(String modelname) {
		this.modelname = modelname;
		return this;
	}
	public ComputerBuilder setRam(int ram) {
		this.ram = ram;
		return this;
	}
	public ComputerBuilder setKeyboardName(String keyboardName) {
		this.keyboardName = keyboardName;
		return this;
	}
	public ComputerBuilder setMouseName(String mouseName) {
		this.mouseName = mouseName;
		return this;
	}
	
	public Computer getComputer () {
		return new Computer(modelname, ram, keyboardName, mouseName);
	}
}

From the above class,

1. It don't have any getter method. We have added only setter method.

2. The last method getComputer returning the object of Computer class.

Let see how we can execute this code from main class.

Computer c = new ComputerBuilder().setKeyboardName("DELL KEyboard").setMouseName("LOGI Mouse").getComputer();
System.out.println("Comp object from builder design pattern is : " + c );

You can notice from the main class,

1. You wont get complex for creating object for computer.

2. Its not mandatory to put all arguments. If you are not providing arguments it will take its initial initialized value.

3. It will be more clear than our normal code creating object through constructor.

Output:
Comp object from builder design pattern is : Computer [modelname=, ram=0, keyboardName=DELL KEyboard, mouseName=LOGI Mouse]

Thursday, August 3, 2017

How to remove first option from select drop down option value

We may get a task sometime to remove the first value from the drop down like Chosse Country, Empty option, --Select-- etc.,

We can have lot of option to remove this. But here we can use simple css style option. Let see the code.

<select name="test">
    <option value="" style="display: none"></option>
    <option value="">Option 2</option>
    <option value="">Option 3</option>
    <option value="">Option 4</option>
    <option value="">Option 5</option>
  </select>

The style:display:none do the job for you!

UML Diagrams - Notations

Below are the list of notations which we have used in UML diagarms. Let see one by one , so that we can understand while using UML diagrams. 

Actor

It may be a Human user , System or Subsystem etc., Mostly actor will be acted from OUTSIDE.

Object 
 An object - This is a student object and its type is not specified. Underline is must there.

Asynchronous Message
 Its describing an asynchronous action, sender no need to wait for an receiver response. Just assume our normal java async thread flow. The arrow is OPEN.

Boundary
Mostly developers will use this in MVC pattern to mention at screen level. Means, capturing user interactions with system.

Comment 

 Comment , which we can use to describe related to your actions in diagram.

Controller

Controller which is used to mention our MVC pattern controller related to an entity.

DataBase
Database , which is mentioning an back end side to store and retrieve data.

Destroy

Destroy or delete which is mentioning an deleting action. Cross symbol must need to be add to mention its an destroy.

Entity
Entity which is mentioning a Model of  MVC model pattern. Model will capture an information.

Object with Type
Object which is mentioning an instance of type student and its name is s. 


Loop
Loop - Which is mentioning an normal loop with condition.

 Object Without Type
An object named as student and its type is not specified here.

Condition Met
If the condition is met then only it will proceed further.

Return
Return message or response which should be mentioned as dotted lines.

Message Itself

Its used to describe an recursion function. 

Synchronous

A normal synchronous action.

Non Instantaneous
Its describing an amount of time will take to reach other side. Example is network calls.

Friday, July 21, 2017

Editable and searchable Drop down with Javascript

Below is the select drop down, here you able to Edit, Search and Select the value. But forgot to implement arrow icon for the drop down.

However I will do another post which will show you how to hide and show drop down arrow image with the help of css.

Comment below if you need any query.

<html>
<head>
<title>Own Drop Down Component</title>

</head>
<body>
<form name="myfrm">
<input id="filter">
<select id="countries" multiple onchange="onChangeValue()" style="width:11%">
  <option value="india">India</option>
  <option value="america">America</option>
  <option value="germany">Germany</option>
  <option value="russia">Russia</option>
</select>
</form>
<script type="text/javascript">
(function () {
    // the IIFE  for local variable store information
    var optionsCache = [];

    // add option values to the cache with reduce
    function optionsArray(select) {
        var reduce = Array.prototype.reduce;
  //addToCache for cache
        return reduce.call(select.options, function addToCache(options, option) {
            options.push(option);
            return options;
        }, []);
    }
    // give a list of options matching the filter value with match function
    function filterOptions(filterValue, optionsCache) {
        return optionsCache.reduce(function filterCache(options, option) {
            var optionText = option.textContent;
            if (option.text.toLowerCase().match(filterValue.toLowerCase())) {
                options.push(option);
            }
            return options;
        }, []);
    }
    // replace current with new options
    function replaceOptions(select, options) {
 //document.getElementById("countries").size = select.options.length;
        while (select.options.length > 0) {
            select.remove(0);
        }
        options.forEach(function addOption(option) {
            select.add(option);
        });
    }
    
    function filterOptionsHandler(evt) {
        var filterField = evt.target;
        var targetSelect = document.getElementById("countries");
        if (optionsCache.length < 1) {
            optionsCache = optionsArray(targetSelect);
        }
        var options = filterOptions(filterField.value, optionsCache);
        replaceOptions(targetSelect, options);
  var x = document.getElementById("countries").length;
  //alert("bbb"+x)
  if (x > 0) {
  document.getElementById("countries").size = x;
  } else {
   document.getElementById("countries").size = 1;
   var select = document.getElementById("countries");
   select.options[select.options.length] = new Option('No Results','empty');}
    }
    // attach whatever event
    var filter = document.getElementById("filter");
 
    filter.addEventListener( 'click', function(){
  document.getElementById("countries").style.display = "block";
 } );
 filter.addEventListener("keyup", filterOptionsHandler, false);
 document.getElementById("countries").style.display = "none";
}());

function onChangeValue () {
var e = document.getElementById("countries");
var strUser = e.options[e.selectedIndex].text;
//alert(strUser);
  
  if (strUser != null) {
    //alert("Test" + strUser);
 document.getElementById('filter').value = strUser;
 document.getElementById("countries").style.display = "none";
  }
 }
  
</script>
</body>
</html>

Wednesday, July 5, 2017

How to add a particular word starting and end position of notepad++?

1. Press CTRL + H to open Find/Replace Dialog box.

2. Click "Regular expressions" checkbox near to the bottom of the dialog box.

3. Then To add your particular word, "test" (example) to the beginning of each line,
     type `^` in the "Find what" field,
     and "test" in the "Replace with" field. Just click hit "Replace All". (Alt+A Shortcut)

4. To add particular word ,"test" end of each line, type `$` in the "Find what" field,  and "test" in the       "Replace with" field. Then hit "Replace All".

That's All!

Friday, June 16, 2017

Load css based on browser identification

Loading a CSS file based on browser is not a good idea, However I will share the below code to identify browser.

Let it to do by javascript by onload method.

<script type="text/javascript">
 //Short code with ternary
 window.onload = function() {

  var link = document.createElement('link');
  link.rel = "stylesheet";
  link.type = "text/css";

  //Browser Detection
  link.href = (navigator.userAgent.indexOf("Chrome") != -1) ?link.href = "./css/grid.css";
    : (!(window.ActiveXObject) && "ActiveXObject" in window) ? link.href = "./css/iegrid.css";
      : "";
  document.querySelector("head").appendChild(link);
 }
</script>

Some people may document.write method, but It will not work in all case. Since document.write will swipes out the screen. So based on your task situation you should use this.

Friday, May 5, 2017

How to use eclipse effectively ?

Almost , most of the developers are using eclipse. But very rare developers only know all the tricky parts of eclipse IDE, means some shortcuts and way of using eclipse effectively. 

Here I am providing lot of wonderful tips and tricks of using eclipse. Remember this handling techniques you must do it again and again. I assure your productivity will increase compared to your earlier.

1. What is Open Type in eclipse ?

    Shortcut is Ctrl + Shift + T, Which will open any class , interface etc., Remember Ctrl + Shift +       R, which will open a files.

2. What is quick outline and How to use that ?

    Shortcut is Ctrl + O,  which will show you all the methods available in the current class. Press once again Ctrl + O,  which will show you inherited members for current class.

You can search method or inherited members also possible at the top search box.

3. What is open Type Hierarchy ?

    Shortcut is Ctrl + T or F4 , which will show you the hierarchy of your files. Means, inheritance class or implements interface. If you will press again Ctrl + T, it will only show you the super type hierarchy.

4. Search with eclipse Java Search File Search Method search etc.,

   You can click Search icon from the toolbar or Shortcut is Ctrl + H or by menu Search -- > Search, which will show you the effective way for search method , package , constructor etc.,

If you dont know the exact name of method or any other searchable word, just use * . eg. *action

5. What is open Declaration ?

    Right click on variable or object whatever it is, click open declaration or Shortcut F3,  which will show you where it was declared.

6. What is open call hierarchy ?

    Really a wonderful feature by eclipse to check where the caller, callees etc., Shortcut is Ctrl +Alt + H,  After call hierarchy window open check the right corner menu to get more like caller Hierarchy, callee hierarchy , history etc.,

7. References in eclipse ?

    Shortcut is Ctrl + Shift + G, it will show you related references from work space , Project , Hierarchy etc.,
    
8. Generate constructors using fields ?

     Like generate setters and getters there is an option to generate constructor also based on your class field. You can travel by Alt + Shift + S or go by Right Click.


9. Templates , how to use ?

   Eclipse templates will give you the best shortcut option for your code, for eg , sysout and putting Ctrl + Space will show you Syste.out.println . Like this you can create your own template.

I will post a separate topic , how to add new template in eclipse. Until then If you want to check about templates, Window - > Preferences - > Java -> Editor -> Templates.

12. Formatting source code by eclipse ?

   Shortcut is Ctrl + Shift + F,  which will format your source code. Suppose if you need your own style format code you can add it by code Style option. 

13. Refactor code in eclipse for local variable constants and method?

   Code refactor is the big topic , and I will post you the separate post for this. Its nothing but, will you an option to rename the method or variable or whatever , it will reflect all place. Moving the code , extract the code also possible.

14. Enable line numbers 

   Line number of the code is useful when you get error which will show nth line number missing ; So if you enable line number , you can go directly to code line.

To enable Right click side bar of the code and select Show Line numbers option.

Friday, April 7, 2017

Hibernate Interview Questions

1. What is the difference between openSession and getCurrentSession?

         openSession will open a new session and getCurrentSessiona will use an existing one which is in available in context.

2. What is the difference between get/load and createCriteria?   

         load will not hit database(because of fake object) and it will throw object not found exception if data not available.

         get will hit database and it will throw null if data is not available.

       createCriteria is a method of session interface and it will create a criteria object of persistence object of you requested class.

e.g : Criteria cr  = session.createCriteria(Employee.class)

3. Why we need to use hibernate ?

        1. HQL - You do not want to write query and it will be suitable to all database when we change in future.

        2. OOPS concept -   You will get oops concept since you are using table as entity in hibernate. So inheritance, encapsulation etc., all you will get.

         3. Caching Mechanism - First level cache and second level cache possible.

         4. Lazy loading - You can set when child has to be loaded while parent loading.

4. How many ways configure hibernate.config.xml file ?

        1. By using xml file (hibernate.config.xml)
        2.By using setProperty() method of configuration
        3.By using properties file

5. How you do hibernate pagination ?

    You can set the result per page wise. 

        Query query = session.createQuery("From Person");
        query.setFirstResult(0);
        query.setMaxResults(10);

ScrollableResults also we can use for pagination.

For more please check this stackoverflow link.

6. What is hibernate First level cache ?

1. First level cache is associated with session object.
2. Default it will enable and you can not disable it.
3. When we query for first time, it will get from DB and second time if you excecute the same query it will get from cache.

7. What is second level cache ?

Second level cache is associated with session Factory object. Actually it will reduce our database traffic. We have lot of option to enable second level cache in hibernate. But mostly all will use EHCache, since its fast and lightweight. It will support read only , read/write operation 

8. How to enable second level cache in hibernate ?

You can enable it through hibernate.cfg.xml. It look likes below.


<hibernate-configuration>
      <session-factory>
          <property  name=hibernate.cache.provider_class">
                     org.hibernate.cache.EHCacheProvider
          </property>
          <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
      </session-factory>
</hibernate-configuration>

9. What is evict method in hibernate ?

evict method will be useful, to remove session from first level cache.

Person t = (Person) session.load(Person.class, new Integer(1));
   
session.evict(t);

It will remove only t cached from particular session . But session.clear() remove all cached.

10. What is hibernate versioning ?

If you want to find how many times your Object was modified ,  then you should apply versioning in hibernate. Whenever you modified the object it will increment one number automatically.

11. How do you call aggregate functions in hibernate?

String hql = "select count(name) from Product";

Query query = session.createQuery(hql);
List listResult = query.list();

You can use all sum(), avg(), min(), max() etc.,

12. How to disable Hibernate first level cache ?

We can not disable hibernate first level cache and it will be enabled by default.

13. What are the interfaces available in hibernate ?

Session Interface

Session Factory Interface

Configuration Interface

Transaction Interface

Query and Criteria Interface

Wednesday, February 22, 2017

How to send Cookie in Request header

I did one file upload with Form data by using fetch. I tried to send Cookie and content type as multipart/form-data. But its not taking these two attributes in header. Finally I solved it through ajax as well as fetch.

1. If you want to send cookie you must add credentials like below.

fetch('/users', {
  credentials: 'same-origin'
})

Suppose if its a cross origin request, credentials should be like below.

fetch('https://xxxxxxxx.com:4321/users', {
  credentials: 'include'
})

and Finally you dont want to add content type as multipart/form-data. Your request will add this automatically.

2. Suppose if you are using ajax request,  your code should be like below.

$.ajax({
       url : 'xxxxxxxxxxxxxxxxxxxxx',
       type : 'POST',
       data : formData,     // form data appended values
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType -  It will set multipart by request automatically
       success : function(data) {
           console.log(data);
           alert(data);
       }
});


Check Internet explorer and open Network tab (F12) request header. Now all the header attributes were added perfectly.

Chrome may not show cookies in network tab, check Application tab, there cookies will be stored.


Thursday, February 16, 2017

Chrome throwing 302 Error and Working fine in Internet Explorer

Ago some days back, I got an issue in chrome browser for one service which is returning a status code error 302. I checked the same in REST Client and this also returning error code 302.

But the same service working fine with IE browser. Initially I tried lot of tried with setting header filed cache etc., But nothing worked.

What are the possibilities for 302 status code error and How to handle it ?

The below are some of the possibilities only. But mostly it will be involved within this.

1. There is redirect issue. possibility, you might have used sendRedirect method instead of forward in java.

2. If you have load balancing then definitely there redirect will happen. The way of handling redirect may produce 302 issue.

3. Chrome throwing 302 exception since it have additional security than IE.

4. Check REST client (Chrome web store) older version, it wont produce this 302 error. But latest Rest client will produce 302 error.

5. Firewall also may produce 302 error, but in this case IE also wont work.

6. If you are using client side request through fetch, you add credential= same-origin. It will solve this issue. It will cookies for your request.

7. Finally , You have an option to play around with the below important attributes.
 Access-Control-Allow-Origin : http://www.xxxxxxx.com
Access-Control-Allow-Credentials : true