Sunday, December 31, 2017

Reporting Tool for Spring Projects (Getting data from different databases in one report)

In spring projects , we use different databases for  different services .
There will be requirement to get  data from different databases in  to one report . It is practically not an easy task .

But  in  BIRT (an open source technology platform used to create data visualizations and reports that can be embedded into rich client and web applications) reporting tool can address this  issue easily .

First you have to create new separate Data Source connections for all  databases that you want to use .
Second step is  create separate Data Sets (Query to get data from particular database)  for  each  database that you want to use .

Third step is  create new  Join Data Set  using already created data sets in second step . Through this join data sets , you  can easily get data  from different databases to your report without much effort(you can create many Join Data Sets  as you wish) .

We allso have to do something for Open Source community back .


Saturday, December 30, 2017

Tip to Avoid Procastination (5 Seconds Rule)

In Our life ,
  1. Knowing what to do will never be enough.
  2. Knowing why you need to do it will never be enough.
So what we need is something that’s going to launch us into a state of action. Because if you’re sitting around waiting for motivation, I’m here to tell you it’s not coming.
If you don’t start doing the things you don’t feel like doing, you will wake up one year from today and be in exactly the same place.

So here’s the one-liner definition of the 5 second rule:

If you have an impulse to act on a goal, you must physically move within 5 seconds or your brain will kill the idea.



Saturday, December 16, 2017

Birt - Business Intelligence Reporting Tool

BIRT stands for “business intelligence and reporting tools”.It’s a completely open-source project.  Can be use with java projects.

BIRT uses 3 engines: a design engine, a chart engine, and a reporting engine. Its user interface is easy to use, and it will handle everything in the data analytics sphere you’ll need. One of main advantage of Birt reporting tool as I see is  , you can have  multiple  main data sources in same report . Through that you  get   data from multiple  databases in single report  without much development effort and you can join those  two data sources also  . It is  very important and  useful when you  developing report  with Spring architecture .



Configuring BIRT  (Extracted from :- wiki.eclipse.org/Servlet_Example_(BIRT)2.1)
  

(Servlet Example)

This example demonstrates using the RE API within a servlet. Note if possible it is better to use the BIRT Web Viewer Example. An example for BIRT 2.2 and 2.5 is listed in the comments. Add comments at the bottom of the example.


BIRT Report Engine API Return to the BIRT Report Engine API examples

Setup

1. Create a WebReport/WEB-INF/lib directory underneath the Tomcat webapps directory.
2. Copy all the jars in the birt-runtime-2_1_1/ReportEngine/lib directory from the Report Engine download into your WebReport/WEB-INF/lib directory.
Steps 3 and 4 are not needed if you are using the BIRT 3.7 POJO Runtime. The POJO Runtime does not have a platform directory.
3. Create a directory named platform in your WEB-INF folder.
4. Copy the birt-runtime-2_1_1/Report Engine/plugins and birt-runtime-2_1_1/ReportEngine/configuration directories to the platform directory you just created.

Document1 01.png
This example application consist of three files that are archived into webreport.jar. If you are using Eclipse to build the servlet make sure to add all the jars, from the birt-runtime-2_1_1/ReportEngine/lib directory to your build path. You will also need servlet.jar, from the Tomcat Eclipse plug-in in your build path. Either build or copy webreport.jar from the example and place it in your WEB-INF/lib directory.

  • BirtConfig.properties - Configuration properties for the Engine.
  • BirtEngine.java - Class used to initialize the Report Engine.
  • WebReport.java - The servlet that handles report generation on a GET command.
Note that if your report references classes from your application, the following code is required in order for the RunAndRenderTask/RunTask to use your application's classloader:
config.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, Thread.currentThread().getContextClassLoader());
You can also add to your classpath using the following appcontext setting; This can be used to setup jars that implement event handlers.
config.getAppContext().put(EngineConstants.WEBAPP_CLASSPATH_KEY, "c:/jars/mjo.jar");
Modify the appcontext before starting up the Platform.
Platform.startup( config );
This behaviour has changed from earlier versions of BIRT. See example version for 2.2 at the bottom of page.

Source

BirtConfig.properties
logDirectory=c:/temp
logLevel=FINEST
BirtEngine.java
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;

import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import javax.servlet.*;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import  org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {

private static IReportEngine birtEngine = null;

private static Properties configProps = new Properties();

private final static String configFile = "BirtConfig.properties";

public static synchronized void initBirtConfig() {
 loadEngineProps();
}

public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
 if (birtEngine == null) 
 {
  EngineConfig config = new EngineConfig();
  if( configProps != null){
   String logLevel = configProps.getProperty("logLevel");
   Level level = Level.OFF;
   if ("SEVERE".equalsIgnoreCase(logLevel)) 
   {
    level = Level.SEVERE;
   } else if ("WARNING".equalsIgnoreCase(logLevel))
   {
    level = Level.WARNING;
   } else if ("INFO".equalsIgnoreCase(logLevel)) 
   {
    level = Level.INFO;
   } else if ("CONFIG".equalsIgnoreCase(logLevel))
   {
    level = Level.CONFIG;
   } else if ("FINE".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINE;
   } else if ("FINER".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINER;
   } else if ("FINEST".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINEST;
   } else if ("OFF".equalsIgnoreCase(logLevel)) 
   {
    level = Level.OFF;
   }

   config.setLogConfig(configProps.getProperty("logDirectory"), level);
  }

  config.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, Thread.currentThread().getContextClassLoader()); 
  //if you are using 3.7 POJO Runtime no need to setEngineHome
  config.setEngineHome("");
  IPlatformContext context = new PlatformServletContext( sc );
  config.setPlatformContext( context );


  try
  {
   Platform.startup( config );
  }
  catch ( BirtException e )
  {
   e.printStackTrace( );
  }

  IReportEngineFactory factory = (IReportEngineFactory) Platform
  .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
  birtEngine = factory.createReportEngine( config );


 }
 return birtEngine;
}

public static synchronized void destroyBirtEngine() {
 if (birtEngine == null) {
  return;
 }  
 birtEngine.shutdown();
 Platform.shutdown();
 birtEngine = null;
}

public Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException();
}

private static void loadEngineProps() {
 try {
  //Config File must be in classpath
  ClassLoader cl = Thread.currentThread ().getContextClassLoader();
  InputStream in = null;
  in = cl.getResourceAsStream (configFile);
  configProps.load(in);
  in.close();


 } catch (IOException e) {
  e.printStackTrace();
 }

}

}
WebReport.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IReportEngine;


public class WebReport extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;
/**
 * Constructor of the object.
 */
private IReportEngine birtReportEngine = null;
protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );

public WebReport() {
 super();
}

/**
 * Destruction of the servlet. 

 */
public void destroy() {
 super.destroy(); 
 BirtEngine.destroyBirtEngine();
}


/**
 * The doGet method of the servlet. 

 *
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp)
  throws ServletException, IOException {

 //get report name and launch the engine
 resp.setContentType("text/html");
 //resp.setContentType( "application/pdf" ); 
 //resp.setHeader ("Content-Disposition","inline; filename=test.pdf");  
 String reportName = req.getParameter("ReportName");
 ServletContext sc = req.getSession().getServletContext();
 this.birtReportEngine = BirtEngine.getBirtEngine(sc);
 
 //setup image directory
 HTMLRenderContext renderContext = new HTMLRenderContext();
 renderContext.setBaseImageURL(req.getContextPath()+"/images");
 renderContext.setImageDirectory(sc.getRealPath("/images"));
 
 logger.log( Level.FINE, "image directory " + sc.getRealPath("/images"));  
 System.out.println("stdout image directory " + sc.getRealPath("/images"));
 
 HashMap<String, HTMLRenderContext> contextMap = new HashMap<String, HTMLRenderContext>();
 contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext );
 
 IReportRunnable design;
 try
 {
  //Open report design
  design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
  //create task to run and render report
  IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );  
  task.setAppContext( contextMap );
  
  //set output options
  HTMLRenderOption options = new HTMLRenderOption();
  options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
  //options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
  options.setOutputStream(resp.getOutputStream());
  task.setRenderOption(options);
  
  //run report
  task.run();
  task.close();
 }catch (Exception e){
  
  e.printStackTrace();
  throw new ServletException( e );
 }
}

/**
 * The doPost method of the servlet. 

 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 out.println("<HTML>");
 out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 out.println("  <BODY>");
 out.println(" Post does nothing");
 out.println("  </BODY>");
 out.println("</HTML>");
 out.flush();
 out.close();
}

/**
 * Initialization of the servlet. 

 *
 * @throws ServletException if an error occure
 */
public void init() throws ServletException {
 BirtEngine.initBirtConfig();
 
}

}

Comments

Please enter comments below by selecting the edit icon to the right. You will need a Bugzilla account to add comments.

BIRT 2.5 example project Media:WebReport2.5.zip
BIRT 2.2 Example. Listed below is the WebReport.java class with changes for BIRT 2.2 WebReport.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.HTMLRenderContext;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IReportEngine;


public class WebReport extends HttpServlet {

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 /**
  * Constructor of the object.
  */
 private IReportEngine birtReportEngine = null;
 protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );
 
 public WebReport() {
  super();
 }

 /**
  * Destruction of the servlet. 

  */ 
 public void destroy() { 
  super.destroy(); 
  BirtEngine.destroyBirtEngine();
 }
 

 /**
  * The doGet method of the servlet. 

  *
  */
 public void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {

  //get report name and launch the engine
  resp.setContentType("text/html");
  //resp.setContentType( "application/pdf" ); 
  //resp.setHeader ("Content-Disposition","inline; filename=test.pdf");  
  String reportName = req.getParameter("ReportName");
  ServletContext sc = req.getSession().getServletContext();
  this.birtReportEngine = BirtEngine.getBirtEngine(sc);
  
  
  IReportRunnable design;
  try
  {
   //Open report design
   design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
   //create task to run and render report
   IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );  
   //set output options
   HTMLRenderOption options = new HTMLRenderOption();
                       //set the image handler to a HTMLServerImageHandler if you plan on using the base image url.
                       options.setImageHandler(new HTMLServerImageHandler());
   options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
   //options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
   options.setOutputStream(resp.getOutputStream());
   options.setBaseImageURL(req.getContextPath()+"/images");
   options.setImageDirectory(sc.getRealPath("/images"));
   task.setRenderOption(options);
   
   //run report
   task.run();
   task.close();
  }catch (Exception e){
   
   e.printStackTrace();
   throw new ServletException( e );
  }
 }

 /**
  * The doPost method of the servlet. 

  *
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
  out.println("<HTML>");
  out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
  out.println("  <BODY>");
  out.println(" Post Not Supported");
  out.println("  </BODY>");
  out.println("</HTML>");
  out.flush();
  out.close();
 }

 /**
  * Initialization of the servlet. 

  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  BirtEngine.initBirtConfig();
  
 }

}






Useful Resources
  • http://www.eclipse.org/birt/documentation/reference.php
  • https://www.youtube.com/channel/UCcqqPlXBTUcA8Hw1QmT2WMw 
  • https://www.youtube.com/playlist?list=PLXBve0kMIQOMqk1gI71jKZUEKK0zjl207 
  • https://wiki.eclipse.org/Category:BIRT
  •  BIRT Developer Youtube Channel

What is Business Inteligence ?

 Decision support
# Increased  data  collection  and greater storage capacity
# dats strucuters - sturectured , unstructred  and semi sturectured
#1 st step >>BI >> taking inventory of the data your  company produces
#data  marts
#finally data is  transferred into the central warehouse or datamart
#hadoop
#hadoop is an an storing and processing large amt of  data  across multiple  servers  - uses cluster system
    # ad- hoc queries
    #map reduce
#analyzing big data
#data mining  - analysis of large sets of data in order to find patterns and correlations , connections.
#analyzing big data

#INSIGHTS FROM ANALYTICS  REPORTS INFLUENCE COMPANY DIRECTION , PRODUCT LINEUPS ,AND EVEN HIRING DECISIONS

#Text analytics
#Business analytics - analyzing and  drawing connections between data
      Through that     #Predict future trends
                               #Gain compettive advantages
                                #Reveal unknown innefficencies .
#There  are 3 main forms of business analytics
        #Descriptive - programs analyze past data and identify trends and relationships.
        #Predictive  - companies to infer future patterns from past trends.
        #Decision - looks at a company's internal data , then analyzes external conditions
                            (such as manufacturing trends, or predict supply shortages)
                           to recommend the best course of action for a company.

#Data Visualization - Graphic display of the results  of data mining or analytics, often in real time
         #Dashboards - the interfaces that represent specific analyses .

#Problems - getting access to clean,high quality data remains difficult for some companies.

#Current Trends
    #In memory Processing - those systems utilize RAM memory - instead of hard drives to execute
     queries.This increases application performance
    #Usability and Visualization


Resources - https://www.youtube.com/watch?v=jkCCnwvO_fg

Tuesday, October 24, 2017

Tech Meaning - Words

  • Cohesion -  the action or fact of forming a united whole.
  • Facade -  is a collection of helper methods whose purpose is to hide a library or group of libraries from the application (a facade to a building hides the ugly bits behind it)
  • PAAS - Platform as a service 
  • POJOs -Plain Old Java Objects 
  • REST  - Representational state transfer 
  • SSL (Secure Sockets Layer) -  the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral. 
  • .m2  Folder
    The maven local repository is a local folder that is used to store all your project’s dependencies (plugin jars and other files which are downloaded by Maven). In simple, when you build a Maven project, all dependency files will be stored in your Maven local repository.
    By default, Maven local repository is default to .m2 folder :
  • Unix/Mac OS X – ~/.m2
  • Windows – C:\Documents and Settings\{your-username}\.m2
  •  TDD - Test Driven Development 
               is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case   that     defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.
The following sequence of steps is generally followed:                                                               1. Add a test             2. Run all tests and see if the new one fails                    
                    3.Write some code   4. Run tests                   
                    5.Refactor code        6. Repeat
  • Stand-alone program -  is a computer program that does not load any external module, library function or program and that is designed to boot with the bootstrap procedure of the target processor – it runs on bare metal.
  • Bootstrapping - In general,  usually refers to a self-starting process that is supposed to proceed without external input. 
  • JAR  -   (Java Archive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file for distribution 
  • Stateless Applications
    A stateless app is an application program that does not save client data generated in one session for use in the next session with that client. ... In contrast, a stateful application saves data about each client session and uses that data the next time the client makes a request.
     

Wednesday, October 11, 2017

Command Line -Commands

  • The "cd" command changes the directory, but not what drive you are working with. So when you go "cd d:\temp", you are changing the D drive's directory to temp, but staying in the C drive.
      Execute these two commands:
   D:
   cd temp
     That will get you the results you want.
  • To terminate any running process , type  Ctrl + C

Friday, September 29, 2017

SQL JOINS


  • Using those new standard and earlier standard will execute in same way(Speed etc) , but this new standard is more useful , powerful  .

Sunday, September 10, 2017

Git - Commands


     
  •  Suppose $COMMIT_id  was the last commit id before you performed git pull. What you need to undo the last pull is         

                    git reset --hard $COMMIT_id 
  •  git diff   -   Show unstaged changes between your index and working directory.                                                                                                                                          
  •  git pull    -    This update whole  branches of  local  repository   .                                                                                                                                                                                  
  •  The git pull  command is actually a combination of two other commands, git fetch  followed by git merge ,
    it does a git fetch and then a git merge where it merges branches that have been setup to be merged in your config
                  git fetch just "downloads" the changes from the remote to your local repository. git pull downloads the changes and merges them into your
                  current branch. "In its default  mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD
  • If you want to  get a file( src/main/resources/application-dev.properties) from another branch (master)  to your current working branch then,                                                                               
                  git checkout dev
                  git pull origin  dev
                  git checkout  master -- src/main/resources/application-dev.properties                                                   
  • To remove last commit
     git pull origin  dev
    git reset --hard HEAD~1  //Remove last commit ,1  means one last commit, if  it  is  2,then last two commits gitk git push       origin dev --force
  •  To change commit message  use command ,
     $ git commit --amend
     Then window that will open , change message .Then click Esc  button and type :wq
     Finally push changes.
     
  • If you are currently working on local branch master, and the new remote branch has not been created yet:


    git checkout -b new_branch_name //Creates a local branch(as a copy of the current)
    git push origin new_branch_name //Push it to the remote server 
     
     
     
     
     
     
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    Image result for git  local operations of reset 
     
     
     Image result for git  local operations of reset
    
    
 
 
 

Thursday, September 7, 2017

ReadMe File Creating Using Markdown (MD) Format

If you  are  creating readMe file ,using  Markdown ,Then there  is several tools  that you  can  use  to online create .


 Below some links to markdown tutorials

Tuesday, September 5, 2017

Abbrevations

  •  APM   -  Application Performance Management
  •  DTO    -  Data Transfer Object
  • REST API   -   Representational State Transfer  Application Programming Interface

35 Java Programming Tips And Best Practices For Beginners (Extracted from Freelancer Community)

Java is claimed to be used in more than 3 billion devices and according to Oracle, there are 5 billion active Java cards in the world today. This means Java is everywhere, literally. Let’s look at some of the best tips for you to join the 9M+ programmers using it every day.
These are some simple tips to get started with JAVA on your own. Don’t panic if you have a hard time with them, you can always hire a consultant professional as a freelancer at www.freelancer.com to correct your lines and make your programming perfect.
1. Trace your codes on paper
If you are a complete beginner, the only way to closely follow up on trial and error is by writing it down.
2. Practice in a safe environment
In order to make your mistakes (you’re going to make plenty, believe me) and not destroy anything valuable, practicing in a safe environment is a must. Check here for the basics.
3. Plan the needed objects before you start
Always keep object requirements under check so you don’t create unwanted or unnecessary objects in the code. Remember that every object you create takes memory and processor resources from the system.
4. Avoid the most expensive unnecessary objects first
You have “cheap” and “expensive” operations; this is exactly why it is important Objects are created or initialized if needed. When in doubt, always go for the cheapest.
5. Solving the dilemma; should you use ArrayList or Array?
This choice depends on your requirements. Let´s see some differences in each:
  • It’s easier to remove or add elements from ArrayList than Array.
  • ArrayList can be only one dimension, while an Array can be multi-dimensional
  • ArrayLists have variable sizes, while Arrays have a fixed size.
6. The moment Finally isn’t executed with Try
JVM performs two clear-out tasks before turning off.
  • First, it goes for all the Shutdown hooks registered. It releases the resources to JVM and because of it this, it is very useful.
  • Second, the finalizers. They have been belittled for a long time since they can run on live objects when manipulated by other threads. This ends in undesirable results, or even in a deadlock.
7. Oddity not allowed
Considering Negative Odd Numbers is always a must when you put together your lines, otherwise you will end up with a false result returned, which is incorrect.
8. Quotes, make it a Double?
Whenever you use double quotes, characters are treated as a string. Simple quotes convert to int values through a process known as widening primitive conversion.
9. Memory leaks can be avoided by implementing these simple tricks
Memory leaks often cause the degradation of the software they compose. There are some standard techniques to prevent memory leakage, even though Java manages memory automatically and doesn’t leave much room for programmers to tinker with it.
  • Always release database connections (when querying is complete).
  • Final block is a must whenever possible.
  • The instances which are stored in Static Tables should always be released.
10. No more Deadlocks
When do they occur? Deadlocks are very common and can happen for diverse reasons. While there’s no definitive process for avoiding deadlocks, they normally follow when one synchronized object is waiting for the latch resources that are locked by another synchronized object.
  • Beware of resources locking!
11. Java needs memory, reserve it!
A proper command line can be auxiliary to preserve RAM for high-demanding. Some of the characters to be used are:
  • XX:PermSize = This is the initial size owed during startup of the JVM.
  • Xms = Minimum memory provision pool.
  • XX:MaxPermSize = This is the maximum scope allocated during startup of the JVM.
  • Xmx = Maximum memory provision pool.
12. Can operations be timed in Java?
The time processes in Java have two main formats. Is there a better one to be used? It depends on the circumstances; basically System.nanoTime() is always faster.
13. Should I choose Double or Float?
Double offers far more accuracy, and most processors take the same quantity of processing interval to perform both kinds of procedures. Go for Double whenever possible.
14. The calculation of power
You should always use Multiplication since it is 300-600 times faster.
15. Null Pointer Exceptions treatment
The trick to avoid this collective exclusion is to check Nulls prematurely. This is  so they can be eliminated, and you don’t call any method upon them.
16. Always encode using JSON
This is becoming increasingly widespread due to being extremely light-weight. An ordinary data structure can be programmed in JSON and effortlessly shared all along the pages.
17. Before decoding from JSON
Before doing this, you should be aware of the schema.
18. Searching for the missing Simple String
Java will return the position of index of the desired String Object. When missing, it comes back as -1.
19. How to list the content of a directory
A program can be used to list the insides of a directory. It will simply obtain all the titles, of all the sub-directory and files in an Array.
20. As simple as a Simple IO
Used to read and write a file, this service can generate input and output streams. It is vital to close the streams when the file management is done.
21. Shell Command execution within the Java environment
For running them, Java offers Runtime Class. These are external commands and the exemptions should be handled cautiously, because they are very important.
22. The use of Regex
This is a summary of the most popular expression constructs regularly used that can be found here.
23. Java´s Simple Swing
Javax, Swing and GUI can be created with Java’s help. Components like Button, Text Box, Radio Button, etc. are GUI mechanisms. They can be accompaniments to Boxes and should go on top of the Container.
24. Java, the sound player
This is a feature that´s especially popular when playing games. Audio files can be played along with JAVA codes.
25. Exporting PDF files from Java
Using itextpdf makes it a lot easier to export PDF. You should try it, since transferring a table to PDF is a very common requirement in Java programs.
26. Email anyone from the Java Code
You need to install Java Mail Jar and set its route in your program’s classpath. It is very simple, because the elementary properties are set in the code.
27. Time measurements
Java offers two static approaches in static class:
  • currentTimeMillis(): Shows current interval in milliseconds.
  • nanoTime(): Returns the current value in nanoseconds.
28. Rescaling an Image
This can be achieved using AffineTransform. It will buffer the original and then render the scaled one.
29. Can the mouse hove coordinates be captured?
This is attained by applying MouseMotionListner Interface. It activates when the mouse is hovered over a specific section.
29. What’s the use of File Output Stream vs. the use of File Writer?
If you are attempting to write streams of characters, think about using File Writer. For everything related to raw bytes (like image data), you should go with File Output Stream, because it was created for that.
30. Primitive classes are preferred over Wrapper Class
Primitive classes are faster.
32. Always favor returning Empty Collections rather than Null
We always prefer this outcome. It will help you avoid a lot of “if else” testing on those Null ones.
33. Use the Strings very carefully
You create a new String Object every time two Strings are concatenated by “+” functioning in a “for” loop, growing performance time and producing memory depletion. Added to this, you should always evade constructors when instantiating a String Object. It should occur directly. 

34. Always validate all input sources
From all untrusted data sources, no exceptions! If this step is done properly, you can eradicate virtually all vulnerabilities from that specific software. External data sources may include: network interfaces, command line arguments, environmental variables and user controlled files.
35. Default deny
Everything is guilty before proven innocent. This means that access is denied by default, and the defense scheme recognizes conditions under which admission is allowed

Link to Original Post :-  https://www.freelancer.com/community/articles/35-java-programming-tips-and-best-practices-for-beginners?ft_prog=CFC&ft_prog_id=938

Java Productivity Tips: Top Picks From The Community (Extracted from Freelancer)

Do you find yourself distracted when trying to complete the programming tasks on your to-do list? Many software developers blame Facebook, Twitter, and YouTube for their inefficiencies. Some computer programmers get distracted by PlayStation, and offline computer games.
Are you ready to drop the bad habits that are stopping you being productive?  Incorporate these tips into your professional life:
1. Use Bash scripts
A Bash script is a blank text file that supports a chain of commands. It is superior to the Command Line because you can execute numerous complex commands. This helps a software developer accomplish many tasks through automation. You can also use alias commands to make work easier.
Freelance developers may receive overwhelming orders from clients. A Bash Script comes in handy since it helps them multitask on various complex projects using alias commands. You can access your automation using unlimited shortcuts.
2. Present your code in a reader-friendly format
One common mistake new programmers make is providing codes without reference comments. This makes it hard for a second party to understand certain aspects, or track additional changes, and it can discourage software developers from making valuable additions to the program. Expert computer programmers use one-liner comments to substitute lengthy bits of logic.
A one-liner comment helps you track the logic behind all changes made to the program.  It also minimizes the time spent tracking bugs. Another benefit is obtaining better rankings from credible search engines, since they prefer websites with simple code. Software developers who are working on a group project work more efficiently when using code that is properly formatted. You can learn how to present your code neatly by downloading free samples in various software developers online forums.
3. Do thorough debugging
A bug is a programming error that limits a software’s effectiveness. A software containing numerous bugs may freeze abruptly during use. These bugs hinder users from accessing features because the program cannot execute incomplete commands. Java lets software developers use the internal debugging tool by setting breakpoints.
Breakpoints enable software developers to analyze their programs line by line. You can use different debugging tools to monitor active processes by running the program step by step. This exercise helps you to identify the common mistakes you unknowingly repeat when coding.
For better results you can hire external people at freelancer.com to do the debugging for you.
4. Monitor your system
Software developing involves a variety of stages before the final product gets released to its end users. You need to test it in various scenarios to observe its performance and effectiveness in solving real life problems. Monitoring helps you notice any bugs you might have missed during debugging, and you can spot incompatibility issues that arise when testing the software on various operating systems.
You can use premium tools to monitor your program. Some reliable open sourced tools are  Chef and Puppet.
5. Use Batch processing
Batch processing helps smart software developers execute various recurrent tasks without additional time or costs. You can manage your phone calls, emails, appointments and business social media posts by grouping them into a single batch. Batch processing is popular because no special hardware is required. Most multinational corporations use batch processing for daily data management operations, and handling daily office tasks.
As a team leader, you can use batch processing to handle your group’s daily activities such as posting daily updates of pending projects via email.
6. List the tools you require
Software developers who dive into a project without researching what they require end up wasting time and money. Research helps computer programmers identify software tools that enable them to deliver high-quality results in the shortest time possible. You may realize that you need a different IDE or new library updates to handle a client’s project.
Researching also helps you to identify all possible challenges that may arise during developing and testing. By having an accurate understanding of the project, you’ll formulate a realistic strategy to boost your performance.
7. Develop testable codes
Successful people achieve their dreams by visualizing the desired end product. They develop strategies by beginning with the end in mind. This is a reliable approach to identifying any issues that may pop up during the software’s testing stage. You’ll also spend less time designing a testable code by doing it bit by bit.
Developing testable codes is suitable when working on a group project because it’s easier to track and correct all changes.  Having a testable code ensures you don’t execute your software manually whenever you want to test it.
8. Join online Java forums
Online forums provide unlimited opportunities for both upcoming and established software developers to gain useful knowledge. Popular Java online forums such as StackOverFlowOracle Java Forum or Java Forum are free, and contain links to useful eBooks, video tutorials and blog posts on various Java topics. Many seasoned computer programmers on these forums provide swift answers to questions posted by fellow members.
A majority of novice computer programmers are struggling with Java programming because they lack mentors. It may be difficult to approach a college professor because they might be too busy helping other students. However, it’s easier to approach a fellow Java programmer on an online forum.
9. Tackle new projects
Learning takes place when you expose your mind to different projects that require new skills and programming methods. Handling new programming projects helps budding software developers learn how to use different tools to obtain a variety of results. When you take on a new programming task that’s beyond your current experience, it builds your self-confidence to handle difficult projects.
Various online Java forums host friendly programming tournaments for beginners, intermediate, and expert software developers. These challenges provide ideal opportunities to enhance your programming skills without incurring additional expenses.
To handle new projects, you can utilize the services of other coders at freelancer.com.
10. Maintain a calm state of mind
Software coding is a rigorous mental process that demands attention at all times. A simple distraction could lead to numerous software bugs. To function efficiently, you need 6-8 hours of uninterrupted sleep. Always eat a nutritionally-balanced breakfast to keep your mind alert during your morning coding sessions.  Avoid dwelling on negative situations that increase mental stress, and affect your concentration on pending projects.
How to maximize your daily efficiency
To effectively apply the tips shared above, you need to manage the usual distractions which every software developer deals with on a daily basis.
  • Read your emails towards the end of your day- Your main objective is developing software that functions effectively. This means that you’ll spend a huge portion of your day typing commands and testing the software. Responding to emails at the wrong time distracts your attention from important tasks at hand.
  • Set daily objectives. Most programmers experience slow progress in their projects because they lack goals to guide their efforts. Setting daily goals helps to channel your time and resources to accelerate progress wisely. It’s easy to beat deadlines in good time when you meet your daily objectives.
  • Create a motivating playlist. Did you know that music keeps the mind alert for lengthy periods? It’s a great alternative to consuming coffee and energy drinks to retain alertness. Before commencing on your tasks, take about ten minutes to create a playlist from your favorite songs.
  • Close all idle tabs on your browser. It will prevent you from getting distracted by social media websites.
You don’t need expensive hardware or software to improve your productivity. Simply apply these tips, and you’ll notice improvements in no time.

Sunday, August 13, 2017

JPA - Tips

###  Orphan Removal and  CascadeType

JPA 2 supports an additional and more aggressive remove cascading mode which can be specified using the orphanRemoval element of the @OneToOne and @OneToMany annotations:

@Entity  
class User{ 
  @OneToOne(orphanRemoval=true) 
  private PhoneNum phoneNum;  
}

The difference between the two settings is in the response to disconnecting a relationship. For example, such as when setting the address field to null or to another Address object.

  • If orphanRemoval=true is specified the disconnected Address instance is automatically removed. This is useful for cleaning up dependent objects (e.g.PhoneNum) that should not exist without a
    reference from an owner object (e.g. User).
  • If only cascade=CascadeType.REMOVE is specified no automatic action is taken since disconnecting a relationship is not a remove
    operation.

Saturday, July 29, 2017

Java - Random Helpful Tips

  • Ternary Operator
This  will to reduce line number of  code . 
condition ? ifConditionTrueWhatShouldHappen : ifConditionFalseWhatShouldHappen
 This can  be use instead of ,Normal if  and  else .


  •  Substring
    •     public String substring(int startIndex) : 
   This method returns new String object containing the substring of the given string from specified     startIndex (inclusive). 

    •     public String substring(int startIndex, int endIndex):  
  This method returns new String object containing the substring of the given string from specified     startIndex   to    endIndex (exclusive).
  Index starts  from 0  .Returns index where found, or -1 if not found 
ex :-  
String text = "Here there everywhere";
int a =text.indexOf("there");   // a is 5
int b =text.indexOf("er"); // b is 1 
int c =text.indexOf("eR"); // c is -1, "eR" is not found
  •  For Checking Null
    if(foo != null && foo.bar()) {
       someStuff();
    }
    will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.            
  •  The && and || operators "short-circuit", meaning they don't evaluate the right hand side if it isn't        necessary. The & and | operators, when used as logical operators, always evaluate both sides.


  • Variable Arguments (Varargs) in Java
     
  • There can be only one variable argument in a method.
  • Variable argument (varargs) must be the last argument.
  • ex:-
    // Java program to demonstrate varargs
    class Test1
    {
        // A method that takes variable number of intger
        // arguments.
        static void fun(int ...a)
        {
            System.out.println("Number of arguments: " + a.length);
            // using for each loop to display contents of a
            for (int i: a)
                System.out.print(i + " ");
            System.out.println();
        }
        // Driver code
        public static void main(String args[])
        {
            // Calling the varargs method with different number
            // of parameters
            fun(100);         // one parameter
            fun(1, 2, 3, 4);  // four parameters
            fun();            // no parameter
        }
    }

Friday, July 7, 2017

How to Read Out Loud ,Pdf File etc and Listen to Them Later

If  we  able  to  convert    pdf  files   that  we  have  to read  ,to  audio  files ,It  will  be  great   help  to our   studies .


You  can   use   Adobe  Reader    to  read  out  loud , pdf   files  .But  I    there  is  no direct   way  to convert  those   files  to  MP3  files to  listen  later  .










You  can   use these   steps  in  this  web  page  to use    this  useful  method   Link - Simple Ways on How to Convert PDF to MP3 without any Fuss  .



There  is  other  softwares also ,  But   most  of  them  have  to  pay  to  pay  if  we  convert  them  to  MP3 file  , Watch  this video  .  So  i  think   earlier  way  will  be help most .






Hope   this will  help  to  your   studies . Try  it .

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...