Author Archives: SARAVANAN SIVAJI

Java program to convert a image into PowerPoint PPT

Here is the Java program that converts (uploads) images into PowerPoint .PPT file using Apache POI libraries.

Use (download) the following combination of Apache POI libraries,

poi-3.11-20141221.jar and poi-scratchpad-3.8.jar

Let’s jump into the program


package com.athavan.examples;

import java.awt.Dimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hslf.model.Fill;
import org.apache.poi.hslf.model.Picture;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;

public class CreatePresentation {

private SlideShow ppt;
private Slide slide;
private Fill fill;
private int idx;
private FileOutputStream out;

public static void main(String[] args) {
CreatePresentation cp = new CreatePresentation();
try {
cp.ppt = new SlideShow();
cp.ppt.setPageSize(new Dimension(100, 50));
cp.out = new FileOutputStream(
"G:\\Saravanan\\Pulse\\slideshow2.ppt");

// use the for loop if you have many images to be uploaded into PPT

// for (int k = 0; k < 1; k++) {
String tmp = "G:\\Saravanan\\Pulse\\Software.PNG";
System.out.println(tmp);
cp.createSlideWithChart(cp, tmp);
// }
// Save PPT
cp.ppt.write(cp.out);
cp.out.close();
} catch (Exception fnfe) {
fnfe.printStackTrace();
}
}

public void createSlideWithChart(CreatePresentation cp, String chartName) {
try {
slide = cp.ppt.createSlide();
slide.setFollowMasterBackground(false);
fill = slide.getBackground().getFill();
fill.setFillType(Fill.FILL_PICTURE);
idx = cp.ppt.addPicture(new File(chartName), Picture.PNG);
fill.setPictureData(idx);
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
}
}

}

Input File: Software.PNG
Output File: slideshow2.ppt

Output:

The above program converts a image into PPT. If we want to upload more images in a folder into PPT, then we can have for loop (which is commented) to achieve the same.

Happy learning and sharing… 🙂

Advertisements

Exception in thread “main” java.lang.NoSuchFieldError: filesystem at org.apache.poi.hslf.HSLFSlideShow.getPOIFSFileSystem(HSLFSlideShow.java:79)

I was trying to convert a image into PPT using JAVA with the help of Apache POI libraries.

I got the below exception

Exception in thread "main" java.lang.NoSuchFieldError: filesystem
at org.apache.poi.hslf.HSLFSlideShow.getPOIFSFileSystem(HSLFSlideShow.java:79)
at org.apache.poi.hslf.EncryptedSlideShow.checkIfEncrypted(EncryptedSlideShow.java:57)
at org.apache.poi.hslf.HSLFSlideShow.(HSLFSlideShow.java:141)
at org.apache.poi.hslf.HSLFSlideShow.(HSLFSlideShow.java:115)
at org.apache.poi.hslf.HSLFSlideShow.(HSLFSlideShow.java:103)
at org.apache.poi.hslf.HSLFSlideShow.create(HSLFSlideShow.java:167)
at org.apache.poi.hslf.usermodel.SlideShow.(SlideShow.java:117)
at com.athavan.examples.CreatePresentation.main(CreatePresentation.java:25)

Solution:

I was using poi-3.11-20141221.jar and poi-scratchpad-3.2-FINAL.jar. That’s went wrong here. Then I replaced the poi scratchpad with latest version, the error gone.

poi-scratchpad-3.8.jar worked well.

poi-3.11-20141221.jar and poi-scratchpad-3.8.jar combinations worked!!

Happy learning and sharing 🙂

java.lang.IllegalStateException: Web app root system property already set to different value: ‘webapp.root’ = [/ApplicationPath1] instead of [/ApplicationPath2] – Choose unique values for the ‘webAppRootKey’ context-param in your web.xml files!

Recently I have deployed two J2EE web application in tomcat web server. Both application uses the log4j. Tomcat server is up and running with no issues.

But at regular interval, one of the J2EE web application was going down. I was digging into the logs and google to find the solution. At regular times, it made us to enter into the tomcat manager page to start the application manually which was down.

Then I have identified the following exception message

java.lang.IllegalStateException: Web app root system property already set to different value: 'webapp.root' = [C:\Program Files\Apache Software Foundation\Tomcat7.0.57\webapps\application1\] instead of [C:\Program Files\Apache Software Foundation\Tomcat7.0.57\webapps\application2\] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files!
at org.springframework.web.util.WebUtils.setWebAppRootSystemProperty(WebUtils.java:156)
at org.springframework.web.util.Log4jWebConfigurer.initLogging(Log4jWebConfigurer.java:117)
at org.springframework.web.util.Log4jConfigListener.contextInitialized(Log4jConfigListener.java:46)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Root cause:

Due to the business requirement, we copied the application1’s code base and created the application2’s code base.
I gave unique names wherever necessary in the configuration files. But still I encountered the above error message. After spending long time, I got the below information about the spring framework

“WARNING: Some containers (like Tomcat) do not keep system properties separate per web app. You have to use unique “webAppRootKey” context-params per web app then, to avoid clashes. Other containers like Resin do isolate each web app’s system properties: Here you can use the default key (i.e. no “webAppRootKey” context-param at all) without worrying. ”

It turns out that the webAppRootKey is a Spring context parameter. It exposes the web application’s root directory as a system property. So, it is the value of the webAppRootKey that provides the name for the system property to use. That’s fine if you’ve just got one webapp in Tomcat. Spring will just choose a default value for this (app.root) and off you go. However, as the warning above notes, Tomcat does not keep system properties separate per webApp. This means that when we get to the second application, the same system property (app.root) is being set to a new value (our second application’s root directory, rather than the first!)

The reason this is occurring at all is that Log4JConfigListener is trying to set the webAppRootKey in both cases. This allows log4J to place log and config files in directories relative to the application root directory, rather than in a fixed path.

I decided the easiest thing was just to use a non-default name for the webAppRootKey for each of my applications.

That is, I fixed this by placing the following context-parameter into each of the web application’s web.xml files:

<code><context-param>
<param-name>webAppRootKey</param-name>
<param-value>uniqueAppRootNamee</param-value>
</context-param></code>

This fixed the problem

Where can we download Spring Framework Jars?

We can download Spring JARs as .zip from the following link

http://maven.springframework.org/release/org/springframework/spring/

Cheers 🙂

how to pass LIKE parameters (values) in NamedParameterJdbcTemplate in Spring

Imagine we have a query

SELECT * FROM ARTICLE WHERE TITLE LIKE ‘%spring%’

As we are using NamedParameterJdbcTemplate, I’d like to pass title as a parameter named title holding the value.

So the query would now be SELECT * FROM ARTICLE WHERE TITLE LIKE ‘%:title%’

Solution:
We have to frame the query as like below in Spring JDBC Code

String final GET_QUERY = "SELECT * FROM ARTICLE WHERE TITLE LIKE '%'||:title||'%'";

So, in our spring code

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("title", title);

NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(
getJdbcTemplate().getDataSource());
list = npjt.query(
GET_QUERY, parameters,
new RowMapper() {....});

EhCache.xml Configuration

<ehcache
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:noNamespaceSchemaLocation=”./ehcache.xsd”>
<!–
CacheManager Configuration
==========================
An ehcache.xml corresponds to a single CacheManager. See instructions below or the ehcache
schema (ehcache.xsd) on how to configure. System property tokens can be
specified in this file which are replaced when the configuration is loaded.
For example multicastGroupPort=${multicastGroupPort} can be replaced with the
System property either from an environment variable or a system property
specified with a command line switch such as -DmulticastGroupPort=4446.

DiskStore configuration
=======================
The diskStore element is optional. To turn off disk store path creation, comment out the diskStore element below. Configure it if you have overflowToDisk or diskPersistent
enabled for any cache. If it is not configured, and a cache is created which
requires a disk store, a warning will be issued and java.io.tmpdir will
automatically be used. diskStore has only one attribute – “path”. It is the
path to the directory where .data and .index files will be created. If the
path is one of the following Java System Property it is replaced by its value
in the running VM. For backward compatibility these are not specified without
being enclosed in the ${token} replacement syntax. The following properties
are translated: * user.home – User’s home directory * user.dir – User’s
current working directory * java.io.tmpdir – Default temp file path *
ehcache.disk.store.dir – A system property you would normally specify on the
command line e.g. java -Dehcache.disk.store.dir=/u01/myapp/diskdir …
Subdirectories can be specified below the property e.g. java.io.tmpdir/one
–>
<diskStore
path=”ehcache.disk.store.dir/ehcache/” />

<!–
Mandatory Default Cache configuration. These settings will be applied to
caches created programmtically using CacheManager.add(String cacheName). The
defaultCache has an implicit name “default” which is a reserved cache name.
–>

<defaultCache
maxElementsInMemory=”10000″
eternal=”false”
timeToIdleSeconds=”120″
timeToLiveSeconds=”120″
overflowToDisk=”true”
diskSpoolBufferSizeMB=”30″
maxElementsOnDisk=”10000″
diskPersistent=”false”
diskExpiryThreadIntervalSeconds=”120″
memoryStoreEvictionPolicy=”LRU” />
</ehcache>

Storage Location are specified by hard coading paths.

Legal values for the path attibute are legal file system paths.

E.g., for Unix: /home/application/cache

The following system properties are also legal, in which case they are translated:
user.home – User’s home directory
user.dir – User’s current working directory
java.io.tmpdir – Default temp file path
ehcache.disk.store.dir – A system property

Subdirectories can be specified below the system property, for example:

java.io.tmpdir/one

becomes, on a Unix system:

/tmp/one

How to get the selected value from drop down (select) box from html using JQuery

<!DOCTYPE html>
<html>
<head>

<script src="scripts/jquery-1.11.1.js"></script>

<script>
$(document).ready(function(){

$('#mydropdown').change( function(){
var selectedValue = $(this).children("option").filter(":selected").val();
if(selectedValue == 'default')
return;
else {
alert(selectedValue);
var data = $(this).children("option").filter(":selected").text();
alert(data);
}
});

$( "#garden" ).change(function() {
var value = $( "#garden option:selected" ).val();
if(value == 'default')
return;
else {
alert(value);
var str = $( "#garden option:selected" ).text();
alert(str);
}
});
});
</script>

</head>

<body>

<form method="post" action="">
<table id="myTable" style="width:100%">
<tr>
<th align="center">
<label>Select LOB</label><span> </span>
<select id="mydropdown" name="mydropdown" style="width:20%">
<option value="default" selected="selected">(Select)</option>
<option value="1">ATHAVAN</option>
<option value="2">SIVAJI</option>
<option value="3">AS</option>
<option value="4">SARAVANAN</option>
</select>
</th>
</tr>
<tr>
<tr align="center">
<label>Select LOB</label><span> </span>
<select id="garden" name="garden" style="width:20%">
<option value="default" selected="selected">(Select)</option>
<option value="1">Flowers</option>
<option value="2">Shrubs </option>
<option value="3">Trees</option>
<option value="4">Bushes</option>
</select>
</tr>
</tr>
</table>
</form>

</body>
</html>

Happy learning and sharing 🙂

Web page layout using DIV element with HTML and CSS

Web page layout using DIV element with HTML and CSS

 

<!DOCTYPE html>
<html style=”width:100%; height:100%”>
<head>
<title>HTML Layouts using DIV, SPAN</title>

<style type=”text/css”>

/*

* { margin: 0; padding: 0; border: 0; }

*/

.headerbutton {
color: #000;
background-color: #003300;
border-width: 1px;
border-style: solid;
border-color: #C0FFFF #00F #00F #C0FFFF;
padding: 0px;
margin: 0px;
width: 95%;
height:5%;
font-weight: bold;
color: white;
}

a.headermenubutton:visited {
text-decoration: none;
color: #000;
background-color: #b5dcb3;
display: block;
padding: 3px;

}

.button {

border-width: 1px;
border-style: solid;
border-color: #C0FFFF #00F #00F #C0FFFF;
padding: 0px;
margin: 0px;
width: 95%;
}

a.menubutton:link, a.menubutton:visited {
text-decoration: none;
color: #000;
background-color: #668566;
display: block;
padding: 3px;

}

.mainheader {

background: url(‘headerbgd.PNG’) repeat top left scroll;
height: 100%;
width: 100%;

}

</style>

</head>
<body style=”width:100%; height:100%; font-family: Georgia, Times New Roman, Serif;”>
<div style=”width:100%; height:100%”>
<div style=”background-color:#b5dcb3; height:10%”>

<!– put this in Header.jsp, if you use Tiles in MVC framework–>
<div class=”mainheader”>
<div> </div>
<h1 style=”color:#b5dcb3;”>Saravanan Sivaji Web Portal</h1>
</div>

</div>
<div style=”background-color:white; height:0.5%”></div>
<div style=”background-color:white; height:84%”>
<div style=”background-color:#b5dcb3; height:100%; width:14%;float:left;”>
<!– put this in Menu.jsp, if you use Tiles in MVC framework –>
<div style=”margin: 1%; border: 1px solid red; height:50%; width:95%; float:left; overflow: scroll”>
<div> </div>
<center><div class=”headerbutton”><span class=”headermenubutton”>Main Menu</span></div></center>
<center><div class=”button”><a href=”” class=”menubutton” title=””>CreditCard</a></div></center>
<center><div class=”button”><a href=”” class=”menubutton” title=””>Payments</a></div></center>
<center><div class=”button”><a href=”” class=”menubutton” title=””>Deposits</a></div></center>
</div>
</div>
<div style=”background-color:white; height:100%; width:0.5%;float:left;”></div>
<div style=”background-color:#b5dcb3; height:100%; width:75%;float:left;”>
<!–put this in Content JSP, if you use Tiles in MVC framework –>
<div style=”margin: 1%; border: 1px solid red; height:95%; width:98%; overflow:scroll”>
<p>Technical Recycle Bin</p><br>
<p>Just for demo purposes I have placed border in red line for inner div</p><br>
<p>This layout has been tested in IE, FireFox and Chrome browsers</p><br>
<p>Version of the browsers I used are IE 7.0.5730.13, Chrome Version 38.0.2125.104 m, FireFox 32.0.3</p>
</div>
</div>
<div style=”background-color:white; height:100%; width:0.5%; float:left;”></div>
<div style=”background-color:#b5dcb3; height:100%; width:10%; float:left;”>
<!–put this in Right Menu JSP, if you use Tiles in MVC framework –>
<div style=”margin: 1%; border: 1px solid red; height:50%; width:95%; float:left;”>
<div> </div>
<div><b>Right Menu</b></div>
</div>
</div>
</div>
<div style=”background-color:white;clear:both;height:0.5%”></div>
<div style=”background-color:#b5dcb3;height:5%;border: 2px solid black”>
<!–put this in Footer JSP, if you use Tiles in MVC framework –>
<div style=”margin:0.2%; background-color:#003300; height:60%;border: 2px solid black; color:white”>
<center>
Saravanan Sivaji Technology Solutions
</center>
</div>
</div>
</div>
</body>
</html>

how to insert double quotes in oracle sql queries?

Recently I came across a requirement to insert a word with double-quotes as values to a column from my Oracle Database table using SQL.

SQL> insert into DEFINITION_TABLE values(6,'Amount of Money Written off','The purpose of
this object is to calculate the amount of money classified as '“uncollectable”' by the bank. It should
ideally be as low as possible, because it directly impacts the financial health of the bank in a negative manner.','Amount of Money Writt
en off= Total amount of money classified as '“uncollectable”'','#','Null','Null','Actual Amount of Money Written off vs Predicted Amount of Money Written off,Amount of Money Written off by Product Type,Amount of Money Written off by Product Type on a Monthly Basis,Amount of Money Written off by Region,Amount of Money Written off by R
egion on a Monthly Basis','Quantitative, Lagging','Credit Cards','Minimization of losses',1);

insert into DEFINITION_TABLE values(6,'Amount of Money Written off','The purpose of this

ERROR at line 1:
ORA-00911: invalid character

So now how to do that????

SQL> insert into GLOSRY_KPI_DEFINITION_TABLE values(6,'Amount of Money Written off','[The purpose of
this KPI is to calculate the amount of money classified as "uncollectable" by the bank. It should ideally be as low as possible, because it directly impacts the financial health of the bank in a negative manner.]','[Amount of Money Written off= Total amount of money classified as "uncollectable"]','#','Null','Null','Actual Amount of
Money Written off vs Predicted Amount of Money Written off,Amount of Money Written off by Product Type,Amount of Money Written off by Product Type on a Monthly Basis,Amount of Money Written off by Region,Amount of Money Written off by Region on a Monthly Basis','Quantitative, Lagging','Credit Cards','Minimization of losses',1);

1 row created.

Use SQUARE BRACKETS [] to wrap the whole column value

insert into TABLE values (‘normal value’, ‘[this column value contains “double” quotes]’, ‘normal value’);

Happy Learning and Sharing 🙂

org.hibernate.HibernateException: No Session found for current thread

I was integrating the Spring and Hibernate on a web application. While do so, I end up with the hibernate exception as follows,

org.hibernate.HibernateException: No Session found for current thread

Solution

First we need to understand that the getCurrentSession() only makes sense inside a scope of transaction. We need to declare an appropriate transaction manager, demarcate boundaries of transaction and perform data access inside it. For example, as follows:

<tx:annotation-driven transaction-manager="hibernateTransactionManager"></tx:annotation-driven>

<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="hibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.saravanansivaji.model.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto} </prop>
</props>
</property>
</bean>

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="${database.driver}"></property>
<property name="url" value="${database.url}"></property>
<property name="username" value="${database.user}"></property>
<property name="password" value="${database.password}"></property>
</bean>

At the service and DAO classes, the getSession() method only makes sense inside a scope of transaction, If you are trying to get sessionFactory.getCurrentSession() without defining your class in transactional scope then you will get above exception because getCurrentSession() can be use only in transactional scope. Please make your class transaction using @Transactional annnotation


@Service("employeeService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;

@Override
@Transactional(readOnly = false)
public List listEmployees() {
return employeeDao.listEmployees();
}
}

And from my DAO class EmployeeDao.java

public List listEmployees() {
try {
return (List) sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
}catch(Exception e) {
System.out.println(e);
return null;
}
}

only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services.