semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void convertEncoding(File infile, File outfile, String from, String to) throws IOException, UnsupportedEncodingException {
        InputStream in;
        if (infile != null) in = new FileInputStream(infile); else in = System.in;
        OutputStream out;
        outfile.createNewFile();
        if (outfile != null) out = new FileOutputStream(outfile); else out = System.out;
        if (from == null) from = System.getProperty("file.encoding");
        if (to == null) to = "Unicode";
        Reader r = new BufferedReader(new InputStreamReader(in, from));
        Writer w = new BufferedWriter(new OutputStreamWriter(out, to));
        char[] buffer = new char[4096];
        int len;
        while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len);
        r.close();
        w.close();
    }
public void testFileSystem() throws IOException {
        Fragment f = Fragment.EMPTY;
        Fragment g = f.plus(System.getProperty("java.io.tmpdir"));
        Fragment h = f.plus("april", "1971", "data.txt");
        Fragment i = f.plus(g, h);
        InOutLocation iol = locs.fs.plus(i);
        PrintStream ps = new PrintStream(iol.openOutput());
        List<String> expected = new ArrayList<String>();
        expected.add("So I am stepping out this old brown shoe");
        expected.add("Maybe I'm in love with you");
        for (String s : expected) ps.println(s);
        ps.close();
        InLocation inRoot = locs.fs;
        List<String> lst = read(inRoot.plus(i).openInput());
        assertEquals(expected, lst);
        URL url = iol.toUrl();
        lst = read(url.openStream());
        assertEquals(expected, lst);
    }
public static String hash(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(text.getBytes());
            byte[] digest = md.digest();
            StringBuffer sb = new StringBuffer(digest.length * 2);
            for (int i = 0; i < digest.length; ++i) {
                byte b = digest[i];
                int high = (b & 0xF0) >> 4;
                int low = b & 0xF;
                sb.append(DECIMAL_HEX[high]);
                sb.append(DECIMAL_HEX[low]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new NonBusinessException("Error hashing string", e);
        }
    }
private HttpURLConnection connect() throws MalformedURLException, IOException {
        HttpURLConnection connection = null;
        if (repositoryLocation == null) {
            Utils.debug("RemoteRepository", "repository Location unspecified");
            return null;
        }
        URL url = new URL(repositoryLocation);
        connection = (HttpURLConnection) url.openConnection();
        return connection;
    }
private static byte[] calcMd5(String pass) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(pass.getBytes(), 0, pass.length());
            byte[] hash = digest.digest();
            return hash;
        } catch (NoSuchAlgorithmException e) {
            System.err.println("No MD5 algorithm found");
            System.exit(1);
        }
        return null;
    }
private void addConfigurationResource(final String fileName, NotFoundPolicy notFoundPolicy) {
        try {
            final ClassLoader cl = this.getClass().getClassLoader();
            final Properties p = new Properties();
            final URL url = cl.getResource(fileName);
            if (url == null) {
                throw new NakedObjectException("Failed to load configuration resource: " + fileName);
            }
            p.load(url.openStream());
            LOG.info("configuration resource " + fileName + " loaded");
            configuration.add(p);
        } catch (final Exception e) {
            if (notFoundPolicy == NotFoundPolicy.FAIL_FAST) {
                throw new NakedObjectException(e);
            }
            LOG.info("configuration resource " + fileName + " not found, but not needed");
        }
    }
public String[] retrieveFasta(String id) throws Exception {
        URL url = new URL("http://www.ebi.ac.uk/ena/data/view/" + id + "&display=fasta");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String header = reader.readLine();
        StringBuffer seq = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            seq.append(line);
        }
        reader.close();
        return new String[] { header, seq.toString() };
    }
public FTPClient connect(String host, String userId, String password, String alias) throws IOException {
        FTPClient client = null;
        if (connections.get(alias) != null) {
            client = (FTPClient) connections.get(alias);
            if (client.isConnected() == false) {
                client.connect(host);
            }
        } else {
            client = new FTPClient();
            client.connect(host);
            client.login(userId, password);
            connections.put(alias, client);
        }
        return client;
    }
private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException {
        HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        System.out.println("cg form get: " + response.getStatusLine());
        if (entity != null) {
            InputStream inStream = entity.getContent();
            IOUtils.copy(inStream, System.out);
        }
        System.out.println("cg set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("- " + cookies.get(i).toString());
            }
        }
    }
public String getLastVersion() {
        try {
            String server = icescrum2Properties.get("check.url").toString();
            Boolean useProxy = new Boolean(icescrum2Properties.get("proxy.active").toString());
            Boolean authProxy = new Boolean(icescrum2Properties.get("proxy.auth.active").toString());
            URL url = new URL(server);
            if (useProxy) {
                String proxy = icescrum2Properties.get("proxy.url").toString();
                String port = icescrum2Properties.get("proxy.port").toString();
                Properties systemProperties = System.getProperties();
                systemProperties.setProperty("http.proxyHost", proxy);
                systemProperties.setProperty("http.proxyPort", port);
            }
            URLConnection connection = url.openConnection();
            if (authProxy) {
                String username = icescrum2Properties.get("proxy.auth.username").toString();
                String password = icescrum2Properties.get("proxy.auth.password").toString();
                String login = username + ":" + password;
                String encodedLogin = Base64.base64Encode(login);
                connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin);
            }
            connection.setConnectTimeout(Integer.parseInt(icescrum2Properties.get("check.timeout").toString()));
            InputStream input = connection.getInputStream();
            StringWriter writer = new StringWriter();
            InputStreamReader streamReader = new InputStreamReader(input);
            BufferedReader buffer = new BufferedReader(streamReader);
            String value = "";
            while (null != (value = buffer.readLine())) {
                writer.write(value);
            }
            return writer.toString();
        } catch (IOException e) {
        }
        return null;
    }
public T_Result unmarshall(URL url) throws SAXException, ParserConfigurationException, IOException {
        XMLReader parser = getParserFactory().newSAXParser().getXMLReader();
        parser.setContentHandler(getContentHandler());
        parser.setDTDHandler(getContentHandler());
        parser.setEntityResolver(getContentHandler());
        parser.setErrorHandler(getContentHandler());
        InputSource inputSource = new InputSource(url.openStream());
        inputSource.setSystemId(url.toString());
        parser.parse(inputSource);
        return contentHandler.getRootObject();
    }
private static String getServiceResponse(final String requestName, final Template template, final Map variables) {
        OutputStreamWriter outputWriter = null;
        try {
            final StringWriter writer = new StringWriter();
            final VelocityContext context = new VelocityContext(variables);
            template.merge(context, writer);
            final String request = writer.toString();
            final URLConnection urlConnection = new URL(SERVICE_URL).openConnection();
            urlConnection.setUseCaches(false);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2b4) Gecko/20091124 Firefox/3.6b4");
            urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            urlConnection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
            urlConnection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
            urlConnection.setRequestProperty("Keep-Alive", "115");
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            urlConnection.setRequestProperty("Content-Length", "" + request.length());
            urlConnection.setRequestProperty("SOAPAction", requestName);
            outputWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
            outputWriter.write(request);
            outputWriter.flush();
            final InputStream result = urlConnection.getInputStream();
            return IOUtils.toString(result);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        } finally {
            if (outputWriter != null) {
                try {
                    outputWriter.close();
                } catch (IOException logOrIgnore) {
                }
            }
        }
    }
public static void CopyFile(String in, String out) throws Exception {
        FileChannel sourceChannel = new FileInputStream(new File(in)).getChannel();
        FileChannel destinationChannel = new FileOutputStream(new File(out)).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        sourceChannel.close();
        destinationChannel.close();
    }
public static String getMD5(String password) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            String pwd = new BigInteger(1, md5.digest()).toString(16);
            return pwd;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return password;
    }
public static String[] bubbleSort(String[] unsortedString, boolean ascending) {
        if (unsortedString.length < 2) return unsortedString;
        String[] sortedString = new String[unsortedString.length];
        for (int i = 0; i < unsortedString.length; i++) {
            sortedString[i] = unsortedString[i];
        }
        if (ascending) {
            for (int i = 0; i < sortedString.length - 1; i++) {
                for (int j = 1; j < sortedString.length - 1 - i; j++) if (sortedString[j + 1].compareToIgnoreCase(sortedString[j]) < 0) {
                    String swap = sortedString[j];
                    sortedString[j] = sortedString[j + 1];
                    sortedString[j + 1] = swap;
                }
            }
        } else {
            for (int i = sortedString.length - 2; i >= 0; i--) {
                for (int j = sortedString.length - 2 - i; j >= 0; j--) if (sortedString[j + 1].compareToIgnoreCase(sortedString[j]) > 0) {
                    String swap = sortedString[j];
                    sortedString[j] = sortedString[j + 1];
                    sortedString[j + 1] = swap;
                }
            }
        }
        return sortedString;
    }
private static void insertFiles(Connection con, File file) throws IOException {
        BufferedReader bf = new BufferedReader(new FileReader(file));
        String line = bf.readLine();
        while (line != null) {
            if (!line.startsWith(" ") && !line.startsWith("#")) {
                try {
                    System.out.println("Exec: " + line);
                    PreparedStatement prep = con.prepareStatement(line);
                    prep.executeUpdate();
                    prep.close();
                    con.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        con.rollback();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            line = bf.readLine();
        }
        bf.close();
    }
String openUrlAsString(String address, int maxLines) {
        StringBuffer sb;
        try {
            URL url = new URL(address);
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            sb = new StringBuffer();
            int count = 0;
            String line;
            while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n");
            in.close();
        } catch (IOException e) {
            sb = null;
        }
        return sb != null ? new String(sb) : null;
    }
String[] openUrlAsList(String address) {
        IJ.showStatus("Connecting to " + IJ.URL);
        Vector v = new Vector();
        try {
            URL url = new URL(address);
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while (true) {
                line = br.readLine();
                if (line == null) break;
                if (!line.equals("")) v.addElement(line);
            }
            br.close();
        } catch (Exception e) {
        }
        String[] lines = new String[v.size()];
        v.copyInto((String[]) lines);
        IJ.showStatus("");
        return lines;
    }
public static void addIntegrityEnforcements(Session session) throws HibernateException {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Statement st = session.connection().createStatement();
            st.executeUpdate("DROP TABLE hresperformsrole;" + "CREATE TABLE hresperformsrole" + "(" + "hresid varchar(255) NOT NULL," + "rolename varchar(255) NOT NULL," + "CONSTRAINT hresperformsrole_pkey PRIMARY KEY (hresid, rolename)," + "CONSTRAINT ResourceFK FOREIGN KEY (hresid) REFERENCES resserposid (id) ON UPDATE CASCADE ON DELETE CASCADE," + "CONSTRAINT RoleFK FOREIGN KEY (rolename) REFERENCES role (rolename) ON UPDATE CASCADE ON DELETE CASCADE" + ");");
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
    }
protected RemoteInputStream getUrlResource(URL url) throws IOException {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(url_loading_time_out);
        conn.setReadTimeout(url_loading_time_out);
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.connect();
        long last_modify_time = conn.getLastModified();
        IOCacheService cache_service = CIO.getAppBridge().getIO().getCache();
        if (cache_service != null) {
            RemoteInputStream cache = cache_service.findCache(url, last_modify_time);
            if (cache != null) {
                return cache;
            }
        }
        return new URLConnectionInputStream(url, conn);
    }
public static boolean copyFile(String sourceName, String destName) {
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        boolean wasOk = false;
        try {
            sourceChannel = new FileInputStream(sourceName).getChannel();
            destChannel = new FileOutputStream(destName).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            wasOk = true;
        } catch (Throwable exception) {
            logger.log(Level.SEVERE, "Exception in copyFile", exception);
        } finally {
            try {
                if (sourceChannel != null) sourceChannel.close();
            } catch (Throwable tt) {
            }
            try {
                if (destChannel != null) destChannel.close();
            } catch (Throwable tt) {
            }
        }
        return wasOk;
    }
private static String hashPass(String p) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(p.getBytes("iso-8859-1"), 0, p.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
@Override
    public void send() {
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(getUrl());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                result.append(str);
            }
        } catch (ConnectException ce) {
            logger.error("MockupExecutableCommand excute fail: " + ce.getMessage());
        } catch (Exception e) {
            logger.error("MockupExecutableCommand excute fail: " + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("BufferedReader could not be closed", e);
                }
            }
        }
    }
public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) {
        FileOutputStream os = null;
        DataOutputStream dos = null;
        try {
            LPKTable[] fileTable = new LPKTable[srcFilePath.length];
            long fileOffset = outputOffset(header);
            for (int i = 0; i < srcFilePath.length; i++) {
                String sourceFileName = FileUtils.getFileName(srcFilePath[i]);
                long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]);
                LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset);
                fileOffset = outputNextOffset(sourceFileSize, fileOffset);
                fileTable[i] = ft;
            }
            File file = new File(makeFilePath);
            if (!file.exists()) {
                FileUtils.makedirs(file);
            }
            os = new FileOutputStream(file);
            dos = new DataOutputStream(os);
            dos.writeInt(header.getPAKIdentity());
            writeByteArray(header.getPassword(), dos);
            dos.writeFloat(header.getVersion());
            dos.writeLong(header.getTables());
            for (int i = 0; i < fileTable.length; i++) {
                writeByteArray(fileTable[i].getFileName(), dos);
                dos.writeLong(fileTable[i].getFileSize());
                dos.writeLong(fileTable[i].getOffSet());
            }
            for (int i = 0; i < fileTable.length; i++) {
                File ftFile = new File(srcFilePath[i]);
                FileInputStream ftFis = new FileInputStream(ftFile);
                DataInputStream ftDis = new DataInputStream(ftFis);
                byte[] buff = new byte[256];
                int readLength = 0;
                while ((readLength = ftDis.read(buff)) != -1) {
                    makeBuffer(buff, readLength);
                    dos.write(buff, 0, readLength);
                }
                ftDis.close();
                ftFis.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                    dos = null;
                } catch (IOException e) {
                }
            }
        }
    }
private String download(MacroManagerProgress progress, String fileName, String url) throws Exception {
            URLConnection conn = new URL(url).openConnection();
            progress.setMaximum(Math.max(0, conn.getContentLength()));
            String path = MiscUtilities.constructPath(installDirectory, fileName);
            if (!copy(progress, conn.getInputStream(), new FileOutputStream(path), true, true)) return null;
            if (archive_zip) {
                Enumeration entries;
                ZipFile zipFile;
                try {
                    File tempFile = new File(path);
                    zipFile = new ZipFile(tempFile);
                    entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = (ZipEntry) entries.nextElement();
                        if (entry.isDirectory()) {
                            String dpath = MiscUtilities.constructPath(installDirectory, entry.getName());
                            (new File(dpath)).mkdir();
                            continue;
                        }
                        progress.setMaximum((int) entry.getSize());
                        String ePath = MiscUtilities.constructPath(installDirectory, entry.getName());
                        copy(progress, zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(ePath)), true, true);
                    }
                    zipFile.close();
                    tempFile.delete();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            } else if (archive_gzip) {
                File srce = new File(path);
                GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(srce));
                File temp = File.createTempFile("macro", "mgr");
                progress.setMaximum((int) srce.length());
                copy(progress, gzis, new BufferedOutputStream(new FileOutputStream(temp)), true, true);
                TarArchive tarc = new TarArchive(new FileInputStream(temp));
                tarc.extractContents(new File(installDirectory));
                tarc.closeArchive();
                (new File(path)).delete();
            }
            return path;
        }
public static Builder fromURL(URL url) {
        try {
            InputStream in = null;
            try {
                in = url.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read = -1;
                byte[] buf = new byte[4096];
                while ((read = in.read(buf)) >= 0) {
                    if (read > 0) {
                        baos.write(buf, 0, read);
                    }
                }
                StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray());
                try {
                    b.setSystemId(url.toURI().toString());
                } catch (URISyntaxException use) {
                    b.setSystemId(url.toString());
                }
                return b;
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } catch (IOException ex) {
            throw new XMLUnitException(ex);
        }
    }