semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Test
    public void testRoundTrip() {
        try {
            URL url = new URL("http://localhost:8192/OMFHTTPJMSRoundtripService/");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(testMessageHeader + testMessage);
            wr.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                logger.debug("Line: " + line);
            }
            wr.close();
            rd.close();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.error("InterruptedException caught trying to sleep test: " + e.getMessage());
        }
        boolean messageReceived = false;
        ArrayList<String> messages = testJMSListener.getReceivedMessages();
        for (Iterator<String> iterator = messages.iterator(); iterator.hasNext(); ) {
            String string = (String) iterator.next();
            logger.debug("String received: " + string);
            if (testMessage.equals(string)) messageReceived = true;
        }
        assertTrue("Message should have been received", messageReceived);
    }
public PluginLoader(URL pluginLocation, ClassLoader loader) {
        Loader = loader;
        url = pluginLocation;
        try {
            if (url.toString().substring(0, 3).compareTo("http") == 0) {
                System.out.println("url location is =" + url.toString());
                InputStream ips = url.openStream();
                Reader r = new InputStreamReader(ips);
                ParserDelegator parser = new ParserDelegator();
                HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback() {

                    public void handleText(char[] dat, int pos) {
                        String data = new String(dat);
                        if (accept(new File("."), data)) fileList.addElement(data);
                        System.out.println("\ngot a file in list" + data);
                    }
                };
                parser.parse(r, callback, false);
            } else {
                file = new File(url.getPath());
                System.out.println("File location is =" + file.getPath());
                String[] tempList = file.list(this);
                for (int i = 0; i < tempList.length; i++) fileList.add(tempList[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        classLoader = new SimpleClassLoader(url, Loader);
        System.out.println(file.getAbsolutePath());
        fillVectors();
    }
public static void copyFile(File from, File to) {
            try {
                FileInputStream in = new FileInputStream(from);
                FileOutputStream out = new FileOutputStream(to);
                byte[] buffer = new byte[1024 * 16];
                int read = 0;
                while ((read = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, read);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
public static boolean sendInformation(String reportType, HashMap<String, String> data) {
        if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_UDC)) {
            logger.debug("Report usage information to devs...");
            String transferData = "reportType=" + reportType;
            transferData += "&build=" + Platform.getBundle("de.uni_mannheim.swt.codeconjurer").getHeaders().get("Bundle-Version");
            transferData += "&Suppl-Server=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SERVER);
            for (String key : data.keySet()) {
                transferData += "&Suppl-" + key + "=" + data.get(key);
            }
            try {
                URL url = new URL("http://www.merobase.com:7777/org.code_conjurer.udc/UsageReport");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(transferData);
                writer.flush();
                StringBuffer answer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    answer.append(line + "\r\n");
                }
                writer.close();
                reader.close();
                logger.debug("UDC Server answer: " + answer.toString());
            } catch (Exception e) {
                CrashReporter.reportException(e);
                logger.debug("Could not report usage data: " + e.toString());
                return false;
            }
            return true;
        } else {
            logger.debug("Reporting not wished!");
            return false;
        }
    }
private CathUtils() throws Exception {
        super(Ontology.CATH);
        InputStream is = null;
        BufferedReader reader = null;
        try {
            final String CATH_REGEXP = OntologyFactory.getOntology(Ontology.CATH).getRegularExpression();
            final URL url = new URL("http://release.cathdb.info/v3.4.0/CathNames");
            is = url.openStream();
            reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                final String[] tokens = line.split("\\s+");
                if (RegularExpressionUtils.getMatches(tokens[0], CATH_REGEXP).size() > 0) {
                    idToName.put(tokens[0], line.substring(line.indexOf(':') + 1, line.length()));
                }
            }
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }
    }
private Bitmap downloadBitmap(String url) {
        final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        final HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            getRequest.abort();
            Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return null;
    }
public static void notify(String msg) throws Exception {
        String url = "http://api.clickatell.com/http/sendmsg?";
        url = add(url, "user", user);
        url = add(url, "password", password);
        url = add(url, "api_id", apiId);
        url = add(url, "to", to);
        url = add(url, "text", msg);
        URL u = new URL(url);
        URLConnection c = u.openConnection();
        InputStream is = c.getInputStream();
        IOUtils.copy(is, System.out);
        IOUtils.closeQuietly(is);
    }
private Store openConnection(String url) throws MessagingException {
        URLName urlName = new URLName(url);
        log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost());
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props);
        Store store = session.getStore(urlName);
        store.connect();
        return store;
    }
public String downloadAndOpen(JProgressBar bar) {
        long size = 0;
        try {
            size = photo.getSize();
        } catch (ServiceException ex) {
            ex.printStackTrace();
        }
        try {
            bar.setMaximum((int) size);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        bar.setValue(0);
        image = new File("TMP/" + photo.getTitle().getPlainText());
        try {
            if (!image.exists()) {
                image.createNewFile();
                image.deleteOnExit();
                URL url = null;
                BufferedOutputStream fOut = null;
                try {
                    url = new URL(photo.getMediaContents().get(0).getUrl());
                    InputStream html = null;
                    html = url.openStream();
                    fOut = new BufferedOutputStream(new FileOutputStream(image));
                    byte[] buffer = new byte[32 * 1024];
                    int bytesRead = 0;
                    int in = 0;
                    while ((bytesRead = html.read(buffer)) != -1) {
                        in += bytesRead;
                        bar.setValue(in);
                        fOut.write(buffer, 0, bytesRead);
                    }
                    html.close();
                    fOut.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return image.getAbsolutePath();
    }
protected String encrypt(String text) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
            md.update(text.getBytes("UTF-8"));
            byte raw[] = md.digest();
            String hash = (new BASE64Encoder()).encode(raw);
            return hash;
        } catch (Exception ex) {
            throw new TiiraException(ex);
        }
    }
public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException {
        FileOutputStream fileOut;
        File file;
        ZipEntry zipEntry;
        ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder);
        while ((zipEntry = zipIn.getNextEntry()) != null) {
            file = new File(outputDirectory + File.separator + zipEntry.getName());
            if (zipEntry.isDirectory()) {
                createDirectory(file.getPath(), "");
            } else {
                File parent = file.getParentFile();
                if (!parent.exists()) {
                    createDirectory(parent.getPath(), "");
                }
                fileOut = new FileOutputStream(file);
                int readedBytes;
                while ((readedBytes = zipIn.read(buf)) > 0) {
                    fileOut.write(buf, 0, readedBytes);
                }
                fileOut.close();
            }
            zipIn.closeEntry();
        }
    }
public static void connectServer() {
        if (ftpClient == null) {
            int reply;
            try {
                setArg(configFile);
                ftpClient = new FTPClient();
                ftpClient.setDefaultPort(port);
                ftpClient.configure(getFtpConfig());
                ftpClient.connect(ip);
                ftpClient.login(username, password);
                ftpClient.setDefaultPort(port);
                System.out.print(ftpClient.getReplyString());
                reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    System.err.println("FTP server refused connection.");
                }
            } catch (Exception e) {
                System.err.println("��¼ftp��������" + ip + "��ʧ��");
                e.printStackTrace();
            }
        }
    }
public stock(String ticker) {
        try {
            URL url = new URL("http://finance.yahoo.com/q?s=" + ticker + "&d=v1");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            StringBuffer page = new StringBuffer(8192);
            while ((line = reader.readLine()) != null) {
                page.append(line);
            }
            LispInterpreter lisp = InterpreterFactory.getInterpreter();
            lisp.eval("(load \"nregex\")");
            String quote = lisp.eval("(second (regex \"<b>([0-9][0-9]\\.[0-9][0-9])</b>\" \"" + cleanse(page) + "\"))");
            System.out.println("Current quote: " + quote);
            lisp.exit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public static String getUniqueKey() {
        String digest = "";
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final String timeVal = "" + (System.currentTimeMillis() + 1);
            String localHost = "";
            try {
                localHost = InetAddress.getLocalHost().toString();
            } catch (UnknownHostException e) {
                println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage());
            }
            final String randVal = "" + new Random().nextInt();
            final String val = timeVal + localHost + randVal;
            md.reset();
            md.update(val.getBytes());
            digest = toHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            println("Warn: getUniqueKey() " + e);
        }
        return digest;
    }
protected byte[] createFileID() {
        try {
            COSDocument cosDoc = cosGetDoc();
            if (cosDoc == null) {
                return null;
            }
            ILocator locator = cosDoc.getLocator();
            if (locator == null) {
                return null;
            }
            IRandomAccess ra = cosDoc.stGetDoc().getRandomAccess();
            if (ra == null) {
                ra = new RandomAccessByteArray(StringTools.toByteArray("DummyValue"));
            }
            MessageDigest digest = MessageDigest.getInstance("MD5");
            long time = System.currentTimeMillis();
            digest.update(String.valueOf(time).getBytes());
            digest.update(locator.getFullName().getBytes());
            digest.update(String.valueOf(ra.getLength()).getBytes());
            COSInfoDict infoDict = getInfoDict();
            if (infoDict != null) {
                for (Iterator it = infoDict.cosGetDict().iterator(); it.hasNext(); ) {
                    COSObject object = (COSObject) it.next();
                    digest.update(object.stringValue().getBytes());
                }
            }
            return digest.digest();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
public void run() {
        checkupdates.BetaST.setText("");
        checkupdates.stableST.setText("");
        
        String[] s = new String[7];
       int i=0;
        try {
            
            URL url = new URL("http://memorize-words.sourceforge.net/latest.txt");
            
            BufferedReader in = new BufferedReader(new
                    InputStreamReader(url.openStream()));
            String str;
           
            while (((str = in.readLine()) != null)&&(i<7)) {
                
                s[i]=str;
                i++;
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
       if (i<5) 
       { checkupdates.CheckBT.setEnabled(true);
           return;
       }
       //S[0]=latest Beta version
       //S[1]=latest Stable version
       //s[2]=Beta version download path
       //s[3]=Stable version download path
       //s[4]= Beta name
       //s[5]=Stable name
       boolean updated=false;
       if ((MF.CurVersion<Integer.parseInt(s[0]))&&(checkupdates.BetaCHK.isSelected()))
       {
       checkupdates.BetaST.setText("<HTML>A newer BETA version (<b>"+s[4]+"</b>) is available at<BR> <a href=''>"+s[2]+"</a></HTML>");
       updated=true;
       checkupdates.hasBeta=true;
       checkupdates.BetaURL=s[2];
       }else
           checkupdates.BetaST.setText("");
           
       if ((MF.CurVersion<Integer.parseInt(s[1]))&&(checkupdates.StableCHK.isSelected()))
       {
       checkupdates.stableST.setText("<HTML>A newer STABLE version (<b>"+s[5]+"</b>) is available at<BR> <a href=''>"+s[3]+"</a></HTML>");
       updated=true;
       checkupdates.hasStable=true;
       checkupdates.StableURL=s[3];
       }
       else
           checkupdates.stableST.setText("");
       
       if (updated)
           checkupdates.setVisible(true);
       checkupdates.CheckBT.setEnabled(true);
       // "A newer stable version (memorize-words 1-2-2) is available at http://"
       //   MF.CurVersion;
    }
private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception {
        ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar));
        FileOutputStream fos = new FileOutputStream(toEar);
        ZipOutputStream tempZip = new ZipOutputStream(fos);
        ZipEntry next = earFile.getNextEntry();
        while (next != null) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            byte[] data = new byte[30000];
            int numberread;
            while ((numberread = earFile.read(data)) != -1) {
                content.write(data, 0, numberread);
            }
            if (next.getName().equals("META-INF/application.xml")) {
                content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot);
                next = new ZipEntry("META-INF/application.xml");
            }
            tempZip.putNextEntry(next);
            tempZip.write(content.toByteArray());
            next = earFile.getNextEntry();
        }
        earFile.close();
        tempZip.close();
        fos.close();
    }
private void download(URL url, File outFile) throws IOException {
        System.out.println("Trying to download: " + url);
        InputStream in = null;
        OutputStream out = null;
        try {
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            out = new BufferedOutputStream(new FileOutputStream(outFile));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > -1) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("Unable to close stream.", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("Unable to close stream.", e);
                }
            }
        }
    }
@Override
    protected InputStream getResourceStream(String name) throws Exception {
        final BundleEntry entry = cpm.findLocalEntry(name);
        if (entry != null) return entry.getInputStream();
        final URL url = cpm.getBaseData().getBundle().getResource(name);
        if (url != null) return url.openStream();
        return null;
    }
public void saveDownloadFiles(List downloadFiles) throws SQLException {
        Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
        try {
            conn.setAutoCommit(false);
            Statement s = conn.createStatement();
            s.executeUpdate("DELETE FROM DOWNLOADFILES");
            s.close();
            s = null;
            PreparedStatement ps = conn.prepareStatement("INSERT INTO DOWNLOADFILES " + "(name,targetpath,size,fnkey,enabled,state,downloadaddedtime,downloadstartedtime,downloadfinishedtime," + "retries,lastdownloadstoptime,gqid,filelistfilesha) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
            for (Iterator i = downloadFiles.iterator(); i.hasNext(); ) {
                FrostDownloadItem dlItem = (FrostDownloadItem) i.next();
                int ix = 1;
                ps.setString(ix++, dlItem.getFilename());
                ps.setString(ix++, dlItem.getTargetPath());
                ps.setLong(ix++, (dlItem.getFileSize() == null ? 0 : dlItem.getFileSize().longValue()));
                ps.setString(ix++, dlItem.getKey());
                ps.setBoolean(ix++, (dlItem.isEnabled() == null ? true : dlItem.isEnabled().booleanValue()));
                ps.setInt(ix++, dlItem.getState());
                ps.setLong(ix++, dlItem.getDownloadAddedTime());
                ps.setLong(ix++, dlItem.getDownloadStartedTime());
                ps.setLong(ix++, dlItem.getDownloadFinishedTime());
                ps.setInt(ix++, dlItem.getRetries());
                ps.setLong(ix++, dlItem.getLastDownloadStopTime());
                ps.setString(ix++, dlItem.getGqIdentifier());
                ps.setString(ix++, dlItem.getFileListFileObject() == null ? null : dlItem.getFileListFileObject().getSha());
                ps.executeUpdate();
            }
            ps.close();
            conn.commit();
            conn.setAutoCommit(true);
        } catch (Throwable t) {
            logger.log(Level.SEVERE, "Exception during save", t);
            try {
                conn.rollback();
            } catch (Throwable t1) {
                logger.log(Level.SEVERE, "Exception during rollback", t1);
            }
            try {
                conn.setAutoCommit(true);
            } catch (Throwable t1) {
            }
        } finally {
            AppLayerDatabase.getInstance().givePooledConnection(conn);
        }
    }
public void fileUpload() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://upload.1fichier.com/en/upload.cgi?id=" + uid);
        if (oneFichierAccount.loginsuccessful) {
            httppost.setHeader("Cookie", OneFichierAccount.getSidcookie());
        }
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("file[]", new MonitoredFileBody(file, uploadProgress));
        mpEntity.addPart("domain", new StringBody("0"));
        httppost.setEntity(mpEntity);
        NULogger.getLogger().info("Now uploading your file into 1fichier...........................");
        NULogger.getLogger().log(Level.INFO, "Now executing.......{0}", httppost.getRequestLine());
        status = UploadStatus.UPLOADING;
        HttpResponse response = httpclient.execute(httppost);
        status = UploadStatus.GETTINGLINK;
        httpclient.getConnectionManager().shutdown();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (response.containsHeader("Location")) {
            uploadresponse = response.getFirstHeader("Location").getValue();
            NULogger.getLogger().log(Level.INFO, "Upload location link : {0}", uploadresponse);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again");
        }
    }