Wednesday 3 October 2018

Git Basic Commands

1) for clone git project:
git clone url of project

2) To create a new branch and swith it to at the same time (-b is for switch)
git checkout -b branchNameToCheckout

3) To create a branch then separtely switch (above command is shorthand for)
git branch branchName
git checkout branchName

To delete a branch
git branch -d  branchName
it will be fail if there are any file left for merge and you are still on that branch

4) To add the new files for staging
For all files : git add * 
For any particular file : git add "file name"

5) To commit the changes
git commit -a -m "meanigful message"

6) To merge
first checkout the branch you wish to merge into and then run git merge command
git checkout master
git merge localBranch

7) To see which files are unmerged at any point after a merge conflict, you can run git status
git status

Git Basics

To understand Git fundamentals, it is a good approach to put aside your general thought about GIT that is coming from CVS or SVN background. The major difference between Git and other version control systems is about how they process the information for recording the changes underneath.
CVS, SVN, perforce etc store the record as delta based version control, each version has its own delta which helps to compare the file in their respective system.

However, Git understands the data change in a different way. With Git every time you commit or save the state of project, it basically takes a picture of what all your file look like at that moment and stores a reference to that snapshot, if nothing has changed it does not store the file again but provide a link to the previous identical file it has already stored.

Git is fast because its almost every operation is local. Unlike CVS, SVN we do not need network to compare the history of files, we have all history in our local disk. For the new changes that has been made and pushed by another developer you have to fetch it from server. However, you have a local copy of your project which you can use to commit to, for e.g if you're not connected to internet you can commit your changes to the local repo and push the changes afterwards.

Git maintain its integrity of data by using SHA-1 Hash. Git check-summed the information of file and store it in its database. The SHA-1 Hash is hexa decimal characters and based on the file or the directory structure. In this way, Git clears the doubts of getting the courrpt files.

Git generally only Adds the data, this means when we commit any change in a project the Git database add the data about the change.

Git has three main states that you file can reside in these are:
Committed, Modified and Staged.

Committed means the changes are committed and data is stored in you local database.

Modified means you have made the changes but they are not yet in the database.
Staged means that you have marked your modified files in their current version to go into your next commit snapshot

GIT BRANCHING 

Some people refer Git's branching technique is its "one of kind" feature. For some of you like me who do not have much idea about branching, consider this simple definition that "Branching means you diverge from the main line of development and continue to do work without messing with that main line". In many VCS it is a heavy process because for that branch it is usually we have to copy entire workset. In Git it is incredibly a lightweight process and switching back forth between the branches generally as fast. 

Branch in Git is just a SHA1 hexadecimal file with the information of the commit object which has the reference/pointer to the tree of files that has changed and a pointer to all the previous commits. Well, to digest this we have to take a step back and understand what happens actually behind the scenes when a $git commit is execute. 

Consider you have a directory that contains three files and you are committing it. Firstly, staging these files will compute checksum for each file which Git refers as Blobs and stores those tree objects. Secondly, Git will create a tree object that will hold the metadata information of the saved three blobs and a pointer to them. Thirdly, one commit object that holds the information of the committer, message and pointer to that tree so that it can recreate the snapshot in later time if needed. 

if you make changes and commit again it will store the pointer to the commit that came before it
A branch in Git is just a lightweight movable pointer to one of these commits. The default branch name in Git is MASTER. As you start making commits you are given a master branch that points to last commit you have made. When you create a new branch you create it by running the command $git branch testing. This creates a new pointer to the same commit you are currently on.

HEAD lets you know on which branch you are currently on, it mostly confuse with other concept of CVS but in Git, it means the current branch pointer. You are on master branch it did not switch you to the testing.

You can easily see this by running a simple git log command that shows you where the branch pointers are pointing. This option is called --decorate. 

$ git log --oneline --decorate

To switch to testing branch you need to run command $git checkout testing this will move the HEAD to testing. This is necessary because you should not make changes directly to the master branch, lets say you make a change and commit it, now you can see the benefit:

This shows that your testing branch moved forward and the master reports to the same commit, we can switch between branches and do relative work by using the same checkout command. 

To have a history of all the commits run $ git log --oneline --decorate --graph --all

if you have multiple branches and you are also doing commit work then you will have a divergent history which can be seen by the above command.

For the reason a branch in Git is just a 40 character SHA-1 checksum of the commit it points to it is cheap and quick to create and destroy the branches.

REfrences: git-scm.com/book/en/v2/Getting-Started-Git-Basics


Git Tools.

Git CMD, Git Bash and Git GUI difference

Git provides above three tools for one purpose USING THE GIT, they all can do same operations but these three were created with intention of users capability, 

If the user are more familiar with Linux commands and want to use the git feature with some of the standard unix commands those users can start using git with this tool. 

If the user is more comfortable with Windows command line and like to do git operations by command line interface Git CMD comes into the picture.

However, Git GUI provides minimum features of Git and are in favors of those users who really do not like typing commands and want to do some basic operation without any typos. 
All in all those tools do the same magic in the end and one series of steps for a task can be done by any one or all of them.

Difference between Git Pull and Git Fetch:

It is obvoius for a new commer to see lot of options with similar meanings and get confuse. Git Pull and Fetch are among them untill you read the following paragraph.

Git Fetch: Use when you want to download the changes from the remote repository but not yet sure to merge those changes into your working copy. Or you can say it fetches all the commits from the target branch that do not exist in your current branch and stores them in your local repo but does not integrate them.

Git Pull: it downloads the changes like the Git Fetch and merge them. So, your working copy gets updated without calling merge separately.

Git: Essence of Distributed Version Control System

To understand Git we must understand the need of Git , as we know Git is a popular version control system, But what is Version control system?

Version Control System is like audit log of your changes, changes that has been made to your system. System can be a set of files, any type of project or both. So in general, version control system records changes in order to serve us better in future. For example, it helps you to track the bugs, who report it who solve it and what was the solution by comparing one version back. In addition to this, Version Control System (VCS) allows you to revert the changes back to normal state if you have messed up with a little overhead.

So, the version control system allows you to do these things and more in an efficient manner and the VCS can be used with small or large projects depend upon the nature of the project.
In the past, programmers do it by maintaing local version control, creating version database to a file.
However, the urge of centralised version control system arose due to this because the changes need to be shared among developers. Therefore, systems such as CVS, SVN and Perforce came into existence and widely accepted and used for a long period of time. The unanimous feature that these system offer is a central server which maintains the recording and versioning of the files and the users can access them at a time. Others appealing features was the openess of the changement, which let others know who is doing what, administrators have fine control over roles of developers.



The downsides of Central VCS Server are obvoius, if the central server face some technical issues everybody will be halted from collaboration during the outage. Furthermore, if more developers are collaborating the server it becomes slow and sometimes unresponsive. What worse if the hardisk becomes corrupted and proper backups have not been kept, you lose everything.
This is where the Distributed Version Control System come into the picture. In a DVCS such as Git, Darcs, Mercurial. Developers/Users have their own copy of the files, in this way if the server dies one can put his copy into the place and stand the server up again. Every clone is full backup of data.


References: http://sens.tistory.com/246

Sending Ajax request to server and receive output

For e.g you have a select box and on selection of a specific option you have to send ajax request for fetching some information in our case we are validating information on server side and returning corresponding response.

1) include libraries
<script type="text/JavaScript" src="../Javascripts/ajax.js"></script>

2) Create javascript function

function loadInstallmentOptions(objValue){
if(objValue==<%=SOMECONSTANT%>){
var billCodeId = document.getElementById("Id").value;
var url='validateDetails.jsp?Id='+Id;
ajaxCallSite = new sack();
ajaxCallSite.requestFile = url;
ajaxCallSite.onCompletion = function(){responseOfValidation(ajaxCallSite);};
ajaxCallSite.runAJAX();
}else{
document.getElementById("element1").value="0";
document.getElementById("element2").value="";
document.getElementById("element3").checked=false;
document.getElementById("element4").style.display="none";

}
}

3)  in forwarded jsp do the calculation and send response in JSON using

JSONObject AmountHolder = new JSONObject();
showControls = your business logic response;
maxAllowed = your business logic response;
AmountHolder.put("showControls",showControls);
AmountHolder.put("maxAllowed",maxAllowed);
AmountHolder.put("providedValueIsGreater",providedMaxInstallment>maxAllowed);
response.getWriter().write("("+AmountHolder.toString()+")");
response.getWriter().close();


4) On response do the action

function responseOfValidation(ajaxCall)

responseObj=eval(ajaxCall.response);
var showControls=responseObj.showControls;
if(showControls==true){
document.getElementById("elementControls").style.display="block";
}else{
document.getElementById("element1").value="0";
document.getElementById("element2").value="";
document.getElementById("element3").checked=false;
document.getElementById("element4").style.display="none";
}
}

Mocking

Case: I have a class which uses Autowired on two different classes objects. I have to unit test methods of this class but the methods uses calling to object's methods to perform some operation inside those methods that i want to test.
Therefore, i need to mock the calling of those methods and return something that mock the values and test the rest of the operation. What dived me into struggle that whenever i try to mock those field injection it throws me some sort of error related to Mock method invocation.

Solution:
Firstly, we need to annotate the test class with @RunWith(MockitoJUnitRunner.class) this annotation will help us to initialize the fields annotated with @Mock annotations.

Also we need to use the MockitoAnnotations.initMocks(this) though we can use any of them but in my case it does not seem to be working when removing the @RunWith annotation it throws me Assertion Error (it can be because of the fact that i am testing a VOID function by try catch and Assert.assertTrue). However, the main purpose of the @RunWith annotation is keep tests clean and improves debugging experience.

Second step is to Mock the declaration of the Autowired class attributes and use @InjectMocks on the class that contains the methods you want to mock. (@InjectMocks is used on the field which injection should be performed your private fields)

Third step is to use MockitoAnnotations.initMocks(this) in @Before method. Also, you can specify the mocking logic in this method if the logic repeats itself.

Fourth is to Mock the object's method call such as Mockito.when(firstMockedObject.someMethod(anyArguments)).thenReturn(yourMockedObject)
for e.g see: dzone.com/articles/use-mockito-mock-autowired

We generally use mock when we want to mock whole object's behavior while using spy we will be spying or stubbing specific methods of it. So Mock acheives full mocking and Spy acheives partial mocking.

EXPECTED EXCEPTION
when declaring the ExpectedException it should be declared as public otherwise it won't work


AssumptionViolationException 

An exception class used to implement assumptions. Assumption is a state in which a given test is meaningful and should or should not be executed. A test for which an assumption fails should not generate a test case failure.

MAVEN: Copy test resources from on project to another

CASE: I have two projects A and B, project A has lots of csv files in its src/test/resources folder which project B wants to use in its application. Though it is not an ideal case when a test resources becomes a liablity of some other projects source folder. But we have this case. However, we can use these files in our test classes as well.

SOLUTION:

In project A where the csv files are present you have to make those files compiled in a jar and shared them across in the project B. There are other apporaches as well but this one seems to be working for me till now. Others are usefull when you have to share the resources NOT from the test folder but from the source folder.

Anyway, you have to define the following in the project A pom.xml

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
<executions>
 <execution>
<goals>
                <goal>test-jar</goal>
            </goals>
</execution>
</executions>

</plugin>
</plugins>
</build>

The above code will make snapshot/jar with suffix -tests which will use as classifier afterwards.

In Project b pom.xml you can use the maven dependency-plugin to extract files from jar:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>unpack</id>
                    <phase>prepare-package</phase>
                    <goals>
                        <goal>unpack</goal>
                    </goals>
                    <configuration>
                        <artifactItems>
                            <artifactItem>
                                <groupId>yourSourceGroup</groupId>
                                <artifactId>yourSourceArtifact</artifactId>
                                <version>1.0.0</version>
                                <type>jar</type>
                                <includes>path/to/Files.whatsoever</includes>
                                <outputDirectory>${project.build.directory}/your/target/folder</outputDirectory>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

MAVEN: TO RESTART THE SERVER IN OUR CASE JBOSS THROUGH MAVEN

Normally org.wildfly.plugins provide wildfly-maven-plugin with some basic preinstalled commands that can be run direcly through maven scripts such as deploy,redeploy, run, start, shutdown etc. (For more see docs.jboss.org/wildfly/plugins/maven/latest/plugin-info.html). What I want to accomplish is to restart the jboss application server by running one command the fun part is the server is located somewhere else.

However, first hurdle was to ensure either we can restart the server, for this, i put aside the externel server thing for later and tried to restart the local one. As one can see the Shutdown has an optional parameter for reload, what more i have used is jboss-home because when i was trying to start the server it was using the server that was reside in my deployed project war some other location that i do not want to use.

Therefore, i provided the particular JBOSS directory in the configuration along with the shutdown parameter to let the wildfly knows i want to restart the server not shutdown. Following is the code that i have used:

<plugin>
<groupId>or.wildfly.plugin</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>1.2.1.Final</version>
<configuration>
<jboss-home>C:/.../jboss-eap-7.0</jboss-home>
<reload>true</reload>
<hostname>127.0.0.1</hostname>
</configuration>
</plugin>

The above code helped to restart my local server with the wildfly:shutdown command.