EclipseLink Weaving Feature

June 6, 2014 at 7:56 am | Posted in Uncategorized | Leave a comment
Tags:

     Weaving is a technique of manipulating the byte-code of compiled Java classes. EclipseLink uses weaving to enhance both JPA entities and Plain Old Java Object (POJO) classes for such things as lazy loading, change tracking, fetch groups, and internal optimizations.

This weaving is used for performance optimization. This weaving is extremely important if one want to enable feature of Lazy Loading.

Weaving can be performed either dynamically at runtime, when Entities are loaded, or statically at compile time by post-processing the Entity .class files. By default, EclipseLink uses dynamic weaving whenever possible. This includes inside an Java EE 5/6 application server and in Java SE when the EclipseLink agent is configured. Dynamic weaving is recommended as it is easy to configure and does not require any changes to a project’s build process.

Dynamic Weaving: For enabling Dynamic Weaving we have to follow above steps: 

  1. (For J2SE) Modify your application JVM command line to include the above: -javaagent:eclipselink.jar
  2. Ensure that eclipselink.jar is in your classpath. While running test I found that it complains about eclipselink though the jar file in classpath. For override this I gave whole path of eclipselink.jar. In J2EE container class loader should able to find eclipselink. So we can put eclipselink in classpath or in EAR. 
  3. Package and Deploy application.

Identify Weaving is enabled:

First make sure that your persistance.xml contains logging “eclipselink.logging.level” as a “FINEST”. This not necessary for production but just need to check if weaving applied or not.

Your log file you can find following values :

property=eclipselink.orm.throw.exceptions; default value=true
property=eclipselink.weaving.changetracking; default value=true
property=eclipselink.weaving.lazy; default value=true
property=eclipselink.weaving.eager; default value=false
property=eclipselink.weaving.fetchgroups; default value=true

Now here a word of caution. in your “persistence.xml”  we have to give

<property name=”eclipselink.weaving.internal” value=”false”/>

This is because of a defect which try to store Integer in Double in the case when DB had NULL values.  This is closed on 31 Jan 2012.But I guess we are still using early build which do not have this fix. Bug 313023

    

    

Identify Differences between two DB’s

April 6, 2012 at 4:01 pm | Posted in Java | Leave a comment
Tags:

In any project, developers came across 2 – 3 different DB environments. Mostly DEV, TEST, STAGE and some times PROD. Now most of the times, there is process for adding or changing any DB related stuff to keep smooth transition between DEV, TEST and STAGE. Some of the projects apply DB changes for all DB’s at the same time when application moves from DEV to TEST.

Though there are x processes to keep DB’s same at specific interval of time we came across situations where some of changes did not push to targeting environments. In such situations we feel that there should be some utility which will show you difference between two Databases.

Recently I came across one of such utility which gives you differences between data base schema’s. I got one tool known as MAD for DB (Migration ADvisor for Databases)

It analyzes the differences between two database schema’s. It automatically finds out which changes require individual migration effort and advises migrator which concrete data-sets need fixing. The main benefit of the tool is to quickly filter out database changes which are not relevant for the task of data migration, automatically verify existing data if it matches new constraints and provide a summary sorted by severity of the change.

The only problem, I faced that this includes DB Sanity Report which checks the existing data matches with new constraint takes too much time. If this check is optional then it will be great.

For using this, one need to have two property files each pointed to one DB place in bin directory of mad4db and one should copy your jdbc driver jar file into lib of mad4db.

Property Files: <db / your name>.env.properties

Property file name should end with env.properties.

#db1.env.properties  =>  This property file should contains DB related details.

db_url=jdbc:oracle:thin:@hostname:port:oracle-sid

db_driver=<e.g. for oracle => oracle.jdbc.OracleDriver>

db_user=sa

db_password=sa

db_schema=<your_schema>

For running one should go to bin folder from command prompt:

mad4db db1 db2

For extra information please visit http://databene.org/mad-for-db

Following Reports get generated by this mad4db. Hope you like this.

Severity Report:

The severity report lists changes ordered by their severity, explaining which risk results from a change and what user action is necessary:

Diff View:

The diff view provides an element comparison view over two levels of detail, first a schema diff with a table summary:

For each table, a table view is available which lists all details of the table. For changed tables, a detail diff view is available:

DB Sanity Report

For new constraints on existing data structures (or constraints made more restrictive), Mad For DB uses DB Sanity to check if the existing data matches the new constraint:

Formatting and Parsing Currency

March 31, 2011 at 8:12 pm | Posted in Java | 4 Comments

Suppose you are developing an application in java; may be Web Apps or Standalone App and you have to display Currency Internationalization according to locale. How one can implement it ? May be we can get the numerical data attached Currency Symbol. Am I right ? You might wrong. Because Currency Internationalization is not so simple.

Generally we only look to the currency format but in case of Currency Internationalization there are various factors like rounding, grouping, group separators, fractional separators, currency placement, symbol etc. Generally we need to be consistence to the presentation format of corresponding locale.

Instead of going to each thing I just pick up Grouping Separator.

Grouping Separator : The Integer portion of a number often split into groups by Grouping Separator.

  • Western Numbers generally separate numbers into thousands or groups of 3 digits.
  • Chinese & Japanese Number Systems separate numbers into 10 thousands or groups of 4 digits.
  • While Indian Format groups the lowest order 3 digits (Thousand) & then every 2 digits after that.
  • Grouping Examples
    Culture Example Notes
    British 1,234,567,890.12 Groups of 3
    Chinese,
    Japanese
    12 3456 7890.12

    or
    12 3,456 7,890.12
    Groups of 4, separated by ideographic characters and optionally a thousands separator.
    Indian 1,23,45,67,890.12 One group of 3, then groups of 2
    German 1.234.567.890,12 Groups of 3, separator is full-stop
    Swiss 1’234’567’890,12 Groups of 3, separator is apostrophe1
    French 1 234 567 890,12 Groups of 3,
    separator is a thin non-breaking space2 or “une espace fine insécable”.

    While one has to code currency symbols in UNICODE. One can find the table related to symbol & according unicode

    Currency Symbol Examples
    Currency Unicode Value Notes
    dollar sign U+0024 $
    pound sign U+00A3 £
    yen sign U+00A5 ¥
    yen character U+5186
    euro sign U+20AC
    thai baht sign U+0E3F ฿
    french franc sign U+20A3
    lira sign U+20A4
    korean won sign U+20A9

    Now how one can embed the whole logic related to Separator, currency symbol, position etc. ?

    Here in Java NumberFormat class comes to rescue us. By using only 2 methods we can achieve this.

    NumberFormat.getCurrencyInstance : NumberFormat class provides the functionality for formatting and parsing currency. NumberFormat class also provides methods for defining which locales have currency formats.

    NumberFormat.format() : This method returns a format string of a currency.

    Above one can find code :


    import java.text.*;
    import java.util.*;

    class CurrencyFormatExample {
    public void currencyFormat(Locale currentLocale) {
    Double currency = new Double(9843.21);

    NumberFormat currencyFormatter;
    String currencyOut;

    currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
    currencyOut = currencyFormatter.format(currency);
    System.out.println(currencyOut + " " + currentLocale.toString());
    }

    public static void main(String args[]) {
    Locale[] locales = new Locale[]{new Locale("fr", "FR"), new Locale("de", "DE"),
    new Locale("ca", "CA"),new Locale("rs", "RS"),new Locale("en", "IN")
    };

    CurrencyFormatExample[] formate = new CurrencyFormatExample[locales.length];

    for (int i = 0; i < locales.length; i++) {
    formate[i].currencyFormat(locales[i]);
    }
    }
    }

    Output :

    9 843,21 € fr_FR

    9.843,21 € de_DE

    CAD 9.843,21 ca_CA

    RSD 9,843.21 rs_RS

    Rs.9,843.21 en_IN

    Ref : http://www.xencraft.com/resources/multi-currency.html

    Identify Mobile

    January 12, 2011 at 6:54 pm | Posted in Java | Leave a comment

    Now a days GPRS & 3G is very common. Anybody can browse internet by mobiles / smartphones. Most of the times mobile users gets annoyed because of large images, flash objects etc. So generally companies launch different version mobile-friendly website having domain “.mobi”  or having sub-domain “.m”.

    Now what happens if mobile user comes to the classic web page. User has to bear large images / flash scripts etc. And on footer (s)he might find a link for mobile version. :)

    In this web2.0+ world ( I am not sure this is web 3.0 or in between ) we should detect mobile-user to give rich user experience.  By identifying mobile user we can redirect user to mobile friendly  website. Normally  this can be identified by using UserAgent  header values. This header values depend upon embedded browser & make of device. When I searched user-agents for mobile then I found 70+ different user-agent signatures. Hard code all these signatures is pretty straightforward option but having  heavy maintenance :) .
     
    While searching for  better or smart option I came across one open source project WURFL : Wireless Universal Resource File. The WURFL is XML Configuration file which contains information about capabilities & features of many mobile devices. WURFL supports JAVA, PHP and .NET API and Tera-WURLF supports MySQLDB instead of XML Configuration file.

    Later surprisingly I come to know Spring also having some initiative related to mobile. Spring having two projects :

    1. Spring Android : It is Android Client
    2. Spring Mobile : Detecting device

    While viewing source code of Spring Mobile I realized Spring implement both approaches for detecting device : HardCoded (lite) & WURFL.

    I think Using Spring Mobile with WURFLDevice will be good option if you are using Spring framework. As spring provides light wrapper above WURFL API to integrate in Spring Framework.

    Still I have question how we can change size & resolution of images depend upon the device? The best bet is remove all images. The other options I found in same project under utilities section

    1. GAIA Image Transcoder (http://wurfl.sourceforge.net/utilities/gaia.php)
    2. Image Server (http://wurfl.sourceforge.net/utilities/imageserver.php)

     Worth to look WURFL project !!!

    Usage Of Varargs

    February 22, 2010 at 12:40 pm | Posted in Java | Leave a comment

    In our day to day work we can use variable arguments. This feature gets introduced in J2SE 5.0. In my case I used this to build strings for logger.

    /**
         * Builds the string.
         *
         * @param addSpace the add space
         * @param variableStrings the variable strings
         *
         * @return the string
         */
        public static String buildString(boolean addSpace, String… variableStrings) {
            StringBuilder sb = new StringBuilder();
            if (null != variableStrings) {
                for (String arg : variableStrings) {
                    if (isEmpty(arg)) {
                        arg = CommonConstantsIF.STR_UNDERSCORE;
                    }
                    sb.append(arg);

                    if (addSpace) {
                        sb.append(CommonConstantsIF.SPACE);
                    }
                }
            }
            return sb.toString().trim();
        }

    Now while calling this method you can pass array of strings or comma separated String. Yes it works…
     

        /**
         * Test build strig.
         */
        public void testBuildStrig() {
            String buildString = “”;
            buildString = StringUtil.buildString(true, “Nikhil”, “Suhas”, “Sidhaye”, “:”, “Project”);
            Assert.assertTrue(“Nikhil Suhas Sidhaye : Project”.equals(buildString));
        }

    Here I pass comma separated Strings similarly one can pass String array too… So when you are going using Varargs feature ?

    Create Sitemap by GSA

    February 18, 2010 at 10:50 am | Posted in GSA, Java | Leave a comment
    Tags: ,

    From Google Search Appliance we can generate sitemap.xml.
    Unfortunately this option is not well documented & find one of the api documentation. Following is process of creating sitemap.xml

    Here I am describing process for Google Search Appliance 5.0 (GSA 5.0) but similar step should be applicable for GSA 5+. This option is not working for GSA 4.x

    One should login to admin console of GSA by http://<YourGSABox&gt;:8000/EnterpriseController Go to Status & Reports –> Crawl Diagnostics.

    Now one should select URL display mode as List Format. By default it is Tree Format. After that export all pages to a file.

    Now here is word of caution given by Google that one should exclude all errors otherwise sitemap.xml will contains URL having 404 & other errors.

    For exporting limit is 30,000 URL or 10MB file size. If you have more URLs then one should use collection wise or filter by “URLs starting with” option for export sitemap.

    Please have a look on attached image to get more clarity.

    GSA Sitemap

    TestNG Annotations Problem

    November 25, 2009 at 2:43 pm | Posted in Java | 2 Comments
    Tags: , ,
    Yesterday one of my colleague come to my desk saying some problem in configuring TestNG in Eclipse. I was surprise because I am using TestNG more than 2 years & never ran into any problem.

    RunInfo] Adding method selector: org.testng.internal.XmlMethodSelector@13f5d07 priority: 10
    [TestNGClassFinder] SKIPPING CLASS class com.test.TestController no TestNG annotations found
    [SuiteRunner] Created 1 TestRunners
    [TestRunner] Running test com.test.TestController on 0  classes,  included groups:[] excluded groups:[]
    [TestRunner] WILL BE RUN IN RANDOM ORDER:
    [TestRunner] WILL BE RUN SEQUENTIALLY:
    [TestRunner] ===
    [TestRunner] Found 0 applicable methods

    This problem is strange to me. Even I used my test classes to my colleagues’ machine, problem not get solved.

    When we started from scratch we observed that in run / debug configurations annotation compliance level is javadoc instead of jdk.

    Because of this setting TestNG enable to read annotations & throws error no TestNG annotations found.

    annotation eclipse Settings for TestNG

    The above image will clarify problem more.

    FindBugs Part 1

    November 23, 2009 at 9:48 pm | Posted in Java | Leave a comment
    Tags: , , , , ,

    FindBugsTM : static code analysis tool

    FindBug is a static code analysis tool that examines your class or JAR files looking for potential problems by matching your byte-code against a list of bug patterns. With static code analysis tool, you can analyze software(s) without actually running the program.

    Getting started with FindBugs:

    To run FindBugs, you will need a Java Development Kit (JDK), version 1.4 or higher. One should download the latest release of FindBugs — currently 1.3.9. After downloading the zip or tar, unzip it into a directory of your choice. That’s it — the install is finished.

    Running FindBugs:

    Like most tools these days, you can run FindBugs in multiple ways — from a GUI, from a command line, using Ant, as an Eclipse plug-in and using Maven.

    Using the FindBugs UI:

    Using the FindBugs UI is straightforward, but a couple of points deserves some elaboration. One of the advantages of using the FindBugs UI is the description provided for each type of detected problem. Descriptions are provided for each bug pattern, which is extremely useful when you’re first becoming acquainted with the tool. Equally useful is the Source code tab in the lower pane of the window. If you tell FindBugs where to find your source, it will highlight the offending line of code when you switch to the appropriate tab.

    It’s also important to mention that if you choose xml as your output option when running FindBugs as an Ant task or from the command line, you can load the results of a previous run into the UI. Doing so is a great way to leverage the advantages of the command-line-based tooling and the UI tooling at the same time.

    For day to day activity developers find Eclipse plug-in is more suitable. But for this blog we will stick to ant as it gives us variety of reports depending upon the provided style sheets.

    Integrate with Ant:

    In build.xml we need to write the following code

    <!– =================================

    target: findbugs

    ================================= –>

    <target name=”findbugs” depends=”compile” description=”description”>

    <taskdef name=”FindBugs” classname=”edu.umd.cs.findbugs.anttask.FindBugsTask”>

    <classpath>

    <pathelement location=”${findbugs.home}/lib/findbugs-ant.jar” />

    </classpath>

    </taskdef>

    <FindBugs home=”${findbugs.home}” output=”html” outputFile=” findbug-report.html”  jvmargs=”-Xms60m -Xmx250m” stylesheet=”default.xsl|fancy.xsl|fancy-hist.xsl|plain.xsl|summary.xsl”>

    <class location=”${webinf.dir}/classes” />

    <sourcePath path=”JavaSource” />

    </FindBugs>

    </target>

    Let’s take a closer look at what’s going on in this code.

    Target: Notice that the target depends on the compile. It’s important to remember that FindBugs works on class files, not source files, so making the target depend on the compile target ensure that FindBugs will be running across the up-to-date class files. FindBugs is flexible about what it will accept as input, including a set of class files, JAR files, or a list of directories.

    Taskdef: Here we define task def name. This is general ANT Practice.

    FindBug.home: One should mention directory that contain findbugs.

    findbugs.home=D:/opt/findbugs-1.3.9

    Output: The optional attribute output specifies the output format that FindBugs will use for its results. The possible values are xml, text, or emacs. If no output File is specified, then FindBugs prints to standard out. The XML format has the added advantage of being viewable within the UI.

    jvmargs: In large projects it is tend to get OutOfMemoryException. To take care of such situation we should pass max and minimum memory by jvmargs. This is optional one.

    Stylesheet: It specifies stylesheet to be used if output is html. This is optional attribute.

    Class / ClassRegex: The class element is used to specify which set of JARs, class files, or directories you want FindBugs to analyze. To analyze multiple JARs or class files, specify a separate class element for each. The class element is required unless the project File element is included. See the FindBugs manual for more details.

    AuxClasspath: You list your application’s dependencies by using the nested element auxClasspath. These are classes that your application needs, but you don’t want FindBugs to analyze. If you don’t list your application’s dependencies, FindBugs will still analyze your classes as well as it can, but it will complain when it is unable to find one of the missing classes. as with the class element, you can specify multiple auxClasspath elements in the FindBugs element. The auxClasspath element is optional.

    SourcePath: If the sourcePath element is specified, the path attribute should indicate a directory that contains your application’s source code. Specifying the directory allows FindBugs to highlight the source code in error when viewing the XML results in the GUI. This element is optional.

    Different Bugs identified by FindBugs:

    • Use Long.valueOf(…) instead of new Long(…)
    • Need to replace things like

    int num = (int) (100000 * Math.random());
    by
    Random r = new Random();
    r.nextInt(100000);

    • concatenation with + , use String Buffer or String Builder
    • change key set by entry set

    Bug categorization:

    FindBug categorize the bugs in following categories

    •  Bad practice Warnings
    • Correctness Warnings
    • Malicious code vulnerability Warnings
    • Multithreaded correctness Warnings
    • Performance Warnings
    • Dodgy Warnings

    Refrences:

    Test Next Generation

    October 26, 2009 at 8:31 pm | Posted in Java | Leave a comment
    Tags: , ,

    Test Next Generation !! Definitely TestNG.

    TestNG is a testing framework designed to simply a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers).

    TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use, such as:

    • JDK 5 Annotations (JDK 1.4 is also supported with JavaDoc annotations).
    • Flexible test configuration.
    • Support for data-driven testing (with @DataProvider).
    • Support for parameters.
    • Allows distribution of tests on slave machines.
    • Powerful execution model (no more TestSuite).
    • Supported by a variety of tools and plug-ins (Eclipse, IDEA, Maven, etc…).
    • Embeds BeanShell for further flexibility.
    • Default JDK functions for runtime and logging (no dependencies).
    • Dependent methods for application server testing.

    TestNG is designed to cover all categories of tests:  unit, functional, end-to-end, integration, etc…

    Writing a test is typically a three-step process:

    1. Write the business logic of your test and insert TestNG annotations in your code.
    2. Add the information about your test (e.g. the class name, the groups you wish to run, etc…) in a testng.xml file or in build.xml
    3. Run TestNG

    Requirements:

    TestNG runs on JDK 1.4 and 5.  The examples shown in this documentation assume JDK 5 and therefore, use JDK 5 annotations, but they can easily be translated to JDK 1.4 JavaDoc-type annotations.

    Integration with other tools:

    TestNG can be integrated with Eclipse, IDEA IntelliJ and NetBeans with plugins.
    Also by ant & maven you can integrate this TestNG to any Java Project.

    Simple Example:

    I am giving simple example from testng.org site to visualize how easy to configure TestNG to in any project.

    package example1;

    import org.testng.annotations.*;

    public class SimpleTest {

    @BeforeClass
    public void setUp() {
    // code that will be invoked when this test is instantiated
    }

    @Test(groups = { “fast” })
    public void aFastTest() {
    System.out.println(“Fast test”);
    }

    @Test(groups = { “slow” })
    public void aSlowTest() {
    System.out.println(“Slow test”);
    }

    }

    The method setUp() will be invoked after the test class has been built and before any test method is run.  In this example, we will be running the group fast, so aFastTest() will be invoked while aSlowTest() will be skipped.

    Things to note:

    • No need to extend a class or implement an interface.
    • Even though the example above uses the JUnit conventions, our methods can be called any name you like, it’s the annotations that tell TestNG what they are.
    • A test method can belong to one or several groups. These groups will be used at runtime to determine what test methods should be invoked..

    Once you have compiled your test class into the build directory, you can invoke your test with the command line, an ant task (shown below) or an XML file:

    <project default=”test”>

    <path id=”cp”>
    <pathelement location=”lib/testng-testng-4.4-jdk15.jar”/>
    <pathelement location=”build”/>
    </path>

    <taskdef name=”testng” classpathref=”cp”
    classname=”org.testng.TestNGAntTask” />

    <target name=”test”>
    <testng classpathref=”cp” groups=”fast”>
    <classfileset dir=”build” includes=”example1/*.class”/>
    </testng>
    </target>

    </project>

    Use ant to invoke it:

    D:> ant
    Buildfile: build.xml

    test:
    [testng] Fast test
    [testng] ===============================================
    [testng] Suite for Command line test
    [testng] Total tests run: 1, Failures: 0, Skips: 0
    [testng] ===============================================

    BUILD SUCCESSFUL
    Total time: 4 seconds

    You can view the results from browser for above file test-output\index.html

    Why TestNG:

    • Parametric Testing Ability: One of my favorite features of TestNG is its parametric testing ability, which allows you to create generic test cases and then vary the test values– you can use parameters from XML files or even use the Data Provider feature for a richer parameter type. In fact, for awhile, because it’s my bag baby, I’ve been espousing TestNG’s out of the box parametric testing features as a reason to use TestNG as an opposed to JUnit for higher level testing. JUnit 4, however, now supports parametric tests– and you’ll find that its parametric testing is rather similar to TestNG’s Data Provider.
    • Configurable Test Suite: Second one should not dirty his/her hands to create test suite. Here you just write xml & you done with your test suite. You can define which test should executed etc.
    • Logical Groups: Other feature is grouping. You can create logical groups which may be class level or method level or both by simply annotations. Suppose you have different packages in BO layer so you can define class level group for Business Layer for all classes. & you can run TestNG only for those groups.
    • Reports: You can generate different reports from email-able reports to deep level reports. You also can generate diff. reports using custom style sheets.

    Reports:

    There are different types of Report generated in one go:

    • Chronological Reports: Methods run, sorted chronologically
    • Alphabetical Reports: Methods run, sorted alphabetically
    • Groups Report: Groups used for this test run
    • Not Run Methods: Methods that were not run
    • Reporter Out: If you used Reporter API provided by TestNG.
    • Emailable-report: Small & Sweet Report may be useful for client or PM.

    If possible just try out in your project. It really worth to try.

    What is reCAPTCHA?

    September 29, 2009 at 3:48 pm | Posted in Java | 2 Comments

    reCAPTCHA is an anti-spam method originating from Carnegie Mellon University which uses CAPTCHAs in a genius way. Instead of randomly generating useless characters which users grow tired of continuosly typing in, risking the possibility that spammers will eventually write sophisticated spam bots which use OCR libraries to read the characters, reCAPTCHA uses a different approach.

    While the world is in the process of digitizing books, sometimes certain words cannot be read. reCAPTCHA uses a combination of these words, further distorts them, and then constructs a CAPTCHA image. After a ceratin percentage of users solve the ‘uknown’ word the same way it is assumed that it is the correct spelling of the word. This helps digitize books, giving users a reason to solve reCAPTCHA forms. Because the industry level scanners and OCR software which are used to digitize the books can’t read the words with which the CAPTCHAs are constructed, it is safe to assume that in-house spam-bot OCR techniques will not be able to bypass the CAPTCHA either.

    You can get more details on following links:

    Springs integration is available at recaptcha4j
    Mailhide Tag available for pretecting email address for Spams.

    reCAPTCHA leaves behind other captcha implementations like kaptcha, jCaptcha, simpleCaptcha etc.

    Next Page »

    Create a free website or blog at WordPress.com. | The Pool Theme.
    Entries and comments feeds.

    Follow

    Get every new post delivered to your Inbox.