semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void testReleaseOnAbort() throws Exception {
        HttpParams params = defaultParams.copy();
        ConnManagerParams.setMaxTotalConnections(params, 1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1));
        ThreadSafeClientConnManager mgr = createTSCCM(params, null);
        assertEquals(0, mgr.getConnectionsInPool());
        DefaultHttpClient client = new DefaultHttpClient(mgr, params);
        HttpGet httpget = new HttpGet("/random/20000");
        HttpHost target = getServerHttp();
        HttpResponse response = client.execute(target, httpget);
        ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
        try {
            connreq.getConnection(250, TimeUnit.MILLISECONDS);
            fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException expected) {
        }
        HttpEntity e = response.getEntity();
        assertNotNull(e);
        httpget.abort();
        assertEquals(0, mgr.getConnectionsInPool());
        connreq = mgr.requestConnection(new HttpRoute(target), null);
        ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS);
        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }
public void testReleaseOnIOException() throws Exception {
        localServer.register("/dropdead", new HttpRequestHandler() {

            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
                BasicHttpEntity entity = new BasicHttpEntity() {

                    @Override
                    public void writeTo(final OutputStream outstream) throws IOException {
                        byte[] tmp = new byte[5];
                        outstream.write(tmp);
                        outstream.flush();
                        DefaultHttpServerConnection conn = (DefaultHttpServerConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
                        try {
                            conn.sendResponseHeader(response);
                        } catch (HttpException ignore) {
                        }
                    }
                };
                entity.setChunked(true);
                response.setEntity(entity);
            }
        });
        HttpParams params = defaultParams.copy();
        ConnManagerParams.setMaxTotalConnections(params, 1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1));
        ThreadSafeClientConnManager mgr = createTSCCM(params, null);
        assertEquals(0, mgr.getConnectionsInPool());
        DefaultHttpClient client = new DefaultHttpClient(mgr, params);
        HttpGet httpget = new HttpGet("/dropdead");
        HttpHost target = getServerHttp();
        HttpResponse response = client.execute(target, httpget);
        ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
        try {
            connreq.getConnection(250, TimeUnit.MILLISECONDS);
            fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException expected) {
        }
        HttpEntity e = response.getEntity();
        assertNotNull(e);
        try {
            EntityUtils.toByteArray(e);
            fail("MalformedChunkCodingException should have been thrown");
        } catch (MalformedChunkCodingException expected) {
        }
        assertEquals(0, mgr.getConnectionsInPool());
        connreq = mgr.requestConnection(new HttpRoute(target), null);
        ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS);
        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }
boolean getHTML(URL url) {
        html = "";
        int r;
        BufferedInputStream in = null;
        BufferedInputStream imgIn = null;
        boolean retry;
        Vector imageRd = new Vector(0);
        do {
            retry = false;
            try {
                in = new BufferedInputStream(url.openStream(), 4096);
            } catch (IOException ioe) {
                rbe.stats.error("Unable to open URL.", url.toExternalForm());
                ioe.printStackTrace();
                retry = true;
                continue;
            }
            try {
                while ((r = in.read(buffer, 0, buffer.length)) != -1) {
                    if (r > 0) {
                        html = html + new String(buffer, 0, r);
                    }
                }
            } catch (IOException ioe) {
                rbe.stats.error("Unable to read HTML from URL.", url.toExternalForm());
                retry = true;
                continue;
            }
            if (retry) {
                try {
                    if (waitKey) {
                        rbe.getKey();
                    } else {
                        sleep(1000L);
                    }
                } catch (InterruptedException inte) {
                    System.out.println("In getHTML, caught interrupted exception!");
                    return true;
                }
            }
        } while (retry);
        try {
            in.close();
        } catch (IOException ioe) {
            rbe.stats.error("Unable to close URL.", url.toExternalForm());
        }
        if (DEBUG > 0) {
        }
        if (DEBUG > 10) {
            System.out.println(html);
        }
        int cur = 0;
        if (!RBE.getImage) return true;
        findImg(html, url, imgPat, srcPat, quotePat, imageRd);
        findImg(html, url, inputPat, srcPat, quotePat, imageRd);
        if (DEBUG > 2) {
            System.out.println("Found " + imageRd.size() + " images.");
        }
        while (imageRd.size() > 0) {
            int max = imageRd.size();
            int min = Math.max(max - rbe.maxImageRd, 0);
            int i;
            try {
                for (i = min; i < max; i++) {
                    ImageReader rd = (ImageReader) imageRd.elementAt(i);
                    if (!rd.readImage()) {
                        if (DEBUG > 2) {
                            System.out.println("Read " + rd.tot + " bytes from " + rd.imgURLStr);
                        }
                        imageRd.removeElementAt(i);
                        i--;
                        max--;
                    }
                }
            } catch (InterruptedException inte) {
                System.out.println("In getHTML, caught interrupted exception!");
                return true;
            }
        }
        return true;
    }
public static boolean copyFile(String sourceFileName, String destFileName) {
        if (sourceFileName == null || destFileName == null) return false;
        if (sourceFileName.equals(destFileName)) return false;
        try {
            java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName);
            java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName);
            try {
                byte[] buf = new byte[31000];
                int read = in.read(buf);
                while (read > -1) {
                    out.write(buf, 0, read);
                    read = in.read(buf);
                }
            } finally {
                in.close();
                out.close();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            return false;
        }
        return true;
    }
public static boolean copyFile(final String src, final String dest) {
        if (fileExists(src)) {
            try {
                FileChannel srcChannel = new FileInputStream(src).getChannel();
                FileChannel dstChannel = new FileOutputStream(dest).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
                return true;
            } catch (IOException e) {
                Logger.getAnonymousLogger().severe(e.getLocalizedMessage());
            }
        }
        return false;
    }
public String encrypt(String plaintext) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            System.err.println(e.getMessage());
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }
@Test
    public void testConfigurartion() {
        try {
            Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties");
            log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties"));
            log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml"));
            log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml"));
            if (log.isDebugEnabled()) {
                while (assemblersToRegister.hasMoreElements()) {
                    URL url = (URL) assemblersToRegister.nextElement();
                    InputStream in = url.openStream();
                    BufferedReader buff = new BufferedReader(new InputStreamReader(in));
                    String line = buff.readLine();
                    while (line != null) {
                        log.debug(line);
                        line = buff.readLine();
                    }
                    buff.close();
                    in.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public String MD5(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }
private List<JarFile> webArchives(ServletContext servletContext) throws IOException {
        List<JarFile> list = new ArrayList<JarFile>();
        Set<Object> paths = servletContext.getResourcePaths(WEB_LIB_PREFIX);
        for (Object pathObject : paths) {
            String path = (String) pathObject;
            if (!path.endsWith(".jar")) {
                continue;
            }
            URL url = servletContext.getResource(path);
            String jarURLString = "jar:" + url.toString() + "!/";
            url = new URL(jarURLString);
            JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
            JarEntry signal = jarFile.getJarEntry(FACES_CONFIG_IMPLICIT);
            if (signal == null) {
                if (log().isTraceEnabled()) {
                    log().trace("Skip JAR file " + path + " because it has no META-INF/faces-config.xml resource");
                }
                continue;
            }
            list.add(jarFile);
        }
        return list;
    }
private void onCheckConnection() {
        BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {

            public void run() {
                String baseUrl;
                if (_rdoSRTM3FtpUrl.getSelection()) {
                } else {
                    baseUrl = _txtSRTM3HttpUrl.getText().trim();
                    try {
                        final URL url = new URL(baseUrl);
                        final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.connect();
                        final int response = urlConn.getResponseCode();
                        final String responseMessage = urlConn.getResponseMessage();
                        final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage });
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message);
                    } catch (final IOException e) {
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl));
                        e.printStackTrace();
                    }
                }
            }
        });
    }
public void run() {
                String baseUrl;
                if (_rdoSRTM3FtpUrl.getSelection()) {
                } else {
                    baseUrl = _txtSRTM3HttpUrl.getText().trim();
                    try {
                        final URL url = new URL(baseUrl);
                        final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.connect();
                        final int response = urlConn.getResponseCode();
                        final String responseMessage = urlConn.getResponseMessage();
                        final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage });
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message);
                    } catch (final IOException e) {
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl));
                        e.printStackTrace();
                    }
                }
            }
public static String encrypt(final String password, final String algorithm, final byte[] salt) {
        final StringBuffer buffer = new StringBuffer();
        MessageDigest digest = null;
        int size = 0;
        if ("CRYPT".equalsIgnoreCase(algorithm)) {
            throw new InternalError("Not implemented");
        } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) {
            size = 20;
            if (salt != null && salt.length > 0) {
                buffer.append("{SSHA}");
            } else {
                buffer.append("{SHA}");
            }
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) {
            size = 16;
            if (salt != null && salt.length > 0) {
                buffer.append("{SMD5}");
            } else {
                buffer.append("{MD5}");
            }
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        }
        int outSize = size;
        digest.reset();
        digest.update(password.getBytes());
        if (salt != null && salt.length > 0) {
            digest.update(salt);
            outSize += salt.length;
        }
        final byte[] out = new byte[outSize];
        System.arraycopy(digest.digest(), 0, out, 0, size);
        if (salt != null && salt.length > 0) {
            System.arraycopy(salt, 0, out, size, salt.length);
        }
        buffer.append(Base64.encode(out));
        return buffer.toString();
    }
public static boolean verify(final String password, final String encryptedPassword) {
        MessageDigest digest = null;
        int size = 0;
        String base64 = null;
        if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) {
            throw new InternalError("Not implemented");
        } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) {
            size = 20;
            base64 = encryptedPassword.substring(5);
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) {
            size = 20;
            base64 = encryptedPassword.substring(6);
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) {
            size = 16;
            base64 = encryptedPassword.substring(5);
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) {
            size = 16;
            base64 = encryptedPassword.substring(6);
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else {
            return false;
        }
        final byte[] data = Base64.decode(base64.toCharArray());
        final byte[] orig = new byte[size];
        System.arraycopy(data, 0, orig, 0, size);
        digest.reset();
        digest.update(password.getBytes());
        if (data.length > size) {
            digest.update(data, size, data.length - size);
        }
        return MessageDigest.isEqual(digest.digest(), orig);
    }
public static void loginBitShare() throws Exception {
        HttpParams params = new BasicHttpParams();
        params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        DefaultHttpClient httpclient = new DefaultHttpClient(params);
        System.out.println("Trying to log in to bitshare.com");
        HttpPost httppost = new HttpPost("http://bitshare.com/login.html");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("user", "007007dinesh"));
        formparams.add(new BasicNameValuePair("password", ""));
        formparams.add(new BasicNameValuePair("submit", "Login"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(entity);
        HttpResponse httpresponse = httpclient.execute(httppost);
        Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator();
        Cookie escookie = null;
        while (it.hasNext()) {
            escookie = it.next();
            System.out.println(escookie.getName() + " = " + escookie.getValue());
        }
        System.out.println(EntityUtils.toString(httpresponse.getEntity()));
    }
public String getContentsFromVariant(SelectedVariant selected) {
        if (selected == null) {
            return null;
        }
        ActivatedVariablePolicy policy = selected.getPolicy();
        Variant variant = selected.getVariant();
        if (variant == null) {
            return null;
        }
        Content content = variant.getContent();
        if (content instanceof EmbeddedContent) {
            EmbeddedContent embedded = (EmbeddedContent) content;
            return embedded.getData();
        } else {
            MarinerURL marinerURL = computeURL((Asset) selected.getOldObject());
            URL url;
            try {
                url = context.getAbsoluteURL(marinerURL);
            } catch (MalformedURLException e) {
                logger.warn("asset-mariner-url-retrieval-error", new Object[] { policy.getName(), ((marinerURL == null) ? "" : marinerURL.getExternalForm()) }, e);
                return null;
            }
            String text = null;
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Retrieving contents of URL " + url);
                }
                URLConnection connection = url.openConnection();
                int contentLength = connection.getContentLength();
                if (contentLength > 0) {
                    String charset = connection.getContentEncoding();
                    if (charset == null) {
                        charset = "UTF-8";
                    }
                    InputStreamReader is = new InputStreamReader(connection.getInputStream(), charset);
                    BufferedReader br = new BufferedReader(is);
                    char[] buf = new char[contentLength];
                    int length = br.read(buf, 0, buf.length);
                    text = String.copyValueOf(buf, 0, length);
                }
            } catch (IOException e) {
                logger.warn("asset-url-retrieval-error", new Object[] { policy.getName(), url }, e);
            }
            return text;
        }
    }
private void copyFile(File sourceFile, File destFile) throws IOException {
        if (!sourceFile.exists()) {
            return;
        }
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
protected static void clearTables() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = FidoDataSource.getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            ClearData.clearTables(stmt);
            stmt.executeUpdate("delete from MorphologyTags");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('not')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('plural')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('third singular')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('again')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('past tense')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('against')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('deprive')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('cause to happen')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('nounify')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('someone who believes')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('belief system of')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('capable of')");
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }