semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void run() {
        try {
            Socket socket = getSocket();
            System.out.println("opening socket to " + address + " on " + port);
            InputStream in = socket.getInputStream();
            for (; ; ) {
                FileTransferHeader header = FileTransferHeader.readHeader(in);
                if (header == null) break;
                System.out.println("header: " + header);
                List<String> parts = header.getFilename().getSegments();
                String filename;
                if (parts.size() > 0) filename = "dl-" + parts.get(parts.size() - 1); else filename = "dl-" + session.getScreenname();
                System.out.println("writing to file " + filename);
                long sum = 0;
                if (new File(filename).exists()) {
                    FileInputStream fis = new FileInputStream(filename);
                    byte[] block = new byte[10];
                    for (int i = 0; i < block.length; ) {
                        int count = fis.read(block);
                        if (count == -1) break;
                        i += count;
                    }
                    FileTransferChecksum summer = new FileTransferChecksum();
                    summer.update(block, 0, 10);
                    sum = summer.getValue();
                }
                FileChannel fileChannel = new FileOutputStream(filename).getChannel();
                FileTransferHeader outHeader = new FileTransferHeader(header);
                outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK);
                outHeader.setIcbmMessageId(cookie);
                outHeader.setBytesReceived(0);
                outHeader.setReceivedChecksum(sum);
                OutputStream socketOut = socket.getOutputStream();
                System.out.println("sending header: " + outHeader);
                outHeader.write(socketOut);
                for (int i = 0; i < header.getFileSize(); ) {
                    long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i);
                    System.out.println("transferred " + transferred);
                    if (transferred == -1) return;
                    i += transferred;
                }
                System.out.println("finished transfer!");
                fileChannel.close();
                FileTransferHeader doneHeader = new FileTransferHeader(header);
                doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED);
                doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE);
                doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1);
                doneHeader.setIcbmMessageId(cookie);
                doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1);
                doneHeader.write(socketOut);
                if (doneHeader.getFilesLeft() - 1 <= 0) {
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
public TestReport runImpl() throws Exception {
        DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName);
        File f = (new File(testFileName));
        URL url = f.toURL();
        Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream());
        Element e = doc.getElementById(targetId);
        if (e == null) {
            DefaultTestReport report = new DefaultTestReport(this);
            report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED);
            report.addDescriptionEntry(ENTRY_KEY_ID, targetId);
            report.setPassed(false);
            return report;
        }
        e.setAttribute(targetAttribute, targetValue);
        if (targetValue.equals(e.getAttribute(targetAttribute))) {
            return reportSuccess();
        }
        DefaultTestReport report = new DefaultTestReport(this);
        report.setErrorCode(TestReport.ERROR_TEST_FAILED);
        report.setPassed(false);
        return report;
    }
protected synchronized String encryptThis(String seed, String text) throws EncryptionException {
        String encryptedValue = null;
        String textToEncrypt = text;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(textToEncrypt.getBytes("UTF-8"));
            encryptedValue = (new BASE64Encoder()).encode(md.digest());
        } catch (Exception e) {
            throw new EncryptionException(e);
        }
        return encryptedValue;
    }
public static void reset() throws Exception {
        Session session = DataStaticService.getHibernateSessionFactory().openSession();
        try {
            Connection connection = session.connection();
            try {
                Statement statement = connection.createStatement();
                try {
                    statement.executeUpdate("delete from Post");
                    connection.commit();
                } finally {
                    statement.close();
                }
            } catch (HibernateException e) {
                connection.rollback();
                throw new Exception(e);
            } catch (SQLException e) {
                connection.rollback();
                throw new Exception(e);
            }
        } catch (SQLException e) {
            throw new Exception(e);
        } finally {
            session.close();
        }
    }
public void doCompress(File[] files, File out, List<String> excludedKeys) {
        Map<String, File> map = new HashMap<String, File>();
        String parent = FilenameUtils.getBaseName(out.getName());
        for (File f : files) {
            CompressionUtil.list(f, parent, map, excludedKeys);
        }
        if (!map.isEmpty()) {
            FileOutputStream fos = null;
            ArchiveOutputStream aos = null;
            InputStream is = null;
            try {
                fos = new FileOutputStream(out);
                aos = getArchiveOutputStream(fos);
                for (Map.Entry<String, File> entry : map.entrySet()) {
                    File file = entry.getValue();
                    ArchiveEntry ae = getArchiveEntry(file, entry.getKey());
                    aos.putArchiveEntry(ae);
                    if (file.isFile()) {
                        IOUtils.copy(is = new FileInputStream(file), aos);
                        IOUtils.closeQuietly(is);
                        is = null;
                    }
                    aos.closeArchiveEntry();
                }
                aos.finish();
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(aos);
                IOUtils.closeQuietly(fos);
            }
        }
    }
public static void copierFichier(URL url, File destination) throws CopieException, IOException {
        if (destination.exists()) {
            throw new CopieException("ERREUR : Copie du fichier '" + url.getPath() + "' vers '" + destination.getPath() + "' impossible!\n" + "CAUSE  : Le fichier destination existe d�j�.");
        }
        URLConnection urlConnection = url.openConnection();
        InputStream httpStream = urlConnection.getInputStream();
        FileOutputStream destinationFile = new FileOutputStream(destination);
        byte buffer[] = new byte[512 * 1024];
        int nbLecture;
        while ((nbLecture = httpStream.read(buffer)) != -1) {
            destinationFile.write(buffer, 0, nbLecture);
        }
        log.debug("(COPIE) Copie du fichier : " + url.getPath() + " --> " + destination.getPath());
        httpStream.close();
        destinationFile.close();
    }
public static void main(String[] args) throws Exception {
        DES des = new DES();
        StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt"));
        StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt"));
        SingleKey key = new SingleKey(new Block(64), "");
        key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), "");
        Mode mode = new ECBDESMode(des);
        des.encrypt(reader, writer, key, mode);
    }
public static void replaceEntry(File file, String entryName, InputStream stream) throws PersistenceException {
        try {
            File temporaryFile = File.createTempFile("pmMDA_zargo", ".zargo");
            temporaryFile.deleteOnExit();
            FileInputStream inputStream = new FileInputStream(file);
            ZipInputStream input = new ZipInputStream(inputStream);
            ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile));
            ZipEntry entry = input.getNextEntry();
            while (entry != null) {
                ZipEntry zipEntry = new ZipEntry(entry);
                zipEntry.setCompressedSize(-1);
                output.putNextEntry(zipEntry);
                if (!entry.getName().equals(entryName)) {
                    IOUtils.copy(input, output);
                } else {
                    IOUtils.copy(stream, output);
                }
                input.closeEntry();
                output.closeEntry();
                entry = input.getNextEntry();
            }
            input.close();
            inputStream.close();
            output.close();
            System.gc();
            boolean isSuccess = file.delete();
            if (!isSuccess) {
                throw new PersistenceException();
            }
            isSuccess = temporaryFile.renameTo(file);
            if (!isSuccess) {
                throw new PersistenceException();
            }
        } catch (IOException e) {
            throw new PersistenceException(e);
        }
    }
public static void copy(File src, File dst) throws IOException {
        FileChannel inChannel;
        FileChannel outChannel;
        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(dst).getChannel();
        outChannel.transferFrom(inChannel, 0, inChannel.size());
        inChannel.close();
        outChannel.close();
    }
public static String getMd5Digest(String pInput) {
        try {
            MessageDigest lDigest = MessageDigest.getInstance("MD5");
            lDigest.update(pInput.getBytes());
            BigInteger lHashInt = new BigInteger(1, lDigest.digest());
            return String.format("%1$032x", lHashInt).toLowerCase();
        } catch (NoSuchAlgorithmException lException) {
            throw new RuntimeException(lException);
        }
    }
private void parse(URL url, String description, boolean qualifiersOnTarget) throws org.xml.sax.SAXException, java.io.IOException {
        this.qualifiersOnTarget = qualifiersOnTarget;
        model = new Model(description);
        if (roughMode) model.setRoughMode(true);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/validation", false);
        parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        parser.parse(new InputSource(url.openStream()));
        Document doc = parser.getDocument();
        Element documentEl = doc.getDocumentElement();
        Element contentEl = demandChildElement(documentEl, "XMI.content");
        adapter = Adapter.getAdapter(documentEl);
        parsePackage(contentEl);
        if (!packagePath.isEmpty()) throw new IllegalArgumentException();
        packagePath = null;
        for (Iterator i = generalizations.iterator(); i.hasNext(); ) parseGeneralization((Element) i.next());
        generalizations = null;
        for (Iterator i = associations.keySet().iterator(); i.hasNext(); ) {
            Element assoel = (Element) i.next();
            parseAssociation(assoel, (ModelClass) (associations.get(assoel)));
        }
        associations = null;
        for (Iterator i = classElements.keySet().iterator(); i.hasNext(); ) elaborate((ModelClass) (i.next()));
        classElements = null;
        if (roughMode) model.determineAllSupertypes(); else model.flatten();
        url = null;
    }
private void onOKAction() {
        if (url == null) {
            optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
            JOptionPane.showMessageDialog(this, "URL field cannot be empty", "Empty URL", JOptionPane.ERROR_MESSAGE);
        } else {
            try {
                URLConnection sourceConnection = url.openConnection();
                sourceConnection.setConnectTimeout(10);
                if (sourceConnection.getContentLength() == -1) {
                    throw new IOException("Can't connect to " + url.toString());
                }
                exit_status = OK;
                setVisible(false);
                dispose();
            } catch (IOException e) {
                optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
                JOptionPane.showMessageDialog(this, "Please enter valid, resolvable source and target URLs...\n " + e.getMessage(), "Invalid URL", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
public static void main(String[] args) throws IOException {
        String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt";
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        FSDataInputStream in = null;
        try {
            in = fs.open(new Path(uri));
            IOUtils.copyBytes(in, System.out, 8192, false);
            System.out.println("\n");
            in.seek(0);
            IOUtils.copyBytes(in, System.out, 8192, false);
        } finally {
            IOUtils.closeStream(in);
        }
    }
public boolean update(String dbName, Query[] queries) throws ServiceException {
        Connection con = null;
        PreparedStatement pstmt = null;
        int rows = 0;
        try {
            con = getDbConnection().getConnection(dbName);
            con.setAutoCommit(false);
            for (int i = 0; i < queries.length; i++) {
                Query query = queries[i];
                System.out.println(query.getSql());
                pstmt = con.prepareStatement(query.getSql());
                addParametersToQuery(query, pstmt);
                rows += pstmt.executeUpdate();
            }
            con.commit();
            return rows > 0;
        } catch (DbException e) {
            log.error("[DAOService::update]  " + e.getMessage(), e);
            log.error("[DAOService::update] Execute rollback " + e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                log.error("[DAOService::update] Errore durante il rollback " + e.getMessage(), e);
                throw new ServiceException(e.getMessage());
            }
            throw new ServiceException(e.getMessage());
        } catch (SQLException e) {
            log.error("[DAOService::update]  " + e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                log.error("[DAOService::update] Errore durante il rollback " + e.getMessage(), e);
                throw new ServiceException(e.getMessage());
            }
            throw new ServiceException(e.getMessage());
        } finally {
            closeConnection(con, pstmt, null);
        }
    }
public static void copyFiles(File source, File dest) throws IOException {
        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
            out.write(buf);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }
protected InputStream transform(URL url) throws IOException {
        TransformerFactory tf = TransformerFactory.newInstance();
        InputStream xsl_is = null;
        InputStream url_is = null;
        ByteArrayOutputStream os = null;
        byte[] output;
        try {
            xsl_is = Classes.getThreadClassLoader().getResourceAsStream(getStylesheet());
            url_is = new BufferedInputStream(url.openStream());
            os = new ByteArrayOutputStream();
            Transformer tr = tf.newTransformer(new StreamSource(xsl_is));
            tr.transform(new StreamSource(url_is), new StreamResult(os));
            output = os.toByteArray();
        } catch (TransformerConfigurationException tce) {
            throw new IOException(tce.getLocalizedMessage());
        } catch (TransformerException te) {
            throw new IOException(te.getLocalizedMessage());
        } finally {
            try {
                if (os != null) os.close();
            } catch (Throwable t) {
            }
            try {
                if (url_is != null) url_is.close();
            } catch (Throwable t) {
            }
            try {
                if (xsl_is != null) xsl_is.close();
            } catch (Throwable t) {
            }
        }
        if (logService.isEnabledFor(LogLevel.TRACE)) logService.log(LogLevel.TRACE, new String(output));
        return new ByteArrayInputStream(output);
    }
private void copyResource(String resource, File targetDir) {
        InputStream is = FragmentFileSetTest.class.getResourceAsStream(resource);
        Assume.assumeNotNull(is);
        int i = resource.lastIndexOf("/");
        String filename;
        if (i == -1) {
            filename = resource;
        } else {
            filename = resource.substring(i + 1);
        }
        try {
            FileOutputStream fos = new FileOutputStream(new File(targetDir, filename));
            IOUtils.copy(is, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
    }
private boolean downloadBlacklist() {
        boolean blacklist_updated = false;
        try {
            mLogger.debug("Attempting to download MT blacklist");
            URL url = new URL(blacklistURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            if (this.lastModified != null) {
                connection.setRequestProperty("If-Modified-Since", DateUtil.formatRfc822(this.lastModified));
            }
            int responseCode = connection.getResponseCode();
            mLogger.debug("HttpConnection response = " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                mLogger.debug("MT blacklist site says we are current");
                return false;
            }
            long lastModifiedLong = connection.getHeaderFieldDate("Last-Modified", -1);
            if (responseCode == HttpURLConnection.HTTP_OK && (this.lastModified == null || this.lastModified.getTime() < lastModifiedLong)) {
                mLogger.debug("my last modified = " + this.lastModified.getTime());
                mLogger.debug("MT last modified = " + lastModifiedLong);
                InputStream instream = connection.getInputStream();
                String uploadDir = RollerConfig.getProperty("uploads.dir");
                String path = uploadDir + File.separator + blacklistFile;
                FileOutputStream outstream = new FileOutputStream(path);
                mLogger.debug("writing updated MT blacklist to " + path);
                byte[] buf = new byte[4096];
                int length = 0;
                while ((length = instream.read(buf)) > 0) outstream.write(buf, 0, length);
                outstream.close();
                instream.close();
                blacklist_updated = true;
                mLogger.debug("MT blacklist download completed.");
            } else {
                mLogger.debug("blacklist *NOT* saved, assuming we are current");
            }
        } catch (Exception e) {
            mLogger.error("error downloading blacklist", e);
        }
        return blacklist_updated;
    }
public String index(URL url) {
        InputStream is = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setAllowUserInteraction(false);
            System.setProperty("sun.net.client.defaultConnectTimeout", "15000");
            System.setProperty("sun.net.client.defaultReadTimeout", "15000");
            urlConnection.connect();
            is = urlConnection.getInputStream();
            return index(is);
        } catch (Throwable t) {
        } finally {
            IOUtils.closeQuietly(is);
        }
        return "";
    }
protected byte[] getHashedID(String ID) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(ID.getBytes());
            byte[] digest = md5.digest();
            byte[] bytes = new byte[WLDB_ID_SIZE];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = digest[i];
            }
            return bytes;
        } catch (NoSuchAlgorithmException exception) {
            System.err.println("Java VM is not compatible");
            exit();
            return null;
        }
    }
public String contentType() {
        if (_contentType != null) {
            return (String) _contentType;
        }
        String uti = null;
        URL url = url();
        LOG.info("OKIOSIDManagedObject.contentType(): url = " + url + "\n");
        if (url != null) {
            String contentType = null;
            try {
                contentType = url.openConnection().getContentType();
            } catch (java.io.IOException e) {
                LOG.info("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n");
                String urlString = url.getPath();
                LOG.info("OKIOSIDManagedObject.contentType(): urlString = " + urlString + "\n");
                if (urlString != null) {
                    uti = UTType.preferredIdentifierForTag(UTType.FilenameExtensionTagClass, (NSPathUtilities.pathExtension(urlString)).toLowerCase(), null);
                }
                if (uti == null) {
                    uti = UTType.Item;
                }
                return uti;
            }
            if (contentType != null) {
                LOG.info("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n");
                uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null);
            }
            if (uti == null) {
                uti = UTType.Item;
            }
        } else {
            uti = UTType.Item;
        }
        _contentType = uti;
        LOG.info("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n");
        return uti;
    }
public boolean isPasswordCorrect(String attempt) {
        try {
            MessageDigest digest = MessageDigest.getInstance(attempt);
            digest.update(salt);
            digest.update(attempt.getBytes("UTF-8"));
            byte[] attemptHash = digest.digest();
            return attemptHash.equals(hash);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }