Thursday 24 November 2016

How Calculate the Size of java class Object by using premain method( Instrumention API)


How  Calculate the Size of java class Object by using premain method( Instrumention API)

In Java 1.5 new to API introduce that is  Instrumention API
Instrumention API  provides services needed to instrument Java programming language code. 

one use of  Instrumention API is use to get size of size of object in byte . 




Instrumention API   have an interface name  Instrumentation  .
 First of all we have to obtain an instance of the Instrumentation interface 

                         Step to get size of java class object 

               we create a special agent class with a special premain method, generally compiling it against the rest of our       code so that it can see the definitions of the classes whose memory usage we're interested in measuring;
  1. When a JVM is launched in a way that indicates an agent class. In that case an Instrumentation instance is passed to the premain method of the agent class.
    we package the compiled agent class into a jar with a special manifest file;

     we run our program, passing in the agent jar to the VM command line arguments.




    Step 1  First create the Agent class that is key to get size of object like following  .

     InstrumentAgent.java

    package in.jk;

    import java.lang.instrument.Instrumentation;

    public class InstrumentAgent {
       
         private static volatile Instrumentation globalInstrumentation; 
         
          
           public static void premain(final String agentArgs, final Instrumentation inst) 
           { 
              System.out.println("premain..."); 
              globalInstrumentation = inst; 
           } 
         
        public static long getObjectSize(final Object object) 
           { 
              if (globalInstrumentation == null) 
              { 
                 throw new IllegalStateException("Agent not initialized."); 
              } 
              return globalInstrumentation.getObjectSize(object); 
           } 
          
    }


    Sample java Object to calculate size of object 
    Employee.java
    package in.jk;

    public class Employee {
       
        private String empId;
        private String empName;
        private String desigination;
        private String salary;
        private String company;
       
       

       
       
       
        public String getEmpId() {
            return empId;
        }



        public void setEmpId(String empId) {
            this.empId = empId;
        }



        public String getEmpName() {
            return empName;
        }



        public void setEmpName(String empName) {
            this.empName = empName;
        }



        public String getDesigination() {
            return desigination;
        }



        public void setDesigination(String desigination) {
            this.desigination = desigination;
        }



        public String getSalary() {
            return salary;
        }



        public void setSalary(String salary) {
            this.salary = salary;
        }



        public String getCompany() {
            return company;
        }



        public void setCompany(String company) {
            this.company = company;
        }
    }


    Main class to run program  

    AgentMain.java
     
    package in.jk;

    public class AgentMain {
       

        public static void getObjectSize(final Object obj){
          
            System.out.println("Size Of Employee Object is  == "+ InstrumentAgent.getObjectSize(obj));
        }
          

       public static void main(String[] args) {
          

            Employee emp = new Employee();
            emp.setEmpId("VEL/2015");
            emp.setEmpName("J K Saini");
            emp.setDesigination("Java/J2EE Developer");
            emp.setSalary("20000");
            emp.setCompany("Velocis System pvt Ltd");
          
            AgentMain.getObjectSize(emp);
          
        }




    create a special manifest file with manifest.txt name .
    provide enrty for premain Agent class like as:

    Premain-Class : in.jk.InstrumentAgent



    After the write all above four file open command line prompt compile the all thrre java class by following command :

    javac  -d . *.java  

    it will  compile all of three java class inside package 

    then create jar file by adding manifest.txt file by following command 

    jar -cmf manifest.txt  jks.jar   in/jk/*.class

    above command create a packge jar with jks.jar

    then execute the following command to exeute Agent main class

    java  -javaagent:jks.jar  -cp . in.jk.AgentMain

    on command line you will get following out put 

     

     

     


 



Thursday 18 August 2016

  Jasper Report Example by  Passing  ArrayList collection Datasource  by Using JRBeanCollectionDataSource     with   TIBCO  Jasper Report 6.0

 

Here we  have Second example of jasper Report  by Arraylist collection datasource .

 

First of all  create a jasper design for you report 


here we using the list collection as data source so we have create the field in jasper report 
in order to print the collection bean value 

REMEMBER : - field name must be same as collection bean value .


we have a bean class name EmployeeBean like as 

package confonet.efiling.service.common;

public class EmployeeBean {
private String empId;
private String name;
private String companyName;
private String desgination;
private String salary;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getDesgination() {
return desgination;
}
public void setDesgination(String desgination) {
this.desgination = desgination;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
}



and  my jasper report design is following .






 

 









my main java class for create the data for report and generating report .

EmployeeJasperReport .java

package confonet.efiling.service.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class EmployeeJasperReport {
public static void main(String[] args) {
//create a HashMap for Passing data to jasper report 
        HashMap employeeReportMap = new HashMap<String, Object>();
 
EmployeeBean employeeBean1 = new EmployeeBean();
 employeeBean1.setEmpId("0000");
        employeeBean1.setName("Ambrish");
        employeeBean1.setDesgination("Java Tech Lead");
        employeeBean1.setCompanyName("NIC");
        employeeBean1.setSalary("600000 RS ");
        
     
    EmployeeBean employeeBean2 = new EmployeeBean();
   
    employeeBean2.setEmpId("1111");
    employeeBean2.setName("Depp");
    employeeBean2.setDesgination("Java Developer");
    employeeBean2.setCompanyName("NIC");
    employeeBean2.setSalary("300000 RS ");
       
    EmployeeBean employeeBean3 = new EmployeeBean();
   
    employeeBean3.setEmpId("2222");
    employeeBean3.setName("Gaurav");
    employeeBean3.setDesgination("Java  Developer");
    employeeBean3.setCompanyName("NIC");
    employeeBean3.setSalary("30000 RS ");
       
    EmployeeBean employeeBean4 = new EmployeeBean();
   
    employeeBean4.setEmpId("3333");
    employeeBean4.setName("J K Saini");
    employeeBean4.setDesgination("Java  Developer");
    employeeBean4.setCompanyName("NIC");
    employeeBean4.setSalary("20000 RS ");
   
   
    List reportDataList = new ArrayList<EmployeeBean>();
    reportDataList.add(employeeBean1);
    reportDataList.add(employeeBean2);
    reportDataList.add(employeeBean3);
    reportDataList.add(employeeBean4);
   
   
    // Creating the data Bean Collection  Data Source  for passing to  jasper report design 
    JRBeanCollectionDataSource beanCollectionDataSource = new                  JRBeanCollectionDataSource(reportDataList);
        
try {
       // Give the path of report jrxml file path for complie.
   JasperReport jasperReport = JasperCompileManager.compileReport("C:\\Users\\preeti_mehta\\JaspersoftWorkspace\\MyReports\\EmployeeReportjrxml.jrxml");
     
   //pass data HashMap with compiled jrxml file and a empty data source .
       JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, employeeReportMap,beanCollectionDataSource );
                 
       // export file to pdf to your local system 
       JasperExportManager.exportReportToPdfFile(jasperPrint, "D:/jasperoutput/empReport "+new Date().getTime()+".pdf");
       
       
       System.out.println("Printed----------------------");
       
   } catch (Exception e) {
       e.printStackTrace();
       System.out.println(e.getMessage());
   }
}
}



 here are final report in pdf format  is as:



 

 Please Comment if i commit any mistake .......



 

 

Tuesday 2 August 2016

Jasper Report Example using HashMap As Parameter ....



  Jasper Report Example by  Passing HashMap as parameter     with TIBCO  Jasper Report 6.0




                Jasper Report is  Open Source reporting tool for java  .  


               Step to Creating Jasper Report  ....

              Step 1  .   Create design in jasper report as per your requirement here we using only                      parameter to print data on report.
               Step 2    Write a java code to do following thing

                               1 generate Data for print  on report (in this we example we it HashMap)  
                               2. complie the your jrxml report file 
                               3. fill data to your report 
                               4 . export the report .



              Step 1  .   Create design in jasper report as per your requirement here we using only                                         parameter to print data on report.

             Employee Report Design


     

create Design in jasper report  . create parameter  as per requirement  remember name of parameter must be same as key HashMap  that we using to  passing  data to report


EmpoyeeReport.jrxml File 


<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.0.final using JasperReports Library version 6.1.0  -->
<!-- 2016-08-02T15:21:55 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="EmployeeReportjrxml" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="61eff370-1c61-42b6-b26c-a3051e3db114">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<parameter name="empId" class="java.lang.String"/>
<parameter name="name" class="java.lang.String"/>
<parameter name="company" class="java.lang.String"/>
<parameter name="desgination" class="java.lang.String"/>
<parameter name="salary" class="java.lang.String"/>
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="60" splitType="Stretch">
<staticText>
<reportElement x="150" y="18" width="220" height="30" uuid="a4bfa63b-fa27-40ca-a15c-1a575d816c99"/>
<textElement textAlignment="Center">
<font size="20" isBold="true"/>
</textElement>
<text><![CDATA[Employee Report ]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height="5" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="42" splitType="Stretch">
<staticText>
<reportElement mode="Opaque" x="1" y="0" width="100" height="25" backcolor="#8F8989" uuid="eccabb75-a7f3-450c-8291-cac8dba31178"/>
<text><![CDATA[Emplyee ID]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="102" y="0" width="100" height="25" backcolor="#8F8989" uuid="44d4d90a-622a-4381-aad2-3302d41d20cb"/>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="203" y="0" width="100" height="25" backcolor="#8F8989" uuid="c27bc7e1-53e9-4ef9-89ff-e2f67b9669d6"/>
<text><![CDATA[Company]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="304" y="1" width="100" height="24" backcolor="#8F8989" uuid="8bb45ea0-59e4-48ce-b636-ea03fe8d4db3"/>
<text><![CDATA[Designation]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="405" y="0" width="85" height="25" backcolor="#8F8989" uuid="c0989a07-a41e-4c14-8c3f-6fddda67dc75"/>
<text><![CDATA[Salary]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="125" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="30" uuid="33223d04-6a30-458e-87f9-f6fa611fdfdd"/>
<textFieldExpression><![CDATA[$P{empId}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="102" y="4" width="100" height="30" uuid="8021fb5f-8f9b-4be7-8fce-7cdca8ec253a"/>
<textFieldExpression><![CDATA[$P{name}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="212" y="5" width="82" height="30" uuid="c43f8c69-13be-4a78-b784-72a8594d53de"/>
<textFieldExpression><![CDATA[$P{company}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="294" y="2" width="111" height="30" uuid="2625dbe4-a64c-497b-8725-7611504c71f3"/>
<textFieldExpression><![CDATA[$P{desgination}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="410" y="6" width="111" height="30" uuid="2951baea-1eae-46ba-9952-79430b022fd6"/>
<textFieldExpression><![CDATA[$P{salary}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>



Java File for Create jasper report 



package confonet.efiling.service.common;

import java.util.Date;
import java.util.HashMap;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class EmployeeJasperReport {
public static void main(String[] args) {
//create a HashMap for Passing data to jasper report 
        HashMap employeeReportMap = new HashMap<String, Object>();
 
  
employeeReportMap.put("empId", "JK- OOP");
employeeReportMap.put("name", "J K Saini");
employeeReportMap.put("company", "NIC New Delhi");
employeeReportMap.put("desgination", "Java/J2EE Doveloper");
employeeReportMap.put("salary", "18000 RS");
try {
       // Give the path of report jrxml file path for complie.
   JasperReport jasperReport = JasperCompileManager.compileReport("C:\\Users\\preeti_mehta\\JaspersoftWorkspace\\MyReports\\EmployeeReportjrxml.jrxml");
     
   //pass data HashMap with compiled jrxml file and a empty data source .
       JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, employeeReportMap,new JREmptyDataSource() );
                 
       // export file to pdf to your local system 
       JasperExportManager.exportReportToPdfFile(jasperPrint, "D:/jasperoutput/empReport "+new Date().getTime()+".pdf");
       
       
       System.out.println("Done----------------------");
       
   } catch (Exception e) {
       e.printStackTrace();
       System.out.println(e.getMessage());
   }
}

}


Japser Report File in PDF 












Tuesday 12 July 2016

Never say these 15 things to your boss in public

Never say these 15 things to your boss in public


Speaking to your boss in front of other people is like a public test. Your professionalism and etiquette towards a senior are put to test in front of an audience that may include your clients, co-workers or other seniors. All of these people have their eyes on you, and whether you like it or not, they are going to judge your behaviour based on what they see. If you’re someone who can’t resist speaking your mind under any circumstances, it can sometimes be hard to identify what to say and what not to. But whatever the scenario, make sure you avoid stating these 15 things to your boss publicly:


“That isn’t possible.”


It is important to speak to your boss regarding what can be achieved and met. Never tell him/her that a target/goal cannot be done because it puts your inefficiency on display. Repercussions can be that you might not be entrusted with crucial work later on in the organisation.

It does not matter with whom you can or can’t work with. The only thing that matters to your boss is whether the work can be done. Also, if you openly express to your boss whom you can’t work with in front of others, it sends a grapevine through the organisation and people could perceive you as someone who is not very approachable.




“But I already told you about it.”


Unfortunately, you are not in a position where you can ‘alert’ or ‘remind’ your boss that you have already told him/her something. It can be rather rude with other people standing around you and also portrays the manager in a poor light. Your boss is someone who usually has much more responsibilities than the others, and making a statement like this publicly is not only unfair, it’s rude.
Advertisement

“It isn’t my fault.”


Playing the blame game in front of your colleagues or any other person won’t get you too far in your professional life. Own up and be accountable for anything you do. This sends a message of responsibility.

“We always do it this way.”


Maybe you do, but an efficient and smart employee will take cues from their senior and find a better way to do it instead of complaining like a child about how it is different from the norm.

“You didn’t tell me to do it.”


Your boss isn’t going to nag you like your mother did. You’ll have to wake up and get work done when you know you have to. You mustn’t arrive at a situation where anyone needs to tell you what to do. Also, saying this in front of others will only make them think that they all need to be ‘told’ what to do.

“That takes a lot of time.”


It probably does, but you will have to do it anyway without complaining to your boss in front of others. When you are working for someone and if you have to do what you’ve been told, just do it.

“It’s difficult.”


Again, this is complaining, and it won’t take you very far. Saying this to your boss is one thing, but saying it in the presence of others makes it a lot worse. You will be viewed as an incompetent employee. Instead, say “I will give my best to make it work.”

“Let’s agree to disagree.”


You never agree to disagree unless you’re on par with your boss, and that is, of course, not the case. Whether it is said in a passive-aggressive tone or in a casual way, you are viewed as someone fuelling an argument with your boss, and this will not be taken lightly.

“That’s not my responsibility.”


It may not be, but when the boss has requested you to get a particular work done, it’s always better to do it. It’s likely that your boss him/herself knows it’s not your responsibility and is entrusting you with work. So don’t fail to impress.

“I need a raise.”


Never have salary negotiations with your boss in front of other people. You may be viewed as someone who is money-hungry rather than work-driven. Approach the topic with considerable achievements in your hat and preferably without people around.

“In my last job, we did it this way.”


Maybe you did, but things obviously work differently in your current workplace. Referring to your last job makes you sound like you think that the present workplace isn’t efficient enough.

“I’m busy.”


You might be already busy with the work assigned to you, but if you want to make this heard, remind him/her about your present assignment and ask if it can wait. Or, simply ask which task is of utmost priority now.
Advertisement

“My shift is over.”


There is nothing more disheartening to seniors than hearing employees expressing disinterest in putting in extra effort, unless he/she is absolutely overworked. This could also discourage others from finishing their projects or not putting in all their worth.                                                    



                                                                                                                     Ref-Techgig.com










J K Saini

Java/J2EE Developer 


Monday 25 April 2016

Simple CDI Dependency Injection Example with JSF2.1 and JBoss weld 2.2.6 and CDI 1.2 and Tomcat 8.


Contexts and  Dependency Injection is  new API   introduce by Oracle . CDI is a standard way to provide dependency injection in java application .

CDI (JSR-299): Contexts and Dependency Injection for the Java EE platform was finalized in December 2009. CDI 1.1 is due to be released in the first half of 2013 to coincide with the release of Java EE 7.

JBOSS Weld is a stranded implementation   of CDI API .

We will take simple example with JSF application .

Following  jar file required for JSF-CDI Application
for JSF
javax.el-api-3.0.0.jar
javax.faces-2.2.8-02.jar
javax.faces-api-2.2.jar
javax.interceptor-api-1.2.jar

for CDI
weld-servlet-2.2.6.Final.jar
javax.inject-1.jar
cdi-api-1.2.jar

following file required for this application

index.xhtml
web.xml
beans.xml
context.xml
faces-config.xml
Message.java
MessageImpl.java
MessageBean.java

first of all create Message interface





Message.java
public interface  Message {

public void showMessage();

}

MessageImpl.java

package in.jk.cdi;

public class MessageImpl implements Message {

    @Override
    public void showMessage() {
  
        System.out.println("Welcome in the World of CDI with JSF  and JBOSS Weld and Tomcat 8");
      
    }

}
MessageBean.java

package in.jk.cdi;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named("jk")
@RequestScoped
public class MessageBean{

@Inject Message message;

public void showMessage(){
    System.out.println("Context and Dependency Injection ");
    message.showMessage();
}
 }

index.xhtml

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
    <title>Title</title>
</h:head>
<h:body>

    <h:form>
<h:commandButton value="Get Messgae  " action="#{jk.showMessage}"></h:commandButton>
</h:form>
</h:body>
</html>

Put the following  context.xml file in META_INF folder of application  

context.xml 

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/tomcat-test">
  <Resource
    name="BeanManager"
    auth="Container"
    type="javax.enterprise.inject.spi.BeanManager"
    factory="org.jboss.weld.resources.ManagerObjectFactory"
    />
</Context>

Put the following three file xml   file in WEB_INF folder of application 

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
  xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
  bean-discovery-mode="all">
 
</beans>

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
   
    </faces-config>



web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>efiling</display-name>

  <welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>

  </welcome-file-list>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
 
  <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
      <!-- This enrty require in web.xml to register CDI Dependency Manager  -->
 <resource-env-ref>
    <!-- Enable Weld CDI, also needs META-INF/context.xml entry -->
    <resource-env-ref-name>BeanManager</resource-env-ref-name>
    <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>
  </resource-env-ref>



</web-app>





Output  is at Console ,...

Context and Dependency Injection
Welcome in the World of CDI with JSF  and JBOSS Weld and Tomcat 8