semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private static FTPClient getFtpClient(String ftpHost, String ftpUsername, String ftpPassword) throws SocketException, IOException {
        FTPClient ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        ftp.connect(ftpHost);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return null;
        }
        if (!ftp.login(ftpUsername, ftpPassword)) {
            return null;
        }
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        return ftp;
    }
private synchronized void renewToken() {
        if (!(System.currentTimeMillis() > (lastTokenRenewal + 10000))) return;
        lastTokenRenewal = System.currentTimeMillis();
        String token = null;
        System.out.println("loading error - refresh token");
        byte[] buff = null;
        try {
            BufferedInputStream bis = null;
            System.out.println("Calling timeout : " + getServingURL() + "?token_timeout=true");
            URL remoteurl = new URL(getServingURL() + "?token_timeout=true");
            URLConnection connection = remoteurl.openConnection();
            connection.setRequestProperty("Referer", getServingURL());
            int length = connection.getContentLength();
            InputStream in = connection.getInputStream();
            buff = new byte[length];
            int bytesRead = 0;
            while (bytesRead < length) {
                bytesRead += in.read(buff, bytesRead, in.available());
            }
            token = new String(buff);
        } catch (Exception e) {
        }
        if (token != null && !token.equals("")) {
            token = token.trim();
            this.info.setToken(token);
        } else {
            System.out.println("Token returned was null");
        }
    }
private void getRandomGUID(boolean secure, Object o) {
        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(o.getClass().getName());
            sbValueBeforeMD5.append(":");
            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 long copy(File src, long amount, File dst) {
        final int BUFFER_SIZE = 1024;
        long amountToRead = amount;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src));
            out = new BufferedOutputStream(new FileOutputStream(dst));
            byte[] buf = new byte[BUFFER_SIZE];
            while (amountToRead > 0) {
                int read = in.read(buf, 0, (int) Math.min(BUFFER_SIZE, amountToRead));
                if (read == -1) break;
                amountToRead -= read;
                out.write(buf, 0, read);
            }
        } catch (IOException e) {
        } finally {
            close(in);
            flush(out);
            close(out);
        }
        return amount - amountToRead;
    }
private void copyImage(ProjectElement e) throws Exception {
        String fn = e.getName();
        if (!fn.toLowerCase().endsWith(".png")) {
            if (fn.contains(".")) {
                fn = fn.substring(0, fn.lastIndexOf('.')) + ".png";
            } else {
                fn += ".png";
            }
        }
        File img = new File(resFolder, fn);
        File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib");
        boolean copy = true;
        if (img.exists() && config.containsKey(img.getName())) {
            long modified = Long.parseLong(config.get(img.getName()));
            if (modified >= img.lastModified()) {
                copy = false;
            }
        }
        if (copy) {
            convertImage(e.getFile(), img);
            config.put(img.getName(), String.valueOf(img.lastModified()));
        }
        DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz)));
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(img));
        int read;
        while ((read = in.read()) != -1) {
            out.write(read);
        }
        out.close();
        in.close();
        imageFiles.add(imgz);
        imageNames.put(imgz, e.getName());
    }
private void createImageArchive() throws Exception {
        imageArchive = new File(resoutFolder, "images.CrAr");
        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive)));
        out.writeInt(toNativeEndian(imageFiles.size()));
        for (int i = 0; i < imageFiles.size(); i++) {
            File f = imageFiles.get(i);
            out.writeLong(toNativeEndian(f.length()));
            out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length()));
        }
        for (int i = 0; i < imageFiles.size(); i++) {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i)));
            int read;
            while ((read = in.read()) != -1) {
                out.write(read);
            }
            in.close();
        }
        out.close();
    }
private void appendArchive() throws Exception {
        String cmd;
        if (profile == CompilationProfile.UNIX_GCC) {
            cmd = "cat";
        } else if (profile == CompilationProfile.MINGW_WINDOWS) {
            cmd = "type";
        } else {
            throw new Exception("Unknown cat equivalent for profile " + profile);
        }
        compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>");
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true));
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive));
        int read;
        while ((read = in.read()) != -1) {
            out.write(read);
        }
        in.close();
        out.close();
    }
private static void copy(File source, File dest) throws FileNotFoundException, IOException {
        FileInputStream input = new FileInputStream(source);
        FileOutputStream output = new FileOutputStream(dest);
        System.out.println("Copying " + source + " to " + dest);
        IOUtils.copy(input, output);
        output.close();
        input.close();
        dest.setLastModified(source.lastModified());
    }
private BundleURLClassPath createBundleURLClassPath(Bundle bundle, Version version, File bundleFile, File cache, boolean alreadyCached) throws Exception {
        String bundleClassPath = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
        if (bundleClassPath == null) {
            bundleClassPath = ".";
        }
        ManifestEntry[] entries = ManifestEntry.parse(bundleClassPath);
        String[] classPaths = new String[0];
        for (int i = 0; i < entries.length; i++) {
            String classPath = entries[i].getName();
            if (classPath.startsWith("/")) {
                classPath = classPath.substring(1);
            }
            if (classPath.endsWith(".jar")) {
                try {
                    File file = new File(cache, classPath);
                    if (!alreadyCached) {
                        file.getParentFile().mkdirs();
                        String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(classPath).toString();
                        OutputStream os = new FileOutputStream(file);
                        InputStream is = new URL(url).openStream();
                        IOUtil.copy(is, os);
                        is.close();
                        os.close();
                    } else {
                        if (!file.exists()) {
                            throw new IOException(new StringBuilder("classpath ").append(classPath).append(" not found").toString());
                        }
                    }
                } catch (IOException e) {
                    FrameworkEvent frameworkEvent = new FrameworkEvent(FrameworkEvent.INFO, bundle, e);
                    framework.postFrameworkEvent(frameworkEvent);
                    continue;
                }
            }
            classPaths = (String[]) ArrayUtil.add(classPaths, classPath);
        }
        if (!alreadyCached) {
            String bundleNativeCode = (String) bundle.getHeaders().get(Constants.BUNDLE_NATIVECODE);
            if (bundleNativeCode != null) {
                entries = ManifestEntry.parse(bundleNativeCode);
                for (int i = 0; i < entries.length; i++) {
                    ManifestEntry entry = entries[i];
                    String libPath = entry.getName();
                    String url = new StringBuilder("jar:").append(bundleFile.toURI().toURL().toString()).append("!/").append(libPath).toString();
                    File file = new File(cache, libPath);
                    file.getParentFile().mkdirs();
                    OutputStream os = new FileOutputStream(file);
                    InputStream is = new URL(url).openStream();
                    IOUtil.copy(is, os);
                    is.close();
                    os.close();
                }
            }
        }
        BundleURLClassPath urlClassPath = new BundleURLClassPathImpl(bundle, version, classPaths, cache);
        return urlClassPath;
    }
@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);
    }
protected Document loadDocument() throws MalformedURLException, DocumentException, IOException {
        if (jiraFilterURL.startsWith("file")) {
            URL url = getSourceURL();
            return parseDocument(url);
        } else {
            HttpClient httpClient = new DefaultHttpClient();
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("os_username", jiraUser));
            formparams.add(new BasicNameValuePair("os_password", jiraPassword));
            formparams.add(new BasicNameValuePair("os_cookie", "true"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            HttpPost post = new HttpPost(getJiraRootUrl() + "/secure/login.jsp");
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            response.getEntity().consumeContent();
            String url_str = StringEscapeUtils.unescapeXml(jiraFilterURL);
            HttpGet get = new HttpGet(url_str);
            response = httpClient.execute(get);
            return parseDocument(response.getEntity().getContent());
        }
    }
private void downloadFile(String url, File destFile) {
        try {
            System.out.println("Downloading " + url + " to " + destFile + "...");
            destFile.getParentFile().mkdirs();
            OutputStream out = new FileOutputStream(destFile);
            URLConnection conn = new URL(url).openConnection();
            InputStream in = conn.getInputStream();
            int totalSize = conn.getContentLength(), downloadedSize = 0, size;
            byte[] buffer = new byte[32768];
            ProgressMonitor pm = new ProgressMonitor(null, "Downloading " + url, "", 0, totalSize);
            pm.setMillisToDecideToPopup(100);
            pm.setMillisToPopup(500);
            boolean canceled = false;
            while ((size = in.read(buffer)) > 0 && !(canceled = pm.isCanceled())) {
                out.write(buffer, 0, size);
                pm.setProgress(downloadedSize += size);
                pm.setNote((100 * downloadedSize / totalSize) + "% finished");
            }
            in.close();
            out.close();
            if (canceled) {
                destFile.delete();
                fatalError("Starting canceled", "Downloading canceled. Exiting...");
            }
            pm.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            destFile.delete();
            fatalError("Download Error", "Couldn't download file " + url + ": " + ex);
        }
    }
public boolean validateZipFile(File zipFile) {
        String tempdir = Config.CONTEXT.getRealPath(getBackupTempFilePath());
        try {
            deleteTempFiles();
            File ftempDir = new File(tempdir);
            ftempDir.mkdirs();
            File tempZip = new File(tempdir + File.separator + zipFile.getName());
            tempZip.createNewFile();
            FileChannel ic = new FileInputStream(zipFile).getChannel();
            FileChannel oc = new FileOutputStream(tempZip).getChannel();
            for (long i = 0; i <= ic.size(); i++) {
                ic.transferTo(0, 1000000, oc);
                i = i + 999999;
            }
            ic.close();
            oc.close();
            if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) {
                ZipFile z = new ZipFile(zipFile);
                ZipUtil.extract(z, new File(Config.CONTEXT.getRealPath(backupTempFilePath)));
            }
            return true;
        } catch (Exception e) {
            Logger.error(this, "Error with file", e);
            return false;
        }
    }
public String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    }
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;
    }
public void open(String server, String user, String pass, int port, String option) throws Exception {
        log.info("Login to FTP: " + server);
        this.port = port;
        ftp = new FTPClient();
        ftp.connect(server, port);
        ftp.login(user, pass);
        checkReply("FTP server refused connection." + server);
        modeBINARY();
        this.me = this;
    }
public void chmod(String remoteFile, String mode) {
        String remotePath = connector.getRemoteDirectory();
        remotePath += PATH_SEPARATOR + remoteFile;
        FTPClient ftp = new FTPClient();
        try {
            String hostname = connector.getUrl().getHost();
            ftp.connect(hostname);
            log.info("Connected to " + hostname);
            log.info(ftp.getReplyString());
            boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword());
            if (loggedIn) {
                String parameters = "chmod " + mode + " " + remotePath;
                ftp.site(parameters);
                ftp.logout();
            }
            ftp.disconnect();
        } catch (SocketException e) {
            log.error("File chmod failed with message: " + e.getMessage());
        } catch (IOException e) {
            log.error("File chmod failed with message: " + e.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
    }
public void delete(String remoteFile) {
        String remotePath = connector.getRemoteDirectory();
        remotePath += PATH_SEPARATOR + remoteFile;
        FTPClient ftp = new FTPClient();
        try {
            String hostname = connector.getUrl().getHost();
            ftp.connect(hostname);
            log.info("Connected to " + hostname);
            log.info(ftp.getReplyString());
            boolean loggedIn = ftp.login(connector.getUsername(), connector.getPassword());
            if (loggedIn) {
                ftp.deleteFile(remotePath);
                ftp.logout();
            }
            ftp.disconnect();
        } catch (SocketException e) {
            log.error("File chmod failed with message: " + e.getMessage());
        } catch (IOException e) {
            log.error("File chmod failed with message: " + e.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
    }
public Map<String, String> getMetadata(WebFileObject fo) throws IOException {
        if (!fo.wfs.getRootURL().getProtocol().equals("ftp")) {
            String realName = fo.pathname;
            boolean exists;
            URL ur = new URL(fo.wfs.getRootURL(), realName);
            HttpURLConnection connect = (HttpURLConnection) ur.openConnection();
            connect.setRequestMethod("HEAD");
            HttpURLConnection.setFollowRedirects(false);
            connect.connect();
            HttpURLConnection.setFollowRedirects(true);
            if (connect.getResponseCode() == 303) {
                String surl = connect.getHeaderField("Location");
                if (surl.startsWith(fo.wfs.root.toString())) {
                    realName = surl.substring(fo.wfs.root.toString().length());
                }
                connect.disconnect();
                ur = new URL(fo.wfs.getRootURL(), realName);
                connect = (HttpURLConnection) ur.openConnection();
                connect.setRequestMethod("HEAD");
                connect.connect();
            }
            exists = connect.getResponseCode() != 404;
            Map<String, String> result = new HashMap<String, String>();
            Map<String, List<String>> fields = connect.getHeaderFields();
            for (Entry<String, List<String>> e : fields.entrySet()) {
                String key = e.getKey();
                List<String> value = e.getValue();
                result.put(key, value.get(0));
            }
            result.put(META_EXIST, String.valueOf(exists));
            connect.disconnect();
            return result;
        } else {
            Map<String, String> result = new HashMap<String, String>();
            URL url = new URL(fo.wfs.getRootURL(), fo.pathname);
            URLConnection urlc = url.openConnection();
            try {
                urlc.connect();
                urlc.getInputStream().close();
                result.put(META_EXIST, "true");
            } catch (IOException ex) {
                result.put(META_EXIST, "false");
            }
            return result;
        }
    }
private void copy(File source, File destinationDirectory) throws IOException {
        if (source.isDirectory()) {
            File newDir = new File(destinationDirectory, source.getName());
            newDir.mkdir();
            File[] children = source.listFiles();
            for (int i = 0; i < children.length; i++) {
                if (children[i].getName().equals(".svn")) {
                    continue;
                }
                copy(children[i], newDir);
            }
        } else {
            File newFile = new File(destinationDirectory, source.getName());
            if (newFile.exists() && source.lastModified() == newFile.lastModified()) {
                return;
            }
            FileOutputStream output = new FileOutputStream(newFile);
            FileInputStream input = new FileInputStream(source);
            byte[] buff = new byte[2048];
            int read = 0;
            while ((read = input.read(buff)) > 0) {
                output.write(buff, 0, read);
            }
            output.flush();
            output.close();
            input.close();
        }
    }
public synchronized String encrypt(String plaintext) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
            md.update(plaintext.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            log().error("failed to encrypt the password.", e);
            throw new RuntimeException("failed to encrypt the password.", e);
        } catch (UnsupportedEncodingException e) {
            log().error("failed to encrypt the password.", e);
            throw new RuntimeException("failed to encrypt the password.", e);
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }
@Override
    public void handlePeerEvent(PeerEvent event) {
        if (event.geteventInfo() instanceof EventServiceInfo) {
            EventServiceInfo info = (EventServiceInfo) event.geteventInfo();
            if (info.getServiceState() != ServiceState.Deployed) return;
            long bid = info.getBundleId();
            Bundle bundle = context.getBundle(bid);
            Enumeration entries = bundle.findEntries("OSGI-INF/PrivacyPolicy/", "*.xml", true);
            if (entries != null) {
                if (entries.hasMoreElements()) {
                    try {
                        URL url = (URL) entries.nextElement();
                        BufferedInputStream in = new BufferedInputStream(url.openStream());
                        XMLPolicyReader reader = new XMLPolicyReader(this.context);
                        RequestPolicy policy = reader.readPolicyFromFile(in);
                        if (policy != null) {
                            this.policyMgr.addPrivacyPolicyForService(info.getServiceID(), policy);
                        }
                    } catch (IOException ioe) {
                    }
                }
            }
        }
    }