semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception {
        String inputFileName = sourceRoot + extension;
        String outputFileName = targetRoot + extension;
        System.out.println("Copying resource file: " + outputFileName);
        File inputFile = new File(inputFileName);
        if (!inputFile.exists() || !inputFile.canRead()) {
            throw new Exception("Could not read from the file " + inputFileName);
        }
        File outputFile = new File(outputFileName);
        if (!outputFile.exists()) {
            if (!outputFile.createNewFile() || !outputFile.canWrite()) throw new Exception("Could not write to the file " + outputFileName);
        }
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        try {
            char[] buffer = new char[1024];
            int nread = 0;
            while ((nread = in.read(buffer)) != -1) {
                out.write(buffer, 0, nread);
            }
        } finally {
            in.close();
            out.close();
        }
    }
private void doDissemTest(String what, boolean redirectOK) throws Exception {
        final int num = 30;
        System.out.println("Getting " + what + " " + num + " times...");
        int i = 0;
        try {
            URL url = new URL(BASE_URL + "/get/" + what);
            for (i = 0; i < num; i++) {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream in = conn.getInputStream();
                in.read();
                in.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage());
        }
    }
public String hash(String password) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException ex) {
            log.info("No sha-256 available");
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                log.fatal("sha-1 is not available", e);
                throw new RuntimeException("Couldn't get a hash algorithm from Java");
            }
        }
        try {
            digest.reset();
            digest.update((salt + password).getBytes("UTF-8"));
            byte hash[] = digest.digest();
            return new String(Base64.encodeBase64(hash, false));
        } catch (Throwable t) {
            throw new RuntimeException("Couldn't hash password");
        }
    }
public String getHttpText() {
        URL url = null;
        try {
            url = new URL(getUrl());
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        }
        StringBuffer sb = new StringBuffer();
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(getRequestMethod());
            conn.setDoOutput(true);
            if (getRequestProperty() != null && "".equals(getRequestProperty())) {
                conn.setRequestProperty("Accept", getRequestProperty());
            }
            PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), getCharset()));
            out.println(getParam());
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), getCharset()));
            String inputLine;
            int i = 1;
            while ((inputLine = in.readLine()) != null) {
                if (getStartLine() == 0 && getEndLine() == 0) {
                    sb.append(inputLine).append("\n");
                } else {
                    if (getEndLine() > 0) {
                        if (i >= getStartLine() && i <= getEndLine()) {
                            sb.append(inputLine).append("\n");
                        }
                    } else {
                        if (i >= getStartLine()) {
                            sb.append(inputLine).append("\n");
                        }
                    }
                }
                i++;
            }
            in.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return sb.toString();
    }
public void getFile(String srcFile, String destFile) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection conn = null;
        URL url = null;
        byte[] buf = new byte[8096];
        int size = 0;
        try {
            url = new URL(srcFile);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            bis = new BufferedInputStream(conn.getInputStream());
            fos = new FileOutputStream(destFile);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.close();
            bis.close();
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            conn.disconnect();
        }
    }
public static void parseSinaGGTJ(ArrayList<String> dataSource, final ArrayList<SinaGGTJBean> sinaGGTJBeanList) throws IOReactorException, InterruptedException {
        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        if (dataSource != null && dataSource.size() > 0) {
            final CountDownLatch latch = new CountDownLatch(dataSource.size());
            for (int i = 0; i < dataSource.size(); i++) {
                final HttpGet request = new HttpGet(dataSource.get(i));
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine());
                        try {
                            HttpEntity he = response.getEntity();
                            try {
                                String resp = EntityUtils.toString(he, "gb2312");
                                if (resp != null && resp.length() > 0) {
                                    SinaGGTJBean ggtjBean = SinaGGTJPostProcess.postSinaGGTJBeanProcess(resp);
                                    sinaGGTJBeanList.add(ggtjBean);
                                }
                                count++;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            latch.countDown();
                        } catch (RuntimeException re) {
                            latch.countDown();
                        }
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                    }

                    public void cancelled() {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            System.out.println("done");
        }
        if (httpclient != null) {
            httpclient.shutdown();
        }
        System.out.println(sinaGGTJBeanList.size());
    }
public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException {
        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        if (dataSource != null && dataSource.size() > 0) {
            final CountDownLatch latch = new CountDownLatch(dataSource.size());
            for (int i = 0; i < dataSource.size(); i++) {
                final HttpGet request = new HttpGet(dataSource.get(i));
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine());
                        try {
                            HttpEntity he = response.getEntity();
                            try {
                                String resp = EntityUtils.toString(he, "gb2312");
                                if (resp != null && resp.length() > 0) {
                                    SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp);
                                    sohuStockBeanList.add(shstBean);
                                }
                                count++;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            latch.countDown();
                        } catch (RuntimeException re) {
                            latch.countDown();
                        }
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                    }

                    public void cancelled() {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            System.out.println("done");
        }
        if (httpclient != null) {
            httpclient.shutdown();
        }
        System.out.println(sohuStockBeanList.size());
    }
public static String getPasswordHash(String password) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        md.update(password.getBytes());
        byte[] digest = md.digest();
        BigInteger i = new BigInteger(1, digest);
        String hash = i.toString(16);
        while (hash.length() < 32) {
            hash = "0" + hash;
        }
        return hash;
    }
private void internalTransferComplete(File tmpfile) {
        System.out.println("transferComplete : " + tmpfile);
        try {
            File old = new File(m_destination.toString() + ".old");
            old.delete();
            File current = m_destination;
            current.renameTo(old);
            FileInputStream fis = new FileInputStream(tmpfile);
            FileOutputStream fos = new FileOutputStream(m_destination);
            BufferedInputStream in = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            for (int read = in.read(); read != -1; read = in.read()) {
                out.write(read);
            }
            out.flush();
            in.close();
            out.close();
            fis.close();
            fos.close();
            tmpfile.delete();
            setVisible(false);
            transferComplete();
        } catch (Exception exc) {
            exc.printStackTrace();
            JOptionPane.showMessageDialog(this, "An error occurred while downloading!", "ACLocator Error", JOptionPane.ERROR_MESSAGE);
        }
    }
public void init() {
        this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS);
        try {
            if (memeId < 0) {
            } else {
                conurl = new URL(ServerURL + "?meme_id=" + memeId);
                java.io.InputStream xmlstr = conurl.openStream();
                this.removeAllWorkSheets();
                this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT);
                this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE);
                this.setDupeStringMode(WorkBookHandle.SHAREDUPES);
                ExtenXLS.parseNBind(this, xmlstr);
                this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS);
            }
        } catch (Exception ex) {
            throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR);
        }
    }
private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) {
        Statement stmt = query.getStatement();
        String fileDeclaration = stmt.getFile();
        boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration);
        if (hasFileDeclaration) {
            try {
                URL url = sqlDeclarations.get(stmt.getFile());
                if (url != null) {
                    URLConnection conn = url.openConnection();
                    InputStream input = conn.getInputStream();
                    String sqlDeclaration = StreamUtils.obtainStreamContents(input);
                    stmt.setValue(sqlDeclaration);
                    input.close();
                }
            } catch (Exception e) {
            }
        }
    }
public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        HashMap services = configContext.getAxisConfiguration().getServices();
        String filePart = req.getRequestURL().toString();
        String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length());
        if ((services != null) && !services.isEmpty()) {
            Iterator i = services.values().iterator();
            while (i.hasNext()) {
                AxisService service = (AxisService) i.next();
                InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema);
                if (stream != null) {
                    OutputStream out = res.getOutputStream();
                    res.setContentType("text/xml");
                    IOUtils.copy(stream, out, true);
                    return;
                }
            }
        }
    }
private void copia(FileInputStream input, FileOutputStream output) throws ErrorException {
        if (input == null || output == null) {
            throw new ErrorException("Param null");
        }
        FileChannel inChannel = input.getChannel();
        FileChannel outChannel = output.getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inChannel.close();
            outChannel.close();
        } catch (IOException e) {
            throw new ErrorException("Casino nella copia del file");
        }
    }
public boolean backupFile(File oldFile, File newFile) {
        boolean isBkupFileOK = false;
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        try {
            sourceChannel = new FileInputStream(oldFile).getChannel();
            targetChannel = new FileOutputStream(newFile).getChannel();
            targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (IOException e) {
            logger.log(Level.SEVERE, "IO exception occurred while copying config file", e);
        } finally {
            if ((newFile != null) && (newFile.exists()) && (newFile.length() > 0)) {
                isBkupFileOK = true;
            }
            try {
                if (sourceChannel != null) {
                    sourceChannel.close();
                }
                if (targetChannel != null) {
                    targetChannel.close();
                }
            } catch (IOException e) {
                logger.log(Level.INFO, "closing channels failed");
            }
        }
        return isBkupFileOK;
    }
public Long addRole(AuthSession authSession, RoleBean roleBean) {
        PreparedStatement ps = null;
        DatabaseAdapter dbDyn = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            CustomSequenceType seq = new CustomSequenceType();
            seq.setSequenceName("seq_WM_AUTH_ACCESS_GROUP");
            seq.setTableName("WM_AUTH_ACCESS_GROUP");
            seq.setColumnName("ID_ACCESS_GROUP");
            Long sequenceValue = dbDyn.getSequenceNextValue(seq);
            ps = dbDyn.prepareStatement("insert into WM_AUTH_ACCESS_GROUP " + "( ID_ACCESS_GROUP, NAME_ACCESS_GROUP ) values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : ""));
            RsetTools.setLong(ps, 1, sequenceValue);
            ps.setString(2, roleBean.getName());
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1);
            dbDyn.commit();
            return sequenceValue;
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error add new role";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }
public void updateRole(AuthSession authSession, RoleBean roleBean) {
        DatabaseAdapter dbDyn = null;
        PreparedStatement ps = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            String sql = "update WM_AUTH_ACCESS_GROUP " + "set    NAME_ACCESS_GROUP=? " + "WHERE  ID_ACCESS_GROUP=? ";
            ps = dbDyn.prepareStatement(sql);
            ps.setString(1, roleBean.getName());
            ps.setLong(2, roleBean.getRoleId());
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1);
            dbDyn.commit();
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error save role";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }
public void deleteRole(AuthSession authSession, RoleBean roleBean) {
        DatabaseAdapter dbDyn = null;
        PreparedStatement ps = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            if (roleBean.getRoleId() == null) throw new IllegalArgumentException("role id is null");
            String sql = "delete from WM_AUTH_ACCESS_GROUP where ID_ACCESS_GROUP=? ";
            ps = dbDyn.prepareStatement(sql);
            RsetTools.setLong(ps, 1, roleBean.getRoleId());
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1);
            dbDyn.commit();
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error delete role";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }
public void updateUserInfo(AuthSession authSession, AuthUserExtendedInfo infoAuth) {
        log.info("Start update auth");
        PreparedStatement ps = null;
        DatabaseAdapter db = null;
        try {
            db = DatabaseAdapter.getInstance();
            String sql = "update WM_AUTH_USER " + "set " + "ID_FIRM=?, IS_USE_CURRENT_FIRM=?, " + "ID_HOLDING=?, IS_HOLDING=? " + "WHERE  ID_AUTH_USER=? ";
            ps = db.prepareStatement(sql);
            if (infoAuth.getAuthInfo().getCompanyId() == null) {
                ps.setNull(1, Types.INTEGER);
                ps.setInt(2, 0);
            } else {
                ps.setLong(1, infoAuth.getAuthInfo().getCompanyId());
                ps.setInt(2, infoAuth.getAuthInfo().isCompany() ? 1 : 0);
            }
            if (infoAuth.getAuthInfo().getHoldingId() == null) {
                ps.setNull(3, Types.INTEGER);
                ps.setInt(4, 0);
            } else {
                ps.setLong(3, infoAuth.getAuthInfo().getHoldingId());
                ps.setInt(4, infoAuth.getAuthInfo().isHolding() ? 1 : 0);
            }
            ps.setLong(5, infoAuth.getAuthInfo().getAuthUserId());
            ps.executeUpdate();
            processDeletedRoles(db, infoAuth);
            processNewRoles(db, infoAuth.getRoles(), infoAuth.getAuthInfo().getAuthUserId());
            db.commit();
        } catch (Throwable e) {
            try {
                if (db != null) db.rollback();
            } catch (Exception e001) {
            }
            final String es = "Error add user auth";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(db, ps);
            ps = null;
            db = null;
            log.info("End update auth");
        }
    }
private static AndsDoiResponse doiRequest(String serviceUrl, String metaDataXML, String requestType) throws IOException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Method URL: " + serviceUrl);
            LOG.debug("Metadata XML NULL ?: " + StringUtils.isEmpty(metaDataXML));
            LOG.debug("Request Type: " + requestType);
        }
        AndsDoiResponse doiResponse = null;
        OutputStreamWriter wr = null;
        BufferedReader rd = null;
        StringBuffer outputBuffer;
        URL url = new URL(serviceUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        try {
            conn.setDoInput(true);
            if (requestType.equals("POST")) {
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                if (metaDataXML != null) {
                    wr.write("xml=" + URLEncoder.encode(metaDataXML, "UTF-8"));
                }
                wr.flush();
            } else {
                conn.setDoOutput(false);
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug(conn.getResponseCode() + " - " + conn.getResponseMessage());
            }
            outputBuffer = new StringBuffer();
            outputBuffer.append(conn.getResponseMessage() + "\n");
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                outputBuffer.append(line);
            }
            doiResponse = new AndsDoiResponse();
            doiResponse.setMessage(outputBuffer.toString());
            setResponseFlag(conn.getResponseCode(), doiResponse);
        } catch (Exception e) {
            doiResponse = new AndsDoiResponse();
            outputBuffer = new StringBuffer();
            outputBuffer.append(conn.getResponseMessage() + "\n");
            BufferedReader rde = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            while ((line = rde.readLine()) != null) {
                outputBuffer.append(line);
            }
            doiResponse.setSuccess(false);
            doiResponse.setMessage(outputBuffer.toString());
            rde.close();
        } finally {
            if (wr != null) {
                wr.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
        return doiResponse;
    }
public void writeFile(OutputStream outputStream) throws IOException {
            InputStream inputStream = null;
            if (file != null) {
                try {
                    inputStream = new FileInputStream(file);
                    IOUtils.copy(inputStream, outputStream);
                } finally {
                    if (inputStream != null) {
                        IOUtils.closeQuietly(inputStream);
                    }
                }
            }
        }