Saturday, 20 August 2016

How to check whether image is exist in the URL or not using java?

This is to tell most of the time when we show images from the different server may not be available due to (HTTP 404 or HTTP 500). To tackle this issue we can have some default images when image is not available



public static boolean isImageExist(String urlName) throws IOException {
    URL url =new URL(urlName);
    try {
        Image image= ImageIO.read(url.openStream());
        return image != null;
    }
    catch ( FileNotFoundException e) {
        return false;
    }
}

To call this method 


try {
    if (isImageExist(imageUrl)){
        return imageUrl;
    }
} catch (IOException e) {
// Here you can display some no image url 
    return defaultImage;
}


Thursday, 16 June 2016

How to download file dynamically using Wicket's DownloadLink with a file generated using Wicket 7?



Html:
<a wicket:id="downloadLink" >
   Download
</a>


Java class:


 IModel<File> fileModel = new AbstractReadOnlyModel<File>() {
                    @Override
                    public File getObject() {
                        return generatedFile();
                    }
                };


DownloadLink downloadLink= new DownloadLink("downloadLink", fileModel);

//This line used to delete once the download is completed
downloadLinkAddress.setDeleteAfterDownload(true);


The above step will make slow if you are showing many record at a time.



I would prefer below this way , ok let's start


In some scenario we might want to create a file and download dynamically when we click download 


IModel<File> fileModel =Model.of((File) null);

DownloadLink downloadLink = new DownloadLink("downloadlink",fileModel ){
    @Override    public void onClick() {
         File downloadFile = genaratedFile(); /**Call some utils to create a file
        IResourceStream resourceStream =
                new FileResourceStream(new org.apache.wicket.util.file.File(file));
/**Should pass full file path
        getRequestCycle().scheduleRequestHandlerAfterCurrent
                (new ResourceStreamRequestHandler(resourceStream).
                        setFileName(file.getName()));

}
};