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