semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private String getMD5(String data) {
        try {
            MessageDigest md5Algorithm = MessageDigest.getInstance("MD5");
            md5Algorithm.update(data.getBytes(), 0, data.length());
            byte[] digest = md5Algorithm.digest();
            StringBuffer hexString = new StringBuffer();
            String hexDigit = null;
            for (int i = 0; i < digest.length; i++) {
                hexDigit = Integer.toHexString(0xFF & digest[i]);
                if (hexDigit.length() < 2) {
                    hexDigit = "0" + hexDigit;
                }
                hexString.append(hexDigit);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException ne) {
            return data;
        }
    }
private void parseTemplate(File templateFile, Map dataMap) throws ContainerException {
        Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module);
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(templateFile));
        } catch (FileNotFoundException e) {
            throw new ContainerException(e);
        }
        String targetDirectoryName = args.length > 1 ? args[1] : null;
        if (targetDirectoryName == null) {
            targetDirectoryName = target;
        }
        String targetDirectory = ofbizHome + targetDirectoryName + args[0];
        File targetDir = new File(targetDirectory);
        if (!targetDir.exists()) {
            boolean created = targetDir.mkdirs();
            if (!created) {
                throw new ContainerException("Unable to create target directory - " + targetDirectory);
            }
        }
        if (!targetDirectory.endsWith("/")) {
            targetDirectory = targetDirectory + "/";
        }
        Writer writer = null;
        try {
            writer = new FileWriter(targetDirectory + templateFile.getName());
        } catch (IOException e) {
            throw new ContainerException(e);
        }
        try {
            FreeMarkerWorker.renderTemplate(templateFile.getAbsolutePath(), reader, dataMap, writer);
        } catch (Exception e) {
            throw new ContainerException(e);
        }
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new ContainerException(e);
        }
    }
public boolean saveTemplate(Template t) {
        try {
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            String query;
            ResultSet rset;
            if (Integer.parseInt(executeMySQLGet("SELECT COUNT(*) FROM templates WHERE name='" + escapeCharacters(t.getName()) + "'")) != 0) return false;
            query = "select * from templates where templateid = " + t.getID();
            rset = stmt.executeQuery(query);
            if (rset.next()) {
                System.err.println("Updating already saved template is not supported!!!!!!");
                return false;
            } else {
                query = "INSERT INTO templates (name, parentid) VALUES ('" + escapeCharacters(t.getName()) + "', " + t.getParentID() + ")";
                try {
                    stmt.executeUpdate(query);
                } catch (SQLException e) {
                    conn.rollback();
                    conn.setAutoCommit(true);
                    e.printStackTrace();
                    return false;
                }
                int templateid = Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"));
                t.setID(templateid);
                LinkedList<Field> fields = t.getFields();
                ListIterator<Field> iter = fields.listIterator();
                Field f = null;
                PreparedStatement pstmt = conn.prepareStatement("INSERT INTO templatefields(fieldtype, name, templateid, defaultvalue)" + "VALUES (?,?,?,?)");
                try {
                    while (iter.hasNext()) {
                        f = iter.next();
                        if (f.getType() == Field.IMAGE) {
                            System.out.println("field is an image.");
                            byte data[] = ((FieldDataImage) f.getDefault()).getDataBytes();
                            pstmt.setBytes(4, data);
                        } else {
                            System.out.println("field is not an image");
                            String deflt = (f.getDefault()).getData();
                            pstmt.setString(4, deflt);
                        }
                        pstmt.setInt(1, f.getType());
                        pstmt.setString(2, f.getName());
                        pstmt.setInt(3, t.getID());
                        pstmt.execute();
                        f.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()")));
                    }
                } catch (SQLException e) {
                    conn.rollback();
                    conn.setAutoCommit(true);
                    e.printStackTrace();
                    return false;
                }
            }
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException ex) {
            System.err.println("Error saving the Template");
            return false;
        }
        return true;
    }
public static boolean copyFile(String source, String destination, boolean replace) {
        File sourceFile = new File(source);
        File destinationFile = new File(destination);
        if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false;
        if (destinationFile.isFile() && !replace) return false;
        if (!sourceFile.isFile()) return false;
        if (replace) destinationFile.delete();
        try {
            File dir = destinationFile.getParentFile();
            while (dir != null && !dir.exists()) {
                dir.mkdir();
            }
            DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240));
            DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240));
            try {
                while (inStream.available() > 0) {
                    outStream.write(inStream.readUnsignedByte());
                }
            } catch (EOFException eof) {
            }
            inStream.close();
            outStream.close();
        } catch (IOException ex) {
            throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath());
        }
        return true;
    }
protected void initDefaultRolesFile() {
        String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3");
        File mappingFile = new File(webConfigPath + "roles.json");
        if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath());
        if (mappingFile.exists()) return;
        log.info("Init default Role Mapping file! mappingFile:" + mappingFile);
        if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent());
        FileChannel fos = null;
        InputStream is = null;
        try {
            URL url = getClass().getResource("/META-INF/roles-default.json");
            log.info("Use default Mapping File content of url:" + url);
            is = url.openStream();
            ReadableByteChannel inCh = Channels.newChannel(is);
            fos = new FileOutputStream(mappingFile).getChannel();
            int pos = 0;
            while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available());
        } catch (Exception e) {
            log.error("Roles file doesn't exist and the default can't be created!", e);
        } finally {
            close(is);
            close(fos);
        }
    }
private HttpURLConnection prepare(URL url, String method) {
            if (this.username != null && this.password != null) {
                this.headers.put("Authorization", "Basic " + Codec.encodeBASE64(this.username + ":" + this.password));
            }
            try {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                checkFileBody(connection);
                connection.setRequestMethod(method);
                for (String key : this.headers.keySet()) {
                    connection.setRequestProperty(key, headers.get(key));
                }
                return connection;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
public static long copyFile(File source, File target) throws IOException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            FileChannel in = fileInputStream.getChannel();
            FileChannel out = fileOutputStream.getChannel();
            return out.transferFrom(in, 0, source.length());
        } finally {
            if (fileInputStream != null) fileInputStream.close();
            if (fileOutputStream != null) fileOutputStream.close();
        }
    }
public void run() {
        Vector<Update> updates = new Vector<Update>();
        if (dic != null) updates.add(dic);
        if (gen != null) updates.add(gen);
        if (res != null) updates.add(res);
        if (help != null) updates.add(help);
        for (Iterator iterator = updates.iterator(); iterator.hasNext(); ) {
            Update update = (Update) iterator.next();
            try {
                File temp = File.createTempFile("fm_" + update.getType(), ".jar");
                temp.deleteOnExit();
                FileOutputStream out = new FileOutputStream(temp);
                URL url = new URL(update.getAction());
                URLConnection conn = url.openConnection();
                com.diccionarioderimas.Utils.setupProxy(conn);
                InputStream in = conn.getInputStream();
                byte[] buffer = new byte[1024];
                int read = 0;
                int total = 0;
                while ((read = in.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                    total += read;
                    if (total > 10000) {
                        progressBar.setValue(progressBar.getValue() + total);
                        total = 0;
                    }
                }
                out.close();
                in.close();
                String fileTo = basePath + "diccionariorimas.jar";
                if (update.getType() == Update.GENERATOR) fileTo = basePath + "generador.jar"; else if (update.getType() == Update.RESBC) fileTo = basePath + "resbc.me"; else if (update.getType() == Update.HELP) fileTo = basePath + "help.html";
                if (update.getType() == Update.RESBC) {
                    Utils.unzip(temp, new File(fileTo));
                } else {
                    Utils.copyFile(new FileInputStream(temp), new File(fileTo));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        setVisible(false);
        if (gen != null || res != null) {
            try {
                new Main(null, basePath, false);
            } catch (Exception e) {
                new ErrorDialog(frame, e);
            }
        }
        String restart = "";
        if (dic != null) restart += "\nAlgunas de ellas s�lo estar�n disponibles despu�s de reiniciar el diccionario.";
        JOptionPane.showMessageDialog(frame, "Se han terminado de realizar las actualizaciones." + restart, "Actualizaciones", JOptionPane.INFORMATION_MESSAGE);
    }
public static void fileCopy(File sourceFile, File destFile) throws IOException {
        FileChannel source = null;
        FileChannel destination = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(destFile);
            source = fis.getChannel();
            destination = fos.getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            fis.close();
            fos.close();
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
private void copy(File inputFile, File outputFile) throws Exception {
            FileReader in = new FileReader(inputFile);
            FileWriter out = new FileWriter(outputFile);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        }
public void doActionxxx() {
        try {
            System.out.println("app: ggc");
            String server_name = "http://192.168.4.3:8080/";
            server_name = server_name.trim();
            if (server_name.length() == 0) {
                server_name = "http://www.atech-software.com/";
            } else {
                if (!server_name.startsWith("http://")) server_name = "http://" + server_name;
                if (!server_name.endsWith("/")) server_name = server_name + "/";
            }
            URL url = new URL(server_name + "ATechUpdateGetFile?" + "" + "file_id=1" + "&" + "version_requested=1");
            InputStream is = url.openStream();
            RandomAccessFile raf = new RandomAccessFile("/home/andy/test.jpg", "rw");
            ArrayList<Integer> list = new ArrayList<Integer>();
            float size = 671200;
            long current_size = 0;
            System.out.println("File size: " + is.available());
            byte[] array = new byte[1024];
            while (is.available() > 0) {
                if (is.available() < 1024) {
                    array = new byte[is.available()];
                }
                is.read(array);
                raf.write(array);
                current_size += array.length;
                System.out.println("Progress: " + ((current_size / size) * 100));
            }
            System.out.println("Size Arr: " + list.size());
            CheckSumUtility csu = new CheckSumUtility();
            System.out.println("Checksum: " + csu.getChecksumValue("/home/andy/test.jpg"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
private String hashKey(String key) {
        String hashed = "";
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(key.getBytes());
            BigInteger hash = new BigInteger(1, md5.digest());
            hashed = hash.toString(16);
        } catch (Exception ex) {
            ex.printStackTrace();
            hashed = String.valueOf(key.hashCode());
        }
        return hashed;
    }
private byte[] getMD5(String string) throws IMException {
        byte[] buffer = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(string.getBytes("utf-8"));
            buffer = md.digest();
            buffer = getHexString(buffer);
        } catch (NoSuchAlgorithmException e) {
            throw new IMException(e);
        } catch (UnsupportedEncodingException ue) {
            throw new IMException(ue);
        }
        return buffer;
    }
public void load(String url) throws IOException {
        this.url = url;
        int col = url.indexOf(':');
        if (col > 1 && col < 5) {
            load(new URL(url).openStream());
        } else {
            if (new File(url).exists()) {
                System.out.println("Loading JAD from file : " + url);
                FileInputStream fin = new FileInputStream(url);
                try {
                    load(fin);
                } finally {
                    fin.close();
                }
            } else {
                InputStream in = getClass().getResourceAsStream(url);
                if (in != null) {
                    System.out.println("Loading JAD from classpath : " + url);
                    load(in);
                } else {
                    throw new IOException("\"" + url + "\" was found in file system or classpath");
                }
            }
        }
    }
public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            PrintUtil.prt("arguments: sourcefile, destfile");
            System.exit(1);
        }
        FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel();
        ByteBuffer buff = ByteBuffer.allocate(BSIZE);
        while (in.read(buff) != -1) {
            PrintUtil.prt("%%%");
            buff.flip();
            out.write(buff);
            buff.clear();
        }
    }
public Constructor run() throws Exception {
                            String path = "META-INF/services/" + BeanletApplicationContext.class.getName();
                            ClassLoader loader = Thread.currentThread().getContextClassLoader();
                            final Enumeration<URL> urls;
                            if (loader == null) {
                                urls = BeanletApplicationContext.class.getClassLoader().getResources(path);
                            } else {
                                urls = loader.getResources(path);
                            }
                            while (urls.hasMoreElements()) {
                                URL url = urls.nextElement();
                                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                                try {
                                    String className = null;
                                    while ((className = reader.readLine()) != null) {
                                        final String name = className.trim();
                                        if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) {
                                            final Class<?> cls;
                                            if (loader == null) {
                                                cls = Class.forName(name);
                                            } else {
                                                cls = Class.forName(name, true, loader);
                                            }
                                            int m = cls.getModifiers();
                                            if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) {
                                                Constructor constructor = cls.getDeclaredConstructor();
                                                if (!Modifier.isPublic(constructor.getModifiers())) {
                                                    constructor.setAccessible(true);
                                                }
                                                return constructor;
                                            } else {
                                                throw new ClassCastException(cls.getName());
                                            }
                                        }
                                    }
                                } finally {
                                    reader.close();
                                }
                            }
                            throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found.");
                        }
public synchronized FTPClient getFTPClient(String User, String Password) throws IOException {
            if (logger.isDebugEnabled()) {
                logger.debug("getFTPClient(String, String) - start");
            }
            while ((counter >= maxClients)) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    logger.error("getFTPClient(String, String)", e);
                    e.printStackTrace();
                }
            }
            FTPClient result = null;
            String key = User.concat(Password);
            logger.debug("versuche vorhandenen FTPClient aus Liste zu lesen");
            if (Clients != null) {
                if (Clients.containsKey(key)) {
                    LinkedList ClientList = (LinkedList) Clients.get(key);
                    if (!ClientList.isEmpty()) do {
                        result = (FTPClient) ClientList.getLast();
                        logger.debug("-- hole einen Client aus der Liste: " + result.toString());
                        ClientList.removeLast();
                        if (!result.isConnected()) {
                            logger.debug("---- nicht mehr verbunden.");
                            result = null;
                        } else {
                            try {
                                result.changeWorkingDirectory("/");
                            } catch (IOException e) {
                                logger.debug("---- schmei�t Exception bei Zugriff.");
                                result = null;
                            }
                        }
                    } while (result == null && !ClientList.isEmpty());
                    if (ClientList.isEmpty()) {
                        Clients.remove(key);
                    }
                } else {
                }
            } else logger.debug("-- keine Liste vorhanden.");
            if (result == null) {
                logger.debug("Kein FTPCLient verf�gbar, erstelle einen neuen.");
                result = new FTPClient();
                logger.debug("-- Versuche Connect");
                result.connect(Host);
                logger.debug("-- Versuche Login");
                result.login(User, Password);
                result.setFileType(FTPClient.BINARY_FILE_TYPE);
                if (counter == maxClients - 1) {
                    RemoveBufferedClient();
                }
            }
            logger.debug("OK: neuer FTPClient ist " + result.toString());
            ;
            counter++;
            if (logger.isDebugEnabled()) {
                logger.debug("getFTPClient(String, String) - end");
            }
            return result;
        }
protected void fixupCategoryAncestry(Context context) throws DataStoreException {
        Connection db = null;
        Statement s = null;
        try {
            db = context.getConnection();
            db.setAutoCommit(false);
            s = db.createStatement();
            s.executeUpdate("delete from category_ancestry");
            walkTreeFixing(db, CATEGORYROOT);
            db.commit();
            context.put(Form.ACTIONEXECUTEDTOKEN, "Category Ancestry regenerated");
        } catch (SQLException sex) {
            try {
                db.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throw new DataStoreException("Failed to refresh category ancestry");
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (db != null) {
                context.releaseConnection(db);
            }
        }
    }