Package abstrasy

Source Code of abstrasy.Tools

package abstrasy;


import abstrasy.interpreter.InterpreterException;
import abstrasy.interpreter.StdErrors;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import java.util.zip.Deflater;
import java.util.zip.Inflater;


/**
* Abstrasy Interpreter
*
* Copyright : Copyright (c) 2006-2012, Luc Bruninx.
*
* Concédée sous licence EUPL, version 1.1 uniquement (la «Licence»).
*
* Vous ne pouvez utiliser la présente oeuvre que conformément à la Licence.
* Vous pouvez obtenir une copie de la Licence à l’adresse suivante:
*
*   http://www.osor.eu/eupl
*
* Sauf obligation légale ou contractuelle écrite, le logiciel distribué sous
* la Licence est distribué "en l’état", SANS GARANTIES OU CONDITIONS QUELLES
* QU’ELLES SOIENT, expresses ou implicites.
*
* Consultez la Licence pour les autorisations et les restrictions
* linguistiques spécifiques relevant de la Licence.
*
*
* @author Luc Bruninx
* @version 1.0
*/

public class Tools {

    public Tools() {
    }

    public static URL toURL(String str) {
        URL url = null;
        try {
            url = new URL(str);
        }
        catch (MalformedURLException e) {
            return null;
        }
        return url;
    }

    public static String directoryOfFile(String src) {
        File file = new File(src);
        String sf = file.getAbsolutePath();
        if (sf.indexOf(File.separator) >= 0) {
            sf = sf.substring(0, sf.lastIndexOf(File.separator)) + File.separator;
        }
        //System.out.println(sf);
        return sf;
    }

    private final static String byteArrayToHexString_pseudo[] = { "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "a",
        "b",
        "c",
        "d",
        "e",
        "f" };

    private static StringBuffer byteArrayToHexString_out = new StringBuffer();

    public final static String byteArrayToHexString(byte[] in) {
        synchronized (byteArrayToHexString_out) {
            byte ch = 0x00;
            int i = 0;
            if (in == null || in.length <= 0) {
                return null;
            }
            byteArrayToHexString_out.setLength(0);
            while (i < in.length) {
                ch = (byte) (in[i] & 0xF0);
                ch = (byte) (ch >>> 4);
                ch = (byte) (ch & 0x0F);
                byteArrayToHexString_out.append(byteArrayToHexString_pseudo[(int) ch]);
                ch = (byte) (in[i] & 0x0F);
                byteArrayToHexString_out.append(byteArrayToHexString_pseudo[(int) ch]);
                i++;
            }
            return byteArrayToHexString_out.toString();
        }
    }

    public final static byte[] hexStringToByteArray(String hex) {
        String s = (hex.length() % 2 == 0) ? hex: "0" + hex;
        byte[] res = new byte[s.length() / 2];
        int i = 0;
        int j = 0;
        while (i < s.length()) {
            String chunk = s.substring(i, i + 2);
            i += 2;
            res[j++] = (byte) Integer.parseInt(chunk, 16);
        }
        return res;
    }

    /**
     * GZ comporession d'un tableau de bytes.
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public final static byte[] compress(byte[] bytes) throws Exception {
        Deflater compressor = new Deflater();
        compressor.setLevel(Deflater.BEST_COMPRESSION);
        compressor.setInput(bytes);
        compressor.finish();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];
        while (!compressor.finished()) {
            int cnt = compressor.deflate(buffer);
            bos.write(buffer, 0, cnt);
        }
        bos.close();
        return bos.toByteArray();
    }

    /**
     * GZ décompression d'un tableau de bytes.
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public final static byte[] decompress(byte[] bytes) throws Exception {
        Inflater decompressor = new Inflater();
        decompressor.setInput(bytes);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];
        while (!decompressor.finished()) {
            int cnt = decompressor.inflate(buffer);
            bos.write(buffer, 0, cnt);
        }
        bos.close();
        return bos.toByteArray();
    }

    public final static String stringToURLEncode(String s) throws UnsupportedEncodingException {
        return URLEncoder.encode(s, "UTF-8");
    }

    public final static String urlEncodetoString(String s) throws UnsupportedEncodingException {
        return URLDecoder.decode(s, "UTF-8");
    }

    public final static String toQuotedPrintable(byte[] s) {
        StringBuilder r = new StringBuilder();
        for (int i = 0; i < s.length; i++) {
            char c = (char) s[i];
            if (c >= 33 && c <= 126 && c != '=')
                r.append(c);
            else {
                String t = "0" + Integer.toHexString(c).toUpperCase();
                r.append('=').append(t.substring(t.length() - 2));
            }
        }
        return r.toString();
    }

    public final static String toQuotedPrintable(byte[] s, int len) {
        StringBuilder r = new StringBuilder();
        StringBuilder m = new StringBuilder();
        for (int i = 0; i < s.length; i++) {
            char c = (char) s[i];
            if (c >= 33 && c <= 126 && c != '=')
                m.append(c);
            else {
                String t = "0" + Integer.toHexString(c).toUpperCase();
                m.append('=').append(t.substring(t.length() - 2));
            }
            if (m.length() >= len) {
                r.append(m).append("=\r\n");
                m.setLength(0);
            }
        }
        if (m.length() > 0) {
            r.append(m);
        }
        return r.toString();
    }

    public final static byte[] fromQuotedPrintable(String s) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        for (int i = 0; i < s.length(); ) {
            char c = s.charAt(i++);
            if (c == '=') {
                String hex = ("" + s.charAt(i++) + s.charAt(i++)).toUpperCase();
                if (hex.compareTo("00") >= 0 && hex.compareTo("FF") <= 0) {
                    out.write(Integer.parseInt(hex, 16));
                }
            }
            else {
                out.write(c);
            }
        }
        return out.toByteArray();
    }

    public static String replaceCSeq(String src, String fndChar, String rSeq) {
        StringBuffer rs;
        StringBuffer rs2;
        CharSequence ps1;
        CharSequence ps2;
        rs = new StringBuffer((src == null ? "": src));
        int i = rs.indexOf(fndChar);
        int fndC_len = fndChar.length();
        while (i >= 0) {

            if (i == 0) {
                ps1 = null;
            }
            else {
                ps1 = rs.subSequence(0, i);
            }
            if (i >= rs.length() - fndC_len) {
                ps2 = null;
            }
            else {
                int delta_i = i + fndC_len;
                ps2 = rs.subSequence(delta_i, rs.length());
            }
            //System.out.println();
            rs2 = new StringBuffer();
            if (ps1 != null)
                rs2 = rs2.append(ps1);
            rs2 = rs2.append(rSeq);
            if (ps2 != null)
                rs2 = rs2.append(ps2);
            rs = rs2;
            i = rs.indexOf(fndChar, i + rSeq.length());
        }

        return rs.toString();
    }

    public final static String sgmlEncode(String s) {
        return replaceCSeq(replaceCSeq(replaceCSeq(s, "&", "&amp;"), "<", "&lt;"), ">", "&gt;");
    }

    public final static int computeAbsoluteIndex(int maxlen, int index, int seglen) throws InterpreterException {
        if(seglen<=0)
            throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "length:" + seglen+" <= 0"));
        if (index < 0) {
            if ((maxlen + index) < 0)
                throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "index:" + index+"["+(maxlen+index)+"]"));
            if ((maxlen + index + seglen) > maxlen)
                throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "index:" + index+"["+(maxlen+index)+"]" + " + length:" +seglen+" > " +maxlen ));
            return maxlen + index;
        }
        else if (index+seglen > maxlen)
            throw new InterpreterException(StdErrors.extend(StdErrors.Out_of_range, "index:" + index + " + length:" +seglen+" > " +maxlen));
        return index;
    }

}
TOP

Related Classes of abstrasy.Tools

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.