semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static boolean download(String address, String localFileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        try {
            URL url = new URL(address);
            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }
            System.out.println(localFileName + "\t" + numWritten);
        } catch (Exception exception) {
            exception.printStackTrace();
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
                return false;
            }
        }
        return true;
    }
public void apop(String user, char[] secret) throws IOException, POP3Exception {
        if (timestamp == null) {
            throw new CommandNotSupportedException("No timestamp from server - APOP not possible");
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(timestamp.getBytes());
            if (secret == null) secret = new char[0];
            byte[] digest = md.digest(new String(secret).getBytes("ISO-8859-1"));
            mutex.lock();
            sendCommand("APOP", new String[] { user, digestToString(digest) });
            POP3Response response = readSingleLineResponse();
            if (!response.isOK()) {
                throw new POP3Exception(response);
            }
            state = TRANSACTION;
        } catch (NoSuchAlgorithmException e) {
            throw new POP3Exception("Installed JRE doesn't support MD5 - APOP not possible");
        } finally {
            mutex.release();
        }
    }
private void createUser(AddEditUserForm addform, HttpServletRequest request, ActionMapping mapping) throws Exception {
        MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone();
        md.update(addform.getPassword().getBytes("UTF-8"));
        byte[] pd = md.digest();
        StringBuffer app = new StringBuffer();
        for (int i = 0; i < pd.length; i++) {
            String s2 = Integer.toHexString(pd[i] & 0xFF);
            app.append((s2.length() == 1) ? "0" + s2 : s2);
        }
        Session hbsession = HibernateUtil.currentSession();
        try {
            Transaction tx = hbsession.beginTransaction();
            NvUsers user = new NvUsers();
            user.setLogin(addform.getLogin());
            user.setPassword(app.toString());
            hbsession.save(user);
            hbsession.flush();
            if (!hbsession.connection().getAutoCommit()) {
                tx.commit();
            }
        } finally {
            HibernateUtil.closeSession();
        }
    }
public static String encode(String arg) {
        if (arg == null) {
            arg = "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(arg.getBytes(JavaCenterHome.JCH_CHARSET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return toHex(md5.digest());
    }
private void handleFile(File file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filename = file.getName();
        long filesize = file.length();
        String mimeType = getMimeType(filename);
        response.setContentType(mimeType);
        if (filesize > getDownloadThreshhold()) {
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        }
        response.setContentLength((int) filesize);
        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(new FileInputStream(file), out);
        out.flush();
    }
public SqlScript(URL url, IDbDialect platform, boolean failOnError, String delimiter, Map<String, String> replacementTokens) {
        try {
            fileName = url.getFile();
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            log.log(LogLevel.INFO, "Loading sql from script %s", fileName);
            init(IoUtils.readLines(new InputStreamReader(url.openStream(), "UTF-8")), platform, failOnError, delimiter, replacementTokens);
        } catch (IOException ex) {
            log.error(ex);
            throw new RuntimeException(ex);
        }
    }
public void setChecksum() {
        try {
            java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
            String fqn = this.path + this.name;
            md5.update(fqn.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & BYTE_CLEANER_FF;
                if (b < BYTE_CLEANER_10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(b));
            }
            this.checksum = sb.toString();
        } catch (java.security.NoSuchAlgorithmException nsae) {
            this.checksum = this.path + this.name;
        }
    }
public Component loadComponent(URI uri, URI origuri) throws ComponentException {
        try {
            Component comp = null;
            InputStream is = null;
            java.net.URL url = null;
            try {
                url = uri.getJavaURL();
            } catch (java.net.MalformedURLException e) {
                throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage());
            }
            try {
                if (url.getProtocol().equals("ftp")) is = ftpHandler.getInputStream(url); else {
                    java.net.URLConnection conn = url.openConnection();
                    conn.connect();
                    is = conn.getInputStream();
                }
            } catch (IOException e) {
                if (is != null) is.close();
                throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + e.getMessage());
            }
            try {
                comp = componentIO.loadComponent(origuri, uri, is, isSavable(uri));
            } catch (ComponentException e) {
                if (is != null) is.close();
                throw new ComponentException("Error loading component " + origuri + " from " + url + ":\n " + e.getMessage());
            }
            is.close();
            return comp;
        } catch (IOException ioe) {
            Tracer.debug("didn't manage to close inputstream....");
            return null;
        }
    }
public static String getMD5(String s) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(s.getBytes(), 0, s.length());
            return "" + new BigInteger(1, m.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            logger.error("MD5 is not supported !!!");
        }
        return s;
    }
@Override
    protected byte[] computeHash() {
        try {
            final MessageDigest inputHash = MessageDigest.getInstance("SHA");
            inputHash.update(bufferFileData().getBytes());
            return inputHash.digest();
        } catch (final NoSuchAlgorithmException nsae) {
            lastException = nsae;
            return new byte[0];
        } catch (final IOException ioe) {
            lastException = ioe;
            return new byte[0];
        }
    }
public InetSocketAddress getServerAddress() throws IOException {
        URL url = new URL(ADDRESS_SERVER_URL);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setDoOutput(true);
        con.setReadTimeout(2000);
        con.connect();
        BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = rd.readLine();
        if (line == null) throw new IOException("Cannot read address from address server");
        String addr[] = line.split(" ", 2);
        return new InetSocketAddress(addr[0], Integer.valueOf(addr[1]));
    }
@Override
            public void onClick(View v) {
                username = textusername.getText().toString();
                password = textpassword.getText().toString();
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new name_value("uname", username));
                nameValuePairs.add(new name_value("upass", password));
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://www.gotrackit.net/server/check_user.php");
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    is = entity.getContent();
                } catch (Exception e) {
                    Log.e("log_tag", "Error in http connection" + e.toString());
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    sb = new StringBuilder();
                    sb.append(reader.readLine() + "\n");
                    String line = "0";
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }
                if (result.contains("reject")) {
                    Context context = getApplicationContext();
                    int duration = Toast.LENGTH_SHORT;
                    String wrong = "Invalid  Username or Password";
                    Toast toast = Toast.makeText(context, wrong, duration);
                    toast.show();
                } else {
                    MyApp uid = (MyApp) getApplicationContext();
                    uid.setStringValue(result);
                    Intent myintent = new Intent(v.getContext(), UserMap.class);
                    startActivityForResult(myintent, 0);
                }
            }
public static boolean dump(File source, File target) {
        boolean done = false;
        try {
            InputStream is = new BufferedInputStream(new FileInputStream(source));
            OutputStream os = new BufferedOutputStream(new FileOutputStream(target));
            while (is.available() > 0) {
                os.write(is.read());
            }
            os.flush();
            os.close();
            is.close();
            return true;
        } catch (IOException e) {
        }
        return done;
    }
private void _readValuesFromNetwork() {
        if (_intrinsicValuesByAttribute == null) {
            NSMutableDictionary<String, Object> values = new NSMutableDictionary<String, Object>(3);
            values.setObjectForKey(Boolean.FALSE, "NetworkFailure");
            try {
                URLConnection connection = url().openConnection();
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpconnect = (HttpURLConnection) connection;
                    httpconnect.setRequestMethod("HEAD");
                    switch(httpconnect.getResponseCode()) {
                        case HttpURLConnection.HTTP_OK:
                        case HttpURLConnection.HTTP_MOVED_PERM:
                        case HttpURLConnection.HTTP_MOVED_TEMP:
                        case HttpURLConnection.HTTP_NOT_MODIFIED:
                            values.setObjectForKey(Boolean.TRUE, MD.FSExists);
                            break;
                        default:
                            values.setObjectForKey(Boolean.FALSE, MD.FSExists);
                    }
                    LOG.info("_readValuesFromNetwork: " + httpconnect.toString());
                    values.setObjectForKey(new NSTimestamp(httpconnect.getLastModified()), MD.FSContentChangeDate);
                    values.setObjectForKey(new Integer(httpconnect.getContentLength()), MD.FSSize);
                } else {
                    values.setObjectForKey(Boolean.FALSE, MD.FSExists);
                }
            } catch (Exception x) {
                values.setObjectForKey(Boolean.FALSE, MD.FSExists);
                values.setObjectForKey(Boolean.TRUE, "NetworkFailure");
            }
            _intrinsicValuesByAttribute = values;
        }
    }
private ArrayList<IdLocation> doGet(String identifier) throws IdLocatorException {
        String openurl = baseurl.toString() + "?url_ver=Z39.88-2004&rft_id=" + identifier;
        URL url;
        SRUSearchRetrieveResponse sru;
        try {
            url = new URL(openurl);
            HttpURLConnection huc = (HttpURLConnection) (url.openConnection());
            int code = huc.getResponseCode();
            if (code == 200) {
                sru = SRUSearchRetrieveResponse.read(huc.getInputStream());
            } else throw new IdLocatorException("cannot get " + url.toString());
        } catch (MalformedURLException e) {
            throw new IdLocatorException("A MalformedURLException occurred for " + openurl);
        } catch (IOException e) {
            throw new IdLocatorException("An IOException occurred attempting to connect to " + openurl);
        } catch (SRUException e) {
            throw new IdLocatorException("An SRUException occurred attempting to parse the response");
        }
        ArrayList<IdLocation> ids = new ArrayList<IdLocation>();
        for (SRUDC dc : sru.getRecords()) {
            IdLocation id = new IdLocation();
            id.setId(dc.getKeys(SRUDC.Key.IDENTIFIER).firstElement());
            id.setRepo(dc.getKeys(SRUDC.Key.SOURCE).firstElement());
            id.setDate(dc.getKeys(SRUDC.Key.DATE).firstElement());
            ids.add(id);
        }
        Collections.sort(ids);
        return ids;
    }
private static void validateJarFile(URL url) throws IOException {
        InputStream stream = url.openStream();
        JarInputStream jarStream = new JarInputStream(stream, true);
        try {
            while (null != jarStream.getNextEntry()) {
            }
        } finally {
            try {
                jarStream.close();
            } catch (Exception ignore) {
            }
        }
    }
private Callable<Request> newRequestCall(final Request request) {
        return new Callable<Request>() {

            public Request call() {
                InputStream is = null;
                try {
                    if (DEBUG) Log.d(TAG, "Requesting: " + request.uri);
                    HttpGet httpGet = new HttpGet(request.uri.toString());
                    httpGet.addHeader("Accept-Encoding", "gzip");
                    HttpResponse response = mHttpClient.execute(httpGet);
                    String mimeType = response.getHeaders("Content-Type")[0].getValue();
                    if (DEBUG) Log.d(TAG, "mimeType:" + mimeType);
                    if (mimeType.startsWith("image")) {
                        HttpEntity entity = response.getEntity();
                        is = getUngzippedContent(entity);
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        if (mResourceCache.store(request.hash, bitmap)) {
                            mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap));
                            if (DEBUG) Log.d(TAG, "Request successful: " + request.uri);
                        } else {
                            mResourceCache.invalidate(request.hash);
                        }
                    }
                } catch (IOException e) {
                    if (DEBUG) Log.d(TAG, "IOException", e);
                } finally {
                    if (DEBUG) Log.e(TAG, "Request finished: " + request.uri);
                    mActiveRequestsMap.remove(request);
                    if (is != null) {
                        notifyObservers(request.uri);
                    }
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        if (DEBUG) e.printStackTrace();
                    }
                }
                return request;
            }
        };
    }
public Request call() {
                InputStream is = null;
                try {
                    if (DEBUG) Log.d(TAG, "Requesting: " + request.uri);
                    HttpGet httpGet = new HttpGet(request.uri.toString());
                    httpGet.addHeader("Accept-Encoding", "gzip");
                    HttpResponse response = mHttpClient.execute(httpGet);
                    String mimeType = response.getHeaders("Content-Type")[0].getValue();
                    if (DEBUG) Log.d(TAG, "mimeType:" + mimeType);
                    if (mimeType.startsWith("image")) {
                        HttpEntity entity = response.getEntity();
                        is = getUngzippedContent(entity);
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        if (mResourceCache.store(request.hash, bitmap)) {
                            mCache.put(request.uri.toString(), new SoftReference<Bitmap>(bitmap));
                            if (DEBUG) Log.d(TAG, "Request successful: " + request.uri);
                        } else {
                            mResourceCache.invalidate(request.hash);
                        }
                    }
                } catch (IOException e) {
                    if (DEBUG) Log.d(TAG, "IOException", e);
                } finally {
                    if (DEBUG) Log.e(TAG, "Request finished: " + request.uri);
                    mActiveRequestsMap.remove(request);
                    if (is != null) {
                        notifyObservers(request.uri);
                    }
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        if (DEBUG) e.printStackTrace();
                    }
                }
                return request;
            }
@Override
    public void write(OutputStream output) throws IOException, WebApplicationException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final GZIPOutputStream gzipOs = new GZIPOutputStream(baos);
        IOUtils.copy(is, gzipOs);
        baos.close();
        gzipOs.close();
        output.write(baos.toByteArray());
    }
private InputStream getDomainMap() {
        String domainMap = Configuration.getString(MAPPING_KEY);
        InputStream is = new StringBufferInputStream(domainMap);
        if ("".equals(domainMap)) {
            try {
                URL url = getClass().getResource(XML_FILE_NAME).toURI().toURL();
                is = url.openStream();
            } catch (URISyntaxException e) {
                LOG.warn("Could not find domainmapping file", e);
            } catch (MalformedURLException e) {
                LOG.warn("Could not find domainmapping file", e);
            } catch (IOException e) {
                LOG.warn("Error reading/fetching domain map", e);
            }
        }
        return is;
    }
private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException {
        byte[] buf = new byte[2048];
        int read;
        while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read);
        inFile.close();
    }
private boolean checkHashBack(Facade facade, HttpServletRequest req) {
        String txtTransactionID = req.getParameter("txtTransactionID");
        String txtOrderTotal = req.getParameter("txtOrderTotal");
        String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);
        String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);
        String txtHashBack = req.getParameter("txtHashBack");
        String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);
        String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;
        MessageDigest digest;
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(securityValue.getBytes());
            byte[] array = digest.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            String hash = sb.toString();
            System.out.println("com.eshop.http.servlets.PaymentController.checkHashBack: " + hash + " " + txtHashBack);
            if (txtHashBack.equals(hash)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }
private static Properties getProperties(String propFilename) {
        Properties properties = new Properties();
        try {
            URL url = Loader.getResource(propFilename);
            properties.load(url.openStream());
        } catch (Exception e) {
            log.debug("Cannot find SAML property file: " + propFilename);
            throw new RuntimeException("SAMLIssuerFactory: Cannot load properties: " + propFilename);
        }
        return properties;
    }
public static void main(final String[] args) {
        final Runnable startDerby = new Runnable() {

            public void run() {
                try {
                    final NetworkServerControl control = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
                    control.start(new PrintWriter(System.out));
                } catch (final Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        };
        new Thread(startDerby).start();
        final Runnable startActiveMq = new Runnable() {

            public void run() {
                Main.main(new String[] { "start", "xbean:file:active-mq-config.xml" });
            }
        };
        new Thread(startActiveMq).start();
        final Runnable startMailServer = new Runnable() {

            public void run() {
                final SimpleMessageListener listener = new SimpleMessageListener() {

                    public final boolean accept(final String from, final String recipient) {
                        return true;
                    }

                    public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException {
                        System.out.println("FROM: " + from);
                        System.out.println("TO: " + recipient);
                        final File tmpDir = new File(System.getProperty("java.io.tmpdir"));
                        final File file = new File(tmpDir, recipient);
                        final FileWriter fw = new FileWriter(file);
                        try {
                            IOUtils.copy(data, fw);
                        } finally {
                            fw.close();
                        }
                    }
                };
                final SMTPServer smtpServer = new SMTPServer(new SimpleMessageListenerAdapter(listener));
                smtpServer.start();
                System.out.println("Started SMTP Server");
            }
        };
        new Thread(startMailServer).start();
    }