semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void copyFile(File in, File out) {
        if (!in.exists() || !in.canRead()) {
            LOGGER.warn("Can't copy file : " + in);
            return;
        }
        if (!out.getParentFile().exists()) {
            if (!out.getParentFile().mkdirs()) {
                LOGGER.info("Didn't create parent directories : " + out.getParentFile().getAbsolutePath());
            }
        }
        if (!out.exists()) {
            try {
                out.createNewFile();
            } catch (IOException e) {
                LOGGER.error("Exception creating new file : " + out.getAbsolutePath(), e);
            }
        }
        LOGGER.debug("Copying file : " + in + ", to : " + out);
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(in);
            inChannel = fileInputStream.getChannel();
            fileOutputStream = new FileOutputStream(out);
            outChannel = fileOutputStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (Exception e) {
            LOGGER.error("Exception copying file : " + in + ", to : " + out, e);
        } finally {
            close(fileInputStream);
            close(fileOutputStream);
            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (Exception e) {
                    LOGGER.error("Exception closing input channel : ", e);
                }
            }
            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (Exception e) {
                    LOGGER.error("Exception closing output channel : ", e);
                }
            }
        }
    }
public static SlimModCollection parseSlimModification(URL url) {
        try {
            Scanner scanner = new Scanner(url.openStream());
            return parseSlimModification(scanner);
        } catch (IOException e) {
            throw new IllegalStateException("Error reading slim file: " + e.getMessage(), e);
        }
    }
public Reader getReader() throws Exception {
        if (url_base == null) {
            return new FileReader(file);
        } else {
            URL url = new URL(url_base + file.getName());
            return new InputStreamReader(url.openConnection().getInputStream());
        }
    }
@SuppressWarnings("unchecked")
    @Override
    public synchronized void drop(DropTargetDropEvent arg0) {
        Helper.log().debug("Dropped");
        Transferable t = arg0.getTransferable();
        try {
            arg0.acceptDrop(arg0.getDropAction());
            List<File> filelist = (List<File>) t.getTransferData(t.getTransferDataFlavors()[0]);
            for (File file : filelist) {
                Helper.log().debug(file.getAbsolutePath());
                if (file.getName().toLowerCase().contains(".lnk")) {
                    Helper.log().debug(file.getName() + " is a link");
                    File target = new File(rp.getRoot().getFullPath() + "/" + file.getName());
                    Helper.log().debug("I have opened the mayor at " + target.getAbsolutePath());
                    FileOutputStream fo = new FileOutputStream(target);
                    FileInputStream fi = new FileInputStream(file);
                    int i = 0;
                    while (fi.available() > 0) {
                        fo.write(fi.read());
                        System.out.print(".");
                        i++;
                    }
                    Helper.log().debug(i + " bytes have been written to " + target.getAbsolutePath());
                    fo.close();
                    fi.close();
                }
            }
            rp.redraw();
        } catch (Throwable tr) {
            tr.printStackTrace();
        }
        Helper.log().debug(arg0.getSource().toString());
    }
static HttpURLConnection connect(String url, String method, String contentType, String content, int timeoutMillis) throws ProtocolException, IOException, MalformedURLException, UnsupportedEncodingException {
        HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());
        conn.setRequestMethod(method);
        conn.setConnectTimeout(timeoutMillis);
        byte[] bContent = null;
        if (content != null && content.length() > 0) {
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", contentType);
            bContent = content.getBytes("UTF-8");
            conn.setFixedLengthStreamingMode(bContent.length);
        }
        conn.connect();
        if (bContent != null) {
            OutputStream os = conn.getOutputStream();
            os.write(bContent);
            os.flush();
            os.close();
        }
        return conn;
    }
public ProgramMessageSymbol addProgramMessageSymbol(int programID, String name, byte[] bytecode) throws AdaptationException {
        ProgramMessageSymbol programMessageSymbol = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Statement statement = null;
        ResultSet resultSet = null;
        InputStream stream = new ByteArrayInputStream(bytecode);
        try {
            String query = "INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES ( ?, ?, ? )";
            connection = DriverManager.getConnection(CONN_STR);
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setInt(1, programID);
            preparedStatement.setString(2, name);
            preparedStatement.setBinaryStream(3, stream, bytecode.length);
            log.info("INSERT INTO ProgramMessageSymbols(programID, name, " + "bytecode) VALUES (" + programID + ", '" + name + "', " + "<bytecode>)");
            preparedStatement.executeUpdate();
            statement = connection.createStatement();
            query = "SELECT * FROM ProgramMessageSymbols WHERE " + "programID =  " + programID + " AND " + "name      = '" + name + "'";
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Attempt to add program message symbol failed.";
                log.error(msg);
                ;
                throw new AdaptationException(msg);
            }
            programMessageSymbol = getProgramMessageSymbol(resultSet);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in addProgramMessageSymbol";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                preparedStatement.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return programMessageSymbol;
    }
public ProgramMessageSymbol deleteProgramMessageSymbol(int id) throws AdaptationException {
        ProgramMessageSymbol pmt = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "SELECT * FROM ProgramMessageSymbols " + "WHERE id = " + id;
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                String msg = "Attempt to delete program message type " + "failed.";
                log.error(msg);
                ;
                throw new AdaptationException(msg);
            }
            pmt = getProgramMessageSymbol(resultSet);
            query = "DELETE FROM ProgramMessageSymbols " + "WHERE id = " + id;
            statement.executeUpdate(query);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in deleteProgramMessageSymbol";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return pmt;
    }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Git git = Git.getCurrent(req.getSession());
        GitComponentReader gitReader = git.getComponentReader("warpinjector");
        String id = req.getParameter("id");
        GitElement element = gitReader.getElement(id);
        String path = (String) element.getAttribute("targetdir");
        File folder = new File(path);
        PrintWriter out = helper.getPrintWriter(resp);
        MessageBundle messageBundle = new MessageBundle("net.sf.warpcore.cms/servlets/InjectorServletMessages");
        Locale locale = req.getLocale();
        helper.header(out, messageBundle, locale);
        if (git.getUser() == null) {
            helper.notLoggedIn(out, messageBundle, locale);
        } else {
            try {
                MultiPartRequest request = new MultiPartRequest(req);
                FileInfo info = request.getFileInfo("userfile");
                File file = info.getFile();
                out.println("tempfile found: " + file.getPath() + "<br>");
                String fileName = info.getFileName();
                File target = new File(folder, fileName);
                out.println("copying tempfile to: " + target.getPath() + "<br>");
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(target);
                byte buf[] = new byte[1024];
                int n;
                while ((n = fis.read(buf)) > 0) fos.write(buf, 0, n);
                fis.close();
                fos.close();
                out.println("copy successful - deleting old tempfile<br>");
                out.println("deletion result. " + file.delete() + "<p>");
                out.println(messageBundle.getMessage("Done. The file {0} has been uploaded", new String[] { "'" + fileName + "'" }, locale));
                out.println("<p><a href=\"" + req.getRequestURI() + "?id=" + req.getParameter("id") + "\">" + messageBundle.getMessage("Click here to import another file.", locale) + "</a>");
            } catch (Exception ex) {
                out.println(messageBundle.getMessage("An error occured: {0}", new String[] { ex.getMessage() }, locale));
            }
        }
        helper.footer(out);
    }
public static void copyFile(File source, File target) {
        try {
            target.getParentFile().mkdirs();
            byte[] buffer = new byte[4096];
            int len = 0;
            FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target);
            while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len);
            in.close();
            out.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) {
        boolean result = true;
        try {
            notifyCopyStart(destinationFile);
            destinationFile.getParentFile().mkdirs();
            byte[] buffer = new byte[4096];
            int len = 0;
            FileInputStream in = new FileInputStream(sourceFile);
            FileOutputStream out = new FileOutputStream(destinationFile);
            while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len);
            in.close();
            out.close();
        } catch (Exception e) {
            result = false;
            handleException("\n Error in method: copy!\n", e, errorLog);
        } finally {
            notifyCopyEnd(destinationFile);
        }
        return result;
    }
private void calculateCoverageAndSpecificity(String mainCat) throws IOException, JSONException {
        for (String cat : Rules.categoryTree.get(mainCat)) {
            for (String queryString : Rules.queries.get(cat)) {
                String urlEncodedQueryString = URLEncoder.encode(queryString, "UTF-8");
                URL url = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + urlEncodedQueryString + "?appid=" + yahoo_ap_id + "&count=4&format=json&sites=" + site);
                URLConnection con = url.openConnection();
                String line;
                StringBuilder builder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                String response = builder.toString();
                JSONObject json = new JSONObject(response);
                JSONObject jsonObject = json.getJSONObject("ysearchresponse");
                String totalhits = jsonObject.getString("totalhits");
                long totalhitsLong = Long.parseLong(totalhits);
                QueryInfo qinfo = new QueryInfo(queryString, totalhitsLong);
                queryInfoMap.put(queryString, qinfo);
                cov.put(cat, cov.get(cat) + totalhitsLong);
                if (totalhitsLong == 0) {
                    continue;
                }
                ja = jsonObject.getJSONArray("resultset_web");
                for (int j = 0; j < ja.length(); j++) {
                    JSONObject k = ja.getJSONObject(j);
                    String dispurl = filterBold(k.getString("url"));
                    qinfo.addUrl(dispurl);
                }
            }
        }
        calculateSpecificity(mainCat);
    }
public String useService(HashMap<String, String> input) {
        String output = "";
        if (input.size() < 1) {
            return "";
        }
        String data = "";
        try {
            for (String key : input.keySet()) {
                data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(input.get(key), "UTF-8");
            }
            data = data.substring(1);
            URL url = new URL(serviceUrl);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                output += line;
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return output;
    }
@Override
        public long getLastModified(final Resource arg0) {
            try {
                final ServletContext context = CContext.getInstance().getContext();
                final URL url = context.getResource(arg0.getName());
                final URLConnection conn = url.openConnection();
                final long lm = conn.getLastModified();
                try {
                    conn.getInputStream().close();
                } catch (final Exception ignore) {
                    ;
                }
                return lm;
            } catch (final Exception e) {
                return 0;
            }
        }
@Override
        public InputStream getResourceStream(final String arg0) throws ResourceNotFoundException {
            try {
                final ServletContext context = CContext.getInstance().getContext();
                final URL url = context.getResource(arg0);
                return url.openStream();
            } catch (final Exception e) {
                return null;
            }
        }
protected ResourceManager(URL url, String s) {
        try {
            properties.load(url.openStream());
            path = s;
        } catch (Exception e) {
            throw new Error(e.getMessage() + ": trying to load url \"" + url + "\"", e);
        }
    }
@Override
    public void onClick(View view) {
        String ftpHostname = getFtpHostname();
        String ftpUsername = getFtpUsername();
        String ftpPassword = getFtpPassword();
        int ftpPort = getFtpPort();
        String dialogText = getString(R.string.testingFTPConnectionDialogHeaderText) + " " + ftpHostname;
        ProgressDialog dialog = ProgressDialog.show(this, "", dialogText, true);
        String result = "NOTHING??";
        Log.i(TAG, "Test attempt login to " + ftpHostname + " as " + ftpUsername);
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ftpHostname, ftpPort);
            ftpClient.login(ftpUsername, ftpPassword);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                result = getString(R.string.testFTPConnectionDeniedString);
                Log.w(TAG, result);
            } else {
                result = getString(R.string.testFTPSuccessString);
                Log.i(TAG, result);
            }
        } catch (Exception ex) {
            result = getString(R.string.testFTPFailString) + ex;
            Log.w(TAG, result);
        } finally {
            try {
                dialog.dismiss();
                ftpClient.disconnect();
            } catch (Exception e) {
            }
        }
        Context context = getApplicationContext();
        CharSequence text = result;
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
public void test_UseCache_HttpURLConnection_NoCached_GetOutputStream() throws Exception {
        ResponseCache.setDefault(new MockNonCachedResponseCache());
        uc = (HttpURLConnection) url.openConnection();
        uc.setChunkedStreamingMode(10);
        uc.setDoOutput(true);
        uc.getOutputStream();
        assertTrue(isGetCalled);
        assertFalse(isPutCalled);
        assertFalse(isAbortCalled);
        uc.disconnect();
    }
private BibtexDatabase importSpiresEntries(String key, OutputPrinter frame) {
        String url = constructUrl(key);
        try {
            HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
            conn.setRequestProperty("User-Agent", "Jabref");
            InputStream inputStream = conn.getInputStream();
            SPIRESBibtexFilterReader reader = new SPIRESBibtexFilterReader(new InputStreamReader(inputStream));
            ParserResult pr = BibtexParser.parse(reader);
            return pr.getDatabase();
        } catch (IOException e) {
            frame.showMessage(Globals.lang("An Exception ocurred while accessing '%0'", url) + "\n\n" + e.toString(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            frame.showMessage(Globals.lang("An Error occurred while fetching from SPIRES source (%0):", new String[] { url }) + "\n\n" + e.getMessage(), Globals.lang(getKeyName()), JOptionPane.ERROR_MESSAGE);
        }
        return null;
    }
@Override
    public InputStream getInputStream() {
        if (assetPath != null) {
            return buildInputStream();
        } else {
            try {
                return url.openStream();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
@Test
    public void testDocumentDownloadExcel() throws IOException {
        if (uploadedExcelDocumentID == null) {
            fail("Document Upload Test should run first");
        }
        String downloadLink = GoogleDownloadLinkGenerator.generateXlDownloadLink(uploadedExcelDocumentID);
        URL url = new URL(downloadLink);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        InputStream input = url.openStream();
        FileWriter fw = new FileWriter("tmpOutput.kb");
        Reader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String strLine = "";
        int count = 0;
        while (count < 10000) {
            strLine = bufferedReader.readLine();
            if (strLine != null && strLine != "") {
                fw.write(strLine);
            }
            count++;
        }
    }
@Test
    public void testDocumentDownloadKnowledgeBase() throws IOException {
        if (uploadedKbDocumentID == null) {
            fail("Document Upload Test should run first");
        }
        String downloadLink = GoogleDownloadLinkGenerator.generateTextDownloadLink(uploadedKbDocumentID);
        URL url = new URL(downloadLink);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();
        InputStream input = url.openStream();
        FileWriter fw = new FileWriter("tmpOutput.kb");
        Reader reader = new InputStreamReader(input);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String strLine = "";
        int count = 0;
        while (count < 10000) {
            strLine = bufferedReader.readLine();
            if (strLine != null && strLine != "") {
                fw.write(strLine);
            }
            count++;
        }
    }
public boolean crear() {
        int result = 0;
        String sql = "insert into ronda" + "(divisionxTorneo_idDivisionxTorneo, fechaRonda, nRonda, estado ) " + "values (?, ?, ?, ?)";
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement(unaRonda);
            result = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (result > 0);
    }
public boolean actEstadoEnBD(int idRonda) {
        int intResult = 0;
        String sql = "UPDATE ronda " + " SET estado = 1" + " WHERE numeroRonda = " + idRonda;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }