Saturday, February 26, 2011

Java Tiff Image Jpeg Image Png Image Convert


Java Tiff Image Jpeg Image Png Image Convert

package com.store.file;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
import javax.imageio.ImageIO;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.protocol.HTTP;

import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;

import javax.media.jai.JAI;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import javax.media.jai.PlanarImage;

public class PutImageIntoXml {
    public static int DISPLAY_WIDTH = 100;
    public static String transferImage(String storeLocation, String imageName,
            String claimNumber) throws IOException {
        ByteArrayOutputStream stream = null;
        String imageXmlFile = null;
        System.out.println("\nStoreLocation:" + storeLocation);
        System.out.println("\nImage Name:" + imageName);
        String[] contents = imageName.split("\\.");
      
        if (contents.length == 2) {
            if (contents[1].equals("tiff") || contents[1].equals("tif")) {
                try {
                    SeekableStream s = new FileSeekableStream(storeLocation
                            + imageName);
                    TIFFDecodeParam param = null;
                    ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s,
                            param);
                    ArrayList<ByteArrayOutputStream> bytecontents= new ArrayList<ByteArrayOutputStream>();
                    int numofpages = dec.getNumPages();
                    System.out.println(numofpages);
                    for (int i=0; i< numofpages; i++) {
                    RenderedImage op = new  NullOpImage(dec.decodeAsRenderedImage(i),null,null,OpImage.OP_COMPUTE_BOUND);
                    stream = new ByteArrayOutputStream();
                    int width = op.getWidth();
                    int height = op.getHeight();
                    double conversionFactor = (double)DISPLAY_WIDTH / (double)width;
                    float conversionFactor_ = DISPLAY_WIDTH / width;
                    int thumbHeight = (int)((double)height * conversionFactor);
                    int thumbWidth = (int)((double)width * conversionFactor);
                    Dimension dim = new Dimension(thumbHeight, thumbWidth);              
                    JAI.setDefaultRenderingSize(dim);
                    JAI.setDefaultTileSize(dim);
                    JAI.create("encode", op, stream, "tiff");
                    bytecontents.add(stream);
                    }
                    StringBuffer encodedImage = new StringBuffer();
                    int numberofpages = bytecontents.size();
                    for(int i=0;i<numberofpages;i++){
                    stream = bytecontents.get(i);
                    byte[] b = stream.toByteArray();
                    encodedImage =encodedImage.append(Base64.encodeBase64String(b));
                    }
                    imageXmlFile =createImageXML(storeLocation, encodedImage.toString(),
                            claimNumber);
                    System.out.println(imageXmlFile);
                    imageXmlFile=URLEncoder.encode(imageXmlFile,HTTP.UTF_8);
                } catch (Exception e) {
                    e.printStackTrace();
                System.out.println("Some problem with image");
                } finally {
                    stream.close();
                }
            } else {
                try {
                    BufferedImage img = ImageIO.read(new File(storeLocation
                            + imageName));
                    stream = new ByteArrayOutputStream();
                    ImageIO.write(img, "png", stream);
                    stream.flush();
                    String encodedImage = Base64.encodeBase64String(stream
                            .toByteArray());
                    imageXmlFile = createImageXML(storeLocation, encodedImage,
                            claimNumber);
                } catch (Exception e) {
                } finally {
                    stream.close();
                }
                return imageXmlFile;
            }
        }
        return imageXmlFile;

    }

    public static String createImageXML(String storeLocation,
            String encodedImage, String claimNumber) {
        StringBuffer out = null;
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        Random randomGenerator = new Random();
        int randomInt = randomGenerator.nextInt(100);
        try {
            String timeFileSent = sdf.format(cal.getTime());
            out = new StringBuffer();
            out.append("<ABC>");
            out.append("<Document>");
            out.append(encodedImage);
            out.append("</Document>");
            out.append("<WorkType>Documentation</WorkType>");
            out.append(" </ABC>");
            System.out.println("\nWrote the file");
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        } finally {
        }
        return out.toString();
    }

    public static String[] splitStoreLocationAndImageName(String imageName) {
        String[] storeAndImage = new String[2];
        System.out.println("\nImageName:" + imageName);
        int lastIndex = imageName.lastIndexOf("/");
        System.out.println(lastIndex);
        storeAndImage[0] = imageName.substring(0, lastIndex + 1);
        System.out.println();
        storeAndImage[1] = (imageName.substring(lastIndex + 1));
        return storeAndImage;
    }

    public static final String DATE_FORMAT_NOW = "yyyy-MM-ddHH:mm:ss:";
}

Delete all files of directory using Php

<?php
$dir= "/opt/liferay/6.0.4/test2";
   
class Deletefile{
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) {
         chmod($dir, 0777);
        return unlink($dir);}
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!self::deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!self::deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }

}

$df = new Deletefile();
$df->deleteDirectory($dir);
echo "Reached here";

Read a file in Java

public static String readFile(){
        System.out.println("Reading Dummy file");
        StringBuilder contents = new StringBuilder();
        File aFile = new File("/opt/liferay/6.0.4/test.xml");
        try {
              BufferedReader input =  new BufferedReader(new FileReader(aFile));
              try {
                String line = null;
                while (( line = input.readLine()) != null){
                  contents.append(line);
                  contents.append(System.getProperty("line.separator"));
                }
              }
              finally {
                input.close();
              }
            }
            catch (IOException ex){
              ex.printStackTrace();
            }
           
    return contents.toString();

    }

Simple AUI Dialog Box Example

Simple AUI Dialog Box Example

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script src="/js/yui-min.js" type="text/javascript"></script>
<script src="/js/aui-base-min.js" type="text/javascript"></script>

<script type="text/javascript">
    function call() {
        document.getElementById("success").submit();
    }
    $(document).ready(function(){
           $('.go_btn').click(function(e) {
              e.preventDefault();
              if (
                      ($("#aui-3-1-1-199 option:selected").text() != "--Please Select--")&&
                      ($("#aui-3-1-1-194 option:selected").text() != "--Please Select--")&&
                      ($("#aui-3-1-1-199 option:selected").text() != "")&&
                      ($("#aui-3-1-1-194 option:selected").text() != "")&&
                      ($("#aui-3-1-1-199 option:selected").val() != 0)&&
                      ($("#aui-3-1-1-194 option:selected").val() != 0)
              )
              {
                 $('.makeform').submit();
              } else {
                  AUI().ready("aui-dialog","aui-overlay-manager","dd-constrain","event",function(A){
                      var d=new A.Dialog({title:"Error",bodyContent:"Please select  Manufacturer and Model from the list",
                          modal:true,resizable:false,width:275,height:88,centered:true}).render();
              });
              }
           });
        });
   
</script>

2 level Select using JQuery

2 level Select using JQuery



 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script src="/js/yui-min.js" type="text/javascript"></script>
<script src="/js/aui-base-min.js" type="text/javascript"></script>

<div id="login_area">
<select id="aui-3-1-1-194">
    <option value="">---Please Select---</option>
    <option value="Acer">Acer</option>
    <option value="Apple">Apple</option>
    <option value="AT&T">AT&T</option>
    <option value="Dell">Dell</option>
    <option value="HTC">HTC</option>
    <option value="LG">LG</option>
    <option value="Motorola">Motorola</option>
    <option value="Nokia">Nokia</option>
    <option value="Novatel Wireless">Novatel Wireless</option>
    <option value="Option">Option</option>
    <option value="Pantech">Pantech</option>
    <option value="Palm">Palm</option>
    <option value="RIM">RIM</option>
    <option value="Samsung">Samsung</option>
    <option value="Sharp">Sharp</option>
    <option value="Sony Erricsson">Sony Ericsson</option>
    <option value="Other">Other</option>
</select> <select id="aui-3-1-1-199"></select>
<input class="go_btn" id="device_go" type="submit" value="" /></div>
<script type="text/javascript">
    jQuery(document).ready(function() {

                        function arrwalk(e) {
                            for ( var i = 0; i < e.length; i++) {
                                jQuery('#aui-3-1-1-199').append(
                                        jQuery('<option></option>').val(e[i])
                                                .html(e[i]));
                            }
                        }

                        var acer = [ '--Please Select--', 'Aspire' ];
                        var apple = [ '--Please Select--', 'iPhone 3GS', 'iPhone 4','iPad' ];
                        var dell = [ '--Please Select--', 'Aero', 'Inspiron Mini' ];
                        var htc = [ '--Please Select--', 'Aria (A636)', 'Tilt 2', 'Surround' ];
                        var lg = [ '--Please Select--', 'Adrenaline', 'Encore 550', 'Neon', 'Quantum', 'Vu Plus' ];
                        var motorola = [ '--Please Select--', 'Backflip MB300', 'Bravo', 'Flipout', 'Flipside' ];
                        var nokia = [ '--Please Select--', '2330', '2720', '6350' ];
                        var novatel = [ '--Please Select--', 'Mifi 2372' ];
                        var option = [ '--Please Select--', 'Velocity' ];
                        var palm = [ '--Please Select--', 'Pixi Plus', 'Pre Plus' ];
                        var pantech = [ '--Please Select--', 'Breeze II P2000','Impact P7000', 'Link P7040', 'Pursuit P9020' ];
                        var rim = [ '--Please Select--', 'Curve 8520', 'Curve 8900', 'Pearl 3G', 'Curve 9300', 'Bold 9700', 'Torch 9800' ];
                        var samsung = [ '--Please Select--', 'Captivate i897', 'Go N310', 'Jack', 'SGH-A777', 'Flight A797', 'Focus SGH-i917', 'Galaxy Tab', 'Impression', 'Mythic A897', 'Rugby II A847', 'Strive A687' ];
                        var sharp = [ '--Please Select--', 'FX' ];
                        var att = [ '--Please Select--', 'USB Sierra Lightning', '3G Microcell' ];
                        var sony = [ '--Please Select--', 'SEMC Xperia X10', 'Vivaz' ];
                        var other = [ '--Please Select--', 'Other' ];

                        jQuery('#aui-3-1-1-194').change(
                                function() {
                                    jQuery('#aui-3-1-1-199').empty();
                                    var manvalue = jQuery(
                                            '#aui-3-1-1-194 :selected').text();
                                    switch (manvalue) {
                                    case "Acer":
                                        arrwalk(acer);
                                        break;
                                    case "Apple":
                                        arrwalk(apple);
                                        break;
                                    case "AT&T":
                                        arrwalk(att);
                                        break;
                                    case "Dell":
                                        arrwalk(dell);
                                        break;
                                    case "HTC":
                                        arrwalk(htc);
                                        break;
                                    case "LG":
                                        arrwalk(lg);
                                        break;
                                    case "Motorola":
                                        arrwalk(motorola);
                                        break;
                                    case "Nokia":
                                        arrwalk(nokia);
                                        break;
                                    case "Novatel Wireless":
                                        arrwalk(novatel);
                                        break;
                                    case "Option":
                                        arrwalk(option);
                                        break;
                                    case "Palm":
                                        arrwalk(palm);
                                        break;
                                    case "Pantech":
                                        arrwalk(pantech);
                                        break;
                                    case "RIM":
                                        arrwalk(rim);
                                        break;
                                    case "Samsung":
                                        arrwalk(samsung);
                                        break;
                                    case "Sharp":
                                        arrwalk(sharp);
                                        break;
                                    case "Sony Ericsson":
                                        arrwalk(sony);
                                        break;
                                    case "Other":
                                        arrwalk(other);
                                        break;
                                    }
                                });
                        jQuery('#aui-3-1-1-199').change(
                                   function() {
                                            var phone = jQuery(
                                                    '#aui-3-1-1-194 :selected')
                                                    .text()
                                                    + jQuery(
                                                            '#aui-3-1-1-199 :selected')
                                                            .text();
                                            var prodId = "";
                                            var phoneUrl = "";
                                            var articleId = "a_id/6579/c/277";
                                            var phoneImage = "";
                             
                                            switch (phone) {
                                            case "DellAero":
                                          
                                            case "OtherOther":
                                          
  break;
                                            default:
                                                break;
                                            }
                                            jQuery('#hurl').val(phoneUrl);
                                           :selected').text());
                                            jQuery('#hmodel').val(jQuery('#aui-3-1-1-199 :selected').text());

                                        });
                    });
</script>
</form>
</div>
<%
    } else {
%>
<div id="login_area">
<form id="success" action="https://blabla"
    method="post" class="success">

<div id="choose_device">
<div class="entry_text"><em>Please choose the enrolled
device.<img alt="" class="tooltip_trigger"
    src="/mts-theme/images/mts/tooltip_icon.jpg"
    style="width: 18px; height: 18px;" /></em>
<div class="tooltip"></a></em></div>

</div>
<select id="aui-3-1-1-194">
    <option value="<%=make%>" selected="selected"><%=make%></option>
    <option value="">---Please Select---</option>
</select> <select id="aui-3-1-1-199">
    <option value="<%=model%>" selected="selected"><%=model%></option>
    <option value="">---Please Select---</option>
</select> <input class="go_btn" id="device_go" type="submit" value="" /></div>
</form>
</div>
<body onLoad="call()">
</body>
<%
    }
%>

Java Excel Csv File

 Java Excel Csv File

First Convert the excel file into the .csv file and then read through

public static ArrayList<CsvBean> setUpMakeAndModel(String storeLocation) {
        System.out.println("Updating the bean list");
        beanList=new ArrayList<CsvBean>();
        try {
            File file = new File("/..localtion to the file/device.csv");
            BufferedReader bufRdr = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = bufRdr.readLine()) != null) {
                CsvBean cb = new CsvBean();
                int col=0;
                String[] rowContents=new String[9];
                StringTokenizer st = new StringTokenizer(line, ",");
                while (st.hasMoreTokens()) {
                    rowContents[col] = st.nextToken();
                    col++;
                    if(col==9){
                        break;
                    }
                }
                cb.iD=rowContents[0]==null?"":rowContents[0];
                cb.brand=rowContents[1]==null?"":rowContents[1];
                cb.equipmentMaster=rowContents[1]==null?"":rowContents[2];
                cb.make=rowContents[3]==null?"":rowContents[3];
                cb.model=rowContents[4]==null?"":rowContents[4];
                cb.image=rowContents[5]==null?"":rowContents[5];
                cb.productID=rowContents[6]==null?"":rowContents[6];
                cb.articleID=rowContents[7]==null?"":rowContents[7];
                cb.url=rowContents[8]==null?"":rowContents[8];
                beanList.add(cb);
            }
            bufRdr.close();
        } catch (Exception e) {
            System.out.println("Location of the device list not recognized");
            return null;
        }
        return beanList;