Check the tomcat app.log in case of unexpected error

If you encounter some unexpected error with your web app, the best place to check what’s wrong is Tomcat’s app.log file.

1. Firstly, ssh to the server containing your app:

$ssh -A xxx.dev.XXX ( you can set shortcuts like in this file  ~/.ssh/config)

2. Get the root access

$sudo su –

3. Get the tail of the log. Tail command is useful to see the latest log entries and -f helps to keep refreshing it.

$tail -f app.log

Then replicate the bug, you should see the error message there. It can be null pointer exception for instance.

Advertisements

JavaScript, why are you like this?

JavaScript have some weird quirks. And one of them is how pointer “this” works.

look at the code below:

var c = {
name: "this is c object",
log : function(){
this.name = "updated c object";
var setName = function(newname){
this.name = newname;
}
setName("Updating again! The c object");
console.log(this);
}
}

Look at the line 6, you might think that name has been set to value “Updating again! The c object”, because this is pointing to c object. BUT, if you run the code, you will find out that actually line 6, is creating new Global variable name, and setting it’s value to “Updating again! The c object”. This happens because of how the execution context is created in JavaScript. In JS, the interpreter will hoist all the variables and methods first. Meaning before real execution line 6 is interpreted and variable is set to global variable(sort of being pushed all the way up the code).

The solution would be to store the reference to c object then pass it.

 var c = {
name: "this is c object",
log : function(){
var self = this;
// note some developers use "that" instead of self
self.name = "updated c object";
var setName = function(newname){
self.name = newname;
}
setName("Updating again! The c object");
console.log(self);
}
} 

This way, we will not set the name to be global variable and it will be set to c object. So c.name will return “Updating again! The c object”

String … and Generating Javadocs

In java we can pass some arguments in methods. Sometimes we want to pass the array of objects. So if you see writeText(String … text) is actually nothing but array of Strings. It’s same as writeText(String[] text).

To easily Generate javadocs in Intelij Idea you can use this shorcut.

type /** then press enter. This applies for the methods. Later you can add more details to that javadoc

ex.:

/**

public String addText(String[] text){

return ‘abc’;}

becomes

/**
 *
 * @param text
 * @return 
 */

public String addText(String[] text){

return ‘abc’;}

Java Streams

Since java 8, we have access to java streams api. It works similar to java collections(List, Set, Queue).

The Java 8 Streams can be seen as lazily constructed Collections, where the values are computed when user demands for it. Actual Collections behave absolutely opposite to it and they are set of eagerly computed values (no matter if the user demands for a particular value or not).

Just like functional programming languages, Streams support Aggregate Operations. The common aggregate operations are filter, map, reduce, find, match, sort. These operations can be executed in series or in parallel.

The Streams also support Pipelining and Internal Iterations. The Java 8 Streams are designed in such a way that most of its stream operations returns Streams only. This help us creating chain of various stream operations. This is called as pipelining. The pipelined operations looks similar to a sql query. ex. a.b().c()

Source: https://dzone.com/articles/understanding-java-8-streams-1

Check if the JSP file on app server is latest

Sometimes deploying the app may not refresh jsp files on app server. So you might see in browser that app has old logic. To confirm that app server doesn’t have latest files go to app server. Typically:

$ssh -A appServer (https://sheberlik.wordpress.com/2017/09/20/connect-to-batch-server/)

Then switch to root

$ sudo su –

Then navigate to the folder

$cd /opt/tomcat/webapps/ROOT/WEB-INF/views/

then open the jsp file and see the content

If the file is old, just re-deploy via Jenkins

 

How to merge the previous branch to current one using SmartGit

In Smartgit, click Merge, then click branches. Uncheck all. Then check the Origin->Previous sprint – > Merge to Working Tree.

Then see if there is conflicts. If there is one, you can either right click ->Resolve then choose our file or their file. 2nd way is to open conflict by clicking twice on the file, then clicking on the arrow to accept the correct code.

Then Commit->Push

10 JavaScript concepts

original link: http://www.javaworld.com/article/3196070/application-development/10-javascript-concepts-nodejs-programmers-must-master.html

1. Immediately invoked function expressions

(function(){
                        // all your code here
                        // ...
            })();

this will immediatlly execute the code

2. Closures

A closure in JavaScript is an inner function that has access to its outer function’s scope, even after the outer function has returned control. A closure makes the variables of the inner function private

var count = (function () {
            var _counter = 0;
            return function () {return _counter += 1;}
})();
count();
count();
count();
// the counter is now 3

3. Prototypes

Every JavaScript function has a prototype property that is used to attach properties and methods. This property is not enumerable. It allows the developer to attach methods or member functions to its objects. JavaScript supports inheritance only through the prototype property. In case of an inherited object, the prototype property points to the object’s parent. A common approach to attach methods to a function is to use prototypes as shown below:

function Rectangle(x, y) {
            this._length = x;
            this._breadth = y;
}

Rectangle.prototype.getDimensions = function () {
            return { length : this._length, breadth : this._breadth };
};

Rectangle.prototype.setDimensions = function (len, bred) {
            this._length = len;
            this._breadth = bred;
};

4. Private properties, using closures

JavaScript lets you define private properties by special technique. By default js don’t provide any private property. We use _ on the variable name as convention to let everyone know that this is private variable.

Defining private properties using closures will help you solve this problem. The member functions that need access to private properties should be defined on the object itself. You can make private properties using closures as shown below:

function Rectangle(_length, _breadth) {
            this.getDimensions = function () {
            return { length : _length, breadth : _breadth };
            };

            this.setDimension = function (len,bred) {
            _length = len;
            _breadth = bred
            };
}

5. The Module pattern

The Module pattern is the most frequently used design pattern in JavaScript for achieving loosely coupled, well-structured code. It allows you to create public and private access levels. One way to achieve a Module pattern is shown below:

var Direction = (function() {
  var _direction = 'forward'

  var changeDirection = function(d) {
            _direction = d;
  }

  return {
            setDirection: function(d) {
            changeDirection(d);
            console.log(_direction);
            }
  };

})();

Direction.setDirection('backward');   // Outputs: 'backward'
console.log(Direction._direction);

6. Hoisting

JavaScript moves variables and function declarations to the top of their scope before code execution. This is called hoisting. Regardless of where you place the declaration of functions and variables in your code, they are moved to the top of their scope by the interpreter.

The priority is given below from higher to lower:

  • Variable assignment
  • Function declaration
  • Variable declarations

x = 5; // Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element

var x; // Declare x

Declare Your Variables At the Top !

7. Currying

A technique using partial evaluation. Currying refers to the process of transforming a function with multiple arity into the same function with less arity. The curried effect is achieved by binding some of the arguments to the first function invoke, so that those values are fixed for the next invocation.

var myFirstCurry = function(word) {
  return function(user) {
            return [word , ", " , user].join("");
  };
};

var HelloUser = myFirstCurry("Hello");
HelloUser("Rahul"); // Output: "Hello, Rahul"

The original curried function can be called directly by passing each of the parameters in a separate set of parentheses one after the other as shown below:

myFirstCurry("Hey, wassup!")("Rahul"); // Output: "Hey, wassup!, Rahul"

8. The apply, call, and bind methods

It’s imperative for any JavaScript developer to understand the difference between the call, apply, and bind methods.

Of the three, call is the easiest. It’s the same as invoking a function while specifying its context. Here’s an example:

var user = {
     name: "Rahul Mhatre",
     whatIsYourName: function() {
     console.log(this.name);
     }
};

user.whatIsYourName(); // Output: "Rahul Mhatre",
var user2 = {
     name: "Neha Sampat"
};

user.whatIsYourName.call(user2); // Output: "Neha Sampat"

apply is nearly the same as call. The only difference is that you pass arguments as an array and not separately. Arrays are easier to manipulate in JavaScript, opening a larger number of possibilities for working with functions. Here is an example using apply and call:

var user = {
     greet: "Hello!",
     greetUser: function(userName) {
     console.log(this.greet + " " + userName);
     }
};

var greet1 = {
     greet: "Hola"
};

user.greetUser.call(greet1,"Rahul") // Output: "Hola Rahul"

user.greetUser.apply(greet1,["Rahul"]) // Output: "Hola Rahul"

The bind method allows you to pass arguments to a function without invoking it. A new function is returned with arguments bounded preceding any further arguments. Here is an example:

           var user = {
                greet: "Hello!",
                greetUser: function(userName) {
                console.log(this.greet + " " + userName);
                }
           };

           var greetHola = user.greetUser.bind({greet: "Hola"});
           var greetBonjour = user.greetUser.bind({greet: "Bonjour"});

           greetHola("Rahul") // Output: "Hola Rahul"
           greetBonjour("Rahul") // Output: "Bonjour Rahul"

9. Memoization

Memoization is an optimization technique that speeds up function execution by storing results of expensive operations and returning the cached results when the same set of inputs occur again. JavaScript objects behave like associative arrays, making it easy to implement memoization in JavaScript. For example, we can convert a recursive factorial function into a memoized factorial function as shown below:

function memoizeFunction(func) {
  var cache = {};
  return function() {
            var key = arguments[0];
            if(cache[key]) {
            return cache[key];
            }
            else {
            var val = func.apply(this, arguments);
            cache[key] = val;
            return val;
            }
  };
}

var fibonacci = memoizeFunction(function(n) {
  return (n === 0 || n === 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
});

10. Method overloading

Method overloading allows multiple methods to have the same name but different arguments. The compiler or interpreter determines which function to call based on the number of arguments passed. Method overloading is not directly supported in JavaScript. But you can achieve something very much like it as shown below:

function overloadMethod(object, name, fn){

            if(!object._overload){
            object._overload = {};
            }

            if(!object._overload[name]){
            object._overload[name] = {};
            }

            if(!object._overload[name][fn.length]){
            object._overload[name][fn.length] = fn;
            }

              object[name] = function() {
                        if(this._overload[name][arguments.length])
                        return this._overload[name][arguments.length].apply(this, arguments);
              };
}

function Students(){
  overloadMethod(this, "find", function(){
            // Find a student by name
  });

  overloadMethod(this, "find", function(first, last){
            // Find a student by first and last name
  });

}

var students = new Students();
students.find(); // Finds all
students.find("Rahul"); // Finds students by name
students.find("Rahul", "Mhatre"); // Finds users by first and last name