How we can set environment variables in Docker?

May 16, 2017 at 11:41 am | Posted in Docker | Leave a comment

While working with docker, sometimes we want to set specific environment variables. We can set up environment variables by using different ways.

Solution 1:
One can pass parameters by using -e param while running docker run command.

-e JAVA_OPTS=”-Xmx1G” or –env JAVA_OPTS=”-Xmx1G”

While executing docker run command you can pass environment parameter by following command

$ docker run -d -p 80:9080 -p 443:9443 \
-e JAVA_OPTS=”-Xmx1G” \
-v {your}.war:/{your_path}/{your}.war \
{your_image_file}

Just like -e one can use env_file option. Using this option one can write all environment variables in one file in similar syntax we used in properties file.

Solution 2: Use docker-compose.

Using docker compose file, one can set environments. Although we are not harnessing real power of docker compose in following example, you can see docker compose makes configuration very easy to understand. I like docker compose due to it’s simplicity, easy to share and execute.

version: “2”
services:
MyService:
image: {image which you are going to use}
ports:
– “80:9080”
– “443:9443”
volumes:
– ./{your}.war:/{your_path}/{your}.war
environment:
– “JAVA_OPTS=-Xmx1G”

In docker compose, one can use env_file instead of environment.

Solution 3: Create / extend image.

This solution is far complex for our scenario. But still yes, one can create custom image with needed environment details by writing custom image in dockerfile. Creating image just for setting up environment variables is definitely not a good idea, but useful if you already having image or extending some image.

One can use following command in docerfile:

RUN export JAVA_OPTS=”-Xmx1G”

 

Advertisements

JDBC Specs 4.3 Sneak Peek

April 28, 2017 at 12:10 pm | Posted in Java | Leave a comment

What is JDBC 4.3 Specs / API ?
This is nothing but proposed changes for Maintenance Release 3 which are recently published on JCP site. One can think of this as an extension of JSR 221.

If you see history then you will come to know that every JDK version (Exception 1.3 & 1.5) JDBC specs changed.

  • Since 9 — new in the JDBC 4.3 API and part of the Java SE platform, version 9
  • Since 1.8 — new in the JDBC 4.2 API and part of the Java SE platform, version 8
  • Since 1.7 — new in the JDBC 4.1 API and part of the Java SE platform, version 7
  • Since 1.6 — new in the JDBC 4.0 API and part of the Java SE platform, version 6
  • Since 1.4 — new in the JDBC 3.0 API and part of the J2SE platform, version 1.4
  • Since 1.2 — new in the JDBC 2.0 API and part of the J2SE platform, version 1.2
  • Since 1.1 or no “since” tag — in the original JDBC 1.0 API and part of the JDK™, version 1.1

In short if you look for JDK 9 preview release then you can see updated new JDBC 4.3 API’s which are not formally published.

What are proposed changes?

  • Added Sharding support
  • Enhanced Connection to be able to provide hints to the driver that a request, an independent unit of work, is beginning or ending
  • Enhanced DatabaseMetaData to determine if Sharding is supported
  • Added the method drivers to DriverManager to return a Stream of the currently loaded and available JDBC drivers
  • Added support to Statement for enquoting literals and simple identifiers
  • Clarified the Java SE version that methods were deprecated

 

What is Sharding Support :

Main notable feature is Sharding Support. For Sharding, JDBC API added 2 classes ShardingKeyBuilder & ShardingKey and obvious changes in DatabaseMetadata class, Connection related interfaces.

Sharding is a method of splitting and storing a single logical dataset in multiple databases. By distributing the data among multiple machines, a cluster of database systems can store larger dataset and handle additional requests.

In today’s distributed world Shrading is key and modern databases like Cassandra, HBase, SQLite, MongoDB natively supports shrading.

 

Where I can see JDBC API difference?

You can find links on Java Community Process for JSR 221 to fetch proposed changes & java doc diff.

JDBC 4.3 Ref:

 

Is static method in Util Class ThreadSafe?

July 29, 2016 at 3:40 am | Posted in Java | Leave a comment

Recently one person ask me this question and my obvious answer was “OK, This should not be any problem to Threads…”. I am from old school and believed that most of time all thread related problems will run away if you stick to local variables. Am I correct?

Continue Reading Is static method in Util Class ThreadSafe?…

Spring Boot – 1

July 16, 2016 at 2:30 am | Posted in Java, Spring | 1 Comment

Unfortunately I never get any hands-on Spring Boot, (although I worked on various Spring based projects) so I started my own project in Spring Boot. I am sharing my experiences here in this blog.

Continue Reading Spring Boot – 1…

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 | 5 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

    Next Page »

    Blog at WordPress.com.
    Entries and comments feeds.