Thứ Ba, 9 tháng 12, 2014

NaturalOrderComparator.java

/*
NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java.
Copyright (C) 2003 by Pierre-Luc Paour <natorder@paour.com>
Based on the C version by Martin Pool, of which this is more or less a straight conversion.
Copyright (C) 2000 by Martin Pool <mbp@humbug.org.au>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
import java.util.*;
public class NaturalOrderComparator implements Comparator
{
int compareRight(String a, String b)
{
int bias = 0;
int ia = 0;
int ib = 0;
// The longest run of digits wins. That aside, the greatest
// value wins, but we can't know that it will until we've scanned
// both numbers to know that they have the same magnitude, so we
// remember it in BIAS.
for (;; ia++, ib++)
{
char ca = charAt(a, ia);
char cb = charAt(b, ib);
if (!Character.isDigit(ca) && !Character.isDigit(cb))
{
return bias;
}
else if (!Character.isDigit(ca))
{
return -1;
}
else if (!Character.isDigit(cb))
{
return +1;
}
else if (ca < cb)
{
if (bias == 0)
{
bias = -1;
}
}
else if (ca > cb)
{
if (bias == 0)
bias = +1;
}
else if (ca == 0 && cb == 0)
{
return bias;
}
}
}
public int compare(Object o1, Object o2)
{
String a = o1.toString();
String b = o2.toString();
int ia = 0, ib = 0;
int nza = 0, nzb = 0;
char ca, cb;
int result;
while (true)
{
// only count the number of zeroes leading the last number compared
nza = nzb = 0;
ca = charAt(a, ia);
cb = charAt(b, ib);
// skip over leading spaces or zeros
while (Character.isSpaceChar(ca) || ca == '0')
{
if (ca == '0')
{
nza++;
}
else
{
// only count consecutive zeroes
nza = 0;
}
ca = charAt(a, ++ia);
}
while (Character.isSpaceChar(cb) || cb == '0')
{
if (cb == '0')
{
nzb++;
}
else
{
// only count consecutive zeroes
nzb = 0;
}
cb = charAt(b, ++ib);
}
// process run of digits
if (Character.isDigit(ca) && Character.isDigit(cb))
{
if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0)
{
return result;
}
}
if (ca == 0 && cb == 0)
{
// The strings compare the same. Perhaps the caller
// will want to call strcmp to break the tie.
return nza - nzb;
}
if (ca < cb)
{
return -1;
}
else if (ca > cb)
{
return +1;
}
++ia;
++ib;
}
}
static char charAt(String s, int i)
{
if (i >= s.length())
{
return 0;
}
else
{
return s.charAt(i);
}
}
public static void main(String[] args)
{
String[] strings = new String[] { "1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01",
"pic2", "pic02", "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic05", "pic 5",
"pic 5 something", "pic 6", "pic 7", "pic100", "pic100a", "pic120", "pic121",
"pic02000", "tom", "x2-g8", "x2-y7", "x2-y08", "x8-y8" };
List orig = Arrays.asList(strings);
System.out.println("Original: " + orig);
List scrambled = Arrays.asList(strings);
Collections.shuffle(scrambled);
System.out.println("Scrambled: " + scrambled);
Collections.sort(scrambled, new NaturalOrderComparator());
System.out.println("Sorted: " + scrambled);
}
}

Thứ Bảy, 6 tháng 12, 2014

Resize Image Java

public static void main(String[] args) throws IOException {
        String path = "E:\\xampp\\htdocs\\khoan.com\\static\\image\\product\\thumb\\";
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        System.out.println("Total No of Files:" + listOfFiles.length);
        Image img = null;
        BufferedImage tempPNG = null;
        BufferedImage tempJPG = null;
        File newFilePNG = null;
        File newFileJPG = null;
        for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                System.out.println("File " + listOfFiles[i].getName());
                img = ImageIO.read(new File(path + listOfFiles[i].getName()));
//                tempPNG = resizeImage(img, 100, 100);
                tempJPG = resizeImage(img, 225, 145);
//                newFilePNG = new File("/Users/pankaj/Desktop/images/resize/" + listOfFiles[i].getName() + "_New.png");
                newFileJPG = new File("E:\\xampp\\htdocs\\khoan.com\\static\\image\\product\\thumb_" + listOfFiles[i].getName());
//                ImageIO.write(tempPNG, "png", newFilePNG);
                ImageIO.write(tempJPG, "jpg", newFileJPG);
            }
        }
        System.out.println("DONE");
    }

    public static BufferedImage resizeImage(final Image image, int width, int height) {
        final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics2D = bufferedImage.createGraphics();
        graphics2D.setComposite(AlphaComposite.Src);
        //below three lines are for RenderingHints for better image quality at cost of higher processing time
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.drawImage(image, 0, 0, width, height, null);
        graphics2D.dispose();
        return bufferedImage;
    }

String util java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.util.HashMap;

/**
 *
 * @author chieu
 */
public class StringUtil {

    //static final Logger logger = Logger.getLogger(StringUtil.class);
    public static String filterUTF8(String input) {
        char[] u = {
            'Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'U',
            'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'Ư',
            'ú', 'ù', 'ủ', 'ũ', 'ụ',
            'ứ', 'ừ', 'ử', 'ữ', 'ự', 'ư',};
        char[] a = {
            'Á', 'À', 'Ả', 'Ã', 'Ạ', 'A',
            'Ắ', 'Ằ', 'Ẩ', 'Ẵ', 'Ặ', 'Ă',
            'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Â',
            'á', 'à', 'ả', 'ã', 'ạ',
            'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'ă',
            'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'â'};
        char[] e = {
            'É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'E',
            'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ', 'Ê',
            'é', 'è', 'ẻ', 'ẽ', 'ẹ',
            'ế', 'ề', 'ể', 'ễ', 'ệ', 'ê'
        };
        char[] o = {
            'Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'O',
            'Ố', 'Ồ', 'Ỗ', 'Ỗ', 'Ộ', 'Ô',
            'Ớ', 'Ờ', 'Ỡ', 'Ỡ', 'Ợ', 'Ơ',
            'ó', 'ò', 'ỏ', 'õ', 'ọ',
            'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ô',
            'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ơ'
        };
        char[] i = {
            'Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'I',
            'í', 'ì', 'ỉ', 'ĩ', 'ị',};
        char[] y = {
            'Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Y',
            'ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ',};
        char[] d = {'Đ', 'đ'};
        int length = input.length();
        char current_character;
        boolean added = false;
        StringBuilder strbdr = new StringBuilder(/*length*/);
        for (int j = 0; j < length; j++) {
            added = false;
            current_character = input.charAt(j);
//            System.out.println(current_character);
            for (char c : u) {
                if (c == current_character) {
//                    System.out.println("check "+ c +" "+current_character);
                    strbdr.append('u');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : a) {
                if (c == current_character) {
                    strbdr.append('a');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : e) {
                if (c == current_character) {
                    strbdr.append('e');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : o) {
                if (c == current_character) {
                    strbdr.append('o');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : i) {
                if (c == current_character) {
                    strbdr.append('i');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : y) {
                if (c == current_character) {
                    strbdr.append('y');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            for (char c : d) {
                if (c == current_character) {
                    strbdr.append('d');
                    added = true;
                    break;
                }
            }
            if (added == true) {
                continue;
            }
            strbdr.append(current_character);
        }
        return strbdr.toString();
    }

    public static String toLowerVnm(String input) {
        String str = input;
        char[] u = {
            'Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'U',
            'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'Ư',};
        char[] u1 = {
            'ú', 'ù', 'ủ', 'ũ', 'ụ', 'u',
            'ứ', 'ừ', 'ử', 'ữ', 'ự', 'ư'};
        char[] a = {
            'Á', 'À', 'Ả', 'Ã', 'Ạ', 'A',
            'Ắ', 'Ằ', 'Ẩ', 'Ẵ', 'Ặ', 'Ă',
            'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Â',};
        char[] a1 = {
            'á', 'à', 'ả', 'ã', 'ạ', 'a',
            'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'ă',
            'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'â'};
        char[] e = {
            'É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'E',
            'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ', 'Ê',};
        char e1[] = {
            'é', 'è', 'ẻ', 'ẽ', 'ẹ', 'e',
            'ế', 'ề', 'ể', 'ễ', 'ệ', 'ê'
        };
        char[] o = {
            'Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'O',
            'Ố', 'Ồ', 'Ỗ', 'Ỗ', 'Ộ', 'Ô',
            'Ớ', 'Ờ', 'Ỡ', 'Ỡ', 'Ợ', 'Ơ',};
        char[] o1 = {
            'ó', 'ò', 'ỏ', 'õ', 'ọ', 'o',
            'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ô',
            'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ơ'
        };
        char[] ii = {
            'Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'I',};
        char[] ii1 = {
            'í', 'ì', 'ỉ', 'ĩ', 'ị', 'i',};
        char[] y = {
            'Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Y',};
        char[] y1 = {
            'ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'y'
        };
        char[] d = {'Đ',};
        char[] d1 = {'đ'};

        for (int i = 0; i < a.length; i++) {
            str = str.replace(a[i], a1[i]);
        }
        for (int i = 0; i < d.length; i++) {
            str = str.replace(d[i], d1[i]);
        }
        for (int i = 0; i < e.length; i++) {
            str = str.replace(e[i], e1[i]);
        }
        for (int i = 0; i < ii.length; i++) {
            str = str.replace(ii[i], ii1[i]);
        }

        for (int i = 0; i < o.length; i++) {
            str = str.replace(o[i], o1[i]);
        }

        for (int i = 0; i < u.length; i++) {
            str = str.replace(u[i], u1[i]);
        }
        for (int i = 0; i < y.length; i++) {
            str = str.replace(y[i], y1[i]);
        }
        str = str.toLowerCase();
        return str;
    }

 
    public static String removeTextBetweenBracket(String input) {
        String t = input;
        t = t.replaceAll("\\(.*\\)", "");
//        t = "Áo sơ mi caro đỏ tay ngắn[Mã SP: 168]";
        t = t.replaceAll("\\[.*\\]", "");
//        logger.info(t);
//        t = "Áo sơ mi caro đỏ tay ngắn*Mã SP: 168*";
        t = t.replaceAll("\\*.*\\*", "");
//        logger.info(t);
//        t = "Áo sơ mi caro đỏ tay ngắn{Mã SP: 168}";
        t = t.replaceAll("\\{.*\\}", "");
        return t;
    }

    public static String makeBold(String orginal, String relative) {
        String[] t = orginal.replaceAll(" +", " ").split(" ");
        String output = relative.replaceAll(" +", " ").trim();
        output = " " + output + " ";
        for (String str : t) {
            if (str.trim().length() == 0) {
                continue;
            }
            if (relative.contains(str)) {
                output = output.replace(str, "<b>" + str + "</b>");
            }
        }
        output = output.replace("</b> <b>", " ");
        return output.trim();
    }

    public static String removeNonWord(String input) {
        //[^\\p{L}\\p{N}]
        return input.replaceAll("[^\\p{L} ]", "");
    }

    public static String generateIdFromName(String input) {
        if (input == null) {
            return "";
        }
        String output = filterUTF8(input);
        output = toLowerVnm(output);
        output = output.replace(" ", "-").replace("/", "");
        return output;
    }


}

Pager Java

 public Pager(long totalItem, long currentPage) {
        totalPage = totalItem / AppConfig.NUM_PRODUCT_PER_PAGE;
        if (totalPage * AppConfig.NUM_PRODUCT_PER_PAGE < totalItem) {
            totalPage = totalPage + 1;
        }
        this.currentPage = currentPage;
       
        startPage = currentPage - AppConfig.NUM_LINK_PER_PAGE / 2;
        endPage = currentPage + AppConfig.NUM_LINK_PER_PAGE / 2;

        if (endPage > totalPage) {
            endPage = totalPage;
            startPage = endPage - AppConfig.NUM_LINK_PER_PAGE;
            if (startPage < 1) {
                startPage = 1;
            }
        }

        if (startPage < 1) {
            startPage = 1;
            endPage = startPage + AppConfig.NUM_LINK_PER_PAGE;
            if (endPage > totalPage) {
                endPage = totalPage;
            }
        }
       
        if (this.currentPage < startPage || this.currentPage > endPage) {
            this.currentPage = (endPage + startPage) / 2;
        }

    }

FTPUploader Java

//public class FTPUploader {
//
//    FTPClient ftp = null;
//
//    public FTPUploader(String host, String user, String pwd) throws Exception {
//        ftp = new FTPClient();
//        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
//        int reply;
//        ftp.connect(host);
//        reply = ftp.getReplyCode();
//        if (!FTPReply.isPositiveCompletion(reply)) {
//            ftp.disconnect();
//            throw new Exception("Exception in connecting to FTP Server");
//        }
//        ftp.login(user, pwd);
//        ftp.setFileType(FTP.BINARY_FILE_TYPE);
//        ftp.enterLocalPassiveMode();
//    }
//
//    public void uploadFile(String url, String fileName, String hostDir)
//            throws Exception {
//        InputStream input = new URL(url).openStream();
//        BufferedImage originalImage = ImageIO.read(input);
////        BufferedImage originalImage = ImageIO.read(new File(input));
//        int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
////        logger.info(originalImage.getHeight() * Config.THUMB_WIDTH / originalImage.getWidth());
//        BufferedImage resizedImage = new BufferedImage(100, originalImage.getHeight() * 100 / originalImage.getWidth(), type);
//        Graphics2D g = resizedImage.createGraphics();
//        g.drawImage(originalImage, 0, 0, resizedImage.getWidth(), resizedImage.getHeight(), null);
//        g.dispose();
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        ImageIO.write(resizedImage, "jpg", os);
//        InputStream input1 = new ByteArrayInputStream(os.toByteArray());
//        this.ftp.makeDirectory(hostDir);
//        this.ftp.storeFile(hostDir + fileName, input1);
////        try (InputStream input = new FileInputStream(new File("/home/chieu/75x75.png"))) {
////            this.ftp.makeDirectory(hostDir);
////            this.ftp.storeFile(hostDir + fileName, input);
////        }
//    }
//
//    public void disconnect() {
//        if (this.ftp.isConnected()) {
//            try {
//                this.ftp.logout();
//                this.ftp.disconnect();
//            } catch (IOException f) {
//                // do nothing as file is already saved to server
//            }
//        }
//    }
//
//    public static void main(String[] args) throws Exception {
//        System.out.println("Start");
//        FTPUploader ftpUploader = new FTPUploader("ftp.aocuoitphcm.com", "chieu91.H1703@aocuoitphcm.com", "AA51ZeBt351");
//        //FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload
//        // files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/"
//        ftpUploader.uploadFile("http://s2.img.edn.vn/2013/d/9/d9ab6349753c140dbe6df0c5034d037d_200x200.jpg",
//                "test1.jpg", "/upload/a/");
//        ftpUploader.disconnect();
//        System.out.println("Done");
//    }
//}