semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException {
        int chunkLength;
        OutputStream os = null;
        try {
            if (!urlIsFile) {
                URL urlObj = new URL(filePath);
                URLConnection uc = urlObj.openConnection();
                os = uc.getOutputStream();
                if (charCoding == null) {
                    String type = uc.getContentType();
                    if (type != null) {
                        charCoding = getCharCodingFromType(type);
                    }
                }
            } else {
                File f = new File(filePath);
                os = new FileOutputStream(f);
            }
            Writer w;
            if (charCoding == null) {
                w = new OutputStreamWriter(os);
            } else {
                w = new OutputStreamWriter(os, charCoding);
            }
            w.write(data);
            w.flush();
        } finally {
            if (os != null) os.close();
        }
    }
public static void loadPackage1(String ycCode) {
        InputStream input = null;
        try {
            TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() };
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
            uc.setHostnameVerifier(new FakeHostnameVerifier());
            uc.setConnectTimeout(CONNECTION_TIMEOUT);
            uc.setReadTimeout(CONNECTION_TIMEOUT);
            input = uc.getInputStream();
            StringBuilder sb = new StringBuilder();
            int c;
            while ((c = input.read()) != -1) {
                sb.append((char) c);
            }
            Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString());
            String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml";
            YouthClub.getMiniModel().getXMLParser().writeXML(doc, target);
            Debug.log("YC XML saved to " + target);
        } catch (Exception e) {
            Debug.logException(e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }
public static String getMD5(String in) {
        if (in == null) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(in.getBytes());
            byte[] hash = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xFF & hash[i]);
                if (hex.length() == 1) {
                    hex = "0" + hex;
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            Debug.logException(e);
        }
        return null;
    }
private void saveURL(URL url, String filename) throws IOException {
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStreamReader ReadIn = new InputStreamReader(connection.getInputStream());
        BufferedReader BufData = new BufferedReader(ReadIn);
        FileWriter FWriter = new FileWriter(filename);
        BufferedWriter BWriter = new BufferedWriter(FWriter);
        String urlData = null;
        while ((urlData = BufData.readLine()) != null) {
            BWriter.write(urlData);
            BWriter.newLine();
        }
        BWriter.close();
    }
public synchronized void run() {
        logger.info("SEARCH STARTED");
        JSONObject json = null;
        logger.info("Opening urlConnection");
        URLConnection connection = null;
        try {
            connection = url.openConnection();
            connection.addRequestProperty("Referer", HTTP_REFERER);
        } catch (IOException e) {
            logger.warn("PROBLEM CONTACTING GOOGLE");
            e.printStackTrace();
        }
        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE");
            e.printStackTrace();
        }
        logger.info("Google RET: " + builder.toString());
        try {
            json = new JSONObject(builder.toString());
            json.append("query", q);
        } catch (JSONException e) {
            logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE");
            e.printStackTrace();
        }
        sc.onSearchFinished(json);
    }
private String doMessageDigestAndBase64Encoding(String sequence) throws SeguidException {
        if (sequence == null) {
            throw new NullPointerException("You must give a non null sequence");
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            sequence = sequence.trim().toUpperCase();
            messageDigest.update(sequence.getBytes());
            byte[] digest = messageDigest.digest();
            String seguid = Base64.encodeBytes(digest);
            seguid = seguid.replace("=", "");
            if (log.isTraceEnabled()) {
                log.trace("SEGUID " + seguid);
            }
            return seguid;
        } catch (NoSuchAlgorithmException e) {
            throw new SeguidException("Exception thrown when calculating Seguid for " + sequence, e.getCause());
        }
    }
public static void copyFile(String inputFile, String outputFile) throws IOException {
        FileInputStream fis = new FileInputStream(inputFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b);
        fos.close();
        fis.close();
    }
public Atividade insertAtividade(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")";
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            if (result == 1) {
                String sqlSelect = "select last_value from seq_atividade";
                ResultSet rs = stmt.executeQuery(sqlSelect);
                while (rs.next()) {
                    atividade.setIdAtividade(rs.getInt("last_value"));
                }
            }
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
        return null;
    }
public void candidatarAtividade(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "insert into Atividade_has_recurso_humano " + "(atividade_idatividade, usuario_idusuario, ativo) " + "values " + "(" + atividade.getIdAtividade() + ", " + "" + atividade.getRecursoHumano().getIdUsuario() + ", " + "'false')";
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }
public void desistirCandidatura(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "delete from Atividade_has_recurso_humano where atividade_idatividade=" + atividade.getIdAtividade() + " and usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario();
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }
public void aprovarCandidato(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario();
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }
public void testResponseTimeout() throws Exception {
        server.enqueue(new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4"));
        server.enqueue(new MockResponse().setBody("DEF"));
        server.play();
        URLConnection urlConnection = server.getUrl("/").openConnection();
        urlConnection.setReadTimeout(1000);
        InputStream in = urlConnection.getInputStream();
        assertEquals('A', in.read());
        assertEquals('B', in.read());
        assertEquals('C', in.read());
        try {
            in.read();
            fail();
        } catch (SocketTimeoutException expected) {
        }
        URLConnection urlConnection2 = server.getUrl("/").openConnection();
        InputStream in2 = urlConnection2.getInputStream();
        assertEquals('D', in2.read());
        assertEquals('E', in2.read());
        assertEquals('F', in2.read());
        assertEquals(-1, in2.read());
        assertEquals(0, server.takeRequest().getSequenceNumber());
        assertEquals(0, server.takeRequest().getSequenceNumber());
    }
public static String getMyGlobalIP() {
        try {
            URL url = new URL(IPSERVER);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String ip = in.readLine();
            in.close();
            con.disconnect();
            return ip;
        } catch (Exception e) {
            return null;
        }
    }
protected String loadPage(String url_string) {
        try {
            URL url = new URL(url_string);
            HttpURLConnection connection = null;
            InputStream is = null;
            try {
                connection = (HttpURLConnection) url.openConnection();
                int response = connection.getResponseCode();
                if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK) {
                    is = connection.getInputStream();
                    String page = "";
                    while (page.length() < MAX_PAGE_SIZE) {
                        byte[] buffer = new byte[2048];
                        int len = is.read(buffer);
                        if (len < 0) {
                            break;
                        }
                        page += new String(buffer, 0, len);
                    }
                    return (page);
                } else {
                    informFailure("httpinvalidresponse", "" + response);
                    return (null);
                }
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
        } catch (Throwable e) {
            informFailure("httploadfail", e.toString());
            return (null);
        }
    }
public void setImage(String imageUrl) {
        try {
            InputStream url = ProjectManager.getCurrentProject().getUrl(imageUrl).openStream();
            Image im = new Image(getDisplay(), url);
            if (im != null) setImage(im);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
protected void init() {
        if (this.strUrl != null) {
            InputStream in = null;
            try {
                URL url = ClassLoader.getSystemClassLoader().getResource(strUrl);
                if (url != null) {
                    in = url.openStream();
                    if (in != null) {
                        props.load(in);
                    }
                }
            } catch (IOException e) {
                Logger.defaultLogger().error("Error during framework properties loading", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }
public void listgroups() throws Exception {
        String lapage = new String("");
        Pattern pat;
        Matcher mat;
        int data;
        URL myurl = new URL("http://groups.yahoo.com/mygroups");
        URLConnection conn;
        URI myuri = new URI("http://groups.yahoo.com/mygroups");
        YahooInfo yi;
        clearAll();
        System.out.print("http://groups.yahoo.com/mygroups : ");
        do {
            myurl = new URL(myurl.toString());
            conn = myurl.openConnection();
            conn.connect();
            if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
                System.out.println(conn.getHeaderField(0).toString());
                return;
            }
            System.out.print(".");
            InputStream in = conn.getInputStream();
            lapage = "";
            for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
            pat = Pattern.compile("<td class=\"grpname selected\"><a href=\"(.+?)\".*?><em>(.+?)</em></a>");
            mat = pat.matcher(lapage);
            while (mat.find()) {
                yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString());
                UrlList.add(yi);
            }
            pat = Pattern.compile("<a href=\"(.+?)\">Next &gt;</a>");
            mat = pat.matcher(lapage);
            myurl = null;
            if (mat.find()) {
                myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL();
            }
        } while (myurl != null);
        System.out.println("");
    }
public String getpage(String leurl) throws Exception {
        int data;
        StringBuffer lapage = new StringBuffer();
        URL myurl = new URL(leurl);
        URLConnection conn = myurl.openConnection();
        conn.connect();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return lapage.toString();
        }
        InputStream in = conn.getInputStream();
        for (data = in.read(); data != -1; data = in.read()) lapage.append((char) data);
        return lapage.toString();
    }
public static void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        in.close();
        out.close();
    }
public static String getDigest(String seed, String code) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(seed.getBytes("UTF-8"));
            byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        }
    }
public static String getDigest(String seed, byte[] code) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(seed.getBytes("UTF-8"));
            byte[] passwordMD5Byte = md.digest(code);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        }
    }
public static int my_rename(String source, String dest) {
            logger.debug("RENAME " + source + " to " + dest);
            if (source == null || dest == null) return -1;
            {
                logger.debug("\tMoving file across file systems.");
                FileChannel srcChannel = null;
                FileChannel dstChannel = null;
                FileLock lock = null;
                try {
                    srcChannel = new FileInputStream(source).getChannel();
                    dstChannel = new FileOutputStream(dest).getChannel();
                    lock = dstChannel.lock();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    dstChannel.force(true);
                } catch (IOException e) {
                    logger.fatal("Error while copying file '" + source + "' to file '" + dest + "'. " + e.getMessage(), e);
                    return common_h.ERROR;
                } finally {
                    try {
                        lock.release();
                    } catch (Throwable t) {
                        logger.fatal("Error releasing file lock - " + dest);
                    }
                    try {
                        srcChannel.close();
                    } catch (Throwable t) {
                    }
                    try {
                        dstChannel.close();
                    } catch (Throwable t) {
                    }
                }
            }
            return common_h.OK;
        }
public UserFunction loadMFileViaWeb(URL codeBase, String directoryAndFile, String mFileName) {
        String code = "";
        UserFunction function = null;
        ErrorLogger.debugLine("MFileLoader: loading >" + mFileName + ".m<");
        try {
            URL url = new URL(codeBase, directoryAndFile);
            InputStream in = url.openStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = inReader.readLine()) != null) {
                code += line + "\n";
            }
            inReader.close();
        } catch (Exception e) {
            Errors.throwMathLibException("MFileLoader: m-file exception via web");
        }
        ErrorLogger.debugLine("MFileLoader: code: begin \n" + code + "\ncode end");
        FunctionParser funcParser = new FunctionParser();
        function = funcParser.parseFunction(code);
        function.setName(mFileName);
        ErrorLogger.debugLine("MFileLoader: finished webloading >" + mFileName + ".m<");
        return function;
    }
public void sendFile(File file, String filename, String contentType) throws SearchLibException {
        response.setContentType(contentType);
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new SearchLibException(e);
        } catch (IOException e) {
            throw new SearchLibException(e);
        } finally {
            if (inputStream != null) IOUtils.closeQuietly(inputStream);
        }
    }
public static String getMD5Str(String source) {
        String s = null;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
public static byte[] getMD5(String source) {
        byte[] tmp = null;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            tmp = md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmp;
    }
private void initStreams() throws IOException {
        if (audio != null) {
            audio.close();
        }
        if (url != null) {
            audio = new OggInputStream(url.openStream());
        } else {
            audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref));
        }
    }
public static List<String> retrieveLanguages() throws Exception {
        List<String> result = new ArrayList<String>();
        URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site");
        String str = StreamUtil.toString(url.openStream());
        Pattern pattern = Pattern.compile(".*language=([^;\"]+).*");
        Matcher m = pattern.matcher(str);
        while (m.find()) {
            String lang = m.group(1);
            if (!result.contains(lang)) {
                result.add(lang);
            }
        }
        return result;
    }
public static JsonNode getJSONFromURL(String httpUrl) throws Exception {
        URL url;
        InputStream inputStream = null;
        DataInputStream dataInputStream;
        try {
            url = new URL(httpUrl);
            inputStream = url.openStream();
            dataInputStream = new DataInputStream(new BufferedInputStream(inputStream));
            return JsonUtil.getNode(dataInputStream);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ioe) {
            }
        }
    }