Compress PDFs and combine in Linux

Wanted to reduce the size and also combine a few scanned files in pdf format.

Ghost script was very nifty

gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dPDFSETTINGS=/ebook -sOutputFile=out.pdf scan1.pdf scan2.pdf scan3.pdf scan4.pdf

-dPDFSETTINGS=/ebook – was the key for resolution

-dPDFSETTINGS=/screen   (screen-view-only quality, 72 dpi images)
-dPDFSETTINGS=/ebook    (low quality, 150 dpi images)
-dPDFSETTINGS=/printer  (high quality, 300 dpi images)
-dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs)
-dPDFSETTINGS=/default  (almost identical to /screen)


Refer : http://milan.kupcevic.net/ghostscript-ps-pdf/#refs

Thanks to http://stackoverflow.com/questions/8158584/ghostscript-to-merge-pdfs-compresses-the-result

A Opionion Poll with Live Updates using Atmosphere

Hi all,

My favorite show in television is Airtel Super Singer Junior (that identifies and encourages music talent in kids). The season 3 of the show had its Grand Finale yesterday(26th Oct 2012). Final results were based on the Audience poll. Inspired by this – I wanted to try creating a web app that can leverage the ATMOSPHERE SERVER PUSH to show live updates as votes are being recorded.

I wanted to use Jersey RESTful webservices & a simple HTML form for gathering the VOTES. Reasoning behind this choice was that – existing user flows in applications I work with, have the UI interacts with RESTful webservices to capture data.

I wanted to understand how the java based atmosphere framework can be plugged into this scheme and be used for server push purposes alone. As a week old toddler in Atmosphere – I’m still exploring the framework – so there could be other, probably better integrations possible. But this acted as a very good exercise for me to explore different parts of atmosphere.

So here we go –

1. As a first step – I created a pom.xml (I extended the pom.xml from Atmosphere samples base directory). My pom.xml was again a verbatim replica of the pom.xml shipped with rest-chat sample.

2. I updated the web.xml to redirect all /rest/* URLs to Jersey REST Servlet. Similarly /assp/* (assp was actually airtel super singer poll that was the initial trigger ) URLs to Atmosphere Servlet

3. Next I wanted 2 sets of files

a. Voting related files based on JERSEY REST that consists of

(i) vote.html – basic html form with radio buttons (representing choices in the opinion poll)

(ii) voting.js – my custom script that will send the votes to server through ajax

(iii) VoteResource.java – Jersey REST based resource that will have the @POST method.

(iv) Contestant.java – A simple POJO with 2 attributes – contestantName, noOfVotes. For making sure that the noOfVotes  is incremented in a consistent way from multiple threads of the web application – I used a atomic long ( incrementAndGet is used to increment the votes)

(v) VoteMap.java – For the purposes of this post – this will be our in memory store and will be modeled as a singleton. This will contain a ConcurrentHashMap<String,Contestant> – contestantName will be the key and the instance of Contestant POJO will be the value.

In a typical flow – users will visit vote.html to make their choice for the opinion poll. This information will be posted back to server through ajax. @POST method in VoteResource will be invoked to record the vote. The contestantName will be used to lookup the Contestant instance from the voteMap. Increment method of Contestant POJO will use increment method of atomic long to increment the votes.

After updating the no of votes – it has to send a update to all the connected clients through server push. It will use the

MetaBroadcaster.getDefault().broadcastTo(“/”, VoteMap.getInstance().toString());

Above line does the magic to sending the JSON containing contestants and votes to clients.

For purposes of this post – I overrode the toString method of Contestant & VoteMap to return a JSON representation of these objects. I would definitely look forward to making use of automatic JSON conversion using JAXB / Jackson Mapping capabilities of Jersey.

Till now – this has been a regular JERSEY REST project that records the vote choices from UI sent through ajax.

b. Server Push related files that will display the results sent periodically through server push.

(i) results.html – a simple HTML file that will display the results of the poll as a bar chart

(ii)application.js – will use atmosphere based javascript APIs to connect to the server. Further everytime, server sends a update – it will parse the JSON to update the graph

(iii) jqBarChart.js – third party http://www.workshop.rs/jqbargraph/ that will be used for plotting the graph

(iv) AsspResource.java – Main Atmosphere based resource. It has a @GET method annotated additionally @Suspend. As explained in docs – requests to this resource through GET method will be suspended.

When a broadcaster sends data – it is received by these suspended broadcasters

I’m cleaning up the source code removing all unnecessary code – would attach the same soon!!

Here we go – I’ve uploaded the source code zip file to ubuntu one – rest-assp.zip

 

Getting started with Atmosphere

Atmosphere is a cool framework – I wanted to run atmosphere samples in my ubuntu 12.10

sai@sai-home:~$ git clone https://github.com/Atmosphere/atmosphere

sai@sai-home:~$ cd atmosphere/

sai@sai-home:~/atmosphere$ ls
integration-tests  modules  README.md  scripts
license            pom.xml  samples    tmpFile

sai@sai-home:~$ cd samples

sai@sai-home:~/atmosphere/samples$ mvn clean install

This did the magic of creating all the different war files in the target directory of each of the samples.

I then tried deploying the war files to tomcat 7 – but somehow it was not working. Worked very fine with Jetty 8.1.

sai@sai-home:~/atmosphere/samples$ cd ~/Downloads/jetty-distribution-8.1.7.v20120910/
sai@sai-home:~/Downloads/jetty-distribution-8.1.7.v20120910$ java -jar start.jar jetty.port=9090

Launch the sample by launching for instance the atmosphere-chat-sse

http://localhost:9090/atmosphere-chat-sse/

I could chat from 2 tabs.

Now that I have the samples working in jetty – I’d be trying my own samples in the next few days. Also I’d be interested in getting this to run in tomcat 7 as well

I found that the chat-sse sample was already fine in tomcat 7. Only atmosphere-twitter-live-feed sample was NOT working with tomcat 7. I was checking firebug what was happening when the application was deployed with tomcat 7. Found that the js files were not getting downloaded from the webapp context path for atmosphere-twitter-live-feed.

So after some debugging – I found the servlet mapping in web.xml

<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

I just had a thought that this could intercept all requests including those for static resources. So I changed it to

<servlet-mapping>
<servlet-name>AtmosphereServlet</servlet-name>
<url-pattern>/tweet/*</url-pattern>
</servlet-mapping>

And in the index.html – I had to update the URL to which client sends a subscribe request

function subscribe() {
var request = { url : document.location.toString() + ‘/search/’ + getElementByIdValue(‘topic’),
transport: getElementByIdValue(‘transport’),
trackMessageLength : true
};

to

function subscribe() {
var request = { url : document.location.toString() + ‘/tweet/search/’ + getElementByIdValue(‘topic’),
transport: getElementByIdValue(‘transport’),
trackMessageLength : true
};

Bingo!! it is working now in tomcat 7 as well

http://stackoverflow.com/questions/132052/servlet-for-serving-static-content – seems to indicate this difference in behavior

Server Push In Java with Atmosphere

After socket.io and node.js – I wanted to check if there is something that can be useful for enterprise java webapps that are typically deployed into Tomcat.

I had read about Jetty Supporting Server push and tomcat 7 having something similar.

Wanted something that will have server and client side pieces – very similar to socket.io on node.

Stumbled upon Atmosphere – https://github.com/Atmosphere/atmosphere

The only Portable WebSocket/Comet Framework supporting Scala, Groovy and Java — Read more

http://jfarcand.wordpress.com

Will start my exploration on that

Server push with node.js and socket.io

Continuing my exploration on Node.js – I started working on the server push. I had read that socket.io (a node.js module).

Since I had node installed in my Ubuntu 12.10 (64-bit) – I was able to get the basic example done in 5 minutes.

1. Create a directory serverpush and go into that directory

sai@sai-home:~$ mkdir serverpush
sai@sai-home:~$ cd serverpush/

2. Create a package.json in the serverpush directory

{
“name”: “serverpush”,
“version”: “0.0.1”,
“private”: true,
“scripts”: {
“start”: “node app”
},
“dependencies”: {
“socket.io”: “~0.9.6”
},
“engines”: {
“node”: “0.8.x”
}
}

3. To install all dependancies – we need to use npm (node package manager) that uses the information in package.json

sai@sai-home:~/serverpush$ npm install -d

The above command installed all missing dependencies

4.Next is to create the node.js server file called app.js

var app = require(‘http’).createServer(handler)
, io = require(‘socket.io’).listen(app)
, fs = require(‘fs’)

app.listen(8888);

function handler (req, res) {
fs.readFile(__dirname + ‘/index.html’,
function (err, data) {
if (err) {
res.writeHead(500);
return res.end(‘Error loading index.html’);
}

    res.writeHead(200);
res.end(data);
});
}
function sendData(socket){
var thisRef = this;
var currentTimeObj = new Date();

// though there are better ways to format time – living with this for the time being
var formattedTime = currentTimeObj.getDate() + “-” +currentTimeObj.getMonth() + “-” + currentTimeObj.getFullYear() + ” ” + currentTimeObj.getHours() + “:” + currentTimeObj.getMinutes() + “:” + currentTimeObj.getSeconds();
socket.emit(‘timeUpdate’, { currentTime:  formattedTime});
setTimeout(function(){
sendData.call(thisRef,socket)
},1000);
}

io.sockets.on(‘connection’, function (socket) {
socket.emit(‘welcomeMessage’, { welcome: ‘Welcome to server poller’ });
sendData(socket);
});

4. Create the index.html that will be used as the client code

<!DOCTYPE html>
<html>
<head>
<title>Server Time poller</title>
<meta charset=”UTF-8″>
</head>
<body>
<div id=”statusMessageDiv”>

</div>
<div id=”serverTimeDiv”></div>
</body>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js”></script&gt;
<script src=”/socket.io/socket.io.js”></script>
<script>
$(document).ready(function(){
var socket = io.connect(‘http://localhost&#8217;);
socket.on(‘welcomeMessage’,function(data){
$(“#statusMessageDiv”).html(data.welcomeMessage);
});
socket.on(‘timeUpdate’, function (data) {
$(“#serverTimeDiv”).html(data.currentTime);

});
});
</script>
</html>

5. Run the server file using node

sai@sai-home:~/serverpush$ node app.js
info  – socket.io started

6. Launch the server through browser http://localhost:8888 – we will see our server time running

That’s it  – really amazed at the productivity with Node.js

Planning to use server push to write a twitter clone next 🙂

Node.js Error: listen EACCES

I was really looking forward to get started with Node.js. Wrote a very small program called eg1.js

<code>

console.log(“Hello node”);
var http = require(‘http’);
var url = require(‘url’);
http.createServer(function (req, res) {
console.log(“Request: ” + req.method + ” to ” + req.url);
res.writeHead(200, “OK”);
res.write(“<h1>Hello</h1>Node.js is working”);
res.end();
}).listen(81); // LOOK AT THIS
console.log(“Ready on port 8081”);

</code>

When I ran it

sai@sai-home:~/nodes$ node

Hello node
Ready on port 8081

events.js:68
throw arguments[1]; // Unhandled ‘error’ event
^
Error: listen EACCES
at errnoException (net.js:769:11)
at Server._listen2 (net.js:892:19)
at listen (net.js:936:10)
at Server.listen (net.js:985:5)
at Object.<anonymous> (/home/sai/nodes/example1.js:9:4)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)

As we could the console.log are print – so I was thinking about the other anonymous calls – eaily understood that it was the listen call that failing.

But I was confused as 81 was a free port (confirmed thro netstat as well).

Thanks to stackoveflow

http://stackoverflow.com/questions/12127293/writing-a-node-application-and-encountering-an-error-when-running-node-server-j

I needed to change the port to something > 1024 or use sudo while running the program

Prime Number puzzle

Consider all prime number pairs separated by just one number (like <5,7>, <11,13>….etc). We can clearly observe that the number in between is divisible is 6.

Can we prove that this is always be true for any pair of prime numbers.

Solution :
Let the prime numbers be n, n+2. Our case is to prove n+1 is divisible by 6, ie n+1 is divisible by 2 and 3.

In this case – since n is prime, it will be odd – so we can easily say n+1 will be even, divisible by 2

Next is to prove it is divisible by 3 as well. This proved to be baffling for me.

Later realized – for any 3 consecutive numbers, atleast one of them should always be divisible by 3. This is true for any 3 consecutive numbers as multiples of 3 repeat at that interval.

So definitely one of n,n+1,n+2 should be divisible by 3. Since n and n+2 are prime – they cannot be multiples of 3 – so n+1 should be a multiple of 3.

Doctor puzzle

I was recently given this puzzle in a interview discussion

A patient is given 2 vials of tablets labeled A & B. He has to take one tablet from each vial daily. Neither can he skip nor can he take overdose – as these would prove fatal.

One day – aftert taking one tablet from vial A, 2 fall from vial B. Now he has 1A and 2Bs. By a clever logic – he manages to avoid overdose even though there is no way to differentiate the tablets to be from A or B. They are same in color, texture, size, appearance etc etc.

Solution : (Thanks to the interviewer who patiently helped me with some clues)

He divides the tablets into halves. He gets 2 pieces of each. After this he consumes one half of this ==>

1/2B + 1/2B + 1/2A = 1B + 1/2A. To avoid under dosage – he takes a new tablet from vial A, consumes half of it. The remaining half of this A and the remnants from breaking done in step before, are preserved and he uses them for the next day 🙂

Clever 🙂