semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private final void findSubclasses(URL location, String packageName, Class superClass, Set setOfClasses) {
        synchronized (results) {
            String fqcn = searchClass.getName();
            List knownLocations = new ArrayList();
            knownLocations.add(location);
            for (int loc = 0; loc < knownLocations.size(); loc++) {
                URL url = (URL) knownLocations.get(loc);
                File directory = new File(url.getFile());
                if (directory.exists()) {
                    File[] files = directory.listFiles(CLASSES_ONLY);
                    for (int i = 0; i < files.length; i++) {
                        String filename = files[i].getName();
                        String classname = filename.substring(0, filename.length() - 6);
                        try {
                            if (!fqcn.equals(packageName + "." + classname)) {
                                Class c = callClassForName(packageName + "." + classname);
                                manageClass(setOfClasses, superClass, c, url);
                            }
                        } catch (Throwable t) {
                            errors.add(t);
                        }
                    }
                } else {
                    try {
                        JarURLConnection conn = (JarURLConnection) url.openConnection();
                        JarFile jarFile = conn.getJarFile();
                        Enumeration e = jarFile.entries();
                        while (e.hasMoreElements()) {
                            JarEntry entry = (JarEntry) e.nextElement();
                            String entryname = entry.getName();
                            if (!entry.isDirectory() && entryname.endsWith(".class")) {
                                String classname = entryname.substring(0, entryname.length() - 6);
                                if (classname.startsWith("/")) classname = classname.substring(1);
                                classname = classname.replace('/', '.');
                                try {
                                    if (!fqcn.equals(classname)) {
                                        Class c = callClassForName(classname);
                                        manageClass(setOfClasses, superClass, c, url);
                                    }
                                } catch (Throwable t) {
                                    errors.add(t);
                                }
                            }
                        }
                    } catch (IOException ioex) {
                        errors.add(ioex);
                    }
                }
            }
        }
    }
private void uploadFile() {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(actionUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            DataOutputStream ds = new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + newName + "\"" + end);
            ds.writeBytes(end);
            FileInputStream fStream = new FileInputStream(uploadFile);
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            while ((length = fStream.read(buffer)) != -1) {
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            fStream.close();
            ds.flush();
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            showDialog(b.toString().trim());
            ds.close();
        } catch (Exception e) {
            showDialog("" + e);
        }
    }
private static void downloadImages(String uriPrefix, String fileWithListOfImages, String outputDir) throws Exception {
        Properties list = new Properties();
        list.load(new FileInputStream(fileWithListOfImages));
        long current = 0;
        long startTime = System.currentTimeMillis();
        System.out.println("Downloading files from " + uriPrefix + " to " + outputDir);
        System.out.println("Total " + list.size() + " files, think of 1 sec per file");
        System.out.println("Images with the same size as the 'no-image' image are ignored and not displayed");
        for (Iterator<Object> it = list.keySet().iterator(); it.hasNext(); ) {
            String urlString = it.next().toString().replace('\\', '/');
            if (urlString.contains("=")) throw new Exception("Symbol '=' found in file names, while it is reserved for denoting '/' in flat-file names");
        }
        for (Iterator<Object> it = list.keySet().iterator(); it.hasNext(); ) {
            String urlString = it.next().toString().replace('\\', '/');
            URL url = new URL(uriPrefix + urlString);
            File file = new File(outputDir + "/" + imageNameToFileName(urlString));
            current++;
            if (!file.exists()) {
                try {
                    BufferedInputStream in = new BufferedInputStream(url.openStream(), 64000);
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file), 64000);
                    int c;
                    while ((c = in.read()) != -1) {
                        out.write(c);
                    }
                    out.close();
                    in.close();
                    System.out.print(current + " /" + list.size() + ". " + file.getName() + ", ");
                    System.out.println("saved");
                } catch (Exception e) {
                    System.out.print(current + " /" + list.size() + ". " + file.getName() + ", FAILED, error: " + e.getMessage());
                }
            } else {
                System.out.print(current + " /" + list.size() + ". " + file.getName() + ", ");
                System.out.println("already exists");
            }
            if (current / 100 == current / 100.0) {
                long delta = (System.currentTimeMillis() - startTime);
                System.out.println("Total time " + delta + " ms, " + (delta / current) + " ms/file");
            }
        }
        long delta = (System.currentTimeMillis() - startTime);
        System.out.println("Total time " + delta + " ms, " + (delta / list.size()) + " ms/file");
    }
protected synchronized InputStream openURLConnection(StreamDataSetDescriptor dsd, Datum start, Datum end, StringBuffer additionalFormData) throws DasException {
        String[] tokens = dsd.getDataSetID().split("\\?|\\&");
        String dataSetID = tokens[1];
        try {
            String formData = createFormDataString(dataSetID, start, end, additionalFormData);
            if (dsd.isRestrictedAccess()) {
                key = server.getKey("");
                if (key != null) {
                    formData += "&key=" + URLEncoder.encode(key.toString(), "UTF-8");
                }
            }
            if (redirect) {
                formData += "&redirect=1";
            }
            URL serverURL = this.server.getURL(formData);
            this.lastRequestURL = String.valueOf(serverURL);
            DasLogger.getLogger(DasLogger.DATA_TRANSFER_LOG).info("opening " + serverURL.toString());
            URLConnection urlConnection = serverURL.openConnection();
            urlConnection.connect();
            String contentType = urlConnection.getContentType();
            if (!contentType.equalsIgnoreCase("application/octet-stream")) {
                BufferedReader bin = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line = bin.readLine();
                String message = "";
                while (line != null) {
                    message = message.concat(line);
                    line = bin.readLine();
                }
                throw new DasIOException(message);
            }
            InputStream in = urlConnection.getInputStream();
            if (isLegacyStream()) {
                return processLegacyStream(in);
            } else {
                throw new UnsupportedOperationException();
            }
        } catch (IOException e) {
            throw new DasIOException(e);
        }
    }
protected String getCache() throws IOException {
        if (cache == null) {
            URL url = ((URI) hasContent()).toURL();
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) ;
            in.close();
            cache = inputLine;
        }
        return cache;
    }
@Override
    public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException {
        URL baseUrl = this.baseUrl;
        if (this.baseUrl == null) {
            baseUrl = url;
        }
        InputStream in;
        try {
            in = url.openStream();
        } catch (IOException ex) {
            throw new FileNotFoundException("Can't read " + url);
        }
        return load(new BufferedInputStream(in), baseUrl);
    }
protected static List<Pattern> getBotPatterns() {
        List<Pattern> patterns = new ArrayList<Pattern>();
        try {
            Enumeration<URL> urls = AbstractPustefixRequestHandler.class.getClassLoader().getResources("META-INF/org/pustefixframework/http/bot-user-agents.txt");
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                InputStream in = url.openStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.startsWith("#")) {
                        Pattern pattern = Pattern.compile(line);
                        patterns.add(pattern);
                    }
                }
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException("Error reading bot user-agent configuration", e);
        }
        return patterns;
    }
public static void main(String[] args) throws Exception {
        FileChannel fc = new FileOutputStream("data.txt").getChannel();
        fc.write(ByteBuffer.wrap("Some text ".getBytes()));
        fc.close();
        fc = new RandomAccessFile("data.txt", "rw").getChannel();
        fc.position(fc.size());
        fc.write(ByteBuffer.wrap("Some more".getBytes()));
        fc.close();
        fc = new FileInputStream("data.txt").getChannel();
        ByteBuffer buff = ByteBuffer.allocate(BSIZE);
        fc.read(buff);
        buff.flip();
        while (buff.hasRemaining()) System.out.print((char) buff.get());
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        String requestURI = req.getRequestURI();
        logger.info("The requested URI: {}", requestURI);
        String parameter = requestURI.substring(requestURI.lastIndexOf(ARXIVID_ENTRY) + ARXIVID_ENTRY_LENGTH);
        int signIndex = parameter.indexOf(StringUtil.ARXIVID_SEGMENTID_DELIMITER);
        String arxivId = signIndex != -1 ? parameter.substring(0, signIndex) : parameter;
        String segmentId = signIndex != -1 ? parameter.substring(signIndex + 1) : null;
        if (arxivId == null) {
            logger.error("The request with an empty arxiv id parameter");
            return;
        }
        String filePath = segmentId == null ? format("/opt/mocassin/aux-pdf/%s" + StringUtil.arxivid2filename(arxivId, "pdf")) : "/opt/mocassin/pdf/" + StringUtil.segmentid2filename(arxivId, Integer.parseInt(segmentId), "pdf");
        if (!new File(filePath).exists()) {
            filePath = format("/opt/mocassin/aux-pdf/%s", StringUtil.arxivid2filename(arxivId, "pdf"));
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(filePath);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IOUtils.copy(fileInputStream, byteArrayOutputStream);
            resp.setContentType("application/pdf");
            resp.setHeader("Content-disposition", String.format("attachment; filename=%s", StringUtil.arxivid2filename(arxivId, "pdf")));
            ServletOutputStream outputStream = resp.getOutputStream();
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.error("Error while downloading: PDF file= '{}' not found", filePath);
        } catch (IOException e) {
            logger.error("Error while downloading the PDF file", e);
        }
    }
public static void main(String[] args) {
        try {
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode("admin", "UTF-8");
            data += "&" + URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode("k", "UTF-8");
            data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("asdf", "UTF-8");
            data += "&" + URLEncoder.encode("login", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8");
            URL url = new URL("http://localhost:80/test/index.php");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
private URL retrieveFirstURL(URL url, RSLink link) {
        link.setStatus(RSLink.STATUS_WAITING);
        URL result = null;
        HttpURLConnection httpConn = null;
        BufferedReader inr = null;
        Pattern formStartPattern = Pattern.compile("<form.+action=\"");
        Pattern freeUserPattern = Pattern.compile("input type=\"submit\" value=\"Free user\"");
        Pattern formEndPattern = Pattern.compile("</form>");
        Pattern urlString = Pattern.compile("http://[a-zA-Z0-9\\.\\-/_]+");
        try {
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoOutput(false);
            httpConn.setDoInput(true);
            inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line = null;
            String urlLine = null;
            boolean freeUser = false;
            Matcher matcher = null;
            while ((line = inr.readLine()) != null) {
                if (urlLine == null) {
                    matcher = formStartPattern.matcher(line);
                    if (matcher.find()) {
                        urlLine = line;
                    }
                } else {
                    matcher = formEndPattern.matcher(line);
                    if (matcher.find()) {
                        urlLine = null;
                    } else {
                        matcher = freeUserPattern.matcher(line);
                        if (matcher.find()) {
                            freeUser = true;
                            break;
                        }
                    }
                }
            }
            if (freeUser) {
                matcher = urlString.matcher(urlLine);
                if (matcher.find()) {
                    result = new URL(matcher.group());
                }
            }
        } catch (MalformedURLException ex) {
            log("Malformed URL Exception!");
        } catch (IOException ex) {
            log("I/O Exception!");
        } finally {
            try {
                if (inr != null) inr.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
            }
            if (httpConn != null) httpConn.disconnect();
            link.setStatus(RSLink.STATUS_NOTHING);
            return result;
        }
    }
private Object[] retrieveSecondURL(URL url, RSLink link) {
        link.setStatus(RSLink.STATUS_WAITING);
        Object[] result = new Object[2];
        HttpURLConnection httpConn = null;
        BufferedReader inr = null;
        DataOutputStream outs = null;
        Pattern mirrorLinePattern = Pattern.compile("'<input.+checked.+type=\"radio\".+name=\"mirror\".+\\\\'.+\\\\'");
        Pattern mirrorUrlPattern = Pattern.compile("\\\\'.+\\\\'");
        Pattern counterPattern = Pattern.compile("var c=[0-9]+;");
        Pattern counterIntPattern = Pattern.compile("[0-9]+");
        try {
            String line = null;
            String urlLine = null;
            Integer counter = null;
            String postData = URLEncoder.encode("dl.start", "UTF-8") + "=" + URLEncoder.encode("Free", "UTF-8");
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
            httpConn.setRequestProperty("Content-Language", "en-US");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            outs = new DataOutputStream(httpConn.getOutputStream());
            outs.writeBytes(postData);
            outs.flush();
            inr = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            Matcher matcher = null;
            while ((line = inr.readLine()) != null) {
                matcher = mirrorLinePattern.matcher(line);
                if (matcher.find()) {
                    matcher = mirrorUrlPattern.matcher(line);
                    if (matcher.find()) {
                        urlLine = matcher.group().substring(2, matcher.group().length() - 2);
                        result[0] = new URL(urlLine);
                    }
                }
                matcher = counterPattern.matcher(line);
                if (matcher.find()) {
                    matcher = counterIntPattern.matcher(line);
                    if (matcher.find()) {
                        counter = new Integer(matcher.group());
                        result[1] = counter;
                    }
                }
            }
        } catch (IOException ex) {
            log("I/O Exception!");
        } finally {
            try {
                if (outs != null) outs.close();
                if (inr != null) inr.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
            }
            if (httpConn != null) httpConn.disconnect();
            link.setStatus(RSLink.STATUS_NOTHING);
            return result;
        }
    }
private void retrieveFile(URL url, RSLink link) {
        link.setStatus(RSLink.STATUS_DOWNLOADING);
        HttpURLConnection httpConn = null;
        DataOutputStream outs = null;
        BufferedInputStream bins = null;
        BufferedOutputStream bouts = null;
        try {
            String postData = URLEncoder.encode("mirror", "UTF-8") + "=" + URLEncoder.encode(url.toString(), "UTF-8");
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));
            httpConn.setRequestProperty("Content-Language", "en-US");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            outs = new DataOutputStream(httpConn.getOutputStream());
            outs.writeBytes(postData);
            outs.flush();
            Pattern mimePattern = Pattern.compile(".+/html.+");
            Matcher matcher = mimePattern.matcher(httpConn.getContentType());
            if (matcher.find()) {
                log("Can not download, maybe all RS slots are busy!");
                return;
            }
            link.setSize(httpConn.getContentLength());
            bins = new BufferedInputStream(httpConn.getInputStream(), 4096);
            bouts = new BufferedOutputStream(new FileOutputStream(link.getFile()), 4096);
            link.setStatus(RSLink.STATUS_DOWNLOADING);
            link.setDown(0);
            byte[] byteBuffer = new byte[4096];
            int count;
            while ((count = bins.read(byteBuffer)) != -1) {
                bouts.write(byteBuffer, 0, count);
                link.setDown(link.getDown() + count);
                if (!Main.start.get()) {
                    link.setStatus(RSLink.STATUS_NOTHING);
                    return;
                }
            }
            link.setStatus(RSLink.STATUS_DONE);
        } catch (IOException ex) {
            log("I/O Exception!");
            link.setStatus(RSLink.STATUS_NOTHING);
        } finally {
            try {
                if (outs != null) outs.close();
                if (bouts != null) bouts.close();
                if (bins != null) bins.close();
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "Can not close some connections:\n" + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
            }
            if (httpConn != null) httpConn.disconnect();
        }
    }
private static void execute(String fileName) throws IOException, SQLException {
        InputStream input = DatabaseConstants.class.getResourceAsStream(fileName);
        StringWriter writer = new StringWriter();
        IOUtils.copy(input, writer);
        String sql = writer.toString();
        Statement statement = connection.createStatement();
        statement.execute(sql);
    }
public void sortIndexes() {
        int i, j, count;
        int t;
        count = m_ItemIndexes.length;
        for (i = 1; i < count; i++) {
            for (j = 0; j < count - i; j++) {
                if (m_ItemIndexes[j] > m_ItemIndexes[j + 1]) {
                    t = m_ItemIndexes[j];
                    m_ItemIndexes[j] = m_ItemIndexes[j + 1];
                    m_ItemIndexes[j + 1] = t;
                }
            }
        }
    }
void setURLObject(URL url, boolean forceLoad) {
        if (url != null) {
            if (urlString != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5"));
            try {
                InputStream stream;
                stream = url.openStream();
                stream.close();
            } catch (Exception e) {
                throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0"));
            }
        }
        this.url = url;
        if (forceLoad) dispatchMessage();
    }