Friday, April 8, 2016

Convert Images to PDF

This is a simple program which converts images to PDF.

package imageconversion;

import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.imageio.ImageIO;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Element;

public class ImageToPDF {
 
 public static void main(String args[]) {
  
  try {
   ImageToPDF imgToPDF = new ImageToPDF();
   //convertJPGTOPDFinSpecificFolder(imgToPDF.getRootFolderPathFromConfig());
   convertJPGToPDFInAllTheSubFolders(imgToPDF.getRootFolderPathFromConfig());
   System.out.println("----------------------------------------------------------------------------------------");
   System.out.println("All the JPG images are in '" + imgToPDF.getRootFolderPathFromConfig() 
     + "' folder and it's sub folders, have been converted to PDF successfully");
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 // Reading the root folder path from the configuration file
 private String getRootFolderPathFromConfig() throws IOException {
  InputStream inputStream;
  Properties prop = new Properties();
  String propFileName = "config.properties";
  
  inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
   
  if (inputStream != null) {
   prop.load(inputStream);
  } else {
   throw new FileNotFoundException("Property file '" + propFileName + "' not found in the classpath");
  }
  
  String rootPath = prop.getProperty("rootPath");
  return rootPath;
 }
 
 // This converts JPG images to PDF in root folder specified in configuration file
 private static void convertJPGTOPDFinSpecificFolder(String folderPath) {
  File folder = new File(folderPath);
  File[] listOfFiles = folder.listFiles();

  if (listOfFiles.length == 0) {
   System.out.println("No Image files in the " + folderPath + " directory");
  }
  
  for (int i = 0; i < listOfFiles.length; i++) {
   if (listOfFiles[i].isFile()) {
    
    String fileName = listOfFiles[i].getName();
    String absoluteFilePath = listOfFiles[i].getAbsolutePath();
    
    if (getFileExtension(fileName).equalsIgnoreCase("JPG") || getFileExtension(fileName).equalsIgnoreCase("JPEG")) {
     convertJPGToPDF(fileName, absoluteFilePath);
    }
    
   }
  }
 }
 
 // This is for travel through all the sub folders from the root folder specified in the configuration file
 // and convert JPG images to PDF
 private static void convertJPGToPDFInAllTheSubFolders(String folderPath) {

        File root = new File( folderPath );
        File[] listOfFiles = root.listFiles();

  if (listOfFiles == null) {
   System.out.println("No files in the directory : " + folderPath);
   return;
  }

  for (File file : listOfFiles) {
   if (file.isDirectory()) {
    convertJPGToPDFInAllTheSubFolders(file.getAbsolutePath());
   } else if (file.isFile()) {

    String fileName = file.getName();
    String absoluteFilePath = file.getAbsolutePath();

    if (getFileExtension(fileName).equalsIgnoreCase("JPG") || 
      getFileExtension(fileName).equalsIgnoreCase("JPEG")) {
     convertJPGToPDF(fileName, absoluteFilePath);
    } 
   }
  }
   
 }

 // Method which convert JPG to PDF
 private static void convertJPGToPDF(String fileName, String absoluteFilePath) {
  try {
   String currentFolder = absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(fileName));
   System.out.println("----------------------------------------------------------------------------------------");
   System.out.println("Starting to convert the image '" + fileName + "' to PDF in '" + currentFolder + "'");

   String inputImageFileName = absoluteFilePath;
   String outputPDFFileName = absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf('.')) + ".pdf";

   // Deleting the PDF iff it exists
   deleteExsistingPDF(outputPDFFileName);
   
   // create document object
   Document doc = new Document();
   
   // create pdf writer object to write the document to the output file
   PdfWriter.getInstance(doc, new FileOutputStream(outputPDFFileName));
   
   // get a4 paper size
   Rectangle r = PageSize.A4;
   
   // read the image
   BufferedImage orImg = ImageIO.read(new File(inputImageFileName));
   
   // initialize image width and height
   int width = orImg.getWidth();
   int height = orImg.getHeight();
   // resize the image that is bigger than A4 size
   if (width > r.getWidth())
    width = (int) r.getWidth();
   if (height > r.getHeight())
    height = (int) r.getHeight();
   
   // create a blank buffered image
   BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   
   // create graphic2d object from the buffered image
   Graphics2D g2d = bi.createGraphics();
   
   // draw the original image on the buffered image
   // so the image is resized to fit the A4 paper size if it is bigger
   // than A4 size
   g2d.drawImage(orImg, 0, 0, width, height, null);
   
   // store the image data in memory
   ByteArrayOutputStream bas = new ByteArrayOutputStream();
   ImageIO.write(bi, "png", bas);
   
   // create image from the image data stored in memory
   Image img = Image.getInstance(bas.toByteArray());
   
   // centrally align the image on the pdf page
   img.setAlignment(Element.ALIGN_CENTER);
   
   // open document
   doc.open();
   // add image to the document
   doc.add(img);
   // close the document
   doc.close();
   
   File outputFile = new File(outputPDFFileName);
   System.out.println("'" + fileName + "' was successfully converted to '" + outputFile.getName() + "' in '" + currentFolder + "'");
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 // This is to get the file extension
 private static String getFileExtension(String fileName) {
  if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
   return fileName.substring(fileName.lastIndexOf(".") + 1);
  } else {
   return "";
  }
 }
 
 // This is to delete the existing PDF file
 private static void deleteExsistingPDF(String fileName) {
  File file = new File(fileName);
  String currentFolder = fileName.substring(0, fileName.lastIndexOf(file.getName()));

  if (file.exists()) {
   if (file.delete()) {
    System.out.println("Existing '" + file.getName() + "' was deleted in '" + currentFolder + "'");
   } else {
    System.out.println("Delete operation failed. Please check '" + file + "'");
   }
  }
 }
 
 // This is basic method to convert JPG to PDF. Usage as below
 // String input = "C:\\Users\\sgat001\\Desktop\\Images\\Test1.jpg";
 // String output = "C:\\Users\\sgat001\\Desktop\\Images\\Test1.pdf";
 // imageTopdf(input, output);
 private static void imageTopdf(String input, String output) {
  Document document = new Document();
  try {
   FileOutputStream fos = new FileOutputStream(output);
   PdfWriter writer = PdfWriter.getInstance(document, fos);

   writer.open();
   document.open();
   document.add(Image.getInstance(input));
   document.close();
   writer.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}


Configuration property file as follows

rootPath = C:\\Users\\sgat001\\Desktop\\Images\\

Tuesday, January 13, 2015

How to work with Apache Stratos 4.1.0 with Kubernetes

Below are the simple steps, how to configure Kubernetes cluster and work it with Apache Stratos.

Setup Kubernetes host cluster by cloning and setting up the virtual machines      
Login to Kubernetes master and pull the following Docker image
  • cd [vagrant-kubernetes-setup-folder]
  • vagrant ssh master
  • sudo systemctl restart controller-manager
  • docker pull stratos/php:4.1.0-alpha

Verify Kubernetes cluster status, once the following command is run there should be at least one minion listed
  • cd [vagrant-kubernetes-setup-folder]
  • vagrant ssh master
  • kubecfg list minions

Start Stratos instance and tail the log
  • cd [stratos-home-folder]
  • sh bin/stratos.sh start
  • tail -f repository/logs/wso2carbon.log

Set Message Broker and Complex Event Processor IP addresses to Stratos host IP address in the Kubernetes custer
  • cd [stratos-samples-folder]
  • vim single-cartridge/kubernetes/artifacts/kubernetes-cluster.json

 "property":[
   {
      "name":"payload_parameter.MB_IP",
      "value":"192.168.59.3"
   },
   {
      "name":"payload_parameter.CEP_IP",
      "value":"192.168.59.3"
   }
]


Once the server is started run one of the Kubernetes samples available in the Stratos samples checked out above
  • cd [stratos-samples-folder]
  • cd single-cartridge/kubernetes
  • ./deploy.sh

Monitor Stratos log and wait until the application activated log is printed
  • INFO {org.apache.stratos.autoscaler.applications.topic.ApplicationsEventPublisher} -  Publishing Application Active event for [application]: single-cartridge-app [instance]:single-cartridge-app-1


Thursday, July 24, 2014

How to subscribe and access published API in WSO2 API Cloud

In this video I'm going to show how to subscribe and access published API in WSO2 API Cloud. You can view the first step of this video series from here.



How to create simple API using WSO2 API Cloud and publish it

In this video I'm going to show how to create simple API uisng WSO2 API Cloud and publish it. This is the first step of this video series. You can view the second part of the video "How to subscribe and access published API in WSO2 API Cloud" from here.





Friday, July 18, 2014

SaaS App Development with Windows Cartridge in Apache Stratos

Software as a Service (SaaS) is a software delivery method that provides access to software and its functionalities as a service, and it has become a common delivery model for many business applications. Apache Stratos is a polyglot PaaS framework, which helps to run Tomcat, PHP and MySQL apps as a service on all major cloud infrastructures. It brings self-service management, elastic scaling, multi-tenant deployment, and usage monitoring as well. Apache Stratos has the capability to develop and deploy SaaS applications in different environments, such as Linux and Windows.
In this webinar, Reka Thirunavukkarasu, senior software engineer and Manula Thanthriwatte, software engineer at WSO2 will demonstrate the functionality of SaaS app development in the Windows environment and demonstrate how you can develop a windows cartridge with .NET and deploy the application using Apache Stratos.
Topics to be covered include
  • Introduction to Apache Stratos as PaaS framework
  • Pluggable architecture of different environments to stratos
  • Capabilities of Apache Stratos to provide self service management for your windows environment
  • SaaS app development using .NET in a distributed environment
If you are a windows app developer and seeking ways to provide monitoring, elastic scaling, and security in the cloud for your app, this webinar is for you.

Friday, June 20, 2014

WSO2 Private PaaS Demo Setup

In this video I'm going to show how to configure and run the WSO2 Private PaaS in EC2 environment. You can download WSO2 Private PaaS from here and find the WSO2 Private PaaS documentation from here.


Wednesday, April 16, 2014

How to write subscriber and publisher to JBOSS MQ topic

This Post explains Topics in JBOSS MQ with Subscribing and Publishing. For this we will write two java clients.

  • TopicSubscriber.java to Subcribe for messages
  • TopicPublisher.java to to Publish the messages
First you have to download JBOSS Application Server from here. In this sample I'm using jboss-4.2.2.GA. Before starting the JBOSS application server you have to create a topic in JBOSS server. To do that, you have to create myTopoc-service.xml (you can used what every name you want) under the <JBOSS_SERVER>/server/default/deploy and enter following xml into it.


1
2
3
<mbean code="org.jboss.mq.server.jmx.Topic" name="jboss.mq.destination:service=Queue,name=topicA">
        <depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>

After that you can start the JBOSS application server. From the console log you can verify the topicA was created.

Now you can create the sample project on IDE that you preferred. Also make sure to add client and lib directory jars in the JBOSS application server to the project. Now you can create TopicSubscriber.java and TopicPublisher.java sample programs as follows.

TopicSubscriber.java sample program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package simple;

import java.util.Properties;

import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TopicSubscriber {

    private String topicName = "topic/topicA";

    private boolean messageReceived = false;

    private static javax.naming.Context mContext = null;
    private static TopicConnectionFactory mTopicConnectionFactory = null;
    private TopicConnection  topicConnection = null;

    public static void main(String[] args) {
        TopicSubscriber subscriber = new TopicSubscriber();
        subscriber.subscribeWithTopicLookup();
    }

    public void subscribeWithTopicLookup() {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        properties.put(Context.PROVIDER_URL, "jnp://localhost:1099");
        properties.put("topic." + topicName, topicName);

        try {

            mContext = new InitialContext(properties);
            mTopicConnectionFactory = (TopicConnectionFactory)mContext.lookup("ConnectionFactory");

            topicConnection = mTopicConnectionFactory.createTopicConnection();

            System.out.println("Create Topic Connection for Topic " + topicName);

            while (!messageReceived) {
                try {
                    TopicSession topicSession = topicConnection
                            .createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

                    Topic topic = (Topic) mContext.lookup(topicName);
                    // start the connection
                    topicConnection.start();

                    // create a topic subscriber
                    javax.jms.TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);

                    TestMessageListener messageListener = new TestMessageListener();
                    topicSubscriber.setMessageListener(messageListener);

                    Thread.sleep(5000);
                    topicSubscriber.close();
                    topicSession.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                } catch (NamingException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (NamingException e) {
            throw new RuntimeException("Error in initial context lookup", e);
        } catch (JMSException e) {
            throw new RuntimeException("Error in JMS operations", e);
        } finally {
            if (topicConnection != null) {
                try {
                    topicConnection.close();
                } catch (JMSException e) {
                    throw new RuntimeException(
                            "Error in closing topic connection", e);
                }
            }
        }
    }

    public class TestMessageListener implements MessageListener {
        public void onMessage(Message message) {
            try {
                System.out.println("Got the Message : "
                        + ((TextMessage) message).getText());
                messageReceived = true;
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }

}

TopicPublisher.java sample program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package simple;

import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;

public class TopicPublisher {
    private String topicName = "topic/topicA";

    private static javax.naming.Context mContext = null;
    private static TopicConnectionFactory mTopicConnectionFactory = null;

    public static void main(String[] args) {
        TopicPublisher publisher = new TopicPublisher();
        publisher.publishWithTopicLookup();
    }

    public void publishWithTopicLookup() {
        Properties properties = new Properties();
        TopicConnection topicConnection = null;
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        properties.put(Context.PROVIDER_URL, "jnp://localhost:1099");
        properties.put("topic." + topicName, topicName);

        try {

            mContext = new InitialContext(properties);
            mTopicConnectionFactory = (TopicConnectionFactory)mContext.lookup("ConnectionFactory");
            topicConnection = mTopicConnectionFactory.createTopicConnection();

            try {
                TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

                // create or use the topic
                System.out.println("Use the Topic " + topicName);
                Topic topic = (Topic) mContext.lookup(topicName);

                javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);

                String msg = "Hi, I am Test Message";
                TextMessage textMessage = topicSession.createTextMessage(msg);

                topicPublisher.publish(textMessage);
                System.out.println("Publishing message " + textMessage);

                topicPublisher.close();
                topicSession.close();

                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        } catch (JMSException e) {
            throw new RuntimeException("Error in JMS operations", e);
        } catch (NamingException e) {
            throw new RuntimeException("Error in initial context lookup", e);
        }
    }

}u

You have to used PROVIDER_URL as "java.naming.provider.url" and INITIAL_CONTEXT_FACTORY as "java.naming.factory.initial".

First you have to run TopicSubscriber and then run the TopicPublisher. Here are the output of them.

TopicSubscriber;
Create Topic Connection for Topic topic/topicA
Got the Message : Hi, I am Test Message

TopicPublisher;
Use the Topic topic/topicA
Publishing message SpyTextMessage {
Header {
   jmsDestination  : TOPIC.topicA
   jmsDeliveryMode : 2
   jmsExpiration   : 0
   jmsPriority     : 4
   jmsMessageID    : ID:2-13977171929621
   jmsTimeStamp    : 1397717192962
   jmsCorrelationID: null
   jmsReplyTo      : null
   jmsType         : null
   jmsRedelivered  : false
   jmsProperties   : {}
   jmsPropReadWrite: true
   msgReadOnly     : false
   producerClientId: ID:2
}
Body {
   text            :Hi, I am Test Message
}

}


Java Code Geeks