    public static File copyFile(File srcFile, File destFolder, FileCopyListener copyListener) {
        File dest = new File(destFolder, srcFile.getName());
        try {
            FileInputStream in = new FileInputStream(srcFile);
            FileOutputStream out = new FileOutputStream(dest);
            byte[] readBuf = new byte[1024 * 512];
            int readLength;
            long totalCopiedSize = 0;
            long totalSize = srcFile.length();
            boolean canceled = false;
            if (copyListener == null) {
                while ((readLength = in.read(readBuf)) != -1) {
                    out.write(readBuf, 0, readLength);
                }
            } else {
                while ((readLength = in.read(readBuf)) != -1) {
                    out.write(readBuf, 0, readLength);
                    if (!copyListener.updateCheck(readLength, totalSize)) {
                        canceled = true;
                        break;
                    }
                }
            }
            in.close();
            out.close();
            if (canceled) {
                dest.delete();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dest;
    }


    public static byte[] gerarHash(String frase) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(frase.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    public void render(Map map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
        File file = (File) map.get("targetFile");
        IOUtils.copy(new FileInputStream(file), baos);
        httpServletResponse.setContentType(getContentType());
        httpServletResponse.setContentLength(baos.size());
        httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + file.getName());
        ServletOutputStream out = httpServletResponse.getOutputStream();
        baos.writeTo(out);
        out.flush();
    }


    public static void copy(final File src, final File dest) throws IOException {
        OutputStream stream = new FileOutputStream(dest);
        FileInputStream fis = new FileInputStream(src);
        byte[] buffer = new byte[16384];
        while (fis.available() != 0) {
            int read = fis.read(buffer);
            stream.write(buffer, 0, read);
        }
        stream.flush();
    }


    public static File downloadFromUrl(String urlString, String ext) throws Exception {
        URL url = new URL(urlString);
        InputStream is = url.openStream();
        byte bytes[] = new byte[20480];
        File result = File.createTempFile("temp_", ext);
        FileOutputStream fos = new FileOutputStream(result);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int nbread = 0;
        int loops = 0;
        while ((nbread = is.read(bytes)) > -1) {
            bos.write(bytes, 0, nbread);
            loops++;
            System.out.println(loops);
        }
        bos.close();
        return result;
    }


    public boolean moveFileSafely(final File in, final File out) throws IOException {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        final File tempOut = File.createTempFile("move", ".tmp");
        try {
            fis = new FileInputStream(in);
            fos = new FileOutputStream(tempOut);
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            try {
                if (inChannel != null) inChannel.close();
            } catch (IOException e) {
                LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel);
            }
            try {
                if (outChannel != null) outChannel.close();
            } catch (IOException e) {
                LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel);
            }
            try {
                if (fis != null) fis.close();
            } catch (IOException e) {
                LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis);
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
                LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos);
            }
        }
        out.delete();
        if (!out.exists()) {
            tempOut.renameTo(out);
            return in.delete();
        }
        return false;
    }


    public static void main(String[] args) {
        String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1";
        URL url = null;
        AcmSearchresultPageParser_2011Jan cb = new AcmSearchresultPageParser_2011Jan();
        try {
            url = new URL(u);
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.setUseCaches(false);
            InputStream is = uc.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            ParserDelegator pd = new ParserDelegator();
            pd.parse(br, cb, true);
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("all doc num= " + cb.getAllDocNum());
        for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) {
            HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i);
            System.out.println(i + "pos= " + m);
        }
    }


    @Override
    public void makeRead(final String user, final long databaseID, final long time) throws SQLException {
        final String query = "insert into fs.read_post (post, user, read_date) values (?, ?, ?)";
        ensureConnection();
        final PreparedStatement statement = m_connection.prepareStatement(query);
        try {
            statement.setLong(1, databaseID);
            statement.setString(2, user);
            statement.setTimestamp(3, new Timestamp(time));
            final int count = statement.executeUpdate();
            if (0 == count) {
                throw new SQLException("Nothing updated.");
            }
            m_connection.commit();
        } catch (final SQLException e) {
            m_connection.rollback();
            throw e;
        } finally {
            statement.close();
        }
    }


    private String buildShaHashOf(String source) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(source.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }


    public static boolean ejecutarDMLTransaccion(List<String> tirasSQL) throws Exception {
        boolean ok = true;
        try {
            getConexion();
            conexion.setAutoCommit(false);
            Statement st = conexion.createStatement();
            for (String cadenaSQL : tirasSQL) {
                if (st.executeUpdate(cadenaSQL) < 1) {
                    ok = false;
                    break;
                }
            }
            if (ok) conexion.commit(); else conexion.rollback();
            conexion.setAutoCommit(true);
            conexion.close();
        } catch (SQLException e) {
            if (conexion != null && !conexion.isClosed()) {
                conexion.rollback();
            }
            throw new Exception("Error en Transaccion");
        } catch (Exception e) {
            throw new Exception("Error en Transaccion");
        }
        return ok;
    }


    public static JSGFRuleGrammar newGrammarFromJSGF(URL url, JSGFRuleGrammarFactory factory) throws JSGFGrammarParseException, IOException {
        Reader reader;
        BufferedInputStream stream = new BufferedInputStream(url.openStream(), 256);
        JSGFEncoding encoding = getJSGFEncoding(stream);
        if ((encoding != null) && (encoding.encoding != null)) {
            System.out.println("Grammar Character Encoding \"" + encoding.encoding + "\"");
            reader = new InputStreamReader(stream, encoding.encoding);
        } else {
            if (encoding == null) System.out.println("WARNING: Grammar missing self identifying header");
            reader = new InputStreamReader(stream);
        }
        return newGrammarFromJSGF(reader, factory);
    }


    public static String MD5(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }


    protected boolean update(String sql, int requiredRows, int maxRows) throws SQLException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("executing " + sql + "...");
        }
        Connection connection = null;
        boolean oldAutoCommit = true;
        try {
            connection = dataSource.getConnection();
            connection.clearWarnings();
            oldAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();
            int rowsAffected = statement.executeUpdate(sql);
            if (requiredRows != -1 && rowsAffected < requiredRows) {
                LOG.warn("(" + rowsAffected + ") less than " + requiredRows + " rows affected, rolling back...");
                connection.rollback();
                return false;
            }
            if (maxRows != -1 && rowsAffected > maxRows) {
                LOG.warn("(" + rowsAffected + ") more than " + maxRows + " rows affected, rolling back...");
                connection.rollback();
                return false;
            }
            connection.commit();
            return true;
        } catch (SQLException e) {
            LOG.error("Unable to update database using: " + sql, e);
            throw e;
        } finally {
            try {
                if (connection != null) {
                    connection.setAutoCommit(oldAutoCommit);
                    connection.close();
                }
            } catch (SQLException e) {
                LOG.error("Unable to close connection: " + e, e);
            }
        }
    }


    protected byte[] retrieveImageData() throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int fileSize = connection.getContentLength();
        Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + (fileSize <= 0 ? "size unknown" : Integer.toString(fileSize)) + ")");
        BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
        try {
            if (fileSize <= 0) {
                Log.w(LOG_TAG, "Server did not set a Content-Length header, will default to buffer size of " + defaultBufferSize + " bytes");
                ByteArrayOutputStream buf = new ByteArrayOutputStream(defaultBufferSize);
                byte[] buffer = new byte[defaultBufferSize];
                int bytesRead = 0;
                while (bytesRead != -1) {
                    bytesRead = istream.read(buffer, 0, defaultBufferSize);
                    if (bytesRead > 0) buf.write(buffer, 0, bytesRead);
                }
                return buf.toByteArray();
            } else {
                byte[] imageData = new byte[fileSize];
                int bytesRead = 0;
                int offset = 0;
                while (bytesRead != -1 && offset < fileSize) {
                    bytesRead = istream.read(imageData, offset, fileSize - offset);
                    offset += bytesRead;
                }
                return imageData;
            }
        } finally {
            try {
                istream.close();
                connection.disconnect();
            } catch (Exception ignore) {
            }
        }
    }


    public boolean uploadToUrl(URL url, Map postData) {
        boolean success = false;
        OutputStream oStream;
        HttpURLConnection urlConn = null;
        try {
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);
            urlConn.setAllowUserInteraction(false);
            String parametersAsString = "";
            Iterator itParams = postData.entrySet().iterator();
            while (itParams.hasNext()) {
                Map.Entry param = (Map.Entry) itParams.next();
                parametersAsString += (String) param.getKey() + "=" + URLEncoder.encode((String) param.getValue(), "UTF-8") + "&";
            }
            byte[] parameterAsBytes = parametersAsString.getBytes();
            urlConn.setRequestProperty("Content=length", String.valueOf(parameterAsBytes.length));
            oStream = urlConn.getOutputStream();
            oStream.write(parameterAsBytes);
            oStream.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.err.println("Response: " + line);
            }
            oStream.close();
            rd.close();
            success = true;
        } catch (MalformedURLException ex) {
            System.err.println(ex + " (uploadToUrl)");
            success = false;
        } catch (java.io.IOException iox) {
            System.out.println(iox + " (uploadToUrl)");
            success = false;
        } catch (Exception generic) {
            System.out.println(generic.toString() + " (uploadToUrl)");
            success = false;
        } finally {
            success = false;
        }
        return success;
    }


    private static String makeLoginRequest(String authenticationUrl, String accountEmail, String accountPassword) throws IOException {
        URL url = new URL(authenticationUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        StringBuffer content = new StringBuffer();
        content.append("Email=").append(URLEncoder.encode(accountEmail, "UTF-8"));
        content.append("&Passwd=").append(URLEncoder.encode(accountPassword, "UTF-8"));
        content.append("&source=").append(URLEncoder.encode("Google Base data API for OFBiz", "UTF-8"));
        content.append("&service=").append(URLEncoder.encode("gbase", "UTF-8"));
        OutputStream outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("UTF-8"));
        outputStream.close();
        int responseCode = urlConnection.getResponseCode();
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }
        return toString(inputStream);
    }


    public String[] getFriends() {
        InputStream is = null;
        String[] answer = null;
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(domain);
            httppost.setEntity(new UrlEncodedFormEntity(library));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + ",");
            }
            is.close();
            result = sb.toString();
            if (result.equals("null,")) {
                answer = new String[1];
                answer[0] = "none";
                return answer;
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        try {
            JSONArray json = new JSONArray(result);
            answer = new String[json.length()];
            for (int i = 0; i < json.length(); i++) {
                JSONObject jsonId = json.getJSONObject(i);
                answer[i] = jsonId.getString("uid");
            }
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return answer;
    }


    public LinkedList<NameValuePair> getScoreboard() {
        InputStream is = null;
        String result = "";
        LinkedList<NameValuePair> scores = new LinkedList<NameValuePair>();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(domain);
            httppost.setEntity(new UrlEncodedFormEntity(library));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + ",");
            }
            is.close();
            result = sb.toString();
            if (result.equals("null,")) {
                return null;
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        try {
            JSONObject json = new JSONObject(result);
            JSONArray data = json.getJSONArray("data");
            JSONArray me = json.getJSONArray("me");
            for (int i = 0; i < data.length(); i++) {
                JSONObject single = data.getJSONObject(i);
                String uid = single.getString("uid");
                String score = single.getString("score");
                scores.add(new BasicNameValuePair(uid, score));
            }
            for (int i = 0; i < me.length(); i++) {
                JSONObject single = me.getJSONObject(i);
                String uid = single.getString("uid");
                String score = single.getString("score");
                scores.add(new BasicNameValuePair(uid, score));
            }
            System.out.println(json);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return scores;
    }


    public LinkedList<NameValuePair> getQuestion() {
        InputStream is = null;
        String result = "";
        LinkedList<NameValuePair> question = new LinkedList<NameValuePair>();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(domain);
            httppost.setEntity(new UrlEncodedFormEntity(library));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            result = sb.toString();
            if (result.equals("null,")) {
                return null;
            }
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        try {
            JSONObject json = new JSONObject(result);
            JSONArray data = json.getJSONArray("data");
            JSONObject quest = data.getJSONObject(0);
            question.add(new BasicNameValuePair("q", quest.getString("q")));
            question.add(new BasicNameValuePair("a", quest.getString("a")));
            question.add(new BasicNameValuePair("b", quest.getString("b")));
            question.add(new BasicNameValuePair("c", quest.getString("c")));
            question.add(new BasicNameValuePair("d", quest.getString("d")));
            question.add(new BasicNameValuePair("correct", quest.getString("correct")));
            return question;
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return null;
    }


    public String getChallengers() {
        InputStream is = null;
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(domain);
            httppost.setEntity(new UrlEncodedFormEntity(library));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + ",");
            }
            is.close();
            result = sb.toString();
            if (result.equals("null,")) {
                return "none";
            } else return result;
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        return "none";
    }


    public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException {
        int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte();
        if (startByte >= 0) {
            FileInputStream fis = new FileInputStream(file);
            FileChannel fc = fis.getChannel();
            ByteBuffer bb = ByteBuffer.allocate(startByte);
            fc.read(bb);
            FileOutputStream out = new FileOutputStream(outputFile);
            out.write(bb.array());
            out.close();
            fc.close();
            fis.close();
            return outputFile;
        }
        throw new TagNotFoundException("There is no ID3v2Tag data in this file");
    }


    public void run() {
        try {
            FTPClient c = new FTPClient();
            c.configure(ftpConfig);
            logger.debug("Trying to connect");
            c.connect("127.0.0.1", 21211);
            logger.debug("Connected");
            c.setSoTimeout(5000);
            if (!FTPReply.isPositiveCompletion(c.getReplyCode())) {
                logger.debug("Houston, we have a problem. D/C");
                c.disconnect();
                throw new Exception();
            }
            if (c.login("drftpd", "drftpd")) {
                logger.debug("Logged-in, now waiting 5 secs and kill the thread.");
                _sc.addSuccess();
                Thread.sleep(5000);
                c.disconnect();
            } else {
                logger.debug("Login failed, D/C!");
                throw new Exception();
            }
        } catch (Exception e) {
            logger.debug(e, e);
            _sc.addFailure();
        }
        logger.debug("exiting");
    }


    public TtsTrackImpl(URL url, String voiceName, VoicesCache vc) throws IOException {
        this.voiceCache = vc;
        isReady = false;
        URLConnection connection = url.openConnection();
        frameSize = (int) (period * format.getChannels() * format.getSampleSizeInBits() * format.getSampleRate() / 8000);
        voice = voiceCache.allocateVoice(voiceName);
        TTSAudioBuffer audioBuffer = new TTSAudioBuffer();
        this.voice.setAudioPlayer(audioBuffer);
        this.voice.speak(connection.getInputStream());
        audioBuffer.flip();
    }


    private void publishPage(URL url, String path, File outputFile) throws IOException {
        if (debug) {
            System.out.println("      publishing page: " + path);
            System.out.println("        url == " + url);
            System.out.println("        file == " + outputFile);
        }
        StringBuffer sb = new StringBuffer();
        try {
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            boolean firstLine = true;
            String line;
            do {
                line = br.readLine();
                if (line != null) {
                    if (!firstLine) sb.append("\n"); else firstLine = false;
                    sb.append(line);
                }
            } while (line != null);
            br.close();
        } catch (IOException e) {
            String mess = outputFile.toString() + ": " + e.getMessage();
            errors.add(mess);
        }
        FileOutputStream fos = new FileOutputStream(outputFile);
        OutputStreamWriter sw = new OutputStreamWriter(fos);
        sw.write(sb.toString());
        sw.close();
        if (prepareArchive) archiveFiles.add(new ArchiveFile(path, outputFile));
    }


    private void processData(InputStream raw) {
        String fileName = remoteName;
        if (localName != null) {
            fileName = localName;
        }
        try {
            FileOutputStream fos = new FileOutputStream(new File(fileName), true);
            IOUtils.copy(raw, fos);
            LOG.info("ok");
        } catch (IOException e) {
            LOG.error("error writing file", e);
        }
    }


    public static boolean canWeConnectToInternet() {
        String s = "http://www.google.com/";
        URL url = null;
        boolean can = false;
        URLConnection conection = null;
        try {
            url = new URL(s);
        } catch (MalformedURLException e) {
            System.out.println("This should never happend. Error in URL name. URL specified was:" + s + ".");
        }
        try {
            conection = url.openConnection();
            conection.connect();
            can = true;
        } catch (IOException e) {
            can = false;
        }
        if (can) {
        }
        return can;
    }


    public static void copyFile(File in, File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            int maxCount = 67076096;
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }


    public String getMediaURL(String strLink) {
        try {
            String res = de.nomule.mediaproviders.KeepVid.getAnswer(strLink, "aa");
            if (NoMuleRuntime.DEBUG) System.out.println(res);
            String regexp = "http:\\/\\/[^\"]+\\/get_video[^\"]+";
            Pattern p = Pattern.compile(regexp);
            Matcher m = p.matcher(res);
            m.find();
            String strRetUrl = res.substring(m.start(), m.end());
            strRetUrl = URLDecoder.decode(strRetUrl, "UTF-8");
            if (TRY_HIGH_QUALITY) {
                NoMuleRuntime.showDebug("HIGH_QUALITY");
                strRetUrl += "&fmt=18";
                try {
                    URL url = new URL(strRetUrl);
                    URLConnection conn = url.openConnection();
                    InputStream in = conn.getInputStream();
                    in.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    strRetUrl = strRetUrl.substring(0, strRetUrl.length() - 7);
                }
            }
            if (NoMuleRuntime.DEBUG) System.out.println(strRetUrl);
            return strRetUrl;
        } catch (UnsupportedEncodingException e) {
            System.out.println("Error in Youtube Media Provider. Encoding is not supported. (How would that happen?!)");
            e.printStackTrace();
        }
        return "";
    }


    void addDataFromURL(URL theurl) {
        String line;
        InputStream in = null;
        try {
            in = theurl.openStream();
            BufferedReader data = new BufferedReader(new InputStreamReader(in));
            while ((line = data.readLine()) != null) {
                thetext.append(line + "\n");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            thetext.append(theurl.toString());
        }
        try {
            in.close();
        } catch (Exception e) {
        }
    }


    private static void loadDefaultSettings(final String configFileName) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(META_INF_DEFAULT_CONFIG_PROPERTIES);
            out = new FileOutputStream(configFileName);
            IOUtils.copy(in, out);
        } catch (final Exception e) {
            log.warn("Unable to pull out the default.", e);
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }


    public boolean copy(File fromFile) throws IOException {
        FileUtility toFile = this;
        if (!fromFile.exists()) {
            abort("FileUtility: no such source file: " + fromFile.getAbsolutePath());
            return false;
        }
        if (!fromFile.isFile()) {
            abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath());
            return false;
        }
        if (!fromFile.canRead()) {
            abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath());
            return false;
        }
        if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName()));
        if (toFile.exists()) {
            if (!toFile.canWrite()) {
                abort("FileUtility: destination file is unwriteable: " + pathName);
                return false;
            }
        } else {
            String parent = toFile.getParent();
            File dir = new File(parent);
            if (!dir.exists()) {
                abort("FileUtility: destination directory doesn't exist: " + parent);
                return false;
            }
            if (dir.isFile()) {
                abort("FileUtility: destination is not a directory: " + parent);
                return false;
            }
            if (!dir.canWrite()) {
                abort("FileUtility: destination directory is unwriteable: " + parent);
                return false;
            }
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
        return true;
    }


    public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException {
        if (!outputDirectory.exists()) {
            outputDirectory.createFolder();
        }
        ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/standalone/resources.zip"), outputDirectory);
        for (Library library : libraryModels) {
            String libraryName = library.getName();
            String libraryLocation = library.getLocation();
            outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder();
            try {
                {
                    String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName);
                    FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.html");
                    Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                }
                {
                    String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("ComponentIndex.xsl"), "libraryName", libraryName);
                    FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("components.html");
                    Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            for (Component component : library.getComponents()) {
                String componentName = component.getName();
                System.out.println("Generating " + libraryName + ":" + componentName + "...");
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("libraryName", libraryName);
                parameters.put("componentName", componentName);
                String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters);
                Writer out = null;
                try {
                    FileObject index = outputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true));
                    out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                    Resource specificationLocation = component.getSpecificationLocation();
                    if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) {
                        File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI());
                        FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource");
                        if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) {
                            File[] files = srcResourcesDirectory.listFiles();
                            if (files != null) {
                                for (File resource : files) {
                                    if (resource.isFile() && !resource.isHidden()) {
                                        FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName());
                                        resourceFileObject.createFile();
                                        InputStream inResource = null;
                                        OutputStream outResource = null;
                                        try {
                                            inResource = new FileInputStream(resource);
                                            outResource = resourceFileObject.getContent().getOutputStream();
                                            IOUtils.copy(inResource, outResource);
                                        } finally {
                                            IOUtils.closeQuietly(inResource);
                                            IOUtils.closeQuietly(outResource);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        {
            Writer out = null;
            try {
                {
                    String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("LibraryIndex.xsl"));
                    FileObject index = outputDirectory.resolveFile("libraries.html");
                    out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                }
                {
                    String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl"));
                    FileObject index = outputDirectory.resolveFile("overview.html");
                    out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                }
                {
                    String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("AllComponents.xsl"));
                    FileObject index = outputDirectory.resolveFile("allcomponents.html");
                    out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }


    private void moveFile(File orig, File target) throws IOException {
        byte buffer[] = new byte[1000];
        int bread = 0;
        FileInputStream fis = new FileInputStream(orig);
        FileOutputStream fos = new FileOutputStream(target);
        while (bread != -1) {
            bread = fis.read(buffer);
            if (bread != -1) fos.write(buffer, 0, bread);
        }
        fis.close();
        fos.close();
        orig.delete();
    }


    private void loadHtmlHeader() {
        String skinUrl = getClass().getResource("/" + Properties.defaultSkinFileName).toString();
        if (Properties.headerSkin != null && !Properties.headerSkin.equals("")) {
            try {
                URL url = new URL(Properties.headerSkin);
                if (url.getProtocol().equalsIgnoreCase("http")) {
                    isHttpUrl = true;
                    HttpURLConnection.setFollowRedirects(false);
                    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                    httpConn.setRequestMethod("HEAD");
                    boolean urlExists = (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK);
                    if (urlExists) skinUrl = Properties.headerSkin;
                } else if (url.getProtocol().equalsIgnoreCase("jar")) {
                    String jarFile = Properties.headerSkin.substring(9).split("!")[0];
                    File skinFile = new File(jarFile);
                    if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin;
                } else if (url.getProtocol().equalsIgnoreCase("file")) {
                    File skinFile = new File(Properties.headerSkin.substring(5));
                    if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin;
                } else {
                    File skinFile = new File(Properties.headerSkin);
                    if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin;
                }
            } catch (Exception ex) {
                XohmLogger.debugPrintln("Header skin url not valid. " + ex.getMessage());
                XohmLogger.debugPrintln("Loading the default skin.");
                ex.printStackTrace();
            }
        }
        XohmLogger.debugPrintln("Header skin file = " + skinUrl);
        try {
            LocalHtmlRendererContext rendererContext = new LocalHtmlRendererContext(htmlHeaderPanel, new SimpleUserAgentContext());
            rendererContext.navigate(skinUrl);
            headerLoaded = true;
        } catch (IOException urlEx) {
            XohmLogger.debugPrintln("Exception occured while loading the skin. " + urlEx.getMessage());
        }
    }


    private void outputSignedOpenDocument(byte[] signatureData) throws IOException {
        LOG.debug("output signed open document");
        OutputStream signedOdfOutputStream = getSignedOpenDocumentOutputStream();
        if (null == signedOdfOutputStream) {
            throw new NullPointerException("signedOpenDocumentOutputStream is null");
        }
        ZipOutputStream zipOutputStream = new ZipOutputStream(signedOdfOutputStream);
        ZipInputStream zipInputStream = new ZipInputStream(this.getOpenDocumentURL().openStream());
        ZipEntry zipEntry;
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (!zipEntry.getName().equals(ODFUtil.SIGNATURE_FILE)) {
                zipOutputStream.putNextEntry(zipEntry);
                IOUtils.copy(zipInputStream, zipOutputStream);
            }
        }
        zipInputStream.close();
        zipEntry = new ZipEntry(ODFUtil.SIGNATURE_FILE);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(signatureData, zipOutputStream);
        zipOutputStream.close();
    }


    public InputLattice(String file, int type, boolean convertJoinMeet) throws FileNotFoundException, IOException {
        InputStream latStream = null;
        labels = new Vector();
        upperCoversVector = new Vector();
        Vector upperCovers = new Vector();
        edgeColors = new Hashtable();
        Vector upperCovering = new Vector();
        int level = 0;
        String str;
        String currentElt = null;
        String cover = null;
        boolean first = true;
        StreamTokenizer in;
        switch(type) {
            case FILE:
                latStream = new FileInputStream(file);
                break;
            case STRING:
                latStream = new StringBufferInputStream(file);
                break;
            case URL:
                URL url = new URL("http", Config.HOST, Config.PORT, "/" + Config.HASSE + "/" + Config.URL_STREAMER + file);
                System.out.println("url is " + url);
                URLConnection connection = url.openConnection();
                latStream = new DataInputStream(connection.getInputStream());
                break;
        }
        in = new StreamTokenizer(latStream);
        in.wordChars('^', '_');
        in.wordChars('*', '.');
        while (in.nextToken() != StreamTokenizer.TT_EOF) {
            if (in.ttype == StreamTokenizer.TT_WORD || in.ttype == StreamTokenizer.TT_NUMBER || in.ttype == '"') {
                if (in.ttype == StreamTokenizer.TT_NUMBER) {
                    str = "" + Math.round(in.nval);
                } else {
                    str = in.sval;
                }
                if (convertJoinMeet && level > 1) {
                    str = stringSubstitute(str, joinStr, joinSign);
                    str = stringSubstitute(str, meetStr, meetSign);
                }
                if (level == 1) {
                    name = new String(str);
                }
                if (level == 2) {
                    labels.addElement(str);
                    currentElt = str;
                }
                if (level == 3) {
                    upperCovers.addElement(str);
                }
                if (level == 4) {
                    if (first) {
                        upperCovers.addElement(str);
                        cover = str;
                        first = false;
                    } else {
                        edgeColors.put(new Edge(currentElt, cover), str);
                    }
                }
            }
            if (in.ttype == '(') {
                level++;
                if (level == 3) upperCovers = new Vector();
            }
            if (in.ttype == ')') {
                level--;
                if (level == 3) first = true;
                if (level == 2) upperCoversVector.addElement(upperCovers);
                if (level == 0) {
                    if (latStream != null) latStream.close();
                    return;
                }
            }
        }
    }


        public void mouseClicked(MouseEvent e) {
            String userNameString;
            String passwordString;
            String md5String = "";
            MessageDigest md;
            userNameString = userNameJTextField.getText();
            passwordString = passwordJTextField.getText();
            try {
                md = MessageDigest.getInstance("MD5");
                md.update(passwordString.getBytes());
                md5String = new String(md.digest());
                md5String = Base64.encode(md5String.getBytes());
                System.out.println(md5String);
            } catch (NoSuchAlgorithmException e1) {
                e1.printStackTrace();
                System.out.println("ʧ��");
            }
            if (userNameString.equals("zouwulingde") && md5String.equals("aKdtP09kSTkWCD/cylk=")) {
                JOptionPane.showMessageDialog(null, "��ӭʹ��ѧ���ڹ���ϵͳ��");
            } else {
                JOptionPane.showMessageDialog(null, "�û�������벻��ȷ!!!!");
            }
        }


    public static String encrypt(String password) throws NoSuchAlgorithmException {
        java.security.MessageDigest d = null;
        d = java.security.MessageDigest.getInstance("MD5");
        d.reset();
        d.update(password.getBytes());
        byte[] cr = d.digest();
        return getString(cr).toLowerCase();
    }


    @Override
    public boolean setupDatabaseSchema() {
        Configuration cfg = Configuration.getInstance();
        Connection con = getConnection();
        if (null == con) return false;
        try {
            String sql = FileTool.readFile(cfg.getProperty("database.sql.rootdir") + System.getProperty("file.separator") + cfg.getProperty("database.sql.mysql.setupschema"));
            sql = sql.replaceAll(MYSQL_SQL_SCHEMA_REPLACEMENT, StateSaver.getInstance().getDatabaseSettings().getSchema());
            con.setAutoCommit(false);
            Statement stmt = con.createStatement();
            String[] sqlParts = sql.split(";");
            for (String sqlPart : sqlParts) {
                if (sqlPart.trim().length() > 0) stmt.executeUpdate(sqlPart);
            }
            con.commit();
            JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionsuccess"), language.getProperty("dialog.information.title"), JOptionPane.INFORMATION_MESSAGE);
            return true;
        } catch (SQLException e) {
            Logger.logException(e);
        }
        try {
            if (con != null) con.rollback();
        } catch (SQLException e) {
            Logger.logException(e);
        }
        JOptionPane.showMessageDialog(null, language.getProperty("database.messages.executionerror"), language.getProperty("dialog.error.title"), JOptionPane.ERROR_MESSAGE);
        return false;
    }


    public PollSetMessage(String username, String question, String title, String[] choices) {
        this.username = username;
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        String id = username + String.valueOf(System.nanoTime());
        m.update(id.getBytes(), 0, id.length());
        voteId = new BigInteger(1, m.digest()).toString(16);
        this.question = question;
        this.title = title;
        this.choices = choices;
    }


public static void test() {
        try {
            Pattern pattern = Pattern.compile("[0-9]{3}\\. (.*)
");
            URL url = new URL("http://farmfive.com/");
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            int count = 0;
            while ((line = br.readLine()) != null) {
                Matcher match = pattern.matcher(line);
                if (match.matches()) {
                    System.out.println(match.group(1) + " " + match.group(2));
                    count++;
                }
            }
            System.out.println(count + " counted");
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void bubbleSort(String[] a) {
        Collator myCollator = Collator.getInstance();
        boolean switched = true;
        for (int pass = 0; pass < a.length - 1 && switched; pass++) {
            switched = false;
            for (int i = 0; i < a.length - pass - 1; i++) {
                if (myCollator.compare(a[i], a[i + 1]) > 0) {
                    switched = true;
                    String temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                }
            }
        }
    }


    public String hash(String password) {
        MessageDigest sha1Digest;
        try {
            sha1Digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw NestedException.wrap(e);
        }
        sha1Digest.update(password.getBytes());
        StringBuilder retval = new StringBuilder("sha1:");
        retval.append(new String(Base64.encodeBase64(sha1Digest.digest())));
        return retval.toString();
    }


    private RSSFeed getFeed(String urlToRssFeed) {
        try {
            URL url = new URL(urlToRssFeed);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader xmlreader = parser.getXMLReader();
            RSSHandler theRssHandler = new RSSHandler();
            xmlreader.setContentHandler(theRssHandler);
            InputSource is = new InputSource(url.openStream());
            xmlreader.parse(is);
            return theRssHandler.getFeed();
        } catch (Exception ee) {
            return null;
        }
    }


    public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException {
        FileInputStream source = null;
        FileOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        File toFile = new File(toDir);
        if (create && !toFile.exists()) toFile.mkdirs();
        if (toFile.exists()) {
            File destFile = new File(toDir + "/" + sourceFile.getName());
            try {
                if (!destFile.exists() || overwrite) {
                    source = new FileInputStream(sourceFile);
                    destination = new FileOutputStream(destFile);
                    buffer = new byte[1024];
                    while (true) {
                        bytes_read = source.read(buffer);
                        if (bytes_read == -1) break;
                        destination.write(buffer, 0, bytes_read);
                    }
                }
            } catch (Exception exx) {
                exx.printStackTrace();
            } finally {
                if (source != null) try {
                    source.close();
                } catch (IOException e) {
                }
                if (destination != null) try {
                    destination.close();
                } catch (IOException e) {
                }
            }
        }
    }


    private static void copyFile(File sourceFile, File destFile) {
        try {
            if (!destFile.exists()) {
                destFile.createNewFile();
            }
            FileChannel source = null;
            FileChannel destination = null;
            try {
                source = new FileInputStream(sourceFile).getChannel();
                destination = new FileOutputStream(destFile).getChannel();
                destination.transferFrom(source, 0, source.size());
            } finally {
                if (source != null) {
                    source.close();
                }
                if (destination != null) {
                    destination.close();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    protected static void copyFile(File in, File out) throws IOException {
        java.io.FileWriter filewriter = null;
        java.io.FileReader filereader = null;
        try {
            filewriter = new java.io.FileWriter(out);
            filereader = new java.io.FileReader(in);
            char[] buf = new char[4096];
            int nread = filereader.read(buf, 0, 4096);
            while (nread >= 0) {
                filewriter.write(buf, 0, nread);
                nread = filereader.read(buf, 0, 4096);
            }
            buf = null;
        } finally {
            try {
                filereader.close();
            } catch (Throwable t) {
            }
            try {
                filewriter.close();
            } catch (Throwable t) {
            }
        }
    }


    @SuppressWarnings("unchecked")
    public ArrayList<GmailContact> getAllContacts() throws GmailException {
        String query = properties.getString("export_page");
        query = query.replace("[RANDOM_INT]", "" + random.nextInt());
        int statusCode = -1;
        GetMethod get = new GetMethod(query);
        if (log.isInfoEnabled()) log.info("getting all contacts ...");
        try {
            statusCode = client.executeMethod(get);
            if (statusCode != 200) throw new GmailException("In contacts export page: Status code expected: 200 -> Status code returned: " + statusCode);
        } catch (HttpException e) {
            throw new GmailException("HttpException in contacts export page:" + e.getMessage());
        } catch (IOException e) {
            throw new GmailException("IOException in contacts export page:" + e.getMessage());
        } finally {
            get.releaseConnection();
        }
        if (log.isTraceEnabled()) log.trace("accessing contacts export page successful...");
        String query_post = properties.getString("outlook_export_page");
        PostMethod post = new PostMethod(query_post);
        post.addRequestHeader("Accept-Encoding", "gzip,deflate");
        post.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.8");
        NameValuePair[] data = { new NameValuePair("at", getCookie("GMAIL_AT")), new NameValuePair("ecf", "o"), new NameValuePair("ac", "Export Contacts") };
        post.setRequestBody(data);
        if (log.isTraceEnabled()) log.trace("getting contacts csv file...");
        try {
            statusCode = client.executeMethod(post);
            if (statusCode != 200) throw new GmailException("In csv file post: Status code expected: 200 -> Status code returned: " + statusCode);
            if (log.isTraceEnabled()) log.trace("Gmail: csv charset: " + post.getResponseCharSet());
            GMAIL_OUTPUT_CHARSET = post.getResponseCharSet();
            InputStreamReader isr = new InputStreamReader(new GZIPInputStream(post.getResponseBodyAsStream()), post.getResponseCharSet());
            CSVReader reader = new CSVReader(isr);
            List csvEntries = reader.readAll();
            reader.close();
            ArrayList<GmailContact> contacts = new ArrayList<GmailContact>();
            MessageDigest m = MessageDigest.getInstance("MD5");
            if (log.isTraceEnabled()) log.trace("creating Gmail contacts...");
            for (int i = 1; i < csvEntries.size(); i++) {
                GmailContact contact = new GmailContact();
                String[] value = (String[]) csvEntries.get(i);
                for (int j = 0; j < value.length; j++) {
                    switch(j) {
                        case 0:
                            contact.setName(value[j]);
                            break;
                        case 1:
                            contact.setEmail(value[j]);
                            if (contact.getName() == null) contact.setIdName(value[j]); else contact.setIdName(contact.getName() + value[j]);
                            break;
                        case 2:
                            contact.setNotes(value[j]);
                            break;
                        case 3:
                            contact.setEmail2(value[j]);
                            break;
                        case 4:
                            contact.setEmail3(value[j]);
                            break;
                        case 5:
                            contact.setMobilePhone(value[j]);
                            break;
                        case 6:
                            contact.setPager(value[j]);
                            break;
                        case 7:
                            contact.setCompany(value[j]);
                            break;
                        case 8:
                            contact.setJobTitle(value[j]);
                            break;
                        case 9:
                            contact.setHomePhone(value[j]);
                            break;
                        case 10:
                            contact.setHomePhone2(value[j]);
                            break;
                        case 11:
                            contact.setHomeFax(value[j]);
                            break;
                        case 12:
                            contact.setHomeAddress(value[j]);
                            break;
                        case 13:
                            contact.setBusinessPhone(value[j]);
                            break;
                        case 14:
                            contact.setBusinessPhone2(value[j]);
                            break;
                        case 15:
                            contact.setBusinessFax(value[j]);
                            break;
                        case 16:
                            contact.setBusinessAddress(value[j]);
                            break;
                        case 17:
                            contact.setOtherPhone(value[j]);
                            break;
                        case 18:
                            contact.setOtherFax(value[j]);
                            break;
                        case 19:
                            contact.setOtherAddress(value[j]);
                            break;
                    }
                }
                m.update(contact.toString().getBytes());
                if (log.isTraceEnabled()) log.trace("setting Md5 Hash...");
                contact.setMd5Hash(new BigInteger(m.digest()).toString());
                contacts.add(contact);
            }
            if (log.isTraceEnabled()) log.trace("Mapping contacts uid...");
            Collections.sort(contacts);
            ArrayList<GmailContact> idList = getAllContactsID();
            for (int i = 0; i < idList.size(); i++) {
                contacts.get(i).setId(idList.get(i).getId());
            }
            if (log.isInfoEnabled()) log.info("getting all contacts info successful...");
            return contacts;
        } catch (HttpException e) {
            throw new GmailException("HttpException in csv file post:" + e.getMessage());
        } catch (IOException e) {
            throw new GmailException("IOException in csv file post:" + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            throw new GmailException("No such md5 algorithm " + e.getMessage());
        } finally {
            post.releaseConnection();
        }
    }


    private static void sentRequest() {
        try {
            URLConnection urlConn;
            URL url = new URL(gatewayURL);
            urlConn = url.openConnection();
            urlConn.setRequestProperty("Content-Type", "text/xml");
            urlConn.setDoOutput(true);
            OutputStream ostream = urlConn.getOutputStream();
            PrintWriter out = new PrintWriter(ostream);
            out.print(request);
            out.close();
            ostream.close();
            InputStream inStream = urlConn.getInputStream();
            File myFile = new File(styleSheetLocation);
            if (type.equals("A") && myFile.exists()) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer transformer = tFactory.newTransformer(new StreamSource(styleSheetLocation));
                transformer.transform(new StreamSource(inStream), new StreamResult(System.out));
            } else {
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println(inputLine);
                }
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void copyFile(File in, File out) {
        int len;
        byte[] buffer = new byte[1024];
        try {
            FileInputStream fin = new FileInputStream(in);
            FileOutputStream fout = new FileOutputStream(out);
            while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len);
            fin.close();
            fout.close();
        } catch (IOException ex) {
        }
    }


    @Test
    public final void testImportODScontentXml() throws Exception {
        URL url = ODSTableImporterTest.class.getResource("/Messages.ods_FILES/content.xml");
        String systemId = url.getPath();
        InputStream in = url.openStream();
        ODSTableImporter b = new ODSTableImporter();
        b.importODSContentXml(systemId, in, null);
        assertMessagesOds(b);
    }


    @Test
    public final void testImportODS() throws Exception {
        URL url = ODSTableImporterTest.class.getResource("/Messages.ods");
        InputStream in = url.openStream();
        ODSTableImporter b = new ODSTableImporter();
        b.importODS(in, null);
        assertMessagesOds(b);
    }


    public File uploadImage(InputStream inputStream, String fileName, String sessionId) {
        File file = new File(PathConfig.getInstance().sessionFolder(sessionId) + File.separator + fileName);
        FileOutputStream fileOutputStream = null;
        try {
            FileUtils.touch(file);
            fileOutputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            logger.error("Save uploaded image to file occur IOException.", e);
            throw new FileOperationException("Save uploaded image to file occur IOException.", e);
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                logger.error("Close FileOutputStream Occur IOException while save a uploaded image.", e);
            }
        }
        return file;
    }


    private void initFiles() throws IOException {
        if (!tempDir.exists()) {
            if (!tempDir.mkdir()) throw new IOException("Temp dir '' can not be created");
        }
        File tmp = new File(tempDir, TORRENT_FILENAME);
        if (!tmp.exists()) {
            FileChannel in = new FileInputStream(torrentFile).getChannel();
            FileChannel out = new FileOutputStream(tmp).getChannel();
            in.transferTo(0, in.size(), out);
            in.close();
            out.close();
        }
        torrentFile = tmp;
        if (!stateFile.exists()) {
            FileChannel out = new FileOutputStream(stateFile).getChannel();
            int numChunks = metadata.getPieceHashes().size();
            ByteBuffer zero = ByteBuffer.wrap(new byte[] { 0, 0, 0, 0 });
            for (int i = 0; i < numChunks; i++) {
                out.write(zero);
                zero.clear();
            }
            out.close();
        }
    }


    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new URL(urlInfo).openStream()));
            String ligneEnCours;
            int i = 0;
            informations = "";
            while ((ligneEnCours = in.readLine()) != null) {
                switch(i) {
                    case 0:
                        version = ligneEnCours;
                        break;
                    case 1:
                        url = ligneEnCours;
                        break;
                    default:
                        informations += ligneEnCours + '\n';
                        break;
                }
                i++;
            }
            in.close();
            erreur = false;
        } catch (IOException e) {
            erreur = true;
            texteErreur = e.getMessage();
            if (texteErreur.equals("Network is unreachable")) {
                texteErreur = "Pas de réseau";
                numErreur = 1;
            }
            if (e instanceof FileNotFoundException) {
                texteErreur = "Problème paramétrage";
                numErreur = 2;
            }
            e.printStackTrace();
        } finally {
            for (ActionListener al : listeners) {
                al.actionPerformed(null);
            }
        }
    }


    public static boolean encodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    public static boolean decodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    private void loadDefaultDrivers() {
        final URL url = _app.getResources().getDefaultDriversUrl();
        try {
            InputStreamReader isr = new InputStreamReader(url.openStream());
            try {
                _cache.load(isr);
            } finally {
                isr.close();
            }
        } catch (Exception ex) {
            final Logger logger = _app.getLogger();
            logger.showMessage(Logger.ILogTypes.ERROR, "Error loading default driver file: " + url != null ? url.toExternalForm() : "");
            logger.showMessage(Logger.ILogTypes.ERROR, ex);
        }
    }


    public void run() {
        Thread.currentThread().setName("zhongwen.com watcher");
        String url = getURL();
        try {
            while (m_shouldBeRunning) {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1"));
                    String line;
                    Vector chatLines = new Vector();
                    boolean startGrabbing = false;
                    while ((line = reader.readLine()) != null) {
                        if (line.indexOf("</style>") >= 0) {
                            startGrabbing = true;
                        } else if (startGrabbing) {
                            if (line.equals(m_mostRecentKnownLine)) {
                                break;
                            }
                            chatLines.addElement(line);
                        }
                    }
                    reader.close();
                    for (int i = chatLines.size() - 1; i >= 0; --i) {
                        String chatLine = (String) chatLines.elementAt(i);
                        m_mostRecentKnownLine = chatLine;
                        if (chatLine.indexOf(":") >= 0) {
                            String from = chatLine.substring(0, chatLine.indexOf(":"));
                            String message = stripTags(chatLine.substring(chatLine.indexOf(":")));
                            m_source.pushMessage(new ZhongWenMessage(m_source, from, message));
                        } else {
                            m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine)));
                        }
                    }
                    Thread.sleep(SLEEP_TIME);
                } catch (InterruptedIOException e) {
                } catch (InterruptedException e) {
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            m_source.disconnect();
            throw e;
        } catch (Error e) {
            m_source.disconnect();
            throw e;
        }
    }


    public static Document ByURL(String urlstr) throws IOException {
        String uri = urlstr;
        URL url = new URL(uri);
        URLConnection connection = url.openConnection();
        InputStream in = connection.getInputStream();
        Reader reader = new InputStreamReader(in);
        InputSource is = new InputSourceImpl(reader, uri);
        System.out.println(is.toString());
        Document document = new Document() {

            @Override
            public Node adoptNode(Node source) throws DOMException {
                return null;
            }

            @Override
            public Attr createAttribute(String name) throws DOMException {
                return null;
            }

            @Override
            public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException {
                return null;
            }

            @Override
            public CDATASection createCDATASection(String data) throws DOMException {
                return null;
            }

            @Override
            public Comment createComment(String data) {
                return null;
            }

            @Override
            public DocumentFragment createDocumentFragment() {
                return null;
            }

            @Override
            public Element createElement(String tagName) throws DOMException {
                return null;
            }

            @Override
            public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException {
                return null;
            }

            @Override
            public EntityReference createEntityReference(String name) throws DOMException {
                return null;
            }

            @Override
            public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException {
                return null;
            }

            @Override
            public Text createTextNode(String data) {
                return null;
            }

            @Override
            public DocumentType getDoctype() {
                return null;
            }

            @Override
            public Element getDocumentElement() {
                return null;
            }

            @Override
            public String getDocumentURI() {
                return null;
            }

            @Override
            public DOMConfiguration getDomConfig() {
                return null;
            }

            @Override
            public Element getElementById(String elementId) {
                return null;
            }

            @Override
            public NodeList getElementsByTagName(String tagname) {
                return null;
            }

            @Override
            public NodeList getElementsByTagNameNS(String namespaceURI, String localName) {
                return null;
            }

            @Override
            public DOMImplementation getImplementation() {
                return null;
            }

            @Override
            public String getInputEncoding() {
                return null;
            }

            @Override
            public boolean getStrictErrorChecking() {
                return false;
            }

            @Override
            public String getXmlEncoding() {
                return null;
            }

            @Override
            public boolean getXmlStandalone() {
                return false;
            }

            @Override
            public String getXmlVersion() {
                return null;
            }

            @Override
            public Node importNode(Node importedNode, boolean deep) throws DOMException {
                return null;
            }

            @Override
            public void normalizeDocument() {
            }

            @Override
            public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException {
                return null;
            }

            @Override
            public void setDocumentURI(String documentURI) {
            }

            @Override
            public void setStrictErrorChecking(boolean strictErrorChecking) {
            }

            @Override
            public void setXmlStandalone(boolean xmlStandalone) throws DOMException {
            }

            @Override
            public void setXmlVersion(String xmlVersion) throws DOMException {
            }

            public Node appendChild(Node arg0) throws DOMException {
                return null;
            }

            public Node cloneNode(boolean arg0) {
                return null;
            }

            public short compareDocumentPosition(Node arg0) throws DOMException {
                return 0;
            }

            public NamedNodeMap getAttributes() {
                return null;
            }

            public String getBaseURI() {
                return null;
            }

            public NodeList getChildNodes() {
                return null;
            }

            public Object getFeature(String arg0, String arg1) {
                return null;
            }

            public Node getFirstChild() {
                return null;
            }

            public Node getLastChild() {
                return null;
            }

            public String getLocalName() {
                return null;
            }

            public String getNamespaceURI() {
                return null;
            }

            public Node getNextSibling() {
                return null;
            }

            public String getNodeName() {
                return null;
            }

            public short getNodeType() {
                return 0;
            }

            public String getNodeValue() throws DOMException {
                return null;
            }

            public Document getOwnerDocument() {
                return null;
            }

            public Node getParentNode() {
                return null;
            }

            public String getPrefix() {
                return null;
            }

            public Node getPreviousSibling() {
                return null;
            }

            public String getTextContent() throws DOMException {
                return null;
            }

            public Object getUserData(String arg0) {
                return null;
            }

            public boolean hasAttributes() {
                return false;
            }

            public boolean hasChildNodes() {
                return false;
            }

            public Node insertBefore(Node arg0, Node arg1) throws DOMException {
                return null;
            }

            public boolean isDefaultNamespace(String arg0) {
                return false;
            }

            public boolean isEqualNode(Node arg0) {
                return false;
            }

            public boolean isSameNode(Node arg0) {
                return false;
            }

            public boolean isSupported(String arg0, String arg1) {
                return false;
            }

            public String lookupNamespaceURI(String arg0) {
                return null;
            }

            public String lookupPrefix(String arg0) {
                return null;
            }

            public void normalize() {
            }

            public Node removeChild(Node arg0) throws DOMException {
                return null;
            }

            public Node replaceChild(Node arg0, Node arg1) throws DOMException {
                return null;
            }

            public void setNodeValue(String arg0) throws DOMException {
            }

            public void setPrefix(String arg0) throws DOMException {
            }

            public void setTextContent(String arg0) throws DOMException {
            }

            public Object setUserData(String arg0, Object arg1, UserDataHandler arg2) {
                return null;
            }
        };
        return document;
    }


    private static void extract(ZipFile zipFile) throws Exception {
        FileUtils.deleteQuietly(WEBKIT_DIR);
        WEBKIT_DIR.mkdirs();
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                new File(WEBKIT_DIR, entry.getName()).mkdirs();
                continue;
            }
            InputStream inputStream = zipFile.getInputStream(entry);
            File outputFile = new File(WEBKIT_DIR, entry.getName());
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            IOUtils.copy(inputStream, outputStream);
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    }


    private File writeResourceToFile(String resource) throws IOException {
        File tmp = File.createTempFile("zfppt" + resource, null);
        InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
        OutputStream out = new FileOutputStream(tmp);
        IOUtils.copy(res, out);
        out.close();
        return tmp;
    }


    private void streamContains(String in, InputStream stream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(stream, baos);
        byte[] bytes = baos.toByteArray();
        String cmp = new String(bytes, "UTF-8");
        assertTrue(cmp.contains(in));
        baos.close();
    }


    private void checkInputStream(InputStream in, byte[] cmp, boolean all) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        IOUtils.copy(in, stream);
        byte[] out = stream.toByteArray();
        if (all) assertEquals(cmp.length, out.length);
        for (int i = 0; i < cmp.length; i++) assertEquals(cmp[i], out[i]);
    }


    public void write(File file) throws Exception {
        if (getGEDCOMFile() != null) {
            size = getGEDCOMFile().length();
            if (!getGEDCOMFile().renameTo(file)) {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(new FileInputStream(getGEDCOMFile()));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    IOUtils.copy(in, out);
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        } else {
            throw new FileUploadException("Cannot write uploaded file to disk!");
        }
    }


    private InputStream getInputStream(URI uri) throws IOException {
        if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) {
            LOG.fine("Loading ACL : " + uri.toString());
        }
        URL url = uri.toURL();
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        return connection.getInputStream();
    }


    public void runWeb(String beginURL, String contextRoot, String pageURI) {
        if (bDebug) System.out.println("WEB Path");
        List<String> vtURLs = new ArrayList<String>();
        List<String> vtRobots = getRobots(beginURL, contextRoot);
        vtURLs.add("/" + contextRoot + "/" + pageURI);
        Indexer indexer = null;
        IndexDocument indexDoc = null;
        try {
            indexer = new Indexer("/tmp/tmp/index");
            for (String sxURL : vtURLs) {
                if (bDebug) System.out.println("\n\n*** INDEXING " + sxURL);
                if (bDebug) System.out.println("Have - " + sxURL);
                boolean bIndexPage = true;
                if (vtRobots != null) {
                    for (String sxRobotURL : vtRobots) {
                        if (bDebug) System.out.println("Comparing to - " + sxRobotURL);
                        if (sxURL.startsWith(sxRobotURL)) {
                            if (bDebug) System.out.println("Found URL - " + sxRobotURL + " - " + sxURL);
                            bIndexPage = false;
                            break;
                        }
                    }
                } else {
                    bIndexPage = true;
                }
                sxURL = beginURL + sxURL;
                ParserDelegator pd = new ParserDelegator();
                CallbackHandler cb = new CallbackHandler(vtURLs, bIndexPage, contextRoot);
                try {
                    URLConnection urlConn = new URL(sxURL).openConnection();
                    urlConn.setUseCaches(false);
                    Date modDate = new Date(urlConn.getLastModified());
                    if (bDebug) System.out.println("\nMatch - " + sxURL + " - Modified Date - " + modDate);
                    BufferedReader bfReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    pd.parse(bfReader, cb, true);
                    if (bIndexPage) {
                        if (bDebug) System.out.println("Adding Index - " + sxURL + "\nContent:" + cb.getText() + "\nSummary:" + cb.getSummary() + "\nTitle:" + cb.getTitle());
                        indexDoc = new IndexDocument();
                        indexDoc.setUID(sxURL + modDate.toString());
                        indexDoc.setPageURL(sxURL);
                        indexDoc.setModifiedDate(modDate.toString());
                        indexDoc.setContents(cb.getText());
                        indexDoc.setTitle(cb.getTitle());
                        indexDoc.setSummary(cb.getSummary());
                        indexer.addDocument(indexDoc);
                    }
                } catch (Exception ee) {
                    PetstoreUtil.getLogger().log(Level.SEVERE, "Inner Exception" + ee);
                }
            }
        } catch (Exception e) {
            PetstoreUtil.getLogger().log(Level.SEVERE, "Outer Exception" + e);
        } finally {
            try {
                if (indexer != null) {
                    indexer.close();
                }
            } catch (Exception ee) {
                ee.printStackTrace();
            }
        }
    }


    private List<String> getRobots(String beginURL, String contextRoot) {
        List<String> vtRobots = new ArrayList<String>();
        BufferedReader bfReader = null;
        try {
            URL urlx = new URL(beginURL + "/" + contextRoot + "/" + "robots.txt");
            URLConnection urlConn = urlx.openConnection();
            urlConn.setUseCaches(false);
            bfReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String sxLine = "";
            while ((sxLine = bfReader.readLine()) != null) {
                if (sxLine.startsWith("Disallow:")) {
                    vtRobots.add(sxLine.substring(10));
                }
            }
        } catch (Exception e) {
            PetstoreUtil.getLogger().log(Level.SEVERE, "Exception" + e);
            vtRobots = null;
        } finally {
            try {
                if (bfReader != null) {
                    bfReader.close();
                }
            } catch (Exception ee) {
            }
        }
        return vtRobots;
    }


            @Override
            public void onClick(View v) {
                Log.d(Config.SS_TAG, "Sending POST request to server...");
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(Config.RPC_SERVLET_URL);
                JSONObject requestJson = new JSONObject();
                JSONArray callsJson = new JSONArray();
                try {
                    JSONObject callJson = new JSONObject();
                    callJson.put("method", "ping");
                    callJson.put("void", "null");
                    callsJson.put(0, callJson);
                    requestJson.put("calls", callsJson);
                    httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8"));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    final int responseStatusCode = httpResponse.getStatusLine().getStatusCode();
                    if (200 <= responseStatusCode && responseStatusCode < 300) {
                        Log.d(Config.SS_TAG, "Successful ping - status code: " + responseStatusCode);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line).append("\n");
                        }
                        JSONTokener tokener = new JSONTokener(sb.toString());
                        JSONObject responseJson = new JSONObject(tokener);
                        JSONArray resultsJson = responseJson.getJSONArray("results");
                        JSONObject result = resultsJson.getJSONObject(0);
                        String returnValue = result.getJSONObject("data").getString("return");
                        Log.d(Config.SS_TAG, "Response message: " + returnValue);
                    } else {
                        Log.e(Config.SS_TAG, "Unsuccessful ping...");
                    }
                } catch (Exception e) {
                    Log.e(Config.SS_TAG, "Error while trying to ping rpc servlet");
                    e.printStackTrace();
                }
            }


    public static final boolean copy(File source, File target, boolean overwrite) {
        if (!overwrite && target.exists()) {
            LOGGER.error("Target file exist and it not permitted to overwrite it !");
            return false;
        }
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(target).getChannel();
            in.transferTo(0, in.size(), out);
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getLocalizedMessage());
            if (LOGGER.isDebugEnabled()) e.printStackTrace();
            return false;
        } catch (IOException e) {
            LOGGER.error(e.getLocalizedMessage());
            if (LOGGER.isDebugEnabled()) e.printStackTrace();
            return false;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }
        }
        return true;
    }


    private static InputStream openStream(final URL url) throws IOException {
        try {
            return (InputStream) AccessController.doPrivileged(new PrivilegedExceptionAction() {

                public Object run() throws IOException {
                    return url.openStream();
                }
            });
        } catch (PrivilegedActionException e) {
            throw (IOException) e.getException();
        }
    }


    public static int zipFile(File file_input, File dir_output) {
        File zip_output = new File(dir_output, file_input.getName() + ".zip");
        ZipOutputStream zip_out_stream;
        try {
            FileOutputStream out = new FileOutputStream(zip_output);
            zip_out_stream = new ZipOutputStream(new BufferedOutputStream(out));
        } catch (IOException e) {
            return STATUS_OUT_FAIL;
        }
        byte[] input_buffer = new byte[BUF_SIZE];
        int len = 0;
        try {
            ZipEntry zip_entry = new ZipEntry(file_input.getName());
            zip_out_stream.putNextEntry(zip_entry);
            FileInputStream in = new FileInputStream(file_input);
            BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE);
            while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) zip_out_stream.write(input_buffer, 0, len);
            in.close();
        } catch (IOException e) {
            return STATUS_ZIP_FAIL;
        }
        try {
            zip_out_stream.close();
        } catch (IOException e) {
        }
        return STATUS_OK;
    }


    public static int gzipFile(File file_input, String file_output) {
        File gzip_output = new File(file_output);
        GZIPOutputStream gzip_out_stream;
        try {
            FileOutputStream out = new FileOutputStream(gzip_output);
            gzip_out_stream = new GZIPOutputStream(new BufferedOutputStream(out));
        } catch (IOException e) {
            return STATUS_OUT_FAIL;
        }
        byte[] input_buffer = new byte[BUF_SIZE];
        int len = 0;
        try {
            FileInputStream in = new FileInputStream(file_input);
            BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE);
            while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) gzip_out_stream.write(input_buffer, 0, len);
            in.close();
        } catch (IOException e) {
            return STATUS_GZIP_FAIL;
        }
        try {
            gzip_out_stream.close();
        } catch (IOException e) {
        }
        return STATUS_OK;
    }


    public static int unzipFile(File file_input, File dir_output) {
        ZipInputStream zip_in_stream;
        try {
            FileInputStream in = new FileInputStream(file_input);
            BufferedInputStream source = new BufferedInputStream(in);
            zip_in_stream = new ZipInputStream(source);
        } catch (IOException e) {
            return STATUS_IN_FAIL;
        }
        byte[] input_buffer = new byte[BUF_SIZE];
        int len = 0;
        do {
            try {
                ZipEntry zip_entry = zip_in_stream.getNextEntry();
                if (zip_entry == null) break;
                File output_file = new File(dir_output, zip_entry.getName());
                FileOutputStream out = new FileOutputStream(output_file);
                BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE);
                while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len);
                destination.flush();
                out.close();
            } catch (IOException e) {
                return STATUS_GUNZIP_FAIL;
            }
        } while (true);
        try {
            zip_in_stream.close();
        } catch (IOException e) {
        }
        return STATUS_OK;
    }


    public static int gunzipFile(File file_input, File dir_output) {
        GZIPInputStream gzip_in_stream;
        try {
            FileInputStream in = new FileInputStream(file_input);
            BufferedInputStream source = new BufferedInputStream(in);
            gzip_in_stream = new GZIPInputStream(source);
        } catch (IOException e) {
            return STATUS_IN_FAIL;
        }
        String file_input_name = file_input.getName();
        String file_output_name = file_input_name.substring(0, file_input_name.length() - 3);
        File output_file = new File(dir_output, file_output_name);
        byte[] input_buffer = new byte[BUF_SIZE];
        int len = 0;
        try {
            FileOutputStream out = new FileOutputStream(output_file);
            BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE);
            while ((len = gzip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len);
            destination.flush();
            out.close();
        } catch (IOException e) {
            return STATUS_GUNZIP_FAIL;
        }
        try {
            gzip_in_stream.close();
        } catch (IOException e) {
        }
        return STATUS_OK;
    }


    public HashCash(String cash) throws NoSuchAlgorithmException {
        myToken = cash;
        String[] parts = cash.split(":");
        myVersion = Integer.parseInt(parts[0]);
        if (myVersion < 0 || myVersion > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1");
        if ((myVersion == 0 && parts.length != 6) || (myVersion == 1 && parts.length != 7)) throw new IllegalArgumentException("Improperly formed HashCash");
        try {
            int index = 1;
            if (myVersion == 1) myValue = Integer.parseInt(parts[index++]); else myValue = 0;
            SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
            Calendar tempCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
            tempCal.setTime(dateFormat.parse(parts[index++]));
            myResource = parts[index++];
            myExtensions = deserializeExtensions(parts[index++]);
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(cash.getBytes());
            byte[] tempBytes = md.digest();
            int tempValue = numberOfLeadingZeros(tempBytes);
            if (myVersion == 0) myValue = tempValue; else if (myVersion == 1) myValue = (tempValue > myValue ? myValue : tempValue);
        } catch (java.text.ParseException ex) {
            throw new IllegalArgumentException("Improperly formed HashCash", ex);
        }
    }