Friday, 8 September 2017

How to Create alerts in Splunk


The Steps include:


  • Open Search page in Search and Reporting Page.
  • Enter your query for which alerts need to be triggered.for example:
         index = os_web sourcetype = custom-prod-up-ext serviceName=SHARP response=failure                  feature=PCI_DE_TOKENIZATION 
  • Select Save as ---->Alert



  • Next Specify Setting,Triggered Condition,Triggered Action.


  • Select Save.

Enjoy Learning.

Tuesday, 29 August 2017

Java program to check unique number


Sample Program:-


 import java.util.*;  
 import java.io.*;  
 /**  
  * Created by Dixit on 29-08-2017.  
  */  
 public class IsUniqueNumber {  
   public static boolean  
   isUniqueUsingHash(String word)  
   {char[] chars = word.toCharArray();  
     Set<Character> set = new HashSet<Character>();  
     for (char c : chars)  
       if (set.contains(c))  
         return false;  
       else {  
         set.add(c);  
       }  
     return true;  
   }  
   public static boolean  
   isUniqueUsingSort(String word)  
   {char[] chars = word.toCharArray();  
     if (chars.length <= 1)  
       return true;  
     Arrays.sort(chars);  
     char temp = chars[0];  
     for (int i = 1; i < chars.length; i++)  
     {if (chars[i] == temp)  
       return false;  
       temp = chars[i];  
     }  
     return true;  
   }  
   public static void main(String[] args)  
       throws IOException  
   {  
     System.out.println(isUniqueUsingHash("1234")? "Unique" : "Not Unique");  
         System.out.println(isUniqueUsingSort("123")? "Unique" : "NotUnique");  
   }  
 }  


Enjoy Coding

Sunday, 20 August 2017

Interesting facts of Java


Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is:
  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
  • Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
  • Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architectural-neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
  • Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
  • Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.
  • Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
  • High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • Distributed: Java is designed for the distributed environment of the internet.
  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Enjoy Learning.

Monday, 26 June 2017

WHAT TO CHOOSE for Android Game Development:- canvas or OpenGL or LibGDX or Game Engines!!

Android Game Development - WHAT TO CHOOSE

Canvas or OpenGL or LibGDX or Game Engines!!


Developing games on android is not straight forward. You need to be very specific about what you are going to develop, what are the content of it and what are the requirement for it. Game can be developed from all these but everyone has its own limitation.  

As I am a java and android developer and developed some games in java and android with simple logic(Graphics lib. for java and Canvas for android) I had concluded some points.
  • If graphics are heavy than your game FPS may jitter even though you have proper architecture, but can be solved from accurate and efficient algorithm.
  • Rendering too much graphics can be tedious task.
  • There should be proper architecture of everything.
  • Efficient and best algorithm should be there.
  • Application manageability depends on how you develop it.


Canvas


It is a predefined class in android sdk. Android application can draw things on screen using this class.

java.lang.Object 
   ↳android.graphics.Canvas

means Object class is the parent class of canvas class. This class hold the "draw" calls. It can draw anything like rectangle, circle, bitmap image, etc. To draw anything some basic components is needed which are mentioned below:-
  • Paint object(to give color and style to drawing)
  • Bitmap to hold the pixels
  • Canvas to receive draw calls(drawing on Bitmap)
  • Drawing primitive(path, text, etc.)
How to use it please check android developer documentation.

OpenGL


It is the environment to develop 2D and 3D graphics. It gives the high visual quality and performance. It is cross platform environment.


OpenGl can process image data as well as geometric data.


LibGDX


It is the free game development framework, also it is open source. It is written in Java programming language with some components written in C and C++ to increase the performance. It is the cross platform framework. It can be used desktop application and also for android also.

However this framework is written in java, so the compiled bytecode is language dependent and can be used in any JVM. It main focus was to ease the simplicity and increase the performance.

Game Engine 


It is the tool for fast development of the 2D and 3D games. It is the software framework to develop the mobile and desktop games. The core functionality of the game engine are:-
  • rendering(for 2D and 3D graphics)
  • Physics(collision detection)
  • Sounds
  • Artificial Intelligence
  • Networking
  • Memory management and many more.....
It makes the portability and reusability of the code. There are so many game engines in the market right now, one can choose as per its convenience. Some popular Game Engines are:-
  • UNITY
  • UNREAL
  • RENDERWARE
  • X-RAY

WHAT TO CHOOSE!!


The choice is based on some factors like how much time is available, availability of resources, quality of product and many more. after considering all these points one should choose accordingly.

But my personal advice would be Game Engine as you can do so much in less time and no heavy programming skill is needed. Not because of less programming but the quality of content is far more good and manageability is easy. If one wants to develop the game from basic logic, one can to understand how things happen but if they want to build heavy game with simple libraries it will be surely very difficult. So, it is better to choose game engine.

I personally prefer the UNITY game engine as it is easy to learn and implement. Others are also good but I hadn't used them. Tutorials for all these are available online.


GAME ENGINE would be good option.  


Thursday, 22 June 2017

Log4j

Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License. Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.
Log4j has three main components:
  • loggers: Responsible for capturing logging information.
  • appenders : Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles.
log4j Features:
  • log4j is thread-safe.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • Logging behavior can be set at runtime using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
Logging Methods:
Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.
public void debug(Object message)
This method prints messages with the level Level.DEBUG.
public void error(Object message)
This method prints messages with the level Level.ERROR.
public void fatal(Object message);
This method prints messages with the level Level.FATAL.
public void info(Object message);
This method prints messages with the level Level.INFO.
public void warn(Object message);
This method prints messages with the level Level.WARN.
public void trace(Object message);
This method prints messages with the level Level.TRACE.
All the levels are defined in the org.apache.log4j.Level class and any of the above mentioned method can be called as follows:
import org.apache.log4j.Logger;  
 public class LogClass {  
  private static Logger log = Logger.getLogger(LogClass.class);  
  public static void main(String[] args) {  
   log.trace("Trace Message!");  
   log.debug("Debug Message!");  
   log.info("Info Message!");  
   log.warn("Warn Message!");  
   log.error("Error Message!");  
   log.fatal("Fatal Message!");  
  }  
 }  
When you compile and run LogClass program it would generate following result:

 Debug Message!   
 Info Message!   
 Warn Message!   
 Error Message!   
 Fatal Message!  
log4j - Log Formatting:
Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way
The Layout Types:
The top-level class in the hierarchy is the abstract class org.apache.log4j.Layout. This is the base class for all other Layout classes in the log4j API.
The Layout class is defined as abstract within an application, we never use this class directly; instead, we work with its subclasses which are as follows:
  • DateLayout
  • HTMLLayout
  • PatternLayout.
  • SimpleLayout
  • XMLLayout
log4j - Sample Program:
Following is a simple configuration file created for our example.It has the following information:
  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file  
 log = /usr/home/log4j  
 log4j.rootLogger = DEBUG, FILE  
 # Define the file appender  
 log4j.appender.FILE=org.apache.log4j.FileAppender  
 log4j.appender.FILE.File=${log}/log.out  
 # Define the layout for file appender  
 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
 log4j.appender.FILE.layout.conversionPattern=%m%n  
Using log4j in Java Program:
The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.
import org.apache.log4j.Logger;  
 import java.io.*;  
 import java.sql.SQLException;  
 import java.util.*;  
 public class log4jExample{  
  /* Get actual class name  to be printed on */  
  static Logger log =  Logger.getLogger(log4jExample.class.getName());  
  public static void main(String[] args) throws IOException,SQLException{  
   log.debug("Hello this is an debug message");  
   log.info("Hello this is an info message");  
  }  
 }  

Enjoy Reading :)

Friday, 16 June 2017

How to get Resolution of android device during runtime

How to get Resolution of android device during runtime


Getting Resolution of the android screen is one of the important aspect when application is to be made for different resolution devices.
So, in order to get the resolution of the device there is predefined library(Display Metrics) in android sdk. You just need to call the method provided by it. The methods are mentioned below.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  

This DM object have the information about no. of pixels in height and width and density of the screen. To get these information Call following method:-

For no. of pixels in length

 DM.heightPixels;  

For no. of pixels in width

 DM.widthPixels;  

For Density of Screen

 DM.densityDpi;  

This information is used frequently in code so it is better to make a wrapper class of this and add some basic functions in it. The custom Wrapper class is defined below.

Wrapper Class for DM object


Firstly you have to pass the DM object to this class's constructor.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  
 ScreenResolution SR = new ScreenResolution(DM);  

Now create the custom class named as ScreenResolution:-

import android.util.DisplayMetrics;
public class ScreenResolution { public static DisplayMetrics dm; public ScreenResolution(DisplayMetrics dm){ this.dm=dm; } public static int getHeight(){ return dm.heightPixels; } public static int getWidth(){ return dm.widthPixels; } public static int getDensity(){ return dm.densityDpi; } public static int percent_of_width(int param){ return ((param*(dm.widthPixels))/100); } public static int percent_of_height(int param){ return ((param*(dm.heightPixels))/100); } }

This class should be placed in custom Package. This class is beneficial in storing and getting the information about the screen's resolution.

ENJOY  DEVELOPING!!

Wednesday, 14 June 2017

ConcurrentHashMap in Java

ConcurrentHashMap

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package.  Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then you only have Hashtable or synchronized Map because HashMap is not thread-safe.
With ConcurrentHashMap, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. ConcurrentHashMap allows concurred read operations and same time, maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented in Java

ConcurrentHashMap provided all functions supported by Hashtable with additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16. This means, 16 thread can operate on Map simultaneously, until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with warning. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map.
Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesn’t throw ConcurrentModificationExceptoin.

ConcurrentHashMap putifAbsent example in Java

Many times we need to insert entry into Map, if it’s not present already, and we wrote following kind of code:

synchronized(map){  
  if (map.get(key) == null){  
    return map.put(key, value);  
  } else{  
    return map.get(key);  
  }  
 }  

Though this code will work fine in HashMap and Hashtable, This won't work in ConcurrentHashMap; because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null which result in one thread overriding value inserted by other thread. Of course, you can wrap whole code in synchronized block and make it thread-safe but that will only make your code single threaded. ConcurrentHashMap provides putIfAbsent(key, value) which does same thing but atomically and thus eliminates above race condition.
Eg:
public class ConcurrentHashMapTest implements Runnable {  
     private String name;  
     private static Map<String,String> conpage=new ConcurrentHashMap<String,String>();  
     ConcurrentHashMapTest(String name){  
        conpage.put("1","A");  
        conpage.put("2","B");  
        conpage.put("3","C");  
        this.name=name;  
     }  
     public void run() {  
        try{  
            Iterator<String> it = conpage.keySet().iterator();  
            while(it.hasNext()){  
               String key=it.next();  
               conpage.put("A"+key, "A"+key);  
            }  
            System.out.println(name +" completed.");  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
     }  
     public static void main(String[] args) {  
        ExecutorService executor= Executors.newCachedThreadPool();  
        executor.execute(new ConcurrentHashMapTest("Thread one"));  
        Iterator<String> itt = conpage.keySet().iterator();  
        while(itt.hasNext()){  
            String key=itt.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.execute(new ConcurrentHashMapTest("Thread two"));  
        Iterator<String> it = conpage.keySet().iterator();  
        while(it.hasNext()){  
            String key=it.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.shutdownNow();  
     }     
 }  

Output-  
 A  
 C  
 B  
 Thread one completed.  
 A  
 A2  
 A1  
 A3  
 C  
 B  
 Thread two completed.  

When to use ConcurrentHashMap in Java

  • ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
  • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
  • For those who have seen the green-box load jobs written in SpringBatch, many of the one-time populated Maps in beforeJob, whch are always read alone, are all ConcurrentHashMap ‘s.

Enjoy Learning :)