semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void copy(File from, File to) {
        boolean result;
        if (from.isDirectory()) {
            File[] subFiles = from.listFiles();
            for (int i = 0; i < subFiles.length; i++) {
                File newDir = new File(to, subFiles[i].getName());
                result = false;
                if (subFiles[i].isDirectory()) {
                    if (newDir.exists()) result = true; else result = newDir.mkdirs();
                } else if (subFiles[i].isFile()) {
                    try {
                        result = newDir.createNewFile();
                    } catch (IOException e) {
                        log.error("unable to create new file: " + newDir, e);
                        result = false;
                    }
                }
                if (result) copy(subFiles[i], newDir);
            }
        } else if (from.isFile()) {
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream(from);
                out = new FileOutputStream(to);
                int fileLength = (int) from.length();
                char charBuff[] = new char[fileLength];
                int len;
                int oneChar;
                while ((oneChar = in.read()) != -1) {
                    out.write(oneChar);
                }
            } catch (FileNotFoundException e) {
                log.error("File not found!", e);
            } catch (IOException e) {
                log.error("Unable to read from file!", e);
            } finally {
                try {
                    if (in != null) in.close();
                    if (out != null) out.close();
                } catch (IOException e1) {
                    log.error("Error closing file reader/writer", e1);
                }
            }
        }
    }
@Override
    public boolean validatePublisher(Object object, String... dbSettingParams) {
        DBConnectionListener listener = (DBConnectionListener) object;
        String host = dbSettingParams[0];
        String port = dbSettingParams[1];
        String driver = dbSettingParams[2];
        String type = dbSettingParams[3];
        String dbHost = dbSettingParams[4];
        String dbName = dbSettingParams[5];
        String dbUser = dbSettingParams[6];
        String dbPassword = dbSettingParams[7];
        boolean validPublisher = false;
        String url = "http://" + host + ":" + port + "/reports";
        try {
            URL _url = new URL(url);
            _url.openConnection().connect();
            validPublisher = true;
        } catch (Exception e) {
            log.log(Level.FINE, "Failed validating url " + url, e);
        }
        if (validPublisher) {
            Connection conn;
            try {
                if (driver != null) {
                    conn = DBProperties.getInstance().getConnection(driver, dbHost, dbName, type, dbUser, dbPassword);
                } else {
                    conn = DBProperties.getInstance().getConnection();
                }
            } catch (Exception e) {
                conn = null;
                listener.connectionIsOk(false, null);
                validPublisher = false;
            }
            if (validPublisher) {
                if (!allNecessaryTablesCreated(conn)) {
                    conn = null;
                    listener.connectionIsOk(false, null);
                    validPublisher = false;
                }
                listener.connectionIsOk(true, conn);
            }
        } else {
            listener.connectionIsOk(false, null);
        }
        return validPublisher;
    }
private static void copier(FichierElectronique source, FichierElectronique cible) throws IOException {
        cible.setNom(source.getNom());
        cible.setTaille(source.getTaille());
        cible.setTypeMime(source.getTypeMime());
        cible.setSoumetteur(source.getSoumetteur());
        cible.setDateDerniereModification(source.getDateDerniereModification());
        cible.setEmprunteur(source.getEmprunteur());
        cible.setDateEmprunt(source.getDateEmprunt());
        cible.setNumeroVersion(source.getNumeroVersion());
        InputStream inputStream = source.getInputStream();
        OutputStream outputStream = cible.getOutputStream();
        try {
            IOUtils.copy(inputStream, outputStream);
        } finally {
            try {
                inputStream.close();
            } finally {
                outputStream.close();
            }
            if (source instanceof FichierElectroniqueDefaut) {
                FichierElectroniqueDefaut fichierElectroniqueTemporaire = (FichierElectroniqueDefaut) source;
                fichierElectroniqueTemporaire.deleteTemp();
            }
        }
    }
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException {
        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(srcFile);
            FileChannel iChannel = is.getChannel();
            os = new FileOutputStream(destFile, false);
            FileChannel oChannel = os.getChannel();
            long doneBytes = 0L;
            long todoBytes = srcFile.length();
            while (todoBytes != 0L) {
                long iterationBytes = Math.min(todoBytes, chunkSize);
                long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes);
                if (iterationBytes != transferredLength) {
                    throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied.");
                }
                doneBytes += transferredLength;
                todoBytes -= transferredLength;
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
        boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified());
        if (!successTimestampOp) {
            log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile);
        }
    }
public void deleteObject(String id) throws SQLException {
        boolean selfConnection = true;
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            if (dbConnection == null) {
                DatabaseConn dbConn = new DatabaseConn();
                conn = dbConn.getConnection();
                conn.setAutoCommit(false);
            } else {
                conn = dbConnection;
                selfConnection = false;
            }
            stmt = conn.prepareStatement(this.deleteSql);
            stmt.setString(1, id);
            stmt.executeUpdate();
            if (selfConnection) conn.commit();
        } catch (Exception e) {
            if (selfConnection && conn != null) conn.rollback();
            throw new SQLException(e.getMessage());
        } finally {
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (selfConnection && conn != null) {
                conn.close();
                conn = null;
            }
        }
    }
protected static byte[] downloadAndSendBinary(String u, boolean saveOnDisk, File f) throws IOException {
        URL url = new URL(u);
        Authenticator.setDefault(new HTTPResourceAuthenticator());
        HTTPResourceAuthenticator.addURL(url);
        logger.debug("Retrieving " + url.toString());
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("User-agent", "PS3 Media Server " + PMS.getVersion());
        InputStream in = conn.getInputStream();
        FileOutputStream fOUT = null;
        if (saveOnDisk && f != null) {
            fOUT = new FileOutputStream(f);
        }
        byte buf[] = new byte[4096];
        int n = -1;
        while ((n = in.read(buf)) > -1) {
            bytes.write(buf, 0, n);
            if (fOUT != null) {
                fOUT.write(buf, 0, n);
            }
        }
        in.close();
        if (fOUT != null) {
            fOUT.close();
        }
        return bytes.toByteArray();
    }
public static String httpGet(URL url) throws Exception {
        URLConnection connection = url.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer content = new StringBuffer();
        String line = null;
        while ((line = reader.readLine()) != null) {
            content.append(line);
        }
        return content.toString();
    }
@Override
    public void dispatchContent(InputStream is) throws IOException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending content message over JMS");
        }
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(is, bos);
        this.send(new MessageCreator() {

            @Override
            public Message createMessage(Session session) throws JMSException {
                BytesMessage message = session.createBytesMessage();
                message.writeBytes(bos.toByteArray());
                return message;
            }
        });
    }
private String md5(String s) {
        StringBuffer hexString = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();
            hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hashPart = Integer.toHexString(0xFF & messageDigest[i]);
                if (hashPart.length() == 1) {
                    hashPart = "0" + hashPart;
                }
                hexString.append(hashPart);
            }
        } catch (NoSuchAlgorithmException e) {
            Log.e(this.getClass().getSimpleName(), "MD5 algorithm not present");
        }
        return hexString != null ? hexString.toString() : null;
    }
Object onSuccess() {
        this.mErrorExist = true;
        this.mErrorMdp = true;
        if (!mClientManager.exists(this.mNewMail)) {
            this.mErrorExist = false;
            if (mNewMdp.equals(mNewMdpConfirm)) {
                this.mErrorMdp = false;
                MessageDigest sha1Instance;
                try {
                    sha1Instance = MessageDigest.getInstance("SHA1");
                    sha1Instance.reset();
                    sha1Instance.update(this.mNewMdp.getBytes());
                    byte[] digest = sha1Instance.digest();
                    BigInteger bigInt = new BigInteger(1, digest);
                    String vHashPassword = bigInt.toString(16);
                    Client vClient = new Client(this.mNewNom, (this.mNewPrenom != null ? this.mNewPrenom : ""), this.mNewMail, vHashPassword, this.mNewAdresse, 1);
                    mClientManager.save(vClient);
                    mComponentResources.discardPersistentFieldChanges();
                    return "Client/List";
                } catch (NoSuchAlgorithmException e) {
                    mLogger.error(e.getMessage(), e);
                }
            }
        }
        return errorZone.getBody();
    }
@Transient
    public byte[] getData() {
        InputStream is = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            is = urlInstance.openStream();
            byte[] bytes = new byte[1024 * 20];
            while (is.available() > 0) {
                int bytesRead = is.read(bytes);
                bos.write(bytes, 0, bytesRead);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            log.error("Error reading URL: " + url, e);
            return null;
        } finally {
            if (is != null) try {
                is.close();
            } catch (Exception e) {
                log.debug("Error closing URL input stream: " + url, e);
            }
        }
    }
public void copyToCurrentDir(File _copyFile, String _fileName) throws IOException {
        File outputFile = new File(getCurrentPath() + File.separator + _fileName);
        FileReader in;
        FileWriter out;
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        in = new FileReader(_copyFile);
        out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
        reList();
    }
private String fetchLocalPage(String page) throws IOException {
        final String fullUrl = HOST + page;
        LOG.debug("Fetching local page: " + fullUrl);
        URL url = new URL(fullUrl);
        URLConnection connection = url.openConnection();
        StringBuilder sb = new StringBuilder();
        BufferedReader input = null;
        try {
            input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = null;
            while ((line = input.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            if (input != null) try {
                input.close();
            } catch (IOException e) {
                LOG.error("Could not close reader!", e);
            }
        }
        return sb.toString();
    }
static String calculateProfileDiffDigest(String profileDiff, boolean normaliseWhitespace) throws Exception {
        if (normaliseWhitespace) {
            profileDiff = removeWhitespaces(profileDiff);
        }
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(profileDiff.getBytes());
        return new BASE64Encoder().encode(md.digest());
    }
protected final void connectFtp() throws IOException {
            try {
                if (!this.ftpClient.isConnected()) {
                    this.ftpClient.connect(getHost(), getPort());
                    getLog().write(Level.INFO, String.format(getMessages().getString("FtpSuccessfullyConnected"), getHost()));
                    int reply = this.ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        this.ftpClient.disconnect();
                        throw new IOException(String.format(getMessages().getString("FtpErrorConnectingRefused"), getHost()));
                    }
                    if (getUsername() != null) {
                        if (!this.ftpClient.login(getUsername(), getPassword())) {
                            this.ftpClient.logout();
                            disconnectFtp();
                            throw new IOException(String.format(getMessages().getString("FtpErrorAuthorizing"), getHost()));
                        }
                    }
                    this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                    this.ftpClient.enterLocalPassiveMode();
                    getLog().write(Level.INFO, String.format(getMessages().getString("FtpSuccessfullyAuthorized"), getHost()));
                }
            } catch (IOException ex) {
                disconnectFtp();
                throw new IOException(String.format(getMessages().getString("FtpErrorConnecting"), getHost(), ex.toString()));
            }
        }
public void initGet() throws Exception {
        cl = new FTPClient();
        URL url = new URL(getURL());
        cl.setRemoteHost(url.getHost());
        cl.connect();
        cl.login(user, pass);
        cl.setType(FTPTransferType.BINARY);
        cl.setConnectMode(FTPConnectMode.PASV);
        cl.restart(getPosition());
    }
private BinaryDocument documentFor(String code, String type, int diagramIndex) {
        code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20");
        StringBuilder builder = new StringBuilder("http://yuml.me/diagram/");
        builder.append(type).append("/");
        builder.append(code);
        URL url;
        try {
            url = new URL(builder.toString());
            String name = "uml" + diagramIndex + ".png";
            diagramIndex++;
            BinaryDocument pic = new BinaryDocument(name, "image/png");
            IOUtils.copy(url.openStream(), pic.getContent().getOutputStream());
            return pic;
        } catch (MalformedURLException e) {
            throw ManagedIOException.manage(e);
        } catch (IOException e) {
            throw ManagedIOException.manage(e);
        }
    }
private void sendToURL(String URL, String file) throws Exception {
        URL url = new URL(URL);
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        OutputStream os = url.openConnection().getOutputStream();
        copyDocument(is, os);
        is.close();
        os.close();
    }
public static String cryptoSHA(String _strSrc) {
        try {
            BASE64Encoder encoder = new BASE64Encoder();
            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(_strSrc.getBytes());
            byte[] buffer = sha.digest();
            return encoder.encode(buffer);
        } catch (Exception err) {
            System.out.println(err);
        }
        return "";
    }
private Document post(String location, String content) throws ApplicationException {
        Document doc = null;
        try {
            URL url = new URL(location);
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.setRequestMethod("POST");
            uc.setRequestProperty("Content-Type", "application/xml");
            uc.setRequestProperty("X-POST_DATA_FORMAT", "xml");
            uc.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
            out.write("<request>");
            out.write("<token>" + configuration.getBackpackPassword() + "</token>");
            if (content != null) {
                out.write("<item><content>" + content + "</content></item>");
            }
            out.write("</request>");
            out.close();
            doc = XmlUtils.readDocumentFromInputStream(uc.getInputStream());
            System.out.println(XmlUtils.toString(doc));
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApplicationException(e);
        }
        return doc;
    }
private void copyFile(File s, File d) throws IOException {
        d.getParentFile().mkdirs();
        FileChannel inChannel = new FileInputStream(s).getChannel();
        FileChannel outChannel = new FileOutputStream(d).getChannel();
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }
        inChannel.close();
        outChannel.close();
        d.setLastModified(s.lastModified());
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        String pluginPathInfo = pathInfo.substring(prefix.length());
        String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1);
        String clPath = CLASSPATH_PREFIX + gwtPathInfo;
        InputStream input = cl.getResourceAsStream(clPath);
        if (input != null) {
            try {
                OutputStream output = resp.getOutputStream();
                IOUtils.copy(input, output);
            } finally {
                input.close();
            }
        } else {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
public void fetchKey() throws IOException {
        String strurl = MessageFormat.format(keyurl, new Object[] { username, secret, login, session });
        StringBuffer result = new StringBuffer();
        BufferedReader reader = null;
        URL url = null;
        try {
            url = new URL(strurl);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (Exception e) {
            }
        }
        Pattern p = Pattern.compile("<key>(.*)</key>");
        Matcher m = p.matcher(result.toString());
        if (m.matches()) {
            this.key = m.group(1);
        }
    }
private static void backupFile(File file) {
        FileChannel in = null, out = null;
        try {
            if (!file.getName().endsWith(".bak")) {
                in = new FileInputStream(file).getChannel();
                out = new FileOutputStream(new File(file.toString() + ".bak")).getChannel();
                long size = in.size();
                MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
                out.write(buf);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                System.gc();
                if (in != null) in.close();
                if (out != null) out.close();
            } catch (Exception e) {
                e.getMessage();
            }
        }
    }
private String doExecute(AbortableHttpRequest method) throws Throwable {
        HttpClient client = CLIENT.newInstance();
        HttpResponse rsp = client.execute((HttpUriRequest) method);
        HttpEntity entity = rsp.getEntity();
        if (entity == null) throw new RequestError("No entity in method");
        InputStream in = null;
        try {
            in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder inStr = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                inStr.append(line).append("\r\n");
            }
            entity.consumeContent();
            return inStr.toString();
        } catch (IOException ex) {
            LOG.error("IO exception: " + ex.getMessage());
            throw ex;
        } catch (RuntimeException ex) {
            method.abort();
            throw ex;
        } finally {
            if (in != null) in.close();
        }
    }
public static String md5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD);
            md.update(data.getBytes(UTF8));
            return encodeHex(md.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
public static byte[] md5raw(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD);
            md.update(data.getBytes(UTF8));
            return md.digest();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }