Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, 5 July 2017

Vagrant - Virtual Environment : Problem while running a command in VM



Problem :  While in Lab 5: Create an RA Project , when I did Task 2 (2. make TOOLKIT_DIR=/home/vagrant/.devops-toolkit toolkit-venv), I get the following error. Earlier it worked for a particular RA( it downloaded something), I’ve tried to create another RA, I see following error. Could please give any clue why I’m getting this.   Many thanks.

vagrant@vagrant-ubuntu-trusty-64:~/shared/myradocker1$ make TOOLKIT_DIR=/home/vagrant/.devops-toolkit toolkit-venv

New python executable in /home/vagrant/shared/myradocker1/env/bin/python2.7
Also creating executable in /home/vagrant/shared/myradocker1/env/bin/python
Traceback (most recent call last):
  File "/usr/local/bin/virtualenv", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 713, in main
    symlink=options.symlink)
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 925, in create_environment
    site_packages=site_packages, clear=clear, symlink=symlink))
  File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 1370, in install_python
    os.symlink(py_executable_base, full_pth)
OSError: [Errno 71] Protocol error
make: *** [toolkit-venv] Error 1
vagrant@vagrant-ubuntu-trusty-64:~/shared/myradocker1$


PS: Earlier I was stuck up at this level when I’m trying to create from first RA it is because Tech Mahindra network as restricted while downloading something, I switched to Open Internet , then it worked. This time, though I’m in Open Internet , still I’m getting this error.

Solution : Running vagrant command (vagrant up ; for VM) solved the problem


Sunday, 31 July 2016

Java Basics - Understanding core concepts


C - can write programs - No OOPS concepts
C++ - got knowledge - partial OOPS concepts


java -
.Net - Framework - C#(== core) java - programing language
C# and java are developed based on OOPS concepts
PHP - developed based on OOPS concepts - FACEBOOK
Phython - developed based on OOPS concepts

OOPs (Concept) - Object Oriented Programing language - java,.net,python,php
Structure oriented programing - c,c++ (partial oops)
OOPS - IPE (Inheritance,Polymorhism and Encapsulation))
Access specifiers - private , public , protected and default

J2SEE - Standard Edition 1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8 - core java - Sun - Oracle(present)

J2EE - Enterprise Edition - J2EE API(Servlets, Jsp) complance - advance java - Sun - Oracle(present)

Servers developed on J2EE API - Apache - Tomcat WS, Jboss AS, IBM- Websphere AS , Weblogic AS
JDBC API - data base - ORACLE, MYSQL, SYBASE, DB2..etc

Sun released API'S like J2SE,J2EE and J2ME - Since Oracle acquired Sun, now all these API's maintaining by Oracle.

JDK (Java Development Kit) - SDK (Software Development Kit) - JDK is to compile your java files to generate .class files out of your .java files usint javac command.
Ex : javac HelloWorld.java   -> HelloWorld.class

javac command nothing but javac.exe resides in JDK, we also call it as java compiler.

javac is responsible to generate byte code (.class files)

JRE - Java Runtime Environment - JRE is nothing but collections libraries (jars) required to run java byte code. In other words to run .class files

java HelloWorld(.class)

While running java code (byte code) you use java command. It's nothing but java.exe available as part of JRE bundle.


For every version of java you'll provided by jdk and jre.
jdk - compile time
jre - run time

J2ME - Mobile Edition - Only for basic mobiles , not for smart phone - Sun - Oracle(present)
Android API on top of J2SE -  .apk - Only for smart phones - released from Google

core java , jdbc, servlets, jsp

Spring , Hibernate and Struts - java frameworks from third party companies developed on top of J2EE API and J2EE API to make the developers life easy.

Path and CLASSPATH are environment variables.
Path - All the executable you want to run from anywhere , then you must keep then in path environment variable.

All windows programs are .exe executables.
You can run executables only from the directory where they are located in the physical directory.
Else, if you want to run them from any directory then keep the directory of them in path variable.

Eg: typical path variable value - echo %PATH%

C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\windows\des_tools;C:\Program Files (x86)\WebEx\Productivity Tools;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\AppSense\Application Manager\Agent\Plugins\EcaRulesEngine\;C:\Program Files\Java\jdk1.8.0_45\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Java\jre7\bin;C:\Users\vnemalik\Documents\001096043\soft\apache-maven-3.2.5\bin

CLASSPATH : - Classpath is also an environment variable but only specific to Java. - Only for java developers.

you keep jar file paths in class path variable to refer these classes/jars from your application.

Class path is needed when your application is dependent on external application that you need refer. You should keep the dependent application as a jar file in the class path variable.

OOPS - very important - OOPS is nothing but a guide lines or specification or standard set for software application development.

Inheritance -
Polymorphism - poly mean many, morphism means forms - many forms
An application or an object plays different role in different times i.e it is exhibiting different behavior at different times is nothing but polymorphism.
Encapsulation -

OOPS gave a solution on problem faced in earlier traditional oriented languages.
OOPS is a solution for the problem faced by developers in C and C++ languages.

Understand all the oops concepts with java examples thoroughly.



Java Interview :-

Core java:
-----------
  1. OOPS concepts
  2. Class
  3. Object
  4. Understanding Object.java class, which is a super class of all the classes in java
  5. packages
  6. inheritance with java example
  7. polymorphism with java example
  8. encapsulation with java example
  9. Abstract classes
  10. Interfaces
  11. exception handling with java example - both checked and unchecked exceptions.
  12. Understanding the difference between Error and Exception
  13. Threads - basics - Thread class and Runnable interface - how many ways we can create threads, what is the default thread in java .. etc
  14. JDBC - How would you connect to any database using java api - understanding DriverManager Class
  15. Java Collections - List , Set , Map , ArrayList , HashMap , HashSet .. etc - pros and cons of using a specific type of collection object.
  16. Java Generics - a new feature added from jdk 1.5
  17. New features introduced in each version of java from 1.5 to 1.8

Advance Java:
----------

Servlet programing
JSP - Java Server Pages
Understanding WebApplication and Enterprise Application
Must have knowledge on at least two application servers for instance Tomcat and JBoss
How to deploy application and work with it.

EJB - Not required for you

Books:

https://havealookonenglish.files.wordpress.com/2015/12/head-first-programming.pdf


Note:

Try a test/certification from these site. I heard companies hiring with the scores fresher's get from these site. Have a look on these once.

https://www.myamcat.com/
https://www.elitmus.com/












Tuesday, 31 May 2016

Key Points



  • CentOS (the community version of Red Hat Enterprise Linux)
  • We can use elevated admin rights than using admin rights since getting admin rights is not very easy while in office work.
  • If you keep a project as a dependency for another project, you don't need to import those files in the another project to use them.

Monday, 1 February 2016

Regular Expressions

.   - Matches each and every character. 

bananas? - The last letter of the word is optional.


foo(bar)? - The enclosed string is optional.


1234?5678 - The digit 4 is optional.


[7-9] - Matches against numbers from 7-9.


[a-zA-Z0-9] - Matches against all alphanumeric characters/numbers.

fo+ - Letter 'O' can be repeated as many as number of times.


test(ing|er|ed)? - The word test can ends with ing , er or ed.


b(a|e|i)d - The middle letter of the word can be a,e or I.


[a-zA-Z1-9_]+@[a-zA-Z1-9]+\.(org|com|net) - Expression to validate Email address.

[a-z]{2} - No of times the characters can be repeated.

[a-z]{1,2} - No of times the characters can be repeated.

^foo$ - Starts with 'f' ends with 'o'


^\s* -  means any line beginning with whitespace.

(?:https?:\/\/)?(?:[a-zA-Z0-9])+\.(?:com|org|net) - Expression to evaluate web url.


<a href=["']([a-zA-Z1-9://\.]+)["']>(.+)<\/a> - Expression to evaluate hyper link



Following link is the excellent link where you can check the regular expressions. Also validate your expressions in very short time.

http://www.regexr.com/

Tuesday, 15 September 2015

Subversion


History for the application can't be tracked with trunk when we are dealing with multiple version of code , whereas in branch the history tracking 'll be more easy. 

Monday, 10 August 2015

volatile Keyword in Java

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

public class Foo extends Thread {
    private volatile boolean close = false;
    public void run() {
        while(!close) {
            // do work
        }
    }
    public void close() {
        close = true;
        // interrupt here if needed
    }
}


Thread.UncaughtExceptionHandler

This can be done using Thread.UncaughtExceptionHandler.

Here’s a simple example:

// create our uncaught exception handler
Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread th, Throwable ex) {
        System.out.println("Uncaught exception: " + ex);
    }
};

// create another thread
Thread otherThread = new Thread() {
    public void run() {
        System.out.println("Sleeping ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
        }
        System.out.println("Throwing exception ...");
        throw new RuntimeException();
    }
};

// set our uncaught exception handler as the one to be used when the new thread
// throws an uncaught exception
otherThread.setUncaughtExceptionHandler(handler);

// start the other thread - our uncaught exception handler will be invoked when
// the other thread throws an uncaught exception
otherThread.start();

ThreadLocal Class

java.lang
Class ThreadLocal<T>

java.lang.Object
java.lang.ThreadLocal<T>
Direct Known Subclasses:
InheritableThreadLocal

public class ThreadLocal<T>
extends Object
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread's ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread's unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Since:
1.2

Strings vs character array


In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you're done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

Strings are immutable in Java it means once created you cannot modify content of String. If you modify it by using toLowerCase(), toUpperCase() or any other method,  It always result in new String. Since String is final there is no way anyone can extend String or override any of String functionality.

Sunday, 9 August 2015

Object class

public class Object
{

    public Object()
    {
    }

    private static native void registerNatives();

    public final native Class getClass();

    public native int hashCode();

    public boolean equals(Object obj)
    {
        return this == obj;
    }

    protected native Object clone()
        throws CloneNotSupportedException;

    public String toString()
    {
        return (new StringBuilder()).append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).toString();
    }

    public final native void notify();

    public final native void notifyAll();

    public final native void wait(long l)
        throws InterruptedException;

    public final void wait(long l, int i)
        throws InterruptedException
    {
        if(l < 0L)
            throw new IllegalArgumentException("timeout value is negative");
        if(i < 0 || i > 999999)
            throw new IllegalArgumentException("nanosecond timeout value out of range");
        if(i >= 500000 || i != 0 && l == 0L)
            l++;
        wait(l);
    }

    public final void wait()
        throws InterruptedException
    {
        wait(0L);
    }

    protected void finalize()
        throws Throwable
    {
    }

    static
    {
        registerNatives();
    }
}

Native methods

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI(Java Native Interface). It marks a method, that it will be implemented in other languages, not in Java. It works together with JNI (Java Native Interface).

Main.java:
public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c:
#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

Compile and run:
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

Output:

4

Monday, 3 August 2015

Throw before return statement



  • The following code gives compilation error as return is unreachable when the throw is not handled.


public class TestThrow {
public static void main(String[] args) throws Exception {
throw new Exception();
return; //Unreacheble code
}
}


  • The following code is alright and the return is reachable with no compilation error as throw is handled.

public class TestThrow {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; // Now it's alright
}
}

Polymorphism works for static ??

No, polymorphism will not work at all for static methods. Method will be executed based on the type of the reference type not on the type of type of object pointed to.

Please find the example below.


public class StaticTest
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
       
        BaseClass bc = new SubClass();
        bc.method1();
    }
}


class BaseClass{

public static void method1(){

System.out.println("Base class");

}
}

class SubClass extends BaseClass{

public static void method1(){

System.out.println("Sub class");

}
}


Output:  Hello World!
                Base class

Friday, 24 July 2015

Generics

Generics in java were introduced as one of features in JDK 5.

generics sole purpose i.e. Type Safety.

Generic types are instantiated to form parameterized types by providing actual type arguments that replace the formal type parameters. A class like LinkedList<E> is a generic type, that has a type parameter E . Instantiations, such as LinkedList<Integer> or a LinkedList<String>, are called parameterized types, and String and Integer are the respective actual type arguments.

If you closely look at java collection framework classes then you will observe that most classes take parameter/argument of type Object and return values from methods as Object. Now, in this form, they can take any java type as argument and return the same. They are essentially heterogeneous i.e. not of a particular similar type.

In original collection framework, having homogeneous collections was not possible without adding extra checks before adding some checks in code. Generics were introduced to remove this limitation to be very specific. They add this type checking of parameters in your code at compile time, automatically. This saves us writing a lot of unnecessary code which actually does not add any value in run-time, if written correctly.

Without this type safety, your code could have infected by various bugs which get revealed only in runtime. Using generics, makes them highlighted in compile time itself and make you code robust even before you get the bytecode of your java source code files.

In the heart of generics is “type safety“. What exactly is type safety? It’s just a guarantee by compiler that if correct Types are used in correct places then there should not be any ClassCastException in runtime.

Another important term in java generics is “type erasure“. It essentially means that all the extra information added using generics into source code will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior java 5 when generics were not added in language.

Class Declarations

public class Throwable
  implements Serializable

public class IdentityHashMap extends AbstractMap
    implements Map, Serializable, Cloneable

public class File
    implements Serializable, Comparable

public class RandomAccessFile
    implements DataOutput, DataInput, Closeable

System Class In Java



The purpose of the System class is to provide access to system resources.

Runtime Class in Java



What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.

Thursday, 23 July 2015

Synchronization in Java

What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.

What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

Serialization in java

public interface Externalizable
    extends Serializable
{

    public abstract void writeExternal(ObjectOutput objectoutput)
        throws IOException;

    public abstract void readExternal(ObjectInput objectinput)
        throws IOException, ClassNotFoundException;
}


How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().


What is the difference between Serializable and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.


What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want some field not to be serialized, you can mark that field transient or static.

Marker Interfaces


java.util.RandomAccess
java.io.Serializable
java.lang.Cloneable
org.springframework.beans.factory.Aware  - Spring framework