Read and Write Images to files in Java

While working with Images we often think images I/O is similar to any other File I/O, I recently faced a situation when I had to work with Images in Java.

There might be several other ways to do it, I liked it through ImageIO utility.

Read Image

   1: //read it from a file.
   2: BufferedImage fromFile = File("path to the file"));
   3: //read it from an InputStream
   4: Buffered fromIs = FileInputStream("path to the file"));
   5: //read it from a URL
   6: Buffered fromUrl = URL("a URL for the image"));

Write Image

   1: //Read the Image from a byte Array - I am assuming the Image coming from a stream

   2: BufferedImage image = ByteArrayOutputStream(bytearray));

   3: //Write the image to a file
   4: ImageIO.write(image,"GIF",new FileOutputStream("path to the file"));


Browser/Web caching


Flex and in general Flash applications are known for its caching both in a good and a bad way. Good way that it decreases the per call transfer size by caching all the core libraries necessary for frequent calls. Bad way it caches everything.

So in this document we are going to understand the term we know and call as “Browser/Web cache”. Once we understand it, we will solve the problem that can occur because of this caching.

Web Cache

A web cache is a mechanism for the temporary storage (caching) of web documents, such as HTML pages and images, to reduce bandwidth usage, server load, and perceived lag.

In detail, a web cache is a temporary storage place for data content requested from the Internet. After an original request for data has been successfully fulfilled, and that data has been stored in the cache, further requests for those files (e.g., HTML pages, images) results in the information being returned from the cache, if certain conditions are met, rather than the original location.

Need for Web Caching

Consider a simple scenario – a Librarian. He is there to help you by giving you books you ask for. Every time a reader comes and asks for a book the librarian has to go to stack to search the book and then give to the reader. If a book is asked for again and again, the most efficient way for Librarian is to have a small drawer next to his desk, which is easily accessible and keep the books recently read or are popular.

In the analogy given above you can identify Librarian as the browser, the book as the content and reader as user.

Flex/Flash application and Web caching

The Flex/Flash applications harness the “Caching” using Flash Player Cache and RSLs. But when it comes to the web caching (which is quite different from Flash Player Cache) it has issues. Browser treats the flex/flash applications to be an object and caches the complete object in the cache.

What’s the problem?

Caching is a well known and widely used mechanism. Then where is the problem? Here are few problems observed –

“The new patches to the application need a browser cache to be cleaned”

Versioning can be a solution!!!

Versioning is considered to be the most important part of any software deployment/development process. An intelligent versioning can be a solution to this above problem.

So here is the scenario, how we will versioning to solve this problem –

  1. Build the project
    1. Most probably the versioning will come into picture when the deployment phase comes.
    2. Build normally should be automated ant/Hudson
  2. Create a version number –
    1. When you a build a project, either through Ant or Hudson make sure you generate a version number.
      1. Version number can be, at its simplest form, an auto increment value that increments with each build.
    2. Hudson automatically generates the variable named – “BUILD_NUMBER”.
  3. Append Version to the generated SWF
    1. This can be done either through command line or in your build file, while compiling the SWF file, Suppose you’re compiling “cre.mxml” and the current generated version number is 44 make your output file to be named as “cre_44.swf”.
  4. Use FlashVars to make your SWF version-aware, to handle Module Loading
    1. FlashVars are the variables/parameters that can be sent from html to flex/flash object as initialization parameter, directly accessible from within the application
  5. Make your HTML wrapper to load new versioned SWF
    1. Tweak your HTML wrapper to load the new cre_44.swf

How we implemented-

We had a problem in hand, and idea in mind. We have the process in place.

  • Ant for building the application
  • Hudson for deployment – will use the generated version number.

Code changes done –

  • In the ant file we did the following change
    • Include the environment variable to access the global variables.
  • Changed the mxmlc task to append the version to the output file.

  • Change the Wrapper to include the new version-ed file
  • If an application uses Modules, which mostly would be the case, Even the modules have to be versioned, for that we have to make our application version-aware*
    • For this there are significant changes that are needed
      • Create a custom html wrapper ( not using the html-wrapper )
      • Use token replacing functionality of the application to include custom attribute (build-number) to be included into the system.
      • Pass the build-number as a parameter to Flex application through FlashVars( can be defined in index.template.html)

Creating Custom Html-Wrapper

“Html-wrapper” task provided by FlexTasks.jar has one problem – you can’t pass your custom attribute to the template file. For example if you want to pass the BUILD_NUMBER to be included as the attribute to index.template.html, it is not possible with html-wrapper. So here is what you should to create a custom html-wrapper –

  1. Make the Template
    1. To create the placeholders use @place_holder@ instead of ${place_holder} that is used with traditional “html-wrapper”
  2. In ant create the Generate-Html target

Flash Player Caching

The Flash Player cache is a new feature available in Flash Player 9 update 3 and above. The cache allows files signed by Adobe to be cached by Flash Player. These files end with the file extension .swz

Flash player caching differs from the browser cache in a slight way-

  • The cached SWZ files can be reused in more than one domain and not limited to the domain in which they were originated.
  • The SWZ files persist indefinitely, even after the browser is closed.
  • The storage location and management is different

Flex and Flash Player Cache

Flex 3 is the first technology to take advantage of Flash Player cache. In Flex 3 the framework library code is rolled into Runtime Shared Libraries (RSL). An RSL can be either SWZ(signed) or SWF(unsigned) and loaded at runtime instead of statically linked.

Proxy Configuration issue in Eclipse


When you work in a web-proxy, you might a problem while installing a plugin in Eclipse  “Proxy authentication required” : This simply means that you need to provide the authentication that your proxy web-server requires. To Solve this problem you might have tried changing the user authentication by going to Window –> Preferences –> General –> Network Connections and select Manual  from the dropdown list and then in the Proxy entries grid change the authentication by clicking on Edit button

I also tried the above solution but It didn’t work for me
So what I did was a simple trick:

  • Go to eclipse installation directory and open eclipse.ini
  • Add the following lines ( of course fill in the proper details for the parameters )


So this might work for you also.

Enjoy !

Resume download using .part file in mozilla


So by the time my file is getting downloaded, Thought of writing a small trick that I found out. We all might have faced a situation where we download a file and after 90% the download breaks saying that the source is not accessible [obviously because of internet link  failure], then thinking of downloading that file is like waste of time.

Here is what you can do, the next time something like this happens to you:

  • Go to the downloads folder [or the folder where you downloaded the file to]
  • Copy both file and its .part file to some different folder say temp_dir
  • From your browser go to the download link again and download the same file.
  • After it downloads few bytes, just pause the download
  • Copy the file and .part  from the temp_dir folder
  • Replace the current downloaded file and .parts with the copied ones.
  • Done ! the file will resume from 90% 😉

Enjoy !

The With Statement in T-SQL – Percentile Calculation


Those who are working with complex SQL might have found a need of using a common intermediate SUB-query result within the execution scope. You can use it with a SELECT, UPDATE, MERGE, INSERT or DELETE. This intermediate result-set is called Common Table Expression. It is even used in Creation of Views.

Here is an example:


So here I have just created the an intermediate table that can be used in Select SQL as a usual table.

The main purpose I am using it is for percentile calculation in SQL-SERVER

DECLARE @percentile FLOAT
SELECT @percentile = .25;

Month= 201011
),emp_sal(DIST_BAL, prev_rank, curr_rank, next_rank) AS
(ROW_NUMBER() OVER ( ORDER BY DIST_BAL ) – 2.0) / ((SELECT COUNT(*) FROM BAL_CALC) – 1) [prev_rank],
(ROW_NUMBER() OVER ( ORDER BY DIST_BAL ) – 1.0) / ((SELECT COUNT(*) FROM BAL_CALC) – 1) [curr_rank],
(ROW_NUMBER() OVER ( ORDER BY DIST_BAL ) + 0.0) / ((SELECT COUNT(*) FROM BAL_CALC) – 1) [next_rank]
ELSE t1.DIST_BAL + (t2.DIST_BAL – t1.DIST_BAL) * ((@percentile – t1.curr_rank) / (t2.curr_rank – t1.curr_rank))
FROM emp_sal t1, emp_sal t2
WHERE (t1.curr_rank = @percentile OR (t1.curr_rank < @percentile AND t1.next_rank > @percentile))
AND (t2.curr_rank = @percentile OR (t2.curr_rank > @percentile AND t2.prev_rank < @percentile)))

Integrate Java and R – Just in a minute

Creating a rich statistical application can become very handy and useful once you integrate Java with R.
Integration needs following to be installed already:

  1. JDK 1.5 or above ( I tried with 1.6 )
  2. R – can be downloaded from CRAN
  3. R_HOME environment variable is set.

Here is how you can integrate and configure your java to work with R:

  1. From R install the rJava package ( can be easily be done with install command in R ). The latest rJava contains JRI implicit so no need to download it manually.
  2. Go to the download directory of R  and you can see the rJava directory, and inside that there will be JRI directory include that in your java.library.path

And you are done 🙂
Enjoy !