semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
int responseTomcat(InetAddress dest, int port, String request, boolean methodPost, StringBuffer response, int timeout) {
        int methodGetMaxSize = 250;
        int methodPostMaxSize = 32000;
        if (request == null || response == null) return -1;
        String fullRequest;
        if (methodPost) {
            String resource;
            String queryStr;
            int qIdx = request.indexOf('?');
            if (qIdx == -1) {
                resource = request;
                queryStr = "";
            } else {
                resource = request.substring(0, qIdx);
                queryStr = request.substring(qIdx + 1);
            }
            fullRequest = "POST " + resource + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n" + queryStr;
        } else {
            fullRequest = "GET " + request + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n";
        }
        if (methodPost && fullRequest.length() > methodPostMaxSize) {
            response.setLength(0);
            response.append("Complete POST request longer than maximum of " + methodPostMaxSize);
            return -5;
        } else if ((!methodPost) && fullRequest.length() > methodGetMaxSize) {
            response.setLength(0);
            response.append("Complete GET request longer than maximum of " + methodGetMaxSize);
            return -6;
        }
        String inputLine = "";
        request = "http://" + dest.getHostName() + ":" + (new Integer(port).toString()) + request;
        try {
            URL urlAddress = new URL(request);
            URLConnection urlC = urlAddress.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                response = response.append(inputLine).append("\n");
            }
        } catch (MalformedURLException e) {
            return -4;
        } catch (IOException e) {
            return -3;
        }
        return 200;
    }
public void backup(File source) throws BackupException {
        try {
            int index = source.getAbsolutePath().lastIndexOf(".");
            if (index == -1) return;
            File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak");
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(dest).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (Exception ex) {
            throw new BackupException(ex.getMessage(), ex, source);
        }
    }
public static String encrypt(String algorithm, String str) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(str.getBytes());
            StringBuffer sb = new StringBuffer();
            byte[] bytes = md.digest();
            for (int i = 0; i < bytes.length; i++) {
                int b = bytes[i] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }
private URLConnection getServletConnection(String strServlet_name) throws MalformedURLException, IOException {
        URL urlServlet = null;
        if (strServlet_name == null) {
            urlServlet = m_Url;
        } else {
            urlServlet = new URL(m_Url, strServlet_name);
        }
        URLConnection connection = urlServlet.openConnection();
        connection.setConnectTimeout(180000);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
        if (m_strJsessionid != null) {
            connection.setRequestProperty("Cookie", m_strJsessionid);
        }
        return connection;
    }
public void testAddFiles() throws Exception {
        File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip"));
        File copy = new File(original.getParentFile(), "1test.zip");
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(original);
            out = new FileOutputStream(copy);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        } finally {
            Util.close(in);
            Util.close(out);
        }
        ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath()));
        archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor());
        IArchive[] children = archive.getChildren();
        boolean found = false;
        for (IArchive child : children) {
            if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true;
        }
        assertTrue(found);
        copy.delete();
    }
private static void download(String urlString) throws IOException {
        URL url = new URL(urlString);
        url = handleRedirectUrl(url);
        URLConnection cn = url.openConnection();
        Utils.setHeader(cn);
        long fileLength = cn.getContentLength();
        Statics.getInstance().setFileLength(fileLength);
        long packageLength = fileLength / THREAD_COUNT;
        long leftLength = fileLength % THREAD_COUNT;
        String fileName = Utils.decodeURLFileName(url);
        RandomAccessFile file = new RandomAccessFile(fileName, "rw");
        System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength));
        CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1);
        long pos = 0;
        for (int i = 0; i < THREAD_COUNT; i++) {
            long endPos = pos + packageLength;
            if (leftLength > 0) {
                endPos++;
                leftLength--;
            }
            new Thread(new DownloadThread(latch, url, file, pos, endPos)).start();
            pos = endPos;
        }
        new Thread(new MoniterThread(latch)).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
private static URL handleRedirectUrl(URL url) {
        try {
            URLConnection cn = url.openConnection();
            Utils.setHeader(cn);
            if (!(cn instanceof HttpURLConnection)) {
                return url;
            }
            HttpURLConnection hcn = (HttpURLConnection) cn;
            hcn.setInstanceFollowRedirects(false);
            int resCode = hcn.getResponseCode();
            if (resCode == 200) {
                System.out.println("URL: " + url);
                return url;
            }
            String location = hcn.getHeaderField("Location");
            hcn.disconnect();
            return handleRedirectUrl(new URL(location.replace(" ", "%20")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }
@SuppressWarnings("unchecked")
    public static <T> List<T> getServices(String service) {
        String serviceUri = "META-INF/services/" + service;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            Enumeration<URL> urls = loader.getResources(serviceUri);
            if (urls.hasMoreElements()) {
                List<T> services = new ArrayList<T>(1);
                Set<String> keys = new HashSet<String>(20);
                do {
                    URL url = urls.nextElement();
                    if (_LOG.isLoggable(Level.FINEST)) {
                        _LOG.finest("Processing: " + url);
                    }
                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        try {
                            while (true) {
                                String line = in.readLine();
                                if (line == null) break;
                                String className = _parseLine(line);
                                if (className != null && keys.add(className)) {
                                    T instance = (T) _getClass(loader, className);
                                    services.add(instance);
                                }
                            }
                        } finally {
                            in.close();
                        }
                    } catch (Exception e) {
                        if (_LOG.isLoggable(Level.WARNING)) {
                            _LOG.log(Level.WARNING, "Error parsing URL: " + url, e);
                        }
                    }
                } while (urls.hasMoreElements());
                if (services.size() == 1) return Collections.singletonList(services.get(0));
                return Collections.unmodifiableList(services);
            }
        } catch (IOException e) {
            if (_LOG.isLoggable(Level.SEVERE)) {
                _LOG.log(Level.SEVERE, "Error loading Resource: " + serviceUri, e);
            }
        }
        return Collections.emptyList();
    }
private static JvUndoableTableModel CSVReader(String filepath) throws IOException {
        try {
            URI url = new URI(filepath);
            return CSVReader(url.toURL().openStream());
        } catch (URISyntaxException ex) {
            File file = new File(filepath);
            return CSVReader(file);
        }
    }
@Override
    public void run() {
        String src = null;
        try {
            src = File.readText(srcFile);
            if (Char.isValidate(src)) {
                java.net.URL url = new java.net.URL(ConsEnv.HOMEPAGE + "code/code0001.ashx");
                java.util.HashMap<String, String> params = new java.util.HashMap<String, String>();
                String ext = File.getExtension(srcFile.getName());
                if (Char.isValidate(ext) && ext.charAt(0) == '.') {
                    ext = ext.substring(1);
                }
                params.put("l", ext);
                params.put("i", "1");
                params.put("n", ck_LineNbr.isSelected() ? "1" : "0");
                params.put("u", ck_LinkUri.isSelected() ? "1" : "0");
                params.put("t", cb_TagStyle.getSelectedItem() + "");
                String tab = tf_TabCount.getText().trim();
                if (java.util.regex.Pattern.matches("^\\d+$", tab)) {
                    tab = "4";
                }
                params.put("s", tab);
                params.put("o", "html");
                params.put("c", src);
                java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection();
                java.io.InputStream stream = Http.post(con, params);
                ep_CodeView.setContentType(con.getContentType());
                src = File.readText(stream);
                stream.close();
                con.disconnect();
                java.io.File tmpFile = java.io.File.createTempFile("src_", ".html");
                tmpFile.deleteOnExit();
                File.saveText(tmpFile, src);
                ep_CodeView.setPage(tmpFile.toURI().toURL());
                ep_CodeView.setFont(ep_CodeView.getFont().deriveFont(20f));
            }
        } catch (Exception exp) {
            Logs.exception(exp);
        }
    }
@Override
    public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException {
        String key = logFileNameExtractor.getFileName(fileStatus);
        int wasWritten = 0;
        FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key);
        RollBackOutputStream outputStream = null;
        File file = null;
        try {
            file = getOutputFile(key);
            lastWrittenFile = file;
            outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true);
            outputStream.mark();
            wasWritten = IOUtils.copy(input, outputStream);
            if (postWriteAction != null) {
                postWriteAction.run(wasWritten);
            }
        } catch (Throwable t) {
            LOG.error(t.toString(), t);
            if (outputStream != null && wasWritten > 0) {
                LOG.error("Rolling back file " + file.getAbsolutePath());
                try {
                    outputStream.rollback();
                } catch (IOException e) {
                    throwException(e);
                } catch (InterruptedException e) {
                    throw e;
                }
            }
            throwException(t);
        } finally {
            try {
                fileOutputStreamPool.releaseFile(key);
            } catch (IOException e) {
                throwException(e);
            }
        }
        return wasWritten;
    }
public String stringOfUrl(String addr) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        IOUtils.copy(url.openStream(), output);
        return output.toString();
    }
public static void refresh() {
        URL[] urls = Constants.Wiki2xhtml.getUpdateURLs();
        content.setLength(0);
        InputStream is = null;
        BufferedReader br = null;
        for (int i = 0; i < urls.length; i++) {
            try {
                is = urls[i].openStream();
                br = new BufferedReader(new InputStreamReader(is));
                String s;
                while ((s = br.readLine()) != null) {
                    if (s.length() == 0) continue;
                    if (s.startsWith("--")) break;
                    content.append(s + '\n');
                }
                is.close();
                break;
            } catch (FileNotFoundException e) {
                System.err.println("File not found: " + urls[i].getHost() + urls[i].getPath());
            } catch (IOException e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
    }
private void fileCopy(final File src, final File dest) throws IOException {
        final FileChannel srcChannel = new FileInputStream(src).getChannel();
        final FileChannel dstChannel = new FileOutputStream(dest).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
    }
public String getmd5(String password) {
        String pwHash = "";
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(password.getBytes());
            byte[] b = md.digest();
            for (int i = 0; i < b.length; i++) {
                pwHash += Integer.toString((b[i] & 0xFF) + 0x100, 16).substring(1);
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.fatal("MD5 Hash Algorithm not found", ex);
        }
        Logger.info("PWHash erzeugt und wird übergeben");
        return pwHash;
    }
public static void reset() throws Exception {
        Session session = DataStaticService.getHibernateSessionFactory().openSession();
        try {
            Connection connection = session.connection();
            try {
                Statement statement = connection.createStatement();
                try {
                    statement.executeUpdate("delete from Tag");
                    connection.commit();
                } finally {
                    statement.close();
                }
            } catch (HibernateException e) {
                connection.rollback();
                throw new Exception(e);
            } catch (SQLException e) {
                connection.rollback();
                throw new Exception(e);
            }
        } catch (SQLException e) {
            throw new Exception(e);
        } finally {
            session.close();
        }
    }
public static void copyFile(String file1, String file2) {
        File filedata1 = new java.io.File(file1);
        if (filedata1.exists()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file1));
                try {
                    int read;
                    while ((read = in.read()) != -1) {
                        out.write(read);
                    }
                    out.flush();
                } catch (IOException ex1) {
                    ex1.printStackTrace();
                } finally {
                    out.close();
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
public void ftpUpload() {
        FTPClient ftpclient = null;
        InputStream is = null;
        try {
            ftpclient = new FTPClient();
            ftpclient.connect(host, port);
            if (logger.isDebugEnabled()) {
                logger.debug("FTP连接远程服务器：" + host);
            }
            ftpclient.login(user, password);
            if (logger.isDebugEnabled()) {
                logger.debug("登陆用户：" + user);
            }
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpclient.changeWorkingDirectory(remotePath);
            is = new FileInputStream(localPath + File.separator + filename);
            ftpclient.storeFile(filename, is);
            logger.info("上传文件结束...路径：" + remotePath + "，文件名：" + filename);
            is.close();
            ftpclient.logout();
        } catch (IOException e) {
            logger.error("上传文件失败", e);
        } finally {
            if (ftpclient.isConnected()) {
                try {
                    ftpclient.disconnect();
                } catch (IOException e) {
                    logger.error("断开FTP出错", e);
                }
            }
            ftpclient = null;
        }
    }
public static ArrayList search(String query) throws Exception {
        ArrayList list = new ArrayList();
        String url = "http://hypem.com/playlist/search/" + query + "/xml/1/list.xspf";
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
        XmlNode node = XmlLoader.load(conn.getInputStream());
        XmlNode tracks[] = node.getFirstChild("trackList").getChild("track");
        for (int i = 0; i < tracks.length; i++) {
            String location = decrypt(tracks[i].getFirstChild("location").getText());
            String annotation = tracks[i].getFirstChild("annotation").getText().replaceAll("[\r\n]", "");
            list.add(location);
            System.out.print("found in Hypem: ");
            System.out.print(annotation);
            System.out.print(", ");
            System.out.println(location);
        }
        return list;
    }
public ForkJavaProject(String projectName, Class<?> activatorClass) {
        this.activatorClass = activatorClass;
        try {
            IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
            this.prj = rootWorkspace.getProject(projectName);
            if (this.prj.exists()) {
                this.prj.delete(true, true, new NullProgressMonitor());
            }
            this.prj.create(new NullProgressMonitor());
            this.prj.open(new NullProgressMonitor());
            IProjectDescription description = this.prj.getDescription();
            description.setNatureIds(new String[] { "org.eclipse.jdt.core.javanature" });
            this.prj.setDescription(description, new NullProgressMonitor());
            createProjectDir(Constants.Dirs.DIR_MAIN_JAVA);
            createProjectDir(Constants.Dirs.DIR_CONFIG);
            createProjectDir(Constants.Dirs.DIR_MAIN_RESOURCES);
            createProjectDir(Constants.Dirs.DIR_MODELS);
            createProjectDir(Constants.Dirs.DIR_TESTS_JAVA);
            createProjectDir(Constants.Dirs.DIR_TESTS_RESOURCES);
            createProjectDir(Constants.Dirs.DIR_CLASSES);
            createProjectDir(Constants.Dirs.DIR_LIB);
            this.prj.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
            this.javaProject = JavaCore.create(this.prj);
            if (this.javaProject.exists() && !this.javaProject.isOpen()) {
                this.javaProject.open(new NullProgressMonitor());
            }
            File javaHome = new File(System.getProperty("java.home"));
            IPath jreLibPath = new Path(javaHome.getPath()).append("lib").append("rt.jar");
            this.javaProject.setOutputLocation(prj.getFolder(Constants.Dirs.DIR_CLASSES).getFullPath(), new NullProgressMonitor());
            JavaCore.setClasspathVariable("JRE_LIB", jreLibPath, new NullProgressMonitor());
            this.javaProject.setRawClasspath(getProjectClassPath(), new NullProgressMonitor());
        } catch (CoreException e) {
            Activator.getDefault().getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID, "An exception has been thrown while creating Project", e));
        }
    }
private void sendBinaryFile(File file) throws IOException, CVSException {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            if (m_bCompressFiles) {
                GZIPOutputStream gzipOut = null;
                InputStream gzipIn = null;
                File gzipFile = null;
                try {
                    gzipFile = File.createTempFile("javacvs", "tmp");
                    gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile)));
                    int b;
                    while ((b = in.read()) != -1) gzipOut.write((byte) b);
                    gzipOut.close();
                    long gzipLength = gzipFile.length();
                    sendLine("z" + Long.toString(gzipLength));
                    gzipIn = new BufferedInputStream(new FileInputStream(gzipFile));
                    for (long i = 0; i < gzipLength; i++) {
                        b = gzipIn.read();
                        if (b == -1) throw new EOFException();
                        m_Out.write((byte) b);
                    }
                } finally {
                    if (gzipOut != null) gzipOut.close();
                    if (gzipIn != null) gzipIn.close();
                    if (gzipFile != null) gzipFile.delete();
                }
            } else {
                long nLength = file.length();
                sendLine(Long.toString(nLength));
                for (long i = 0; i < nLength; i++) {
                    int b = in.read();
                    if (b == -1) throw new EOFException();
                    m_Out.write((byte) b);
                }
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
public boolean openConnection(String url, Properties props) throws SQLException {
        try {
            Class.forName(RunConfig.getInstance().getDriverNameJDBC());
            if (url == null) url = RunConfig.getInstance().getConnectionUrlJDBC();
            connection = DriverManager.getConnection(url, props);
            if (statementTable == null) statementTable = new Hashtable<String, PreparedStatement>();
            if (resultTable == null) resultTable = new Hashtable<String, ResultSet>();
            clearStatus();
            return true;
        } catch (Exception e) {
            setStatus(e);
            return false;
        }
    }