semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public String post(final FetchInfos fetchInfos, final String data) throws HttpException {
        URL url = null;
        try {
            url = new URL(fetchInfos.getUri());
        } catch (MalformedURLException exception) {
            throw new HttpException("uri is malformed '" + fetchInfos.getUri() + "'", exception);
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException exception) {
            fetchInfos.setResult(FETCHING_RESULT.IO_ERROR);
            throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception);
        }
        InputStream input = null;
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
            final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(data);
            wr.flush();
            wr.close();
            input = connection.getInputStream();
            if ("gzip".equals(connection.getHeaderField("content-encoding"))) {
                input = new GZIPInputStream(input);
            }
            if (HttpServiceImpl.LOGGER.isDebugEnabled()) {
                this.logConnection(connection);
                input = new LoggingInputStream(input);
            }
        } catch (SocketTimeoutException exception) {
            fetchInfos.setResult(FETCHING_RESULT.TIME_OUT);
            throw new HttpException("get '" + fetchInfos.getUri() + "' timeout", exception);
        } catch (IOException exception) {
            fetchInfos.setResult(FETCHING_RESULT.IO_ERROR);
            throw new HttpException("get '" + fetchInfos.getUri() + "' failed", exception);
        }
        fetchInfos.setResult(FETCHING_RESULT.OK);
        String response = null;
        try {
            response = this.toString(input);
        } catch (IOException exception) {
            throw new HttpException("converting inputstream to string failed", exception);
        }
        return response;
    }
private void processParameters() throws BadElementException, IOException {
        type = IMGTEMPLATE;
        originalType = ORIGINAL_WMF;
        InputStream is = null;
        try {
            String errorID;
            if (rawData == null) {
                is = url.openStream();
                errorID = url.toString();
            } else {
                is = new java.io.ByteArrayInputStream(rawData);
                errorID = "Byte array";
            }
            InputMeta in = new InputMeta(is);
            if (in.readInt() != 0x9AC6CDD7) {
                throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.placeable.windows.metafile", errorID));
            }
            in.readWord();
            int left = in.readShort();
            int top = in.readShort();
            int right = in.readShort();
            int bottom = in.readShort();
            int inch = in.readWord();
            dpiX = 72;
            dpiY = 72;
            scaledHeight = (float) (bottom - top) / inch * 72f;
            setTop(scaledHeight);
            scaledWidth = (float) (right - left) / inch * 72f;
            setRight(scaledWidth);
        } finally {
            if (is != null) {
                is.close();
            }
            plainWidth = getWidth();
            plainHeight = getHeight();
        }
    }
private Long queryServer(OWLOntology ontologyURI) throws IOException {
        String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer";
        requestString += "?query=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8");
        URL url = new URL(requestString);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer returned = new StringBuffer();
        String str;
        while (null != ((str = input.readLine()))) {
            returned.append(str);
        }
        input.close();
        return new Long(returned.toString());
    }
private ChangeCapsule fetchServer(OWLOntology ontologyURI, Long sequenceNumber) throws IOException {
        String requestString = "http://" + InetAddress.getLocalHost().getHostName() + ":8080/ChangeServer";
        requestString += "?fetch=" + URLEncoder.encode(ontologyURI.getURI().toString(), "UTF-8");
        requestString += "&number" + sequenceNumber;
        URL url = new URL(requestString);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer returned = new StringBuffer();
        String str;
        while (null != ((str = input.readLine()))) {
            returned.append(str);
        }
        input.close();
        ChangeCapsule cp = new ChangeCapsule(returned.toString());
        return cp;
    }
public static boolean fileCopy(String sFileSrc, String sFileDst) {
        boolean ok = true;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            File fSrc = new File(sFileSrc);
            int len = 32768;
            byte[] buff = new byte[(int) Math.min(len, fSrc.length())];
            fis = new FileInputStream(fSrc);
            boolean append = false;
            fos = new FileOutputStream(sFileDst, append);
            while (0 < (len = fis.read(buff))) fos.write(buff, 0, len);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
            ok = false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JdxLog.logError(ex);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JdxLog.logError(ex);
                }
            }
        }
        return ok;
    }
public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-512");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("UTF-8"), 0, text.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
private static void copyFiles(String strPath, String dstPath) throws Exception {
        File src = new File(strPath);
        File dest = new File(dstPath);
        if (src.isDirectory()) {
            dest.mkdirs();
            String list[] = src.list();
            for (int i = 0; i < list.length; i++) {
                String dest1 = dest.getAbsolutePath() + "\\" + list[i];
                String src1 = src.getAbsolutePath() + "\\" + list[i];
                copyFiles(src1, dest1);
            }
        } else {
            FileChannel sourceChannel = new FileInputStream(src).getChannel();
            FileChannel targetChannel = new FileOutputStream(dest).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
            sourceChannel.close();
            targetChannel.close();
        }
    }
@Override
    public Content getContent(Object principal, ContentPath path, Version version, Map<String, Object> properties) throws ContentException {
        String uniqueName = path.getBaseName();
        URL url = buildURL(uniqueName);
        URLContent content = new URLContent(url, this.getName(), uniqueName);
        content.setUniqueName(uniqueName);
        content.setReadable(true);
        content.setWritable(writable);
        content.setExists(true);
        try {
            URLConnection connection = url.openConnection();
            String mimeType = connection.getContentType();
            content.setMimeType(mimeType);
            content.setWritable(true);
        } catch (IOException ex) {
            throw new ContentException("unable to obtain mime type of " + url, ex);
        }
        return content;
    }
@Override
    public void writeToContent(Object principal, String uniqueId, InputStream ins) throws IOException, ContentException {
        if (writable) {
            URL url = buildURL(uniqueId);
            URLConnection connection = url.openConnection();
            OutputStream outs = connection.getOutputStream();
            try {
                ContentUtil.pipe(ins, outs);
            } finally {
                try {
                    outs.close();
                } catch (Exception ex) {
                    log.log(Level.WARNING, "unable to close " + url, ex);
                }
            }
        } else {
            throw new ContentException("not writable");
        }
    }
public static void copy(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
public static String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(password.getBytes());
            byte[] hash = md.digest();
            int hashLength = hash.length;
            StringBuffer hashStringBuf = new StringBuffer();
            String byteString;
            int byteLength;
            for (int index = 0; index < hash.length; index++) {
                byteString = String.valueOf(hash[index] + 128);
                byteLength = byteString.length();
                switch(byteLength) {
                    case 1:
                        byteString = "00" + byteString;
                        break;
                    case 2:
                        byteString = "0" + byteString;
                        break;
                }
                hashStringBuf.append(byteString);
            }
            return hashStringBuf.toString();
        } catch (NoSuchAlgorithmException nsae) {
            System.out.println("Error getting password hash - " + nsae.getMessage());
            return null;
        }
    }
public static void copy(File from, File to, int bufferSize) throws IOException {
        if (to.exists()) {
            logger.info("File " + to + " exists, will replace it.");
            to.delete();
        }
        to.getParentFile().mkdirs();
        to.createNewFile();
        FileInputStream ois = null;
        FileOutputStream cos = null;
        try {
            ois = new FileInputStream(from);
            cos = new FileOutputStream(to);
            byte[] buf = new byte[bufferSize];
            int read;
            while ((read = ois.read(buf, 0, bufferSize)) > 0) {
                cos.write(buf, 0, read);
            }
            cos.flush();
        } finally {
            try {
                if (ois != null) ois.close();
            } catch (IOException ignored) {
                logger.warn("Could not close file input stream " + from, ignored);
            }
            try {
                if (cos != null) {
                    cos.close();
                }
            } catch (IOException ignored) {
                logger.warn("Could not close file output stream " + to, ignored);
            }
        }
    }
public static boolean insert(final Funcionario objFuncionario) {
        int result = 0;
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            final String sql = "insert into funcionario " + "(nome, cpf, telefone, email, senha, login, id_cargo)" + " values (?, ?, ?, ?, ?, ?, ?)";
            pst = c.prepareStatement(sql);
            pst.setString(1, objFuncionario.getNome());
            pst.setString(2, objFuncionario.getCpf());
            pst.setString(3, objFuncionario.getTelefone());
            pst.setString(4, objFuncionario.getEmail());
            pst.setString(5, objFuncionario.getSenha());
            pst.setString(6, objFuncionario.getLogin());
            pst.setLong(7, (objFuncionario.getCargo()).getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (final SQLException e) {
            try {
                c.rollback();
            } catch (final SQLException e1) {
                System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[FuncionarioDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
public static boolean update(Funcionario objFuncionario) {
        int result = 0;
        Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            final String sql = "update funcionario " + " set nome = ? , cpf = ? , telefone = ? , email = ?, senha = ?, login = ?, id_cargo = ?" + " where id_funcionario = ?";
            pst = c.prepareStatement(sql);
            pst.setString(1, objFuncionario.getNome());
            pst.setString(2, objFuncionario.getCpf());
            pst.setString(3, objFuncionario.getTelefone());
            pst.setString(4, objFuncionario.getEmail());
            pst.setString(5, objFuncionario.getSenha());
            pst.setString(6, objFuncionario.getLogin());
            pst.setLong(7, (objFuncionario.getCargo()).getCodigo());
            pst.setLong(8, objFuncionario.getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (SQLException e) {
            try {
                c.rollback();
            } catch (SQLException e1) {
                System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e1.getMessage());
            }
            System.out.println("[FuncionarioDAO.update] Erro ao atualizar -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
public static final synchronized String md5(final String data) {
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data.getBytes());
            final byte[] b = md.digest();
            return toHexString(b);
        } catch (final Exception e) {
        }
        return "";
    }
public String crypt(String suppliedPassword) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(suppliedPassword.getBytes());
        String encriptedPassword = null;
        try {
            encriptedPassword = new String(Base64.encode(md.digest()), "ASCII");
        } catch (UnsupportedEncodingException e) {
        }
        return encriptedPassword;
    }
@Override
    List<String> HttpGet(URL url) throws IOException {
        List<String> responseList = new ArrayList<String>();
        Logger.getInstance().logInfo("HTTP GET: " + url, null, getGatewayId());
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(20000);
        con.setAllowUserInteraction(false);
        responseList.add(con.getResponseCode() + " " + con.getResponseMessage());
        InputStream inputStream = con.getErrorStream();
        if (inputStream == null) inputStream = con.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
        String inputLine;
        while ((inputLine = in.readLine()) != null) responseList.add(inputLine);
        in.close();
        return responseList;
    }
InputStream openReader(String s) {
        System.err.println("Fetcher: trying url " + s);
        try {
            URL url = new URL(s);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            return url.openStream();
        } catch (IOException e) {
        }
        return null;
    }
public static void batchInsertOrder(Order o) throws AppException {
        Connection conn = DBUtils.getDataConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sqlOrder = null;
        String sqlDetail = null;
        try {
            conn.setAutoCommit(false);
            sqlOrder = "insert into SO_SOMain (ID,cSOCode,dDate," + "cBusType,cCusCode,cCusName," + "cDepCode,cSTCode," + "iVTid,cMaker,cMemo) values (?,?,?,?,?,?,?,?,?,?,?)";
            sqlDetail = "insert into SO_SODetails (ID,cSOCode,cInvCode,cInvName," + "iNum,iQuantity,iTaxUnitPrice,iSum,dPreDate,iSOsID,cFree1,cUnitID) values(?,?,?,?,?,?,?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sqlOrder);
            long maxId = getMaxID(conn, pstmt, rs);
            maxId++;
            pstmt.setLong(1, maxId);
            Long l = maxId;
            o.setId(l.intValue());
            String code = o.getCode();
            long maxCSOCode = getMaxCSOCode(code, conn, pstmt, rs);
            String csOCode = getCSOCode(code, maxCSOCode);
            o.setCode(csOCode);
            pstmt.setString(2, csOCode);
            pstmt.setDate(3, DateUtil.getSqlDateFormUtilDate(o.getOrderDate()));
            pstmt.setString(4, o.getBusinessType());
            pstmt.setString(5, o.getC().getId());
            pstmt.setString(6, o.getC().getName());
            pstmt.setString(7, o.getP().getDept().getId());
            pstmt.setString(8, o.getSaleType().getId());
            pstmt.setInt(9, o.getiVtid());
            pstmt.setString(10, o.getP().getName());
            pstmt.setString(11, o.getRemark());
            pstmt.executeUpdate();
            pstmt.clearParameters();
            pstmt = conn.prepareStatement(sqlDetail);
            ArrayList<OrderDetail> ods = o.getOds();
            long iSOsID = getiSOsID(conn, pstmt, rs);
            for (OrderDetail od : ods) {
                pstmt.setLong(1, maxId);
                pstmt.setString(2, csOCode);
                pstmt.setString(3, od.getInventory().getId());
                pstmt.setString(4, od.getInventory().getName());
                pstmt.setInt(5, od.getPiece());
                pstmt.setBigDecimal(6, od.getCount());
                pstmt.setBigDecimal(7, od.getPrice());
                pstmt.setBigDecimal(8, od.getSum());
                pstmt.setDate(9, DateUtil.getSqlDateFormUtilDate(od.getSendDate()));
                pstmt.setLong(10, ++iSOsID);
                pstmt.setString(11, od.getPacking().getcValue());
                pstmt.setString(12, od.getInventory().getSAComUnitCode());
                pstmt.executeUpdate();
                pstmt.clearParameters();
            }
            conn.commit();
        } catch (SQLException sqle) {
            try {
                conn.rollback();
                throw new AppException(sqle.getMessage());
            } catch (SQLException ex) {
                Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex);
                throw new AppException(ex.getMessage());
            }
        } finally {
            DBUtils.closeAll(rs, pstmt, conn);
        }
    }
public static String getDocumentAsString(URL url) throws IOException {
        StringBuffer result = new StringBuffer();
        InputStream inStream = url.openStream();
        int character;
        while ((character = inStream.read()) != -1) {
            result.append((char) character);
        }
        return result.toString();
    }
@Test
    public void testTransactWriteAndRead() throws Exception {
        JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0);
        JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort);
        try {
            server.start();
            RFile file = new RFile("testreadwritetrans.txt");
            RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1);
            out.write("test".getBytes("utf-8"));
            out.close();
            RFileInputStream in = new RFileInputStream(file);
            byte[] buffer = new byte[4];
            int readCount = in.read(buffer);
            in.close();
            assertEquals(4, readCount);
            String resultRead = new String(buffer, "utf-8");
            assertEquals("test", resultRead);
        } finally {
            server.stop();
        }
    }
public static void copyFile(File sourceFile, File destFile) throws IOException {
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            long count = 0;
            long size = source.size();
            while ((count += destination.transferFrom(source, 0, size - count)) < size) ;
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
@Test
    public void testWriteAndRead() throws Exception {
        JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0);
        JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort);
        try {
            server.start();
            RFile file = new RFile("testreadwrite.txt");
            RFileOutputStream out = new RFileOutputStream(file);
            out.write("test".getBytes("utf-8"));
            out.close();
            RFileInputStream in = new RFileInputStream(file);
            byte[] buffer = new byte[4];
            int readCount = in.read(buffer);
            in.close();
            assertEquals(4, readCount);
            String resultRead = new String(buffer, "utf-8");
            assertEquals("test", resultRead);
        } finally {
            server.stop();
        }
    }
private static BreakIterator createBreakInstance(Locale where, int kind, String rulesName, String dictionaryName) {
        ResourceBundle bundle = ICULocaleData.getResourceBundle("BreakIteratorRules", where);
        String[] classNames = bundle.getStringArray("BreakIteratorClasses");
        String rules = bundle.getString(rulesName);
        if (classNames[kind].equals("RuleBasedBreakIterator")) {
            return new RuleBasedBreakIterator(rules);
        } else if (classNames[kind].equals("DictionaryBasedBreakIterator")) {
            try {
                Object t = bundle.getObject(dictionaryName);
                URL url = (URL) t;
                InputStream dictionary = url.openStream();
                return new DictionaryBasedBreakIterator(rules, dictionary);
            } catch (IOException e) {
            } catch (MissingResourceException e) {
            }
            return new RuleBasedBreakIterator(rules);
        } else {
            throw new IllegalArgumentException("Invalid break iterator class \"" + classNames[kind] + "\"");
        }
    }