semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private static boolean downloadFile(URL remote, File local) throws IllegalArgumentException, IOException {
        if (local == null) throw new IllegalArgumentException("Must specify remote file");
        if (local.exists() && !local.canWrite()) throw new IOException("Cannot write to " + local);
        long lengthCurrent = local.exists() ? local.length() : -1l;
        if (lengthCurrent == 0) throw new IOException("Cannot get the length for " + local);
        long lastModifiedCurrent = local.exists() ? local.lastModified() : -1l;
        if (remote == null) throw new IllegalArgumentException("Must specify remote url");
        URLConnection urlConnection = remote.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(false);
        long lengthRemote = urlConnection.getContentLength();
        long lastModifiedRemote = urlConnection.getLastModified();
        if (lengthRemote == lengthCurrent) {
            LOGGER.fine("Not downloading " + remote + " of length " + lengthRemote + " and date " + (lastModifiedRemote > 0 ? new Date(lastModifiedRemote).toString() : "n/a") + " for " + local + " of length " + lengthCurrent + " and date " + new Date(lastModifiedCurrent));
            return false;
        }
        BufferedInputStream inputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            inputStream = new BufferedInputStream(urlConnection.getInputStream(), BUFFER_SIZE);
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(local));
            byte[] buffer = new byte[BUFFER_SIZE];
            do {
                int count = inputStream.read(buffer);
                if (count < 0) break;
                bufferedOutputStream.write(buffer, 0, count);
            } while (true);
            return true;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
            } catch (Throwable throwable) {
            }
            try {
                if (bufferedOutputStream != null) bufferedOutputStream.close();
            } catch (Throwable throwable) {
            }
        }
    }
void copyFile(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        in.close();
        out.close();
    }
public byte[] loadResource(String location) throws IOException {
        if ((location == null) || (location.length() == 0)) {
            throw new IOException("The given resource location must not be null and non empty.");
        }
        URL url = buildURL(location);
        URLConnection cxn = url.openConnection();
        InputStream is = null;
        try {
            byte[] byteBuffer = new byte[2048];
            ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
            is = cxn.getInputStream();
            int bytesRead = 0;
            while ((bytesRead = is.read(byteBuffer, 0, 2048)) >= 0) {
                bos.write(byteBuffer, 0, bytesRead);
            }
            return bos.toByteArray();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
public boolean resourceExists(String location) {
        if ((location == null) || (location.length() == 0)) {
            return false;
        }
        try {
            URL url = buildURL(location);
            URLConnection cxn = url.openConnection();
            InputStream is = null;
            try {
                byte[] byteBuffer = new byte[2048];
                is = cxn.getInputStream();
                while (is.read(byteBuffer, 0, 2048) >= 0) ;
                return true;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        } catch (IOException ex) {
            return false;
        }
    }
public static String encrypt(final String pass) {
        try {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(pass.getBytes("UTF-8"));
            return new String(Base64.encodeBase64(md.digest()));
        } catch (final Exception e) {
            throw new RuntimeException("No se pudo encriptar el password.", e);
        }
    }
public Object process(Atom oAtm) throws IOException {
        File oFile;
        FileReader oFileRead;
        String sPathHTML;
        char cBuffer[];
        Object oReplaced;
        final String sSep = System.getProperty("file.separator");
        if (DebugFile.trace) {
            DebugFile.writeln("Begin FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])");
            DebugFile.incIdent();
        }
        if (bHasReplacements) {
            sPathHTML = getProperty("workareasput");
            if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep;
            sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep;
            sPathHTML += getParameter("nm_pageset").replace(' ', '_') + ".html";
            if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML);
            oReplaced = oReplacer.replace(sPathHTML, oAtm.getItemMap());
            bHasReplacements = (oReplacer.lastReplacements() > 0);
        } else {
            oReplaced = null;
            if (null != oFileStr) oReplaced = oFileStr.get();
            if (null == oReplaced) {
                sPathHTML = getProperty("workareasput");
                if (!sPathHTML.endsWith(sSep)) sPathHTML += sSep;
                sPathHTML += getParameter("gu_workarea") + sSep + "apps" + sSep + "Mailwire" + sSep + "html" + sSep + getParameter("gu_pageset") + sSep + getParameter("nm_pageset").replace(' ', '_') + ".html";
                if (DebugFile.trace) DebugFile.writeln("PathHTML = " + sPathHTML);
                oFile = new File(sPathHTML);
                cBuffer = new char[new Long(oFile.length()).intValue()];
                oFileRead = new FileReader(oFile);
                oFileRead.read(cBuffer);
                oFileRead.close();
                if (DebugFile.trace) DebugFile.writeln(String.valueOf(cBuffer.length) + " characters readed");
                oReplaced = new String(cBuffer);
                oFileStr = new SoftReference(oReplaced);
            }
        }
        String sPathJobDir = getProperty("storage");
        if (!sPathJobDir.endsWith(sSep)) sPathJobDir += sSep;
        sPathJobDir += "jobs" + sSep + getParameter("gu_workarea") + sSep + getString(DB.gu_job) + sSep;
        FileWriter oFileWrite = new FileWriter(sPathJobDir + getString(DB.gu_job) + "_" + String.valueOf(oAtm.getInt(DB.pg_atom)) + ".html", true);
        oFileWrite.write((String) oReplaced);
        oFileWrite.close();
        iPendingAtoms--;
        if (DebugFile.trace) {
            DebugFile.writeln("End FileDumper.process([Job:" + getStringNull(DB.gu_job, "") + ", Atom:" + String.valueOf(oAtm.getInt(DB.pg_atom)) + "])");
            DebugFile.decIdent();
        }
        return oReplaced;
    }
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException {
        InputStream inputStream = url.openStream();
        try {
            return getAudioInputStream(inputStream);
        } catch (UnsupportedAudioFileException e) {
            inputStream.close();
            throw e;
        } catch (IOException e) {
            inputStream.close();
            throw e;
        }
    }
public void transport(File file) throws TransportException {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    transport(file);
                }
            } else if (file.isFile()) {
                try {
                    FileChannel inChannel = new FileInputStream(file).getChannel();
                    FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                } catch (IOException e) {
                    log.error("File transfer failed", e);
                }
            }
        }
    }
public static void copyTo(File inFile, File outFile) throws IOException {
        char[] cbuff = new char[32768];
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        int readedBytes = 0;
        long absWrittenBytes = 0;
        while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) {
            writer.write(cbuff, 0, readedBytes);
            absWrittenBytes += readedBytes;
        }
        reader.close();
        writer.close();
    }
public static String MD5(String input) throws Exception {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(input.getBytes(), 0, input.length());
        input = new BigInteger(1, m.digest()).toString(16);
        if (input.length() == 31) input = "0" + input;
        return input;
    }
public int getDBVersion() throws MigrationException {
        int dbVersion;
        PreparedStatement ps;
        try {
            Connection conn = getConnection();
            ps = conn.prepareStatement("SELECT version FROM " + getTablename());
            try {
                ResultSet rs = ps.executeQuery();
                try {
                    if (rs.next()) {
                        dbVersion = rs.getInt(1);
                        if (rs.next()) {
                            throw new MigrationException("Too many version in table: " + getTablename());
                        }
                    } else {
                        ps.close();
                        ps = conn.prepareStatement("INSERT INTO " + getTablename() + " (version) VALUES (?)");
                        ps.setInt(1, 1);
                        try {
                            ps.executeUpdate();
                        } finally {
                            ps.close();
                        }
                        dbVersion = 1;
                    }
                } finally {
                    rs.close();
                }
            } finally {
                ps.close();
            }
        } catch (SQLException e) {
            logger.log(Level.WARNING, "Could not access " + tablename + ": " + e);
            dbVersion = 0;
            Connection conn = getConnection();
            try {
                if (!conn.getAutoCommit()) {
                    conn.rollback();
                }
                conn.setAutoCommit(false);
            } catch (SQLException e1) {
                throw new MigrationException("Could not reset transaction state", e1);
            }
        }
        return dbVersion;
    }
public static void copyFile(File in, File out, long maxCount) throws IOException {
        final FileChannel sourceChannel = new FileInputStream(in).getChannel();
        final FileChannel destinationChannel = new FileOutputStream(out).getChannel();
        if (maxCount == 0) maxCount = sourceChannel.size();
        try {
            final long size = sourceChannel.size();
            long position = 0;
            while (position < size) {
                position += sourceChannel.transferTo(position, maxCount, destinationChannel);
            }
        } finally {
            sourceChannel.close();
            destinationChannel.close();
        }
    }
public static final File getFile(final URL url) throws IOException {
        final File shortcutFile;
        final File currentFile = files.get(url);
        if (currentFile == null || !currentFile.exists()) {
            shortcutFile = File.createTempFile("windowsIsLame", ".vbs");
            shortcutFile.deleteOnExit();
            files.put(url, shortcutFile);
            final InputStream stream = url.openStream();
            final FileOutputStream out = new FileOutputStream(shortcutFile);
            try {
                StreamUtils.copy(stream, out);
            } finally {
                out.close();
                stream.close();
            }
        } else shortcutFile = currentFile;
        return shortcutFile;
    }
public void run() {
        RandomAccessFile file = null;
        InputStream stream = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
            connection.connect();
            if (connection.getResponseCode() / 100 != 2) {
                error();
            }
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                error();
            }
            if (size == -1) {
                size = contentLength;
                stateChanged();
            }
            file = new RandomAccessFile(saveas, "rw");
            file.seek(downloaded);
            stream = connection.getInputStream();
            while (status == DOWNLOADING) {
                byte buffer[];
                if (size - downloaded > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                int read = stream.read(buffer);
                if (read == -1) break;
                file.write(buffer, 0, read);
                downloaded += read;
                stateChanged();
            }
            if (status == DOWNLOADING) {
                status = COMPLETE;
                stateChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
            error();
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e) {
                }
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {
                }
            }
        }
    }
public static String generateSHA1Digest(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("UTF-8"), 0, text.length());
            sha1hash = md.digest();
            return convertToHex(sha1hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
public void testClickToCallOutDirection() throws Exception {
        init();
        SipCall[] receiverCalls = new SipCall[receiversCount];
        receiverCalls[0] = sipPhoneReceivers[0].createSipCall();
        receiverCalls[1] = sipPhoneReceivers[1].createSipCall();
        receiverCalls[0].listenForIncomingCall();
        receiverCalls[1].listenForIncomingCall();
        logger.info("Trying to reach url : " + CLICK2DIAL_URL + CLICK2DIAL_PARAMS);
        URL url = new URL(CLICK2DIAL_URL + CLICK2DIAL_PARAMS);
        InputStream in = url.openConnection().getInputStream();
        byte[] buffer = new byte[10000];
        int len = in.read(buffer);
        String httpResponse = "";
        for (int q = 0; q < len; q++) httpResponse += (char) buffer[q];
        logger.info("Received the follwing HTTP response: " + httpResponse);
        receiverCalls[0].waitForIncomingCall(timeout);
        assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.RINGING, "Ringing", 0));
        assertTrue(receiverCalls[0].sendIncomingCallResponse(Response.OK, "OK", 0));
        receiverCalls[1].waitForIncomingCall(timeout);
        assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.RINGING, "Ringing", 0));
        assertTrue(receiverCalls[1].sendIncomingCallResponse(Response.OK, "OK", 0));
        assertTrue(receiverCalls[1].waitForAck(timeout));
        assertTrue(receiverCalls[0].waitForAck(timeout));
        assertTrue(receiverCalls[0].disconnect());
        assertTrue(receiverCalls[1].waitForDisconnect(timeout));
        assertTrue(receiverCalls[1].respondToDisconnect());
    }
private static String readUrl(String filePath, String charCoding, boolean urlIsFile) throws IOException {
        int chunkLength;
        InputStream is = null;
        try {
            if (!urlIsFile) {
                URL urlObj = new URL(filePath);
                URLConnection uc = urlObj.openConnection();
                is = uc.getInputStream();
                chunkLength = uc.getContentLength();
                if (chunkLength <= 0) chunkLength = 1024;
                if (charCoding == null) {
                    String type = uc.getContentType();
                    if (type != null) {
                        charCoding = getCharCodingFromType(type);
                    }
                }
            } else {
                if (registeredStreams.containsKey(filePath)) {
                    is = registeredStreams.get(filePath);
                    chunkLength = 4096;
                } else {
                    File f = new File(filePath);
                    long length = f.length();
                    chunkLength = (int) length;
                    if (chunkLength != length) throw new IOException("Too big file size: " + length);
                    if (chunkLength == 0) {
                        return "";
                    }
                    is = new FileInputStream(f);
                }
            }
            Reader r;
            if (charCoding == null) {
                r = new InputStreamReader(is);
            } else {
                r = new InputStreamReader(is, charCoding);
            }
            return readReader(r, chunkLength);
        } finally {
            if (is != null) is.close();
        }
    }
@Override
    public byte[] download(URI uri) throws NetworkException {
        log.info("download: " + uri);
        HttpGet httpGet = new HttpGet(uri.toString());
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            return EntityUtils.toByteArray(httpResponse.getEntity());
        } catch (IOException e) {
            throw new NetworkException(e);
        } finally {
            httpGet.abort();
        }
    }
public static void sendData(final HashMap<String, String> data) {
        YProgressWindowRepeat y = new YProgressWindowRepeat(I18N.t("Send Data to yaams.de"));
        try {
            final StringBuffer send = new StringBuffer("1=1");
            for (final String key : data.keySet()) {
                send.append("&");
                send.append(key);
                send.append("=");
                send.append(URLEncoder.encode(data.get(key), "UTF-8"));
            }
            final URL url = new URL("http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php");
            final URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(send.toString());
            wr.flush();
            final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            final StringBuffer erg = new StringBuffer("");
            while ((line = rd.readLine()) != null) {
                erg.append(line);
            }
            JOptionPane.showMessageDialog(null, erg.toString(), I18N.t("Feedback"), JOptionPane.INFORMATION_MESSAGE);
            wr.close();
            rd.close();
        } catch (final Throwable t) {
            YException.error("Can not send feedback to http://www.rpg-studio.de/libraries/abttools/yaamsFeedback.php", t);
        }
        y.close();
    }
public static String ftpPing(String root, String host, int port, String username, String pw) {
        try {
            ftpClient = new FTPClient();
            ftpClient.setRemoteAddr(InetAddress.getByName(host));
            ftpClient.setControlPort(port);
            ftpClient.setTimeout(4000);
            ftpClient.connect();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ftpClient.login(username, (pw));
            ftpClient.chdir(root);
            JobHandler.releaseFTPLock();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (FTPException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        try {
            ftpClient.quit();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } catch (FTPException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return null;
    }
public static void putWithUserSettings(String from, String to, String renameTo, boolean binary, IProgressMonitor monitor) {
        if (monitor != null && monitor.isCanceled()) {
            return;
        }
        FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, binary);
        synchedSet.add(ftpHolder);
        int ftpqueuesize = PrefPageOne.getIntValue(CONSTANTS.PREF_FTPQUEUE);
        if (synchedSet.size() >= ftpqueuesize) {
            JobHandler.aquireFTPLock();
            try {
                ftpClient = new FTPClient();
                ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST)));
                ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT));
                ftpClient.connect();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD)));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (monitor != null && monitor.isCanceled()) {
                    JobHandler.releaseFTPLock();
                    ftpClient.quit();
                    return;
                }
                synchronized (synchedSet) {
                    for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) {
                        if (monitor != null && monitor.isCanceled()) {
                            JobHandler.releaseFTPLock();
                            ftpClient.quit();
                            return;
                        }
                        Thread.yield();
                        FTPHolder element = (FTPHolder) iter.next();
                        if (element.binary) {
                            ftpClient.setType(FTPTransferType.BINARY);
                        } else {
                            ftpClient.setType(FTPTransferType.ASCII);
                        }
                        ftpClient.put(element.from, element.to);
                        if (element.renameTo != null) {
                            try {
                                ftpClient.delete(element.renameTo);
                            } catch (Exception e) {
                            }
                            ftpClient.rename(element.to, element.renameTo);
                            log.info("RENAME: " + element.to + "To: " + element.renameTo);
                        }
                    }
                    synchedSet.clear();
                }
                JobHandler.releaseFTPLock();
                ftpClient.quit();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (FTPException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }