semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private static MyCookieData parseCookie(Cookie cookie) throws CookieException {
        String value = cookie.getValue();
        System.out.println("original cookie: " + value);
        value = value.replace("%3A", ":");
        value = value.replace("%40", "@");
        System.out.println("cookie after replacement: " + value);
        String[] parts = value.split(":");
        if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value);
        String email = parts[0];
        String nickname = parts[1];
        boolean admin = Boolean.getBoolean(parts[2].toLowerCase());
        String hsh = parts[3];
        boolean valid_cookie = true;
        String cookie_secret = System.getProperty("COOKIE_SECRET");
        if (cookie_secret == "") throw new CookieException("cookie secret is not set");
        if (email.equals("")) {
            System.out.println("email is empty!");
            nickname = "";
            admin = false;
        } else {
            try {
                MessageDigest sha = MessageDigest.getInstance("SHA");
                sha.update((email + nickname + admin + cookie_secret).getBytes());
                StringBuilder builder = new StringBuilder();
                for (byte b : sha.digest()) {
                    byte tmphigh = (byte) (b >> 4);
                    tmphigh = (byte) (tmphigh & 0xf);
                    builder.append(hextab.charAt(tmphigh));
                    byte tmplow = (byte) (b & 0xf);
                    builder.append(hextab.charAt(tmplow));
                }
                System.out.println();
                String vhsh = builder.toString();
                if (!vhsh.equals(hsh)) {
                    System.out.println("hash not same!");
                    System.out.println("hash passed in: " + hsh);
                    System.out.println("hash generated: " + vhsh);
                    valid_cookie = false;
                } else System.out.println("cookie match!");
            } catch (NoSuchAlgorithmException ex) {
            }
        }
        return new MyCookieData(email, admin, nickname, valid_cookie);
    }
public static byte[] encrypt(String x) throws NoSuchAlgorithmException {
        MessageDigest d = null;
        d = MessageDigest.getInstance("SHA-1");
        d.reset();
        d.update(x.getBytes());
        return d.digest();
    }
public boolean downloadFile(String webdir, String fileName, String localdir) {
        boolean result = false;
        checkDownLoadDirectory(localdir);
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url);
            ftp.login(username, password);
            if (!"".equals(webdir.trim())) ftp.changeDirectory(webdir);
            ftp.download(fileName, new File(localdir + "//" + fileName));
            result = true;
            ftp.disconnect(true);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FTPIllegalReplyException e) {
            e.printStackTrace();
        } catch (FTPException e) {
            e.printStackTrace();
        } catch (FTPDataTransferException e) {
            e.printStackTrace();
        } catch (FTPAbortedException e) {
            e.printStackTrace();
        }
        return result;
    }
private Retailer create() throws SQLException, IOException {
        Connection conn = null;
        Statement st = null;
        String query = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            st = conn.createStatement();
            query = "insert into " + DB.Tbl.ret + "(" + col.title + "," + col.addDate + "," + col.authorId + ") " + "values('" + title + "',now()," + user.getId() + ")";
            st.executeUpdate(query, new String[] { col.id });
            rs = st.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Не удается получить generated key 'id' в таблице retailers.");
            }
            int genId = rs.getInt(1);
            rs.close();
            saveDescr(genId);
            conn.commit();
            Retailer ret = new Retailer();
            ret.setId(genId);
            ret.setTitle(title);
            ret.setDescr(descr);
            RetailerViewer.getInstance().somethingUpdated();
            return ret;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (Exception e1) {
            }
            throw e;
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                st.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
public int register(String name, String password, String email, String addr, String contactNo) {
        int uid = 0;
        int result = -1;
        try {
            getCon().setAutoCommit(false);
            if (!checkUser(name, password)) {
                PreparedStatement pstmt = getCon().prepareStatement("insert into user(uname, upass, uemail, uaddr, ucontact)" + " values (?,?,?,?,?)");
                pstmt.setString(1, name);
                pstmt.setString(2, password);
                pstmt.setString(3, email);
                pstmt.setString(4, addr);
                pstmt.setString(5, contactNo);
                int num = pstmt.executeUpdate();
                if (num == 1) {
                    ResultSet rs = pstmt.getGeneratedKeys();
                    if (rs.next()) {
                        result = rs.getInt(1);
                    }
                }
            } else {
                result = -1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result = -1;
            try {
                System.out.println("Transaction roll back due to errors");
                getCon().rollback();
            } catch (Exception ex) {
            }
        }
        return result;
    }
public static String get_content(String _url) throws Exception {
        URL url = new URL(_url);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        String content = new String();
        while ((inputLine = in.readLine()) != null) {
            content += inputLine;
        }
        in.close();
        return content;
    }
private InputStream getConnection() throws BaseException {
        OutputStreamWriter wr = null;
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(getBaseString());
            sb.append(AND);
            sb.append(encode(ACTION, ENCODING));
            sb.append(EQUAL);
            sb.append(encode(ACTION_GET_ALL, ENCODING));
            URL url = new URL(SERVER_URL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();
            return conn.getInputStream();
        } catch (Exception e) {
            throw getException(e, context);
        } finally {
            closeSafely(wr);
        }
    }
private static String fetchImageViaHttp(URL imgUrl) throws IOException {
        String sURL = imgUrl.toString();
        String imgFile = imgUrl.getPath();
        HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection();
        String uri = null;
        try {
            cnx.setAllowUserInteraction(false);
            cnx.setDoOutput(true);
            cnx.addRequestProperty("Cache-Control", "no-cache");
            RequestContext ctx = RequestContext.get();
            if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent);
            cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1));
            cnx.connect();
            if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null;
            InputStream imgData = cnx.getInputStream();
            String ext = FilenameUtils.getExtension(imgFile).toLowerCase();
            if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg";
            uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext;
            File fileDest = new File(img_path + uri);
            if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(fileDest);
            try {
                IOUtils.copy(imgData, fos);
            } finally {
                IOUtils.closeQuietly(imgData);
                IOUtils.closeQuietly(fos);
            }
        } finally {
            cnx.disconnect();
        }
        return RequestContext.get().contextPath() + "/uploads/img/" + uri;
    }
private void handleServerIntroduction(DataPacket serverPacket) {
        DataPacketIterator iter = serverPacket.getDataPacketIterator();
        String version = iter.nextString();
        int serverReportedUDPPort = iter.nextUByte2();
        _authKey = iter.nextUByte4();
        _introKey = iter.nextUByte4();
        _clientKey = makeClientKey(_authKey, _introKey);
        String passwordKey = iter.nextString();
        _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort);
        DataPacket packet = null;
        if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) {
            ParameterBuilder builder = new ParameterBuilder();
            builder.appendUByte2(_udpSocket.getLocalPort());
            builder.appendString(_user);
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ignore) {
            }
            md5.update(_serverKey.getBytes());
            md5.update(passwordKey.getBytes());
            md5.update(_password.getBytes());
            for (byte b : md5.digest()) {
                builder.appendByte(b);
            }
            packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter());
        } else {
            packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY);
        }
        sendTCPPacket(packet);
    }
private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException {
        URL wsdlurl = null;
        try {
            wsdlurl = new URL(uri);
        } catch (MalformedURLException e) {
            return new InputSource(uri);
        }
        if (username == null && wsdlurl.getUserInfo() == null) {
            return new InputSource(uri);
        }
        if (!wsdlurl.getProtocol().startsWith("http")) {
            return new InputSource(uri);
        }
        URLConnection connection = wsdlurl.openConnection();
        if (!(connection instanceof HttpURLConnection)) {
            return new InputSource(uri);
        }
        HttpURLConnection uconn = (HttpURLConnection) connection;
        String userinfo = wsdlurl.getUserInfo();
        uconn.setRequestMethod("GET");
        uconn.setAllowUserInteraction(false);
        uconn.setDefaultUseCaches(false);
        uconn.setDoInput(true);
        uconn.setDoOutput(false);
        uconn.setInstanceFollowRedirects(true);
        uconn.setUseCaches(false);
        String auth = null;
        if (userinfo != null) {
            auth = userinfo;
        } else if (username != null) {
            auth = (password == null) ? username : username + ":" + password;
        }
        if (auth != null) {
            uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(charEncoding)));
        }
        uconn.connect();
        return new InputSource(uconn.getInputStream());
    }
@Override
    public HttpResponse makeRequest() throws RequestCancelledException, IllegalStateException, IOException {
        checkState();
        OutputStream out = null;
        InputStream in = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(destFile));
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[BUFFRE_SIZE];
            int numRead;
            long totalSize = conn.getContentLength();
            long transferred = 0;
            started(totalSize);
            while (!checkAbortFlag() && (numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                out.flush();
                transferred += numRead;
                progress(transferred);
            }
            if (checkAbortFlag()) {
                cancelled();
            } else {
                finished();
            }
            if (checkAbortFlag()) {
                throw new RequestCancelledException();
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return null;
    }
public static byte[] MD5(String... strings) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.reset();
            for (String string : strings) {
                digest.update(string.getBytes("UTF-8"));
            }
            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.toString(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }
public static byte[] SHA1(String... strings) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA1");
            digest.reset();
            for (String string : strings) {
                digest.update(string.getBytes("UTF-8"));
            }
            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.toString(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }
public static String generateMD5(String clear) {
        byte hash[] = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(clear.getBytes());
            hash = md5.digest();
        } catch (NoSuchAlgorithmException e) {
        }
        if (hash != null) {
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String tmp = Integer.toHexString(0xFF & hash[i]);
                if (tmp.length() == 1) {
                    tmp = "0" + tmp;
                }
                hexString.append(tmp);
            }
            return hexString.toString();
        } else {
            return null;
        }
    }
private String sendImpl(String from, String destNumber, String text) throws IOException {
        final QueryStringBuilder query = new QueryStringBuilder();
        query.append("user", username);
        query.append("password", password);
        query.append("api_id", apiId);
        query.append("to", destNumber);
        if (from != null) {
            query.append("from", from);
        }
        query.append("text", text);
        final URL url = new URL(CLICKATELL_GATEWAY_URL + "sendmsg" + query.toString());
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        try {
            return br.readLine();
        } finally {
            br.close();
        }
    }
public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException {
        InputStream input = null;
        BufferedOutputStream bos = null;
        File tempUnit = null;
        try {
            URL url = null;
            int total = 0;
            try {
                url = new URL(urlStr);
                input = url.openStream();
                URLConnection urlConnection;
                urlConnection = url.openConnection();
                total = urlConnection.getContentLength();
            } catch (IOException e) {
                throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e);
            }
            String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
            tempUnit = null;
            try {
                if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit");
                File parent = tempUnit.getParentFile();
                FileUtils.forceMkdir(parent);
                if (!tempUnit.exists()) FileUtils.touch(tempUnit);
                bos = new BufferedOutputStream(new FileOutputStream(tempUnit));
            } catch (FileNotFoundException e) {
                throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e);
            } catch (IOException e) {
                throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e);
            } catch (DeployToolException e) {
                throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e);
            }
            logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr));
            int size = -1;
            try {
                size = IOUtils.copy(input, bos);
                bos.flush();
            } catch (IOException e) {
                logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit));
            }
            if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr));
        } finally {
            if (input != null) IOUtils.closeQuietly(input);
            if (bos != null) IOUtils.closeQuietly(bos);
        }
        logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath()));
        return tempUnit.getAbsolutePath();
    }
public static void copyFile(final File in, final File out) throws IOException {
        final FileChannel inChannel = new FileInputStream(in).getChannel();
        final FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (final IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }
public void sendPOIGpxLocation() {
        this.myloc = new Position(45.56, 5.9);
        this.left = myloc.getY() - 0.025;
        this.right = myloc.getY() + 0.025;
        this.top = myloc.getX() + 0.03;
        this.bottom = myloc.getX() - 0.03;
        assertEquals("left test", left, (5.9 - 0.025));
        assertEquals("right test", right, (5.9 + 0.025));
        assertEquals("top test", top, (45.56 - 0.025));
        assertEquals("bottom test", left, (45.56 + 0.025));
        this.poisCheck.add("amenity");
        try {
            if (this.poisCheck.get(0).compareTo("None") == 0) {
                model.setPointsOfInterest(new Items());
            } else {
                this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                SAXParser pars = null;
                ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext());
                pars = SAXParserFactory.newInstance().newSAXParser();
                pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
                pars.parse(url.openStream(), gpxHandler);
                this.pois = gpxHandler.getPOIResultsItems();
                assertTrue("there is some pois", !this.pois.equals(0));
                assertFalse("there is some pois", this.pois.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            assertFalse(!e.getCause().equals(null));
        }
    }
public void sendPOIGpxNonePOIs() {
        this.myloc = new Position(45.56, 5.9);
        this.left = myloc.getY() - 0.025;
        this.right = myloc.getY() + 0.025;
        this.top = myloc.getX() + 0.03;
        this.bottom = myloc.getX() - 0.03;
        assertEquals("left test", left, (5.9 - 0.025));
        assertEquals("right test", right, (5.9 + 0.025));
        assertEquals("top test", top, (45.56 - 0.025));
        assertEquals("bottom test", left, (45.56 + 0.025));
        this.poisCheck.add("None");
        try {
            if (this.poisCheck.get(0).compareTo("None") == 0) {
                model.setPointsOfInterest(new Items());
            } else {
                this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                SAXParser pars = null;
                ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext());
                pars = SAXParserFactory.newInstance().newSAXParser();
                pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
                pars.parse(url.openStream(), gpxHandler);
                this.pois = gpxHandler.getPOIResultsItems();
                assertFalse("there is some pois", !this.pois.equals(0));
                assertTrue("there is some pois", this.pois.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            assertFalse(!e.getCause().equals(null));
        }
    }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory");
        FileInputStream input = new FileInputStream(srcFile);
        try {
            FileOutputStream output = new FileOutputStream(destFile);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
        if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
        if (preserveFileDate) destFile.setLastModified(srcFile.lastModified());
    }