Monday, 21 December 2015

Create unique ID : use timestamp for it in Java

Whenever we require a unique ID for different purposes. We try with various approach.
One of good approach is to use timestamp with specific format. Please find the code for the same.

getTrackignID function will give you unique ID for the use.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetUniqueID {


         String defaultFormat="yyMMddHHmmss";
         String trackingID=null;

         private final long startTime=System.nanoTime();

private static final long deltaNanos = System.currentTimeMillis() * 1000000L - System.nanoTime();

private DateFormat dateFormat;

public DateFormat getDateFormat() {
return dateFormat;
}

public void setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}

public long getStartTime()
{
return ((this.startTime + deltaNanos) / 1000000L);
}

         public String getTrackignID(){
setDateFormat(new SimpleDateFormat(defaultFormat));
String trackingID=null;
trackingID=getTimestamp();
System.out.println("Generated tracking ID :"+trackingID);
return trackingID;

}

private String getTimestamp() {
return this.dateFormat.format(new Date(getStartTime()));
}
}

output will in format below :

151221123634 as per the format "yyMMddHHmmss"

Get XMLGregorianCalendar timestamp in Java


Get XMLGregorianCalendar timestamp in format :

2016-01-01T11:58:58-05:00

import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public static XMLGregorianCalendar getTimeStamp() throws DatatypeConfigurationException{
Date trailDate=new Date();
XMLGregorianCalendar timestampdate=null;
    GregorianCalendar calendar1 = new GregorianCalendar();
    calendar1.setTime(trailDate);
    try
    {
    timestampdate=DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar1);
    System.out.println("timestampdate :"+timestampdate);
    return timestampdate;
    }
   catch (DatatypeConfigurationException ex)
    {
  System.out.println("Exception in getting xmlGreg Date, setting bydefault a value for Calender");
  return  DatatypeFactory.newInstance().newXMLGregorianCalendar("2016-01-01T11:58:58-05:00");
    }
}


Get shortened stacktrace after exception in Java


Sometimes, we require only set of lines from the stacktrace, so a generic method to get the required number of line from stacktrace.

import java.io.PrintWriter;
import java.io.StringWriter;

public static void main(String[] args) {
       try {
       throw new Exception("Malformed Exception");
   } catch (Exception e) {
       System.err.println(shortenedStackTrace(e, 1));
   }
}

public static String shortenedStackTrace(Exception e, int maxLines) {
   StringWriter writer = new StringWriter();
   e.printStackTrace(new PrintWriter(writer));
   String[] lines = writer.toString().split("\n");
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < Math.min(lines.length, maxLines); i++) {
       sb.append(lines[i]).append("\n");
   }
   return sb.toString();
}

Friday, 16 October 2015

Get Java Web Application project option in Netbeans

Sometime in Netbeans version which we downloaded, we don't see option for some specific type of projects. This is because the concerned plugin is not there.

To install the plugin on your IDE, please do the following :
i) Go to menu bar of Netbeans
ii) Select
     Tools >>
     Plugins >>
     Available plugins tab >>
     Select the plugin you want to install >>
     Finish and you have required option in your Netbeans IDE


For e.g 
You are not able to see option for Java Web Application Project then 
Tools >> Plugins >> Available plugins tab >> Select Java EE Base Plugin >> Install >> Done :)

Thursday, 1 October 2015

Install mysql on your system and connecting it to NetBeans

1) Download mysql setup for your system for e.g. mysql-5.6.26-winx64.
2) Copy it in any folder at any location.
3) And set Variable home for my sql like below.
4) Add the above variable(with bin) in path variable.
5) Now go to bin folder of mysql and run mysqld.exe to run mysql.
6) To verify if mysql is connected or not, run cmd and type mysql. It should be like below.

7) Now for connection to Nebeans, go to services tab in NetBeans >>Serivces Tab >> Databases
8) Right click on the Databases  >> 
            New Connection >> 
            Select MySQL(Connector/J driver) >> 
            Select Driver File(if not there) mysql-connector*bin*.jar >> 
            Next >> 
            Fill the details (Generally passwrod is empty for root user) 
            Next >>
            Finish.
9) One option will be there to connect. Connect the database and use.

Monday, 28 September 2015

Simple steps to convert DOC to PDF

To convert DOC to PDF, we try to find the apps/online though this functionality is there in Microsoft word only :)

Basic thing is to find Create PDF/XPS Document option from menu.

To get this option there are multiple ways, one of them is

1) Open the Word doc.
2) Go to File menu >> Save and Send >> File Types >> Create PDF/XPS Document >> Create PDF/XPS
3) Click on it and save the PDF file with name as you need.
And we are done.

Please find below image for reference.


Wednesday, 23 September 2015

Oracle Jobs

Creating a oracle to job :

BEGIN

DBMS_SCHEDULER.create_job (    job_name        => 'Test_create_job',    

job_type        => 'PLSQL_BLOCK',    

job_action      => 'BEGIN DBMS_STATS.gather_schema_stats(''SCOTT''); END;',-- job action will be procedure which you want to invoke    

start_date      => SYSTIMESTAMP,    

repeat_interval => 'freq=hourly; byminute=0',    

end_date        => NULL,    

enabled         => TRUE,    

comments        => 'Job defined entirely by the CREATE JOB procedure.');

END;

Note : There are many other values for repeat_interval

Stop the Job:

BEGIN

DBMS_SCHEDULER.stop_job (job_name => 'Test_create_job');

END;

Drop the job :

BEGIN  

DBMS_SCHEDULER.drop_job (job_name => 'Test_create_job');

END;

Enable job:

BEGIN

DBMS_SCHEDULER.enable (name => 'Test_create_job');

END;

Disable he job:

BEGIN

DBMS_SCHEDULER.disable (name => 'Test_create_job');

END;

Update any job attribute :
BEGIN
DBMS_SCHEDULER.set_attribute (
    name      => 'Test_create_job',
    attribute => 'repeat_interval',
    value     => 'freq=hourly; byminute=30');
END;

You can check details of the job using follwoing query :

SELECT OWNER, JOB_NAME, JOB_CREATOR, START_DATE, NEXT_RUN_DATE, ENABLED, STATE,REPEAT_INTERVAL FROM dba_scheduler_jobs ds;

Tuesday, 22 September 2015

Custom Logging Appender for log4j version 2 based xml

Requirement :
To have our custom appender where we can play with the log files(names, size etc) which we want to create.

Solution :
Create our own appender and use it to get log files.

Used Tech :
1) log4j-api-2.2.jar
2) log4j-core-2.2.jar

Path where to put XML:
Xml under "WEB-INF\classes\" folder of  custom war.

Log4j XML file:
Please find the path for "log4j2.xml"
https://drive.google.com/open?id=0BwyaWKtCo9z7NUJwbEVaY3pIRjg

Custom Plugin(Java File) created: "LogCustomRollingFileAppender.java"
Java file which is customized version of our plugin. 
https://drive.google.com/open?id=0BwyaWKtCo9z7aEpXSExGZ29TMFU

Wednesday, 5 August 2015

To open the port 3306 or other

Tried to open port 3306 using following steps:

i. Open Control Panel from the Start menu.
ii. Select Windows Firewall.
iii. Select Advanced settings in the left column of the Windows Firewall window.
iv. Select Inbound Rules in the left column of the Windows Firewall with Advanced Security window.
v. Select New Rule in the right column.
vi. Select Port in the New Inbound Rule Wizard and 

     then click Next.
vii.Select which protocol this rule will apply to (TCP or UDP), 

      select Specific local ports, 
      type a port number (80), 
      port numbers (80,81), 
      or a range of port numbers (5000-5010) and 
      then click Next.
viii.Select Allow the connection and 

      then click Next.
ix. Select when this rule applies (check all of them for the port to always stay open) and        then click Next.
x. Give this rule a name and 

      then click Finish to add the new rule.

Thursday, 2 July 2015

JDBCUtility : Find the generic methods to interact with DB

JDBC Utility :

Utility in java to interact with DB, So find some generic functions and use them directly like.
1) getting connecion
2) getIntValue
3) runQuery
4) runIsertStatement
5) runBatchIsertStatement
6) prepareInsertStatement
7) executeProcedure
and many more...

Pelase find the code attached below.
https://drive.google.com/open?id=0BwyaWKtCo9z7SW5LNDZvQi1Gcm9pMzFrSGFWVlpiRXdRdTdr

Sunday, 28 June 2015

Loading property file in java

Loading property file in java code.

Loading property file can be used for following purposes :
i) If you want to configure a value which need to be accessed by your code, then its easy to define in property file and easily configurable.
ii) log4j.property file is also required to pick sometimes if you need sepearate logging mechanism.

Following is the general code to pick property file :

package com.test.timer.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class PropertyUtils {
//protected static final Logger LOGGER   = LogFactory.getLogger(PropertyUtils.class);
private static Properties prop = null;

public static void init(){

//LOGGER.info("PropertyUtils.init called");
InputStream timerPropertiesIS = null;
try {
timerPropertiesIS = new FileInputStream(TimeEJBConstants.PROPERTIES_FILE_NAME);

} catch (FileNotFoundException e) {
//LOGGER.info("FileNotFoundException",e);
}

// props for logger
prop = new Properties();
try {
prop.load(timerPropertiesIS);
//LOGGER.info("Property file "+TimeEJBConstants.PROPERTIES_FILE_NAME+" loaded ");
} catch (IOException e) {
//LOGGER.info("FileNotFoundException",e);
}finally{
try {
timerPropertiesIS.close();
} catch (IOException e) {
//LOGGER.info("IOException",e);
}
}

}

public static String getProperty(String propName) {
return prop.getProperty(propName);
}

public static void init(Properties prop2) {
prop = prop2;

}

}

//Here,
TimeEJBConstants.PROPERTIES_FILE_NAME is name of property file present in domain path
like below :
public static final String PROPERTIES_FILE_NAME ="./CustomerTimer.properties";


Now, wherever you want to use the property file just call init() method 
PropertyUtils.init();
and use the variable defined in file as follows:
Integer.valueOf( PropertyUtils.getProperty(TimeEJBConstants.PRIORITY_Q_ONDEMAND));
for varaible :
public static final String PRIORITY_Q_ONDEMAND ="priority_On_Demand";


where varaible defined in CustomerTimer.properties is like
priority_On_Demand= 8

Saturday, 20 June 2015

Technical Interview Questions

A Short and concise document for technical interview questions comprises of different subjects. Surely help you in your way :)

https://drive.google.com/open?id=0BwyaWKtCo9z7UjQyS3VIc25xNGM&authuser=0

More coming up soon...

Sunday, 24 August 2014

Knowledge Transfer


1) Who hosted the Game which was initially called as British Empire Games 2014 and who is going to host in 2018?
Ans :
    2014     
    Glasgow    
Scotland
2018
Australia

2) Story of Girlfriend and Boyfriend:
Boyfriend had collected many gold coins. He did not want anybody to know about him. One day his girlfriend asked, “How many gold coins do we have?”  After pausing a moment, he replied,” Well! If I divide the coins into two unequal numbers, then 48 times the difference between the two numbers equals the difference between the square of the these numbers.” Girlfriend looked puzzled. Can you help her by finding out how many gold coins boyfriend has?
Ans :48
Exp :Two unequal numbers : x and y
48(x-y)=x^2 – y^2
ð                      x+y=48

3) 3, 6, 18, 90, 63o,?
Ans :6930
Exp : 3, 3*2=6, 6*3=18, 18*5=90, 90*7=630, 630*11=6930
  
4) Introducing a boy, a girl said, "He is the son of the daughter of the father of my uncle." How is the boy related to the girl?
Ans : Brother/ Cousin Brother

The father of the boy's uncle the grandfather of the boy and daughter of the grandfather sister of father.

5) If 15th August, 2008 is Friday then what day will fall on 15th August, 2018?
Ans :Wednesday

6)Name any three countries which share the same date of independence as India (excluding India, holiday name might be different for them).
Ans :
August 15
1971
Independence from the United Kingdom in 1971
August 15
1960
Independence from France in 1960.
August 15
1947
Independence from the United Kingdom on 15 August 1947.
August 15
1945
Independence from Japan was declared on March 1, 1919. Holiday is celebrated on August 15, anniversary of independent Korean governments creation on August 15, 1948

Liechtenstein

August 15

7) The owner of a jewellery shop hired 3 watchmen to guard his diamonds, but a thief still got in and stole some diamonds. On the way out, the thief met each watchman, one at a time. To each he gave ½ of the diamonds he had then, and 2 more besides. He escaped with one diamond. How many did he steel originally.
Ans :36
Exp :No. of diamonds before he gave some diamonds to the third watchman = x-(x/2+2)=1
ð              X-4/2=1  àx=6
Hence he had 6 diamonds before he gave 5 to the third watchman.
Similarly, x-4/2=6  à x=16 (number of diamonds before giving to second watchman)
And also x-4/2=16 à x=36
Therefore, thief stole 36 diamonds

8) 480, 240, 720, 180, 900, 150, ?
Ans :1050
Exp: 480, 480/2=240, 240*3=720, 720/4=180, 180*5=900, 900/6=150, 150*7=1050

9) Deepak said to Nitin, "That boy playing with the football is the younger of the two brothers of the daughter of my father's wife." How is the boy playing football related to Deepak?
Ans : Brother
Father's wife mother. Hence, the daughter of the mother means sister and sister's younger brother means brother. Therefore, the boy is the brother of Deepak.

10)What is the angle between the minute hand and the hour hand when the time is 03:40 hours?
Ans: 130
The total angle made by the minute hand during an hour is 360o. If it takes 360o for an hour, it will take 40/60*360= 240o. The angle between the hour hand the minute hand will therefore, be somewhere between 240 - 90 = 150o, as the hour hand is between 3 and 4.
The angle made by the hour hand when it moves from say 3 to 4 will be 30
o. That is the hour hand makes 30o during the course of an hour.
The hour hand will therefore, move 40/60*30
= 20o.
Therefore, the net angle between the hour hand and the minute hand will be 150 - 20 = 130
o. 

Tuesday, 8 July 2014

How to deploy a Eclipse Java Web Dynamic Project on TomCat


  1. Setup Apache Tomcat on your Sys.
    • Usually all you have to do is download the current version, unzip it, and start it by running apache-tomcat-folder\bin\startup.bat. (You can also donwload an installer and set it up as windows service. Check this link for more details).
    • Make sure you test it before continuing (open its address on a browser, something like http://yourinstaceaddress.com:8080/).
  2. Export your web application .war file
    • In Eclipse, right click on a Web project and select Export. Then select WAR file in the Export window and then select Next. Choose the project, the .war file name and folder to export. More detailed explanation can be found here and here (with pictures).
  3. Deploy the .war file to your Tomcat Server
    • The, by far, simplest way to do this is to place your .war (say myapp.war) file in your apache-tomcat-folder\webapps\ folder.
  4. Test your web app

Saturday, 21 June 2014

Install Decompiler in Eclipse Helios

Simple steps need to follow to install Decompiler,makes your life easy :

Steps:
1)  Open Eclipse IDE of Helios.
2) Click Help->Install New software.
3) Paste URL(http://feeling.sourceforge.net/update) and give name you want like Decompiler.
4) Select the Eclipse Class Decompiler.
5) Click on Next and accept agreements.
6) Install it, some ok and next.
7) Restart Eclipse and check now.

You will have decompiler installed, njy :)

Saturday, 10 May 2014

HTML Overview - Basics-3

1) Absolute Links :
Absolute links are those that include the entire pathname. In most cases, you use absolute links when linking to pages or sites that are not part of your own Web site.
<a href="http://www.yahoo.com">Visit Yahoo!</a>
2)Relative Links :
Relative links are called so because you don’t include the entire pathname of the page to which you are linking. Instead, the pathname you use is relative to the current page.
<a href="contactSk.html">Contact Sumit K</a>
3) Create an Anchor :
An anchor is a place within a page that is given a special name, enabling you to link to it later.
Sample for moving from Top to bottom or vice versa on same page using anchor tag:
https://drive.google.com/file/d/0BwyaWKtCo9z7dUsxTUlaUUlYZFU/edit?usp=sharing
4) E-mail Addresses :
When you want to give someone easy access to your e-mail address, you can include it on
your page as a mailto link.
<a href="mailto:ksumit@gmail.com">Email Sumit K!</a>
OR
<a href="mailto:ksumit@gmail.com?Subject=HTML
Book&cc=blogbooks@gmail.com"> Email me about this Blog</a>
5) Change Link Colors :
Attributes of the body tag to customize the three link colors of aWeb page: normal link colors (link), visited link colors (vlink) and active link colors (alink).
<body bgcolor="#ffffff" text="#000000" link="#003366" vlink="#999999"
alink="#ff33cc">
6) "alt" attribute of the img tag to provide alternative text for an image or an alternate image.
<img src="photo.jpg" width="391" height="274" alt="This photo of my blog, when i first started." />
7) Lists : Three different types of lists possible in HTML:
Ordered lists (ol) : default bullets (1,2,3,...)
Unordered lists (ul) : default bullets (disc sign)
Definition lists (dl)
   My favorite bikes are:
  <ol>
    <li>Bullet</li>
    <li>Pulsar</li>
    <li>Twister</li>
  </ol>
  The end tag for li is optional in HTML, but required in XHTML
  <dl>
  <dt>Coffee</dt>
  <dd>Black hot drink</dd>
  </dl>
8) Table and address :
Files for the reference, please follow the link below
Address:  https://drive.google.com/file/d/0BwyaWKtCo9z7TDJzcWoxN1NhXzQ/edit?usp=sharing
Table and address:  https://drive.google.com/file/d/0BwyaWKtCo9z7d1c0a2Q1X3JUSXM/edit?usp=sharing

HTML Overview - Basics-2

1) HTML is case-insensitive and, in fact, very forgiving. This means all of the following three examples would be considered the same by the browser:
● <html>
● <HTML>
● <HTml>
whereas XHTML is case-sensitive and requires all tags to be lowercase. Of the three previous examples, the browser would properly interpret only the first.
2) HTML doesn’t require quotation marks unless the value of an attribute contains a hash mark or a space, as in the following case:
<font face="Times New Roman">
XHTML does require all attribute values to be placed within straight quotation marks.
3) Comments or notes you need to add to your Web pages
<!-- Remember to like this(ksumitinfo.blogspot.com) blog if you like the info -->
4) CSS offers three types of style sheets:
 ● Inline : Styles are embedded right within the HTML code they affect.
  <h2 style="font-family: verdana;color: #003366">
 ● Internal : Styles are placed within the header information of the Web page, and then
 affect all corresponding tags on the page
 <head>
 <title>CSS Example</title>
 <style type="text/css">
 <!--
 h2 {font-family: verdana; color: blue}
 .red {font-family: verdana; color: red}
 -->
 </style>
 </head>
● External : Styles are coded in a separate document, which is then referenced from  within  the header of the actual Web page
5) Nonbreaking space character entity (&nbsp;)
6) Preformat : 
The only time pressing the RETURN or ENTER key in your page creates line breaks in the browser view is when the pre tag is used. Short for preformat, the pre tag renders text in the browser exactly as you type it.
7) Horizontal Rules :
One way you can separate sections of your Web page is to use the hr tag. By default, this tag produces a thin, gray horizontal line called a horizontal rule.
8) Logical Styles :
<abbr>  Indicates an abbreviation 
<acronym> Indicates an acronym 
<cite> Marks a reference to another source or a short quotation, italic
<dfn> Highlights a definition or defined term, italic
<em> Provides general emphasis, italic
<strong> Provides a stronger general emphasis than with <em>, bold
<var> Suggests a word or phrase that is variable and should be replaced with a specific value, italic
9) Physical Styles : 
<b> bold
<big> increases the font size by 1 each time it is used,(maximum size is 7,default size is 3)
<i> italic
<tt> typewriter font
<small> decreases the font size by 1 each time its used,(minimum sizeis 1,default sizeis 3)
<strike> Strikethrough
<sub> subscript
<sup> superscript
<u> underline

HTML Overview - Basics-1

1) HTML  : Hypertext Markup Language
2) HTML is a means of telling a Web browser how to display a page.
3) HTML files have an .html or .htm file extension.
4) URL : uniform resource locator.
5) The Web was mostly text based until Marc Andreessen created the first graphical Web browser in 1993, called Mosaic. This paved the way for video, sound, and photos on the Web.
6) Web server is a computer, running special software, which is always connected to the Internet.
7) A Web browser is a piece of software that runs on your personal computer and enables you to view Web pages. Web browsers, often simply called “browsers,” interpret the HTML code and provide a visual layout displayed on the screen. Many browsers can also be used to check e-mail and access newsgroups.
8) Dynamic HTML (or DHTML) is a newer version of HTML, in which page content is easily changed and customized on the fly, without having to send and receive additional information from the server. Style sheets, used especially in DHTML.
9) JavaScript is a scripting language designed to give Web pages more interactivity than can be achieved through HTML. Even though the name might make you think otherwise, JavaScript is different from Java, which is a full programming language.
10) !DOCTYPE :  Tells the browser which set of standards your page adheres to 
-Lists the standard (see the section “The Three Flavors of XHTML”) 
–Identifies the location of the standard by linking to the URL.
11) The Three Flavors of XHTML
The W3C has specified that XHTML 1.0 be available in three flavors, or versions, to
accommodate the transition time during which developers and browsers migrate from HTML 4.0 to XHTML. You need to identify your page with one of these three flavors to help the browser validate it. Because most of your pages will probably fall into one of the three categories, you can simply copy-and-paste the DOCTYPE from one page onto all the others.
    a. XHTML Transitional : This is the category under which the majority of your pages will
probably fall. It enables you to use those HTML 4.01 tags that are deprecated, as long as
you also follow the XHTML rules, such as closing all tags (even ones like br, that aren’t
required to be closed in regular HTML). Pages that are transitional are prepared for XHTML,but are also compatible with older browsers that don’t understand XHTML. To validate your pages against this flavor of XHTML, use
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">.
    b. XHTML Strict : Pages that fall into this category don’t contain any deprecated tags.
These pages may not be compatible with older browsers. To validate your pages against
this flavor of XHTML, use
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"DTD/xhtml1-strict.dtd">.
    c. XHTML Frameset:  Sites using HTML frames to divide the pages must identify with the
frameset flavor of XHTML. To validate your pages against this flavor of XHTML, use
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"DTD/xhtml1-frameset.dtd">.

Tuesday, 22 April 2014

PYAR KA WAR -2

     " PYAR KA WAR " - Part 2 (Sequel)

Next din liye hatiyar, aur chla main maidan,
Dekhe to aaj, likha hai kya vidhan.
Dhund dhand ke, mili ek sundar si ladki,
Per jeb main dala hath, to thi bahut kadki. 

Phir bhi himmat juta ke, pahucha uske pass,
Vo to aise khush hui, jaise hu main uske liye khas.
Itni khushi bardash na ho payi mujhse,
Pyar ka bij, pheli bar panpa mujhme.!!!

Jindagi ka har pal kuch alag sa lagne laga tha,
Pyar iss duniya main hota hai, aisa main samajhne laga tha.
Phir vo kehti, ki kahin aadat na pad jaye mujhe apki,
Aur thode hi din baad, hum "Just Friend" keh nikal fatki...

Dil tuta tha, to dard to hona hi tha,
But iss chapter ka, conclusion to nikalna tha.
Ki pyar ke khel main jo bhi uljhe ga,
Muh ke bal, aa ke vo jarur girega.

So, just Rock 'n' Roll 

Note : The characters and incidents portrayed are fictitious and any resemblance to anything is purely coincidental.