Generate Unique number With AtomicLong


import java.util.concurrent.atomic.AtomicLong;

public class UniqueNumGenerator {

    //initial value is 0
    private static AtomicLong uniqueCounter = new AtomicLong(0);

    public static long nextId() {
        return uniqueCounter.incrementAndGet();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            System.out.println(UniqueNumGenerator.nextId());
        }
    }
}

Copy files from host to Docker container and vice versa

Docker command to copy/update the files from host to container

   Command: 
   docker cp LOCALFILE_WITH_PATH CONTAINER_NAME:DEST_PATH
   Example: 
   docker cp config.xml CONTAINER_NAME:/opt/app/config.xml

Docker command to copy the files from container to local host

   Command:
   docker cp CONTAINER_NAME:SOURCE_PATH LOCALDIRPATH
   Example:
   docker cp CONTAINER_NAME:/opt/app/config.xml .

Replace the CONTAINER_NAME appropriately

Apache POI – Add title and page number in Xlsx file


import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HeaderFooter;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFHeaderFooter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class ExcelMain {

    public static void main(String[] args) throws IOException {

        //Initialize xlsx and create sheet and row
        FileOutputStream fileOutputStream = new FileOutputStream(new File("/tmp/header.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet xssfSheet = workbook.createSheet("sheet0");
        XSSFRow xssfRow = xssfSheet.createRow(0);
        XSSFCell cell = xssfRow.createCell(0);
        cell.setCellValue("Test");

        //Set the Page margins
        xssfSheet.setMargin(Sheet.LeftMargin, 0.25);
        xssfSheet.setMargin(Sheet.RightMargin, 0.25);
        xssfSheet.setMargin(Sheet.TopMargin, 0.75);
        xssfSheet.setMargin(Sheet.BottomMargin, 0.75);
        xssfSheet.setAutobreaks(true);
        xssfSheet.setFitToPage(true);
        xssfSheet.setPrintGridlines(true);

        //Set the Header and Footer Margins
        xssfSheet.setMargin(Sheet.HeaderMargin, 0.25);
        xssfSheet.setMargin(Sheet.FooterMargin, 0.25);

        //Setup print layout settings
        XSSFPrintSetup layout = xssfSheet.getPrintSetup();
        layout.setLandscape(true);
        layout.setFitWidth((short) 1);
        layout.setFitHeight((short) 0);
        layout.setPaperSize(PrintSetup.A4_PAPERSIZE);
        layout.setFooterMargin(0.25);

        XSSFHeaderFooter header = (XSSFHeaderFooter) xssfSheet.getHeader();
        header.setCenter(HSSFHeader.font("Calibri", "Bold") + HSSFHeader.fontSize((short) 20) + "TITLE");
        header.setRight(HSSFHeader.font("Stencil-Normal", "Bold") + HSSFHeader.fontSize((short) 15) + "Page Number: " +
                HeaderFooter.page());

        workbook.write(fileOutputStream);

    }
}

Itext PDF- Header – Add title and page number


import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ItextMain {

    public static void main(String[] args) throws DocumentException, FileNotFoundException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/home/bala/itextheader.pdf"));
        PdfHeader event = new PdfHeader();
        writer.setPageEvent(event);
        document.open();
        document.addAuthor("Balachandar");
        document.add(new Paragraph("Hello World!"));
        document.newPage();
        document.add(new Paragraph("Hello World!"));
        document.newPage();
        document.add(new Paragraph("Hello World!"));
        document.close();
    }

    public static class PdfHeader extends PdfPageEventHelper {

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            try {
                Rectangle pageSize = document.getPageSize();
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Title"), pageSize.getLeft(275), pageSize.getTop(30), 0);
                ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(String.format("No:%s", String.valueOf(writer.getCurrentPageNumber()))),
                        pageSize.getRight(30), pageSize.getTop(30), 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}

Remote Debugging in Intellij Idea IDE

Follow the below steps to perform the remote debugging in Intellji Idea IDE

1. Start the java application with the below Java options


-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9995

Ex:
java -jar -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9995 application.jar

Here “application.jar” is the actual jar file which we have

2. Open up the Intellji Idea IDE and click on Run ➝ Edit Configuration, then Select Remote and click on + sign on the menu bar. It will open up a Remote Debug config window. Just change the port number to 9995 and Host accordingly and click on “Apply” and “OK”

3. Open up the Run window, you will see the “Debug “Remote”” option. When you click on it, you will be going to remote debug mode.

4. Then Put up some break points in your code.
5. Access the application from the browser or by running any process
6. The remote process will get started and it will be stopped at the break point. You can continue with the debugging process from there with all the debug options

How to show XML in wordpress page

If we post the XML in a wordpress post, then it wont show properly. So we have to convert the <, > tags to HTML entities appropriately.  If its a small XML, then we can do it easily, but if its a big one, then its somewhat tedious.  I am using the below approach to handle this.

Access this online utility Free Formatter and convert the html tags with appropriate entities. Then add those snippet in the post surrounding with <pre><code> tags.

Please refer the below example,


<person>
<name>bala</name>
<age>90</age>
</person>

How to use Docker Maven plugin

Recently, I have explored on various Docker Maven plugins and used https://github.com/fabric8io/docker-maven-plugin as its somewhat easy. Please note that as of now, this does not have support to integrate with Docker compose file. But it provides a lot of configuration tags by using which we can completely replace all the configurations found in a docker compose file.

Assume that we have two Restful services running on port number 8080, 8081 respectively. Both are entirely different. The first Restful application runs on 8080 access the second Restful application running on port number 8081. Refer below the snippet of pom.xml which uses the docker maven plugin


<build>
    <plugins>
        <plugin>
            <groupId>io.fabric8</groupId>
            <artifactId>docker-maven-plugin</artifactId>
            <version>0.15.1</version>
            <configuration>
                <images>
                    <!-- Application 1 -->
                    <image>
                        <name>middleware-rest</name>
                        <alias>middleware-rest</alias>
                        <build>
                            <cleanup>true</cleanup>
                            <tags>
                                <tag>latest</tag>
                            </tags>
                            <ports>
                                <port>8080</port>
                            </ports>
                            <dockerFileDir>middleware-rest</dockerFileDir>
                            <assembly>
                                <mode>dir</mode>
                                <inline xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
                                    <id>middleware-rest</id>
                                    <files>
                                        <file>
                                            <source>${project.build.directory}/mwRest-${project.version}-appjar.jar</source>
                                            <outputDirectory>./</outputDirectory>
                                            <destName>mwRest.jar</destName>
                                        </file>
                                    </files>
                                </inline>
                            </assembly>
                        </build>
                        <run>
                            <namingStrategy>none</namingStrategy>
                            <ports>
                                <port>8080:8080</port>
                            </ports>
                            <wait>
                                <tcp>
                                    <ports>
                                        <port>8080</port>
                                    </ports>
                                </tcp>
                                <time>60000</time>
                            </wait>
                            <env>
                                <CLIENT_MW_URL>http://client-middleware-rest:8080</CLIENT_MW_URL>
                            </env>
                            <links>
                                <link>client-middleware-rest:client-middleware-rest</link>
                            </links>
                            <log>
                                <enabled>true</enabled>
                                <color>red</color>
                                <driver>
                                    <name>json-file</name>
                                    <opts>
                                        <max-size>10m</max-size>
                                        <max-file>5</max-file>
                                    </opts>
                                </driver>
                            </log>
                        </run>
                    </image>
                    <!-- Application 2  -->
                    <image>
                        <name>client-middleware-rest</name>
                        <alias>client-middleware-rest</alias>
                        <build>
                            <cleanup>true</cleanup>
                            <tags>
                                <tag>latest</tag>
                            </tags>
                            <ports>
                                <port>8081</port>
                            </ports>
                            <dockerFileDir>client-middleware-rest</dockerFileDir>
                            <assembly>
                                <mode>dir</mode>
                                <inline xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
                                    <id>client-middleware-rest</id>
                                    <files>
                                        <file>
                                            <source>${project.build.directory}/clientmwRest-${project.version}-appjar.jar</source>
                                            <outputDirectory>./</outputDirectory>
                                            <destName>clientmwRest.jar</destName>
                                        </file>
                                    </files>
                                </inline>
                            </assembly>
                        </build>
                        <run>
                            <namingStrategy>none</namingStrategy>
                            <ports>
                                <port>8081:8081</port>
                            </ports>
                            <wait>
                                <tcp>
                                    <ports>
                                        <port>8081</port>
                                    </ports>
                                </tcp>
                                <time>60000</time>
                            </wait>
                            <log>
                                <enabled>true</enabled>
                                <color>red</color>
                                <driver>
                                    <name>json-file</name>
                                    <opts>
                                        <max-size>10m</max-size>
                                        <max-file>5</max-file>
                                    </opts>
                                </driver>
                            </log>
                        </run>
                    </image>
                </images>
            </configuration>
            <executions>
                <execution>
                    <id>start</id>
                    <phase>pre-integration-test</phase>
                    <goals>
                        <goal>build</goal>
                        <goal>start</goal>
                    </goals>
                </execution>
                <execution>
                    <id>stop</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                    </goals>
                </execution>
                <execution>
                    <id>remove</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>stop</goal>
                        <goal>remove</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

So once you have this configuration, then we can build the containers by running mvn docker:build

To start all the containers, run mvn docker:start
To stop all the containets, run mvn docker:remove

For further information, Please access https://github.com/fabric8io/docker-maven-plugin

Also refer my other post to know more about this Rest API to produce message to Kafka using Docker Maven Plugin