    public static void copyFile(File in, File out) throws Exception {
        FileChannel sourceChannel = new FileInputStream(in).getChannel();
        FileChannel destinationChannel = new FileOutputStream(out).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        sourceChannel.close();
        destinationChannel.close();
    }

    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    static Matrix readMatrix(String filename, int nrow, int ncol) {
        Matrix cij = new Matrix(nrow, ncol);
        try {
            URL url = filename.getClass().getResource(filename);
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
            for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));
        } catch (Exception xc) {
            xc.printStackTrace();
        }
        return cij;
    }

    public void patch() throws IOException {
        if (mods.isEmpty()) {
            return;
        }
        IOUtils.copy(new FileInputStream(Paths.getMinecraftJarPath()), new FileOutputStream(new File(Paths.getMinecraftBackupPath())));
        JarFile mcjar = new JarFile(Paths.getMinecraftJarPath());
    }


    public boolean referredFilesChanged() throws MalformedURLException, IOException {
        for (String file : referredFiles) {
            if (FileUtils.isURI(file)) {
                URLConnection url = new URL(file).openConnection();
                if (url.getLastModified() > created) return true;
            } else if (FileUtils.isFile(file)) {
                File f = new File(file);
                if (f.lastModified() > created) return true;
            }
        }
        return false;
    }

	public FTPClient sample3a(String ftpserver, int ftpport, String proxyserver, int proxyport, String username, String password) throws SocketException, IOException {
		FTPHTTPClient ftpClient = new FTPHTTPClient(proxyserver, proxyport);
		ftpClient.connect(ftpserver, ftpport);
		ftpClient.login(username, password);
		return ftpClient;
	}


    protected void truncate(final File file) {
        LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");
        if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
            final File backupRoot = new File(this.getBackupDir());
            if (!backupRoot.exists() && !backupRoot.mkdirs()) {
                throw new AppenderInitializationError("Can't create backup dir for backup storage");
            }
            SimpleDateFormat df;
            try {
                df = new SimpleDateFormat(this.getBackupDateFormat());
            } catch (final Exception e) {
                throw new AppenderInitializationError("Invalid date formate for backup files: " + this.getBackupDateFormat(), e);
            }
            final String date = df.format(new Date(file.lastModified()));
            final File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
            ZipOutputStream zos = null;
            FileInputStream fis = null;
            try {
                zos = new ZipOutputStream(new FileOutputStream(zipFile));
                final ZipEntry entry = new ZipEntry(file.getName());
                entry.setMethod(ZipEntry.DEFLATED);
                entry.setCrc(FileUtils.checksumCRC32(file));
                zos.putNextEntry(entry);
                fis = FileUtils.openInputStream(file);
                final byte[] buffer = new byte[1024];
                int readed;
                while ((readed = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, readed);
                }
            } catch (final Exception e) {
                throw new AppenderInitializationError("Can't create zip file", e);
            } finally {
                if (zos != null) {
                    try {
                        zos.close();
                    } catch (final IOException e) {
                        LogLog.warn("Can't close zip file", e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (final IOException e) {
                        LogLog.warn("Can't close zipped file", e);
                    }
                }
            }
            if (!file.delete()) {
                throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
            }
        }
    }

    public void deleteAuthors() throws Exception {
        if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected.");
        String[] pids = proposalIds.split(",");
        String[] uids = usrIds.split(",");
        int pnum = pids.length;
        int unum = uids.length;
        if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected.");
        int i, j;
        PreparedStatement prepStmt = null;
        try {
            con = database.getConnection();
            con.setAutoCommit(false);
            String pStr = "delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?";
            prepStmt = con.prepareStatement(pStr);
            for (i = 0; i < pnum; i++) {
                for (j = 0; j < unum; j++) {
                    if (!uids[j].equals(userId)) {
                        prepStmt.setString(1, pids[i]);
                        prepStmt.setString(2, uids[j]);
                        prepStmt.executeUpdate();
                    }
                }
            }
            con.commit();
        } catch (Exception e) {
            if (!con.isClosed()) {
                con.rollback();
                prepStmt.close();
                con.close();
            }
            throw e;
        }
    }


    public void writeConfiguration(Writer out) throws IOException {
        if (myResource == null) {
            out.append("# Unable to print configuration resource\n");
        } else {
            URL url = myResource.getUrl();
            InputStream in = url.openStream();
            if (in != null) {
                try {
                    IOUtils.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            } else {
                out.append("# Unable to print configuration resource\n");
            }
        }
    }

    private static String scramble(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16));
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    public void testJPEGRaster() throws MalformedURLException, IOException {
        System.out.println("JPEGCodec RasterImage:");
        long start = Calendar.getInstance().getTimeInMillis();
        for (int i = 0; i < images.length; i++) {
            String url = Constants.getDefaultURIMediaConnectorBasePath() + "albums/hund/" + images[i];
            InputStream istream = (new URL(url)).openStream();
            JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);
            Raster raster = dec.decodeAsRaster();
            int width = raster.getWidth();
            int height = raster.getHeight();
            istream.close();
            System.out.println("w: " + width + " - h: " + height);
        }
        long stop = Calendar.getInstance().getTimeInMillis();
        System.out.println("zeit: " + (stop - start));
    }

    @Test
    public void test30_passwordAging() throws Exception {
        Db db = DbConnection.defaultCieDbRW();
        try {
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "5", 1);
            PreparedStatement pst = db.prepareStatement("UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?");
            pst.setString(1, "esis");
            db.executeUpdate(pst);
            db.commit();
            p_logout();
            t30login1();
            assertTrue(isPasswordExpired());
            PeopleInfoLine me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));
            t30chgpasswd();
            assertFalse(isPasswordExpired());
            me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));
            p_logout();
            t30login2();
            assertFalse(isPasswordExpired());
            t30chgpasswd2();
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "0", 1);
            db.commit();
        } catch (Exception e) {
            e.printStackTrace();
            db.rollback();
        } finally {
            db.safeClose();
        }
    }


    public boolean crear() {
        int result = 0;
        String sql = "insert into jugador" + "(apellidoPaterno, apellidoMaterno, nombres, fechaNacimiento, pais, rating, sexo)" + "values (?, ?, ?, ?, ?, ?, ?)";
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement(elJugador);
            result = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (result > 0);
    }

    private static final String hash(String input, String algorithm) {
        try {
            MessageDigest dig = MessageDigest.getInstance(algorithm);
            dig.update(input.getBytes());
            StringBuffer result = new StringBuffer();
            byte[] digest = dig.digest();
            String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
            for (int i = 0; i < digest.length; i++) {
                int u = digest[i];
                u &= 0x000000FF;
                int highCount = u / 16;
                int lowCount = u - (highCount * 16);
                result.append(hex[highCount]);
                result.append(hex[lowCount]);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

    public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
        HttpURLConnection con = null;
        InputStream is = null;
        try {
            URL u = new URL(url);
            if (url.startsWith("file://")) {
                is = new BufferedInputStream(u.openStream());
            } else {
                Proxy proxy;
                if (proxyHost != null) {
                    proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                } else {
                    proxy = Proxy.NO_PROXY;
                }
                con = (HttpURLConnection) u.openConnection(proxy);
                con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
                con.addRequestProperty("Accept-Charset", "UTF-8");
                con.addRequestProperty("Accept-Language", "en-US,en");
                con.addRequestProperty("Accept", "text/html,image/*");
                con.setDoInput(true);
                con.setDoOutput(false);
                con.connect();
                is = new BufferedInputStream(con.getInputStream());
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            return baos.toByteArray();
        } finally {
            IOUtils.closeQuietly(is);
            if (con != null) {
                con.disconnect();
            }
        }
    }


    public static void copy(String fileFrom, String fileTo) throws IOException {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputStream = new FileInputStream(fileFrom);
            outputStream = new FileOutputStream(fileTo);
            inputChannel = inputStream.getChannel();
            outputChannel = outputStream.getChannel();
            inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        } finally {
            try {
                inputChannel.close();
            } finally {
                try {
                    outputChannel.close();
                } finally {
                    try {
                        inputStream.close();
                    } finally {
                        outputStream.close();
                    }
                }
            }
        }
    }

    public String encrypt(String password) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(password.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        String hashword = hash.toString(16);
        return hashword;
    }


    @SuppressWarnings("unchecked")
    private ReaderFeed processEntrys(String urlStr, String currentFlag) throws UnsupportedEncodingException, IOException, JDOMException {
        String key = "processEntrys@" + urlStr + "_" + currentFlag;
        if (cache.containsKey(key)) {
            return (ReaderFeed) cache.get(key);
        }
        List<Post> postList = new ArrayList<Post>();
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Cookie", "SID=" + sid);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        SAXBuilder builder = new SAXBuilder(false);
        Document doc = builder.build(reader);
        Element root = doc.getRootElement();
        Namespace grNamespace = root.getNamespace("gr");
        Namespace namespace = root.getNamespace();
        String newflag = root.getChildText("continuation", grNamespace);
        String title = root.getChildText("title", namespace);
        String subTitle = root.getChildText("subtitle", namespace);
        List<Element> entryList = root.getChildren("entry", namespace);
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        for (Element e : entryList) {
            Post post = new Post();
            post.setTitle(e.getChildText("title", namespace));
            try {
                post.setDate(sdf.parse(e.getChildText("published", namespace)));
            } catch (ParseException e1) {
            }
            post.setUrl(e.getChild("link", namespace).getAttributeValue("href"));
            post.setSauthor(e.getChild("author", namespace).getChildText("name", namespace));
            String content = e.getChildText("content", namespace);
            if (StringUtils.isEmpty(content)) {
                content = e.getChildText("description", namespace);
            }
            if (StringUtils.isEmpty(content)) {
                content = e.getChildText("summary", namespace);
            }
            post.setContent(content);
            postList.add(post);
        }
        ReaderFeed readerFeed = new ReaderFeed();
        readerFeed.setTitle(title);
        readerFeed.setSubTitle(subTitle);
        readerFeed.setFlag(newflag);
        readerFeed.setPostList(postList);
        cache.put(key, readerFeed);
        return readerFeed;
    }

    public void test() throws Exception {
        StorageStringWriter s = new StorageStringWriter(2048, "UTF-8");
        s.addText("Test");
        try {
            s.getOutputStream();
            fail("Should throw IOException as method not supported.");
        } catch (IOException e) {
        }
        s.getWriter().write("ing is important");
        s.close(ResponseStateOk.getInstance());
        assertEquals("Testing is important", s.getText());
        InputStream input = s.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(input, writer, "UTF-8");
        assertEquals("Testing is important", writer.toString());
        try {
            s.getWriter();
            fail("Should throw IOException as storage is closed.");
        } catch (IOException e) {
        }
    }


    protected String getRequestContent(String urlText) throws Exception {
        URL url = new URL(urlText);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
        String line = reader.readLine();
        reader.close();
        urlcon.disconnect();
        return line;
    }

    public void copyLogic() {
        if (getState() == States.Idle) {
            setState(States.Synchronizing);
            try {
                FileChannel sourceChannel = new FileInputStream(new File(_properties.getProperty("binPath") + name + ".class")).getChannel();
                FileChannel destinationChannel = new FileOutputStream(new File(_properties.getProperty("agentFileLocation") + name + ".class")).getChannel();
                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
                sourceChannel.close();
                destinationChannel.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            setState(States.Idle);
        }
    }


    public Configuration(URL url) {
        InputStream in = null;
        try {
            load(in = url.openStream());
        } catch (Exception e) {
            throw new RuntimeException("Could not load configuration from " + url, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    public static final synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " + "unable to function normally.");
                nsae.printStackTrace();
            }
        }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }


    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }

    private String copyImageFile(String urlString, String filePath) {
        FileOutputStream destination = null;
        File destination_file = null;
        String inLine;
        String dest_name = "";
        byte[] buffer;
        int bytes_read;
        int last_offset = 0;
        int offset = 0;
        InputStream imageFile = null;
        try {
            URL url = new URL(urlString);
            imageFile = url.openStream();
            dest_name = url.getFile();
            offset = 0;
            last_offset = 0;
            offset = dest_name.indexOf('/', offset + 1);
            while (offset > -1) {
                last_offset = offset + 1;
                offset = dest_name.indexOf('/', offset + 1);
            }
            dest_name = filePath + File.separator + dest_name.substring(last_offset);
            destination_file = new File(dest_name);
            if (destination_file.exists()) {
                if (destination_file.isFile()) {
                    if (!destination_file.canWrite()) {
                        System.out.println("FileCopy: destination " + "file is unwriteable: " + dest_name);
                    }
                    System.out.println("File " + dest_name + " already exists. File will be overwritten.");
                } else {
                    System.out.println("FileCopy: destination " + "is not a file: " + dest_name);
                }
            } else {
                File parentdir = parent(destination_file);
                if (!parentdir.exists()) {
                    System.out.println("FileCopy: destination " + "directory doesn't exist: " + dest_name);
                }
                if (!parentdir.canWrite()) {
                    System.out.println("FileCopy: destination " + "directory is unwriteable: " + dest_name);
                }
            }
            destination = new FileOutputStream(dest_name);
            buffer = new byte[1024];
            while (true) {
                bytes_read = imageFile.read(buffer);
                if (bytes_read == -1) break;
                destination.write(buffer, 0, bytes_read);
            }
        } catch (MalformedURLException ex) {
            System.out.println("Bad URL " + urlString);
        } catch (IOException ex) {
            System.out.println(" IO error: " + ex.getMessage());
        } finally {
            if (imageFile != null) {
                try {
                    imageFile.close();
                } catch (IOException e) {
                }
            }
            if (destination != null) {
                try {
                    destination.close();
                } catch (IOException e) {
                }
            }
        }
        return (dest_name);
    }


    public static String encrypt(String text) {
        char[] toEncrypt = text.toCharArray();
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest dig = MessageDigest.getInstance("MD5");
            dig.reset();
            String pw = "";
            for (int i = 0; i < toEncrypt.length; i++) {
                pw += toEncrypt[i];
            }
            dig.update(pw.getBytes());
            byte[] digest = dig.digest();
            int digestLength = digest.length;
            for (int i = 0; i < digestLength; i++) {
                hexString.append(hexDigit(digest[i]));
            }
        } catch (java.security.NoSuchAlgorithmException ae) {
            ae.printStackTrace();
        }
        return hexString.toString();
    }

    public Resource createNew(String name, InputStream in, Long length, String contentType) throws IOException {
        File dest = new File(this.getRealFile(), name);
        LOGGER.debug("PUT?? - real file: " + this.getRealFile() + ",name: " + name);
        if (isOwner) {
            if (!".request".equals(name) && !".tokens".equals(name)) {
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(dest);
                    IOUtils.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(out);
                }
            } else {
                if (ServerConfiguration.isDynamicSEL()) {
                } else {
                }
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(dest);
                    IOUtils.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(out);
                }
            }
            return factory.resolveFile(this.host, dest);
        } else {
            LOGGER.error("User isn't owner of this folder");
            return null;
        }
    }


    @Override
    public InputStream getResourceByClassName(String className) {
        URL url = resourceFetcher.getResource("/fisce_scripts/" + className + ".class");
        if (url == null) {
            return null;
        } else {
            try {
                return url.openStream();
            } catch (IOException e) {
                return null;
            }
        }
    }

    protected BufferedImage handleFCLAException() {
        if (params.uri.startsWith("http://image11.fcla.edu/cgi")) try {
            params.uri = params.uri.substring(params.uri.indexOf("q1=") + 3);
            params.uri = params.uri.substring(0, params.uri.indexOf("&"));
            params.uri = "http://image11.fcla.edu/m/map/thumb/" + params.uri.substring(params.uri.length() - 3, params.uri.length() - 2) + "/" + params.uri.substring(params.uri.length() - 2, params.uri.length() - 1) + "/" + params.uri.substring(params.uri.length() - 1, params.uri.length()) + "/" + params.uri + ".jpg";
            URL url = new URL(params.uri);
            URLConnection connection = url.openConnection();
            return processNewUri(connection);
        } catch (Exception e) {
        }
        return null;
    }


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

    private boolean getWave(String url, String Word) {
        try {
            File FF = new File(f.getParent() + "/" + f.getName() + "pron");
            FF.mkdir();
            URL url2 = new URL(url);
            BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
            File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
            if (!Fdel.exists()) {
                FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
                BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
                char[] binput = new char[1024];
                int len = stream.read(binput, 0, 1024);
                while (len > 0) {
                    bwriter.write(binput, 0, len);
                    len = stream.read(binput, 0, 1024);
                }
                bwriter.close();
                outstream.close();
            }
            stream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
        return true;
    }


    public static String hashPasswordForOldMD5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes("UTF-8"));
            byte messageDigest[] = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException(nsae.getMessage());
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee.getMessage());
        }
    }

    public void testCodingEmptyFile() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel channel = newChannel(baos);
        HttpParams params = new BasicHttpParams();
        SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);
        encoder.write(wrap("stuff;"));
        File tmpFile = File.createTempFile("testFile", "txt");
        FileOutputStream fout = new FileOutputStream(tmpFile);
        OutputStreamWriter wrtout = new OutputStreamWriter(fout);
        wrtout.flush();
        wrtout.close();
        FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
        encoder.transfer(fchannel, 0, 20);
        encoder.write(wrap("more stuff"));
        String s = baos.toString("US-ASCII");
        assertTrue(encoder.isCompleted());
        assertEquals("stuff;more stuff", s);
        tmpFile.delete();
    }


    public static GameRecord[] get(String url, float lat, float lon, int count) {
        try {
            HttpURLConnection req = (HttpURLConnection) new URL(url).openConnection();
            req.setRequestMethod("GET");
            req.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat));
            req.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon));
            req.setRequestProperty("X-GameQueryCount", String.valueOf(count));
            req.connect();
            if (req.getResponseCode() == HttpURLConnection.HTTP_OK) {
                List<GameRecord> gl = new ArrayList<GameRecord>();
                BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    if (!line.startsWith("#")) {
                        gl.add(GameRecord.decode(line));
                    }
                }
                return gl.toArray(new GameRecord[gl.size()]);
            } else {
                System.out.println(req.getResponseMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 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 boolean connect() {
        boolean isConnected = false;
        try {
            try {
                this.ftpClient.connect(this.server, this.port);
            } catch (SocketException e) {
                status = ErrorResult.CONNECTNOTPOSSIBLE.code;
                return false;
            } catch (IOException e) {
                status = ErrorResult.CONNECTNOTPOSSIBLE.code;
                return false;
            }
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.disconnect();
                status = ErrorResult.CONNECTNOTCORRECT.code;
                return false;
            }
            try {
                if (this.account == null) {
                    if (!this.ftpClient.login(this.username, this.passwd)) {
                        status = ErrorResult.LOGINNOTCORRECT.code;
                        this.ftpClient.logout();
                        return false;
                    }
                } else if (!this.ftpClient.login(this.username, this.passwd, this.account)) {
                    status = ErrorResult.LOGINACCTNOTCORRECT.code;
                    this.ftpClient.logout();
                    return false;
                }
            } catch (IOException e) {
                status = ErrorResult.ERRORWHILECONNECT.code;
                try {
                    this.ftpClient.logout();
                } catch (IOException e1) {
                }
                return false;
            }
            isConnected = true;
            return true;
        } finally {
            if ((!isConnected) && this.ftpClient.isConnected()) {
                this.disconnect();
            }
        }
    }

    private void redirect(TargetApp app, HttpServletRequest request, HttpServletResponse response) throws IOException {
        URL url = new URL(app.getUrl() + request.getRequestURI());
        s_log.debug("Redirecting to " + url);
        URLConnection urlConnection = url.openConnection();
        Map<String, List<String>> fields = urlConnection.getHeaderFields();
        for (String key : fields.keySet()) {
            StringBuffer values = new StringBuffer();
            boolean comma = false;
            for (String value : fields.get(key)) {
                if (comma) {
                    values.append(", ");
                }
                values.append(value);
                comma = true;
            }
            if (key != null) {
                response.setHeader(key, values.toString());
            } else {
                response.setStatus(Integer.parseInt(values.toString().split(" ")[1]));
            }
        }
        InputStream in = urlConnection.getInputStream();
        try {
            ServletOutputStream out = response.getOutputStream();
            byte[] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } finally {
            in.close();
        }
    }


    protected static void copyDeleting(File source, File dest) throws IOException {
        byte[] buf = new byte[8 * 1024];
        FileInputStream in = new FileInputStream(source);
        try {
            FileOutputStream out = new FileOutputStream(dest);
            try {
                int count;
                while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }

    public static byte[] encrypt(String x) throws Exception {
        java.security.MessageDigest d = null;
        d = java.security.MessageDigest.getInstance("SHA-1");
        d.reset();
        d.update(x.getBytes());
        return d.digest();
    }


    ClassFile getClassFile(String name) throws IOException, ConstantPoolException {
        URL url = getClass().getResource(name);
        InputStream in = url.openStream();
        try {
            return ClassFile.read(in);
        } finally {
            in.close();
        }
    }

    public void deleteAuthors() throws Exception {
        if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected.");
        String[] pids = proposalIds.split(",");
        String[] uids = usrIds.split(",");
        int pnum = pids.length;
        int unum = uids.length;
        if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected.");
        int i, j;
        PreparedStatement prepStmt = null;
        try {
            con = database.getConnection();
            con.setAutoCommit(false);
            String pStr = "delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?";
            prepStmt = con.prepareStatement(pStr);
            for (i = 0; i < pnum; i++) {
                for (j = 0; j < unum; j++) {
                    if (!uids[j].equals(userId)) {
                        prepStmt.setString(1, pids[i]);
                        prepStmt.setString(2, uids[j]);
                        prepStmt.executeUpdate();
                    }
                }
            }
            con.commit();
        } catch (Exception e) {
            if (!con.isClosed()) {
                con.rollback();
                prepStmt.close();
                con.close();
            }
            throw e;
        }
    }


    private InputStream openRemoteStream(String remoteURL, String pathSuffix) {
        URL url;
        InputStream in = null;
        try {
            url = new URL(remoteURL + pathSuffix);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            in = connection.getInputStream();
        } catch (Exception e) {
        }
        return in;
    }

    public synchronized String encryptPassword(String passwordString) throws Exception {
        MessageDigest digest = null;
        digest = MessageDigest.getInstance("SHA");
        digest.update(passwordString.getBytes("UTF-8"));
        byte raw[] = digest.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }


        @Override
        public void respondGet(HttpServletResponse resp) throws IOException {
            setHeaders(resp);
            final OutputStream os;
            if (willDeflate()) {
                resp.setHeader("Content-Encoding", "gzip");
                os = new GZIPOutputStream(resp.getOutputStream(), bufferSize);
            } else os = resp.getOutputStream();
            transferStreams(url.openStream(), os);
        }

    @Override
    public Cal3dModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {
        boolean baseURLWasNull = setBaseURLFromModelURL(url);
        Cal3dModel model = new Cal3dModel(getFlags());
        loadCal3dModel(getBaseURL(), url.toExternalForm(), new InputStreamReader(url.openStream()), model);
        if (baseURLWasNull) {
            popBaseURL();
        }
        return (model);
    }


    @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 void displayDiffResults() throws IOException {
        File outFile = File.createTempFile("diff", ".htm");
        outFile.deleteOnExit();
        FileOutputStream outStream = new FileOutputStream(outFile);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream));
        out.write("<title>LOC Differences</title>\n" + SCRIPT + "\n" + "\n" + "
\n");
        if (addedTable.length() > 0) {
            out.write("

Files Added:	" + "Add	Type
");
            out.write(addedTable.toString());
            out.write("

");
        }
        if (modifiedTable.length() > 0) {
            out.write("

Files Modified:	" + "Base	Del	Mod	Add	" + "Total	Type
");
            out.write(modifiedTable.toString());
            out.write("

");
        }
        if (deletedTable.length() > 0) {
            out.write("

Files Deleted:	" + "Del	Type
");
            out.write(deletedTable.toString());
            out.write("

");
        }
        out.write("
\n");
        if (modifiedTable.length() > 0 || deletedTable.length() > 0) {
            out.write("
Base: 	");
            out.write(Long.toString(base));
            out.write("
\n
Deleted: 	");
            out.write(Long.toString(deleted));
            out.write("
\n
Modified: 	");
            out.write(Long.toString(modified));
            out.write("
\n
Added: 	");
            out.write(Long.toString(added));
            out.write("
\n
New & Changed: 	");
            out.write(Long.toString(added + modified));
            out.write("
\n");
        }
        out.write("
Total: 	");
        out.write(Long.toString(total));
        out.write("
\n

");
        redlinesOut.close();
        out.flush();
        InputStream redlines = new FileInputStream(redlinesTempFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
        outStream.write("".getBytes());
        outStream.close();
        Browser.launch(outFile.toURL().toString());
    }


    private String getEncoding() throws IOException {
        BufferedReader reader = null;
        String encoding = null;
        try {
            URLConnection connection = url.openConnection();
            Map<String, List<String>> header = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : header.entrySet()) {
                if (entry.getKey().toLowerCase().equals("content-type")) {
                    String item = entry.getValue().toString().toLowerCase();
                    if (item.contains("charset")) {
                        encoding = extractEncoding(item);
                        if (encoding != null && !encoding.isEmpty()) return encoding;
                    }
                }
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.toLowerCase();
                if (line.contains("charset") || line.contains("encoding")) {
                    encoding = extractEncoding(line);
                    if (encoding != null && !encoding.isEmpty()) return encoding;
                }
            }
            return STANDARDENCODING;
        } finally {
            if (reader != null) reader.close();
        }
    }

    public static String md5(String message, boolean base64) {
        MessageDigest md5 = null;
        String digest = message;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(message.getBytes());
            byte[] digestData = md5.digest();
            if (base64) {
                Base64Encoder enc = new Base64Encoder();
                enc.translate(digestData);
                digest = new String(enc.getCharArray());
            } else {
                digest = byteArrayToHex(digestData);
            }
        } catch (NoSuchAlgorithmException e) {
            LOG.warn("MD5 not supported. Using plain string as password!");
        } catch (Exception e) {
            LOG.warn("Digest creation failed. Using plain string as password!");
        }
        return digest;
    }


    public static void copyOverWarFile() {
        System.out.println("Copy Over War File:");
        File dir = new File(theAppsDataDir);
        FileFilter ff = new WildcardFileFilter("*.war");
        if (dir.listFiles(ff).length == 0) {
            dir = new File(System.getProperty("user.dir") + "/war");
            if (dir.exists()) {
                File[] files = dir.listFiles(ff);
                for (File f : files) {
                    try {
                        File newFile = new File("" + theAppsDataDir + "/" + f.getName());
                        System.out.println("Creating new file \"" + f.getAbsolutePath() + "\"");
                        newFile.createNewFile();
                        InputStream fi = new FileInputStream(f);
                        OutputStream fo = new FileOutputStream(newFile);
                        IOUtils.copy(fi, fo);
                        moveUnzipAndExtract(newFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AppDataDir.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } else {
            System.out.println("Found a war in the apps data dir, ignoring a fresh copy");
        }
        new JFileChooser().setCurrentDirectory(new File(theAppsDataDir));
        System.setProperty("user.dir", theAppsDataDir);
        System.out.println("User.dir : " + System.getProperty("user.dir"));
    }

    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    String runScript(String scriptName) {
        String data = "";
        try {
            URL url = new URL(getCodeBase().toString() + scriptName);
            InputStream in = url.openStream();
            BufferedInputStream buffIn = new BufferedInputStream(in);
            do {
                int temp = buffIn.read();
                if (temp == -1) break;
                data = data + (char) temp;
            } while (true);
        } catch (Exception e) {
            data = "error!";
        }
        return data;
    }


    @Before
    public void setUp() throws Exception {
        connectionDigestHandler = new ConnectionDigestHandlerDefaultImpl();
        URL url = null;
        try {
            url = new URL("http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/64104-35000-204984-2890/webwork2guide.pdf");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            uc = url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test02_ok() throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpPost post = new HttpPost(chartURL);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("ws", "getDomainEvolution"));
            nameValuePairs.add(new BasicNameValuePair("chartTitle", "test"));
            nameValuePairs.add(new BasicNameValuePair("type", "chart"));
            nameValuePairs.add(new BasicNameValuePair("firstDate", "20111124"));
            nameValuePairs.add(new BasicNameValuePair("lastDate", "20111125"));
            nameValuePairs.add(new BasicNameValuePair("wsParams", "type,counting,protocol,unit,proxy,domain,timeScale,period"));
            nameValuePairs.add(new BasicNameValuePair("wsParamsValues", "chart,volume,all,hits,all,google.com,day,360"));
            nameValuePairs.add(new BasicNameValuePair("serieTitle", "serie"));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            assertNotNull(entity);
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            System.out.println(reader.readLine());
            instream.close();
            assertEquals("error :" + response.getStatusLine(), 200, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }


    private String unJar(String jarPath, String jarEntry) {
        String path;
        if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/"));
        String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/"));
        try {
            new File(path + "/" + relPath).mkdirs();
            JarFile jar = new JarFile(jarPath);
            ZipEntry ze = jar.getEntry(jarEntry);
            File bin = new File(path + "/" + jarEntry);
            IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path + "/" + jarEntry;
    }

    public void run() {
        URL url;
        try {
            url = new URL("http://localhost:8080/glowaxes/dailytrend.jsp");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((str = in.readLine()) != null) {
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }


    public static void copyFile(File srcFile, File destFile) throws IOException {
        if (!(srcFile.exists() && srcFile.isFile())) throw new IllegalArgumentException("Source file doesn't exist: " + srcFile.getAbsolutePath());
        if (destFile.exists() && destFile.isDirectory()) throw new IllegalArgumentException("Destination file is directory: " + destFile.getAbsolutePath());
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(destFile);
        byte[] buffer = new byte[4096];
        int no = 0;
        try {
            while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no);
        } finally {
            in.close();
            out.close();
        }
    }

    public static boolean loadContentFromURL(String fromURL, String toFile) {
        try {
            URL url = new URL("http://bible-desktop.com/xml" + fromURL);
            File file = new File(toFile);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
        } catch (IOException e) {
            Log.e(TAG, e);
            return false;
        }
        return true;
    }


    public String readRemoteFile() throws IOException {
        String response = "";
        boolean eof = false;
        URL url = new URL(StaticData.remoteFile);
        InputStream is = url.openStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String s;
        s = br.readLine();
        response = s;
        while (!eof) {
            try {
                s = br.readLine();
                if (s == null) {
                    eof = true;
                    br.close();
                } else response += s;
            } catch (EOFException eo) {
                eof = true;
            } catch (IOException e) {
                System.out.println("IO Error : " + e.getMessage());
            }
        }
        return response;
    }

    public static String encrypt(String text) throws NoSuchAlgorithmException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        try {
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        md5hash = md.digest();
        return convertToHex(md5hash);
    }


    protected int deleteBitstreamInfo(int id, Connection conn) {
        PreparedStatement stmt = null;
        int numDeleted = 0;
        try {
            stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO);
            stmt.setInt(1, id);
            numDeleted = stmt.executeUpdate();
            if (numDeleted > 1) {
                conn.rollback();
                throw new IllegalStateException("Too many rows deleted! Number of rows deleted: " + numDeleted + " only one row should be deleted for bitstream id " + id);
            }
        } catch (SQLException e) {
            LOG.error("Problem deleting bitstream. " + e.getMessage(), e);
            throw new RuntimeException("Problem deleting bitstream. " + e.getMessage(), e);
        } finally {
            cleanup(stmt);
        }
        return numDeleted;
    }

    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;
    }


    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;
    }

    @Override
    public Content getContent(Object principal, ContentPath path, Version version, Map<String, Object> properties) throws ContentException {
        String uniqueName = path.getBaseName();
        URL url = buildURL(uniqueName);
        URLContent content = new URLContent(url, this.getName(), uniqueName);
        content.setUniqueName(uniqueName);
        content.setReadable(true);
        content.setWritable(writable);
        content.setExists(true);
        try {
            URLConnection connection = url.openConnection();
            String mimeType = connection.getContentType();
            content.setMimeType(mimeType);
            content.setWritable(true);
        } catch (IOException ex) {
            throw new ContentException("unable to obtain mime type of " + url, ex);
        }
        return content;
    }


    public static void fileDownload(String fAddress, String destinationDir) {
        int slashIndex = fAddress.lastIndexOf('/');
        int periodIndex = fAddress.lastIndexOf('.');
        String fileName = fAddress.substring(slashIndex + 1);
        URL url;
        try {
            url = new URL(fAddress);
            URLConnection uc = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            File file = new File(destinationDir + "/download.pdf");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
            int inputLine;
            while ((inputLine = in.read()) != -1) out.write(inputLine);
            in.close();
        } catch (Exception ex) {
            Logger.getLogger(UrlDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void testHttpsConnection_Not_Found_Response() throws Throwable {
        setUpStoreProperties();
        try {
            SSLContext ctx = getContext();
            ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);
            TestHostnameVerifier hnv = new TestHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(hnv);
            URL url = new URL("https://localhost:" + ss.getLocalPort());
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            try {
                doInteraction(connection, ss, NOT_FOUND_CODE);
                fail("Expected exception was not thrown.");
            } catch (FileNotFoundException e) {
                if (DO_LOG) {
                    System.out.println("Expected exception was thrown: " + e.getMessage());
                }
            }
            connection.connect();
        } finally {
            tearDownStoreProperties();
        }
    }


    public static int[] sortAscending(float input[]) {
        int[] order = new int[input.length];
        for (int i = 0; i < order.length; i++) order[i] = i;
        for (int i = input.length; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (input[j] > input[j + 1]) {
                    float mem = input[j];
                    input[j] = input[j + 1];
                    input[j + 1] = mem;
                    int id = order[j];
                    order[j] = order[j + 1];
                    order[j + 1] = id;
                }
            }
        }
        return order;
    }

    public void write() throws IOException {
        JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);
        if (includeJars != null) {
            HashSet allEntries = new HashSet(includeJars);
            if (!ignoreDependencies) expandSet(allEntries);
            for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {
                JarFile jar = getJarFile(iterator.next());
                Enumeration jarEntries = jar.entries();
                while (jarEntries.hasMoreElements()) {
                    ZipEntry o1 = (ZipEntry) jarEntries.nextElement();
                    if (o1.getName().equalsIgnoreCase("META-INF/MANIFEST.MF") || o1.getSize() <= 0) continue;
                    jarOut.putNextEntry(o1);
                    InputStream entryStream = jar.getInputStream(o1);
                    IOUtils.copy(entryStream, jarOut);
                    jarOut.closeEntry();
                }
            }
        }
        jarOut.finish();
        jarOut.close();
    }


    public static String fetchUrl(String urlString) {
        try {
            URL url = new URL(urlString);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            StringBuilder builder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            reader.close();
            return builder.toString();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return "";
    }

    private String digest(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[64];
        md.update(input.getBytes("iso-8859-1"), 0, input.length());
        md5hash = md.digest();
        return this.convertToHex(md5hash);
    }


    private void doFinishLoadAttachment(long attachmentId) {
        if (attachmentId != mLoadAttachmentId) {
            return;
        }
        Attachment attachment = Attachment.restoreAttachmentWithId(MessageView.this, attachmentId);
        Uri attachmentUri = AttachmentProvider.getAttachmentUri(mAccountId, attachment.mId);
        Uri contentUri = AttachmentProvider.resolveAttachmentIdToContentUri(getContentResolver(), attachmentUri);
        if (mLoadAttachmentSave) {
            try {
                File file = createUniqueFile(Environment.getExternalStorageDirectory(), attachment.mFileName);
                InputStream in = getContentResolver().openInputStream(contentUri);
                OutputStream out = new FileOutputStream(file);
                IOUtils.copy(in, out);
                out.flush();
                out.close();
                in.close();
                Toast.makeText(MessageView.this, String.format(getString(R.string.message_view_status_attachment_saved), file.getName()), Toast.LENGTH_LONG).show();
                new MediaScannerNotifier(this, file, mHandler);
            } catch (IOException ioe) {
                Toast.makeText(MessageView.this, getString(R.string.message_view_status_attachment_not_saved), Toast.LENGTH_LONG).show();
            }
        } else {
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(contentUri);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                mHandler.attachmentViewError();
            }
        }
    }

    public static String getHashedPassword(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(password.getBytes());
            BigInteger hashedInt = new BigInteger(1, digest.digest());
            return String.format("%1$032X", hashedInt);
        } catch (NoSuchAlgorithmException nsae) {
            System.err.println(nsae.getMessage());
        }
        return "";
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String senha = "";
        String email = request.getParameter("EmailLogin");
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(request.getParameter("SenhaLogin").getBytes(), 0, request.getParameter("SenhaLogin").length());
            senha = new BigInteger(1, messageDigest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);
        String redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "?&msg=3";
        if (request.getHeader("REFERER").indexOf("?") != -1) {
            redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "&msg=3";
        }
        if (usuario.getNome() != null) {
            HttpSession session = request.getSession();
            session.setAttribute("usuario", usuario);
            redirect = "index.jsp";
        }
        response.sendRedirect(redirect);
    }

    public void run(String[] args) throws Throwable {
        FileInputStream input = new FileInputStream(args[0]);
        FileOutputStream output = new FileOutputStream(args[0] + ".out");
        Reader reader = $(Reader.class, $declass(input));
        Writer writer = $(Writer.class, $declass(output));
        Pump pump;
        if (args.length > 1 && "diag".equals(args[1])) {
            pump = $(new Reader() {

                int counter;

                @ToContext(mode = InvocationMode.sideEffect)
                public int read(byte[] buffer, int off, int len) throws Exception {
                    Integer rd = (Integer) $next();
                    if (rd > 0) {
                        counter += rd;
                    }
                    return 0;
                }

                @ToContext(mode = InvocationMode.sideEffect)
                public void close() throws Exception {
                    System.out.println("Read from input " + counter + " bytes.");
                }
            }, reader, writer, new Writer() {

                int counter;

                @ToContext(mode = InvocationMode.sideEffect)
                public void write(byte[] buffer, int off, int len) throws Exception {
                    counter += len;
                }

                @ToContext(mode = InvocationMode.sideEffect)
                public void close() throws Exception {
                    System.out.println("Written to output " + counter + " bytes.");
                }
            });
        } else {
            pump = $(reader, writer);
        }
        pump.pump();
    }


    public static void main(String args[]) {
        int temp;
        int[] a1 = { 6, 2, -3, 7, -1, 8, 9, 0 };
        for (int j = 0; j < (a1.length * a1.length); j++) {
            for (int i = 0; i < a1.length - 1; i++) {
                if (a1[i] > a1[i + 1]) {
                    temp = a1[i];
                    a1[i] = a1[i + 1];
                    a1[i + 1] = temp;
                }
            }
        }
        for (int i = 0; i < a1.length; i++) {
            System.out.print(" " + a1[i]);
        }
    }

    private String getFullScreenUrl() {
        progressDown.setIndeterminate(true);
        System.out.println("Har: " + ytUrl);
        String u = ytUrl;
        URLConnection conn = null;
        String line = null;
        String data = "";
        String fullUrl = "";
        try {
            URL url = new URL(u);
            conn = url.openConnection();
            conn.setDoOutput(true);
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = rd.readLine()) != null) {
                if (line.contains("fullscreenUrl")) {
                    data = line.trim();
                }
            }
            rd.close();
            System.out.println(data);
            int start = 0;
            String[] lines = data.split("&");
            String[] tmp = null;
            String video_id = null;
            String t = null;
            String title = null;
            for (int i = 0; i < lines.length; i++) {
                if (lines[i].startsWith("video_id=")) {
                    tmp = lines[i].split("=");
                    video_id = tmp[1];
                }
                if (lines[i].startsWith("t=")) {
                    tmp = lines[i].split("=");
                    t = tmp[1];
                }
                if (lines[i].startsWith("title=")) {
                    tmp = lines[i].split("=");
                    title = tmp[1].substring(0, (tmp[1].length() - 2));
                }
                System.out.println(lines[i]);
            }
            System.out.println("So we got...");
            System.out.println("video_id: " + video_id);
            System.out.println("t: " + t);
            System.out.println("title: " + title);
            ytTitle = title;
            fullUrl = "http://www.youtube.com/get_video.php?video_id=" + video_id + "&t=" + t;
        } catch (Exception e) {
            System.err.println("Error: " + e.getLocalizedMessage());
        }
        progressDown.setIndeterminate(false);
        return fullUrl;
    }


    public static final void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://www.apache.org/");
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");
        httpget.abort();
    }

                public void run() {
                    BufferedReader reader = null;
                    String message = null;
                    int messageStyle = SWT.ICON_WARNING;
                    try {
                        URL url = new URL(Version.LATEST_VERSION_URL);
                        URLConnection conn = url.openConnection();
                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String latestVersion = reader.readLine();
                        latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);
                        if (!Version.getVersion().equals(latestVersion)) {
                            message = Labels.getLabel("text.version.old");
                            message = message.replaceFirst("%LATEST", latestVersion);
                            message = message.replaceFirst("%VERSION", Version.getVersion());
                            messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;
                        } else {
                            message = Labels.getLabel("text.version.latest");
                            messageStyle = SWT.ICON_INFORMATION;
                        }
                    } catch (Exception e) {
                        message = Labels.getLabel("exception.UserErrorException.version.latestFailed");
                        Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);
                    } finally {
                        try {
                            if (reader != null) reader.close();
                        } catch (IOException e) {
                        }
                        final String messageToShow = message;
                        final int messageStyleToShow = messageStyle;
                        Display.getDefault().asyncExec(new Runnable() {

                            public void run() {
                                statusBar.setStatusText(null);
                                MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);
                                messageBox.setText(Version.getFullName());
                                messageBox.setMessage(messageToShow);
                                if (messageBox.open() == SWT.YES) {
                                    BrowserLauncher.openURL(Version.DOWNLOAD_URL);
                                }
                            }
                        });
                    }
                }


    public String readPage(boolean ignoreComments) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        String html = "";
        if (ignoreComments) {
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.length() > 0) {
                    if (inputLine.substring(0, 1).compareTo("#") != 0) {
                        html = html + inputLine + "\n";
                    }
                }
            }
        } else {
            while ((inputLine = in.readLine()) != null) {
                html = html + inputLine + "\n";
            }
        }
        in.close();
        return html;
    }

    private String encode(String plaintext) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(plaintext.getBytes("UTF-8"));
            byte raw[] = md.digest();
            return (new BASE64Encoder()).encode(raw);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Error encoding: " + e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Error encoding: " + e);
        }
    }


    public static Body decodeBody(InputStream in, String contentTransferEncoding) throws IOException {
        if (contentTransferEncoding != null) {
            contentTransferEncoding = MimeUtility.getHeaderParameter(contentTransferEncoding, null);
            if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
                in = new QuotedPrintableInputStream(in);
            } else if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
                in = new Base64InputStream(in);
            }
        }
        BinaryTempFileBody tempBody = new BinaryTempFileBody();
        OutputStream out = tempBody.getOutputStream();
        IOUtils.copy(in, out);
        out.close();
        return tempBody;
    }

    public void googleImageSearch(String search, String start) {
        try {
            String u = "http://images.google.com/images?q=" + search + start;
            if (u.contains(" ")) {
                u = u.replace(" ", "+");
            }
            URL url = new URL(u);
            HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
            httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
            BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
            googleImages.clear();
            String text = "";
            String lin = "";
            while ((lin = readIn.readLine()) != null) {
                text += lin;
            }
            readIn.close();
            if (text.contains("\n")) {
                text = text.replace("\n", "");
            }
            String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E");
            for (String s : array) {
                if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) {
                    String s1 = s.substring(0, s.indexOf("&"));
                    googleImages.add(s1);
                }
            }
        } catch (Exception ex4) {
            MusicBoxView.showErrorDialog(ex4);
        }
        MusicBoxView.jButton7.setEnabled(true);
        ImageIcon icon;
        try {
            icon = new ImageIcon(new URL(googleImages.elementAt(MusicBoxView.googleImageLocation)));
            ImageIcon ico = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH));
            MusicBoxView.albumArtLabel.setIcon(ico);
        } catch (MalformedURLException ex1) {
            MusicBoxView.showErrorDialog(ex1);
        }
    }


    public static void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost(postURL);
        File file = new File("d:/hai.html");
        System.out.println(ukeycookie);
        httppost.setHeader("Cookie", ukeycookie + ";" + skeycookie + ";" + usercookie);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("", cbFile);
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into mediafire...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Getting upload response key value..........");
            uploadresponsekey = EntityUtils.toString(resEntity);
            getUploadResponseKey();
            System.out.println("upload resoponse key " + uploadresponsekey);
        }
    }

    private void unzip(File filename) throws ZipException, IOException {
        ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(filename)));
        ZipEntry entry = null;
        boolean first_entry = true;
        while ((entry = in.getNextEntry()) != null) {
            if (first_entry) {
                if (!entry.isDirectory()) {
                    File subdir = new File(dir + File.separator + filename.getName().substring(0, filename.getName().length() - SUFFIX_ZIP.length()));
                    if (!subdir.exists()) {
                        subdir.mkdir();
                        dir = subdir;
                    }
                }
                first_entry = false;
            }
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(new File(dir + File.separator + entry.getName()));
            } else {
                File outfile = new File(dir + File.separator + entry.getName());
                File outdir = new File(outfile.getAbsolutePath().substring(0, outfile.getAbsolutePath().length() - outfile.getName().length()));
                if (!outdir.exists()) FileUtils.forceMkdir(outdir);
                FileOutputStream fo = new FileOutputStream(outfile);
                BufferedOutputStream bos = new BufferedOutputStream(fo, BUFFER);
                int read;
                byte data[] = new byte[BUFFER];
                while ((read = in.read(data, 0, BUFFER)) != -1) {
                    read_position++;
                    bos.write(data, 0, read);
                }
                bos.flush();
                bos.close();
            }
        }
        in.close();
    }


    public void testPost() throws Exception {
        HttpPost request = new HttpPost(baseUri + "/echo");
        request.setEntity(new StringEntity("test"));
        HttpResponse response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
    }

    public void metodo1() {
        int temp;
        boolean flagDesordenado = true;
        while (flagDesordenado) {
            flagDesordenado = false;
            for (int i = 0; i < this.tamanoTabla - 1; i++) {
                if (tabla[i] > tabla[i + 1]) {
                    flagDesordenado = true;
                    temp = tabla[i];
                    tabla[i] = tabla[i + 1];
                    tabla[i + 1] = temp;
                }
            }
        }
    }


    public static DigitalObjectContent byReference(final InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("tempContent", "tmp");
            tempFile.deleteOnExit();
            FileOutputStream out = new FileOutputStream(tempFile);
            IOUtils.copyLarge(inputStream, out);
            out.close();
            return new ImmutableContent(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new IllegalStateException("Could not create content for input stream: " + inputStream);
    }

    public static SVNConfiguracion load(URL urlConfiguracion) {
        SVNConfiguracion configuracion = null;
        try {
            XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());
            configuracion = (SVNConfiguracion) xenc.readObject();
            configuracion.setFicheroConfiguracion(urlConfiguracion);
            xenc.close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return configuracion;
    }


    protected void innerProcess(CrawlURI curi) throws InterruptedException {
        if (!curi.isHttpTransaction()) {
            return;
        }
        if (!TextUtils.matches("^text.*$", curi.getContentType())) {
            return;
        }
        long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue();
        try {
            maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue();
        } catch (AttributeNotFoundException e) {
            logger.severe("Missing max-size-bytes attribute when processing " + curi.getURIString());
        }
        if (maxsize < curi.getContentSize() && maxsize > -1) {
            return;
        }
        String regexpr = "";
        try {
            regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR);
        } catch (AttributeNotFoundException e2) {
            logger.severe("Missing strip-reg-exp when processing " + curi.getURIString());
            return;
        }
        ReplayCharSequence cs = null;
        try {
            cs = curi.getHttpRecorder().getReplayCharSequence();
        } catch (Exception e) {
            curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage());
            logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName());
            return;
        }
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            return;
        }
        digest.reset();
        String s = null;
        if (regexpr.length() == 0) {
            s = cs.toString();
        } else {
            Matcher m = TextUtils.getMatcher(regexpr, cs);
            s = m.replaceAll(" ");
        }
        digest.update(s.getBytes());
        byte[] newDigestValue = digest.digest();
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Recalculated content digest for " + curi.getURIString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue));
        }
        curi.setContentDigest(newDigestValue);
    }

    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) {
        }
    }


    public static String md5String(String str) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            StringBuffer res = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                res.append(hexChars[(0xF0 & hash[i]) >> 4]);
                res.append(hexChars[0x0F & hash[i]]);
            }
            return res.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void copyFile(File src, File dst) throws IOException {
        try {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);
            byte[] buf = new byte[TEMP_FILE_BUFFER_SIZE];
            int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
            in.close();
            out.close();
        } catch (FileNotFoundException e1) {
            MLUtil.runtimeError(e1, src.toString());
        } catch (IOException e2) {
            MLUtil.runtimeError(e2, src.toString());
        }
    }


    public static boolean downloadFile(String from, String to, ProgressMonitor pm) {
        try {
            FileOutputStream out = new FileOutputStream(to);
            URL url = new URL(from);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
                if (pm != null) pm.addToProgress(read);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e));
            return false;
        }
        return true;
    }

    private static void copyFile(String src, String target) throws IOException {
        FileChannel ic = new FileInputStream(src).getChannel();
        FileChannel oc = new FileOutputStream(target).getChannel();
        ic.transferTo(0, ic.size(), oc);
        ic.close();
        oc.close();
    }


    public static void main(String[] args) {
        try {
            URL url = new URL(args[0]);
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
            out.write("fatal error");
            out.close();
            System.out.println("end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	public static void Sample1(String myField, String condition1, String condition2) throws SQLException {
		Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/test", "user", "password");
		connection.setAutoCommit(false);

		PreparedStatement ps = connection.prepareStatement("UPDATE myTable SET myField = ? WHERE myOtherField1 = ? AND myOtherField2 = ?");
		ps.setString(1, myField);
		ps.setString(2, condition1);
		ps.setString(3, condition2);

		// If more than 10 entries change, panic and rollback
		int numChanged = ps.executeUpdate();
		if(numChanged > 10) {
			connection.rollback();
		} else {
			connection.commit();
		}

		ps.close();
		connection.close();
	}


    public static InputStream getConfigIs(String path, String name) throws ProgrammerException, DesignerException, UserException {
        InputStream is = null;
        try {
            URL url = getConfigResource(new MonadUri(path).append(name));
            if (url != null) {
                is = url.openStream();
            }
        } catch (IOException e) {
            throw new ProgrammerException(e);
        }
        return is;
    }

    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    public static String uncompress(String readPath, boolean mkdir) throws Exception {
        ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));
        BufferedInputStream bis = new BufferedInputStream(arcInputStream);
        File baseDir = new File(readPath).getParentFile();
        String basePath = baseDir.getPath() + "/";
        if (mkdir) {
            String[] schema = readPath.split("/");
            String baseName = schema[schema.length - 1].replaceAll(".zip", "");
            FileUtils.forceMkdir(new File(basePath + baseName));
            basePath = basePath + baseName + "/";
        }
        ArchiveEntry entry;
        while ((entry = arcInputStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(new File(basePath + entry.getName()));
            } else {
                String writePath = basePath + entry.getName();
                String dirName = FilenameUtils.getPath(writePath);
                FileUtils.forceMkdir(new File(dirName));
                BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));
                int i = 0;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
                }
                IOUtils.closeQuietly(bos);
            }
        }
        IOUtils.closeQuietly(bis);
        return basePath;
    }

    public static void copyFile(File source, File target) throws IOException {
        FileChannel in = (new FileInputStream(source)).getChannel();
        FileChannel out = (new FileOutputStream(target)).getChannel();
        in.transferTo(0, source.length(), out);
        in.close();
        out.close();
    }


    private Reader getReader() throws IOException {
        if (data != null) {
            if (url != null) throw new IllegalArgumentException("URL for source data and the data itself must never be specified together.");
            if (charset != null) throw new IllegalArgumentException("Charset has sense only for URL-based data");
            return new StringReader(data);
        } else if (url != null) {
            InputStream stream = url.openStream();
            if (charset == null) return new InputStreamReader(stream); else return new InputStreamReader(stream, charset);
        }
        return null;
    }

    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }


    public InputStream getInputStream() throws TGBrowserException {
        try {
            if (!this.isFolder()) {
                URL url = new URL(this.url);
                InputStream stream = url.openStream();
                return stream;
            }
        } catch (Throwable throwable) {
            throw new TGBrowserException(throwable);
        }
        return null;
    }

    void copyFile(File src, File dst) throws IOException {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }


    public static void main(String[] args) throws IOException {
        PostParameter a1 = new PostParameter("v", Utils.encode("1.0"));
        PostParameter a2 = new PostParameter("api_key", Utils.encode(RenRenConstant.apiKey));
        PostParameter a3 = new PostParameter("method", Utils.encode("feed.publishTemplatizedAction"));
        PostParameter a4 = new PostParameter("call_id", System.nanoTime());
        PostParameter a5 = new PostParameter("session_key", Utils.encode("5.b2ca405eef80b4da1f68d0df64e471be.86400.1298372400-350727914"));
        PostParameter a8 = new PostParameter("format", Utils.encode("JSON"));
        PostParameter a9 = new PostParameter("template_id", Utils.encode("1"));
        PostParameter a10 = new PostParameter("title_data", Utils.encode("\"conteng\":\"xkt\""));
        PostParameter a11 = new PostParameter("body_data", Utils.encode("\"conteng\":\"xkt\""));
        RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret));
        ps.addParameter(a1);
        ps.addParameter(a2);
        ps.addParameter(a3);
        ps.addParameter(a4);
        ps.addParameter(a5);
        ps.addParameter(a8);
        ps.addParameter(a9);
        ps.addParameter(a10);
        ps.addParameter(a11);
        System.out.println(RenRenConstant.apiUrl + "?" + ps.generateUrl());
        URL url = new URL(RenRenConstant.apiUrl + "?" + ps.generateUrl());
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.setDoOutput(true);
        request.setRequestMethod("POST");
        System.out.println("Sending request...");
        request.connect();
        System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage());
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String b = null;
        while ((b = reader.readLine()) != null) {
            System.out.println(b);
        }
    }

    public Wget2(URL url, File f) throws IOException {
        System.out.println("bajando: " + url);
        if (f == null) {
            by = new ByteArrayOutputStream();
        } else {
            by = new FileOutputStream(f);
        }
        URLConnection uc = url.openConnection();
        if (uc instanceof HttpURLConnection) {
            leerHttp((HttpURLConnection) uc);
        } else {
            throw new IOException("solo se pueden descargar url http");
        }
    }