semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void copyFile(File in, File out) {
        try {
            FileChannel sourceChannel = new FileInputStream(in).getChannel();
            FileChannel destinationChannel = new FileOutputStream(out).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
            sourceChannel.close();
            destinationChannel.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
@Override
    public InputStream getInputStream() throws IOException {
        if (dfos == null) {
            int deferredOutputStreamThreshold = Config.getInstance().getDeferredOutputStreamThreshold();
            dfos = new DeferredFileOutputStream(deferredOutputStreamThreshold, Definitions.PROJECT_NAME, "." + Definitions.TMP_EXTENSION);
            try {
                IOUtils.copy(is, dfos);
            } finally {
                dfos.close();
            }
        }
        return dfos.getDeferredInputStream();
    }
public boolean refresh() {
        try {
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            if (credential != null) conn.setRequestProperty("Authorization", credential);
            conn.connect();
            int status = ((HttpURLConnection) conn).getResponseCode();
            if (status == 401 || status == 403) errorMessage = (credential == null ? PASSWORD_MISSING : PASSWORD_INCORRECT); else if (status == 404) errorMessage = NOT_FOUND; else if (status != 200) errorMessage = COULD_NOT_RETRIEVE; else {
                InputStream in = conn.getInputStream();
                byte[] httpData = TinyWebServer.slurpContents(in, true);
                synchronized (this) {
                    data = httpData;
                    dataProvider = null;
                }
                errorMessage = null;
                refreshDate = new Date();
                String owner = conn.getHeaderField(OWNER_HEADER_FIELD);
                if (owner != null) setLocalAttr(OWNER_ATTR, owner);
                store();
                return true;
            }
        } catch (UnknownHostException uhe) {
            errorMessage = NO_SUCH_HOST;
        } catch (ConnectException ce) {
            errorMessage = COULD_NOT_CONNECT;
        } catch (IOException ioe) {
            errorMessage = COULD_NOT_RETRIEVE;
        }
        return false;
    }
public TestReport runImpl() throws Exception {
        DefaultTestReport report = new DefaultTestReport(this);
        ParsedURL purl;
        try {
            purl = new ParsedURL(base);
        } catch (Exception e) {
            StringWriter trace = new StringWriter();
            e.printStackTrace(new PrintWriter(trace));
            report.setErrorCode(ERROR_CANNOT_PARSE_URL);
            report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_CANNOT_PARSE_URL, new String[] { "null", base, trace.toString() })) });
            report.setPassed(false);
            return report;
        }
        byte[] data = new byte[5];
        int num = 0;
        try {
            InputStream is = purl.openStream();
            num = is.read(data);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < num; i++) {
            int val = ((int) data[i]) & 0xFF;
            if (val < 16) {
                sb.append("0");
            }
            sb.append(Integer.toHexString(val) + " ");
        }
        String info = ("CT: " + purl.getContentType() + " CE: " + purl.getContentEncoding() + " DATA: " + sb + "URL: " + purl);
        if (ref.equals(info)) {
            report.setPassed(true);
            return report;
        }
        report.setErrorCode(ERROR_WRONG_RESULT);
        report.setDescription(new TestReport.Entry[] { new TestReport.Entry(TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null), TestMessages.formatMessage(ERROR_WRONG_RESULT, new String[] { info, ref })) });
        report.setPassed(false);
        return report;
    }
public static void copyFile(File srcFile, File destFile) throws IOException {
        InputStream src = new FileInputStream(srcFile);
        OutputStream dest = new FileOutputStream(destFile);
        byte buffer[] = new byte[1024];
        int read = 1;
        while (read > 0) {
            read = src.read(buffer);
            if (read > 0) {
                dest.write(buffer, 0, read);
            }
        }
        src.close();
        dest.close();
    }
public static void assertEquals(String xmlpath, Object actualObject) throws Exception {
        InputStreamReader isr;
        try {
            isr = new FileReader(xmlpath);
        } catch (FileNotFoundException e) {
            URL url = AssertHelper.class.getClassLoader().getResource(xmlpath);
            if (null != url) {
                try {
                    isr = new InputStreamReader(url.openStream());
                } catch (Exception e1) {
                    throw new AssertionFailedError("Unable to find output xml : " + xmlpath);
                }
            } else {
                throw new AssertionFailedError("Could not read output xml : " + xmlpath);
            }
        }
        DOMParser parser = new DOMParser();
        parser.parse(new InputSource(isr));
        Document document = parser.getDocument();
        try {
            assertEqual(document.getDocumentElement(), actualObject);
        } catch (AssertionFailedError e) {
            String message = null;
            if (null != e.getCause()) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath);
            Iterator iter = nodestack.iterator();
            while (iter.hasNext()) {
                sbf.append(" -> " + ((Object[]) iter.next())[0]);
                iter.remove();
            }
            AssertionFailedError a = new AssertionFailedError(sbf.toString());
            a.setStackTrace(e.getStackTrace());
            throw a;
        } catch (Exception e) {
            String message = null;
            if (null != e.getCause()) {
                message = e.getCause().getMessage();
            } else {
                message = e.getMessage();
            }
            StringBuffer sbf = new StringBuffer(message + " \n " + xmlpath);
            Iterator iter = nodestack.iterator();
            while (iter.hasNext()) {
                sbf.append(" -> " + ((Object[]) iter.next())[0]);
                iter.remove();
            }
            Exception ex = new Exception(sbf.toString());
            ex.setStackTrace(e.getStackTrace());
            throw ex;
        }
    }
public void generateHtmlPage(String real_filename, String url_filename) {
        String str_content = "";
        URL m_url = null;
        URLConnection m_urlcon = null;
        try {
            m_url = new URL(url_filename);
            m_urlcon = m_url.openConnection();
            InputStream in_stream = m_urlcon.getInputStream();
            byte[] bytes = new byte[1];
            Vector v_bytes = new Vector();
            while (in_stream.read(bytes) != -1) {
                v_bytes.add(bytes);
                bytes = new byte[1];
            }
            byte[] all_bytes = new byte[v_bytes.size()];
            for (int i = 0; i < v_bytes.size(); i++) all_bytes[i] = ((byte[]) v_bytes.get(i))[0];
            str_content = new String(all_bytes, "GBK");
        } catch (Exception urle) {
        }
        try {
            oaFileOperation file_control = new oaFileOperation();
            file_control.writeFile(str_content, real_filename, true);
            String strPath = url_filename.substring(0, url_filename.lastIndexOf("/") + 1);
            String strUrlFileName = url_filename.substring(url_filename.lastIndexOf("/") + 1);
            if (strUrlFileName.indexOf(".jsp") > 0) {
                strUrlFileName = strUrlFileName.substring(0, strUrlFileName.indexOf(".jsp")) + "_1.jsp";
                m_url = new URL(strPath + strUrlFileName);
                m_url.openConnection();
            }
            intWriteFileCount++;
            intWriteFileCount = (intWriteFileCount > 100000) ? 0 : intWriteFileCount;
        } catch (Exception e) {
        }
        m_urlcon = null;
    }
@Override
    public boolean checkConnection() {
        int status = 0;
        try {
            URL url = new URL(TupeloProxy.endpoint);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            status = conn.getResponseCode();
        } catch (Exception e) {
            logger.severe("Connection test failed with code:" + status);
            e.printStackTrace();
        }
        if (status < 200 || status >= 400) return false;
        String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password;
        return true;
    }
public static byte[] decrypt(byte[] ciphertext, byte[] key) throws IOException {
        CryptInputStream in = new CryptInputStream(new ByteArrayInputStream(ciphertext), new SerpentEngine(), key);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        IOUtils.copy(in, bout);
        return bout.toByteArray();
    }
public static String uploadFile(String urlmsg, String path, String name) {
        try {
            System.out.println("Sending: " + urlmsg);
            URL url = new URL(urlmsg);
            if (url == null) {
                System.out.println("Resource " + urlmsg + " not found");
                return null;
            }
            File outFile = new File(path, name);
            FileOutputStream out = new FileOutputStream(outFile);
            InputStream in = url.openStream();
            byte[] buf = new byte[4 * 1024];
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
            out.close();
            in.close();
            return path + name;
        } catch (Exception e) {
            throw new GROBIDServiceException("An exception occured while running Grobid.", e);
        }
    }
public static String getMD5EncodedString(String strIn) {
        try {
            java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(strIn.getBytes());
            byte[] digest = md5.digest();
            StringBuffer hexString = new StringBuffer();
            for (byte aDigest : digest) {
                hexString.append(Integer.toHexString(0xFF & aDigest));
            }
            return hexString.toString();
        } catch (java.security.NoSuchAlgorithmException n) {
            return "";
        }
    }
public static Font createTrueTypeFont(URL url, int style, float size) {
        Font f = null;
        try {
            f = Font.createFont(Font.TRUETYPE_FONT, url.openStream());
        } catch (IOException e) {
            System.err.println("ERROR: " + url + " is not found or can not be read");
            f = new Font("Verdana", 0, 0);
        } catch (FontFormatException e) {
            System.err.println("ERROR: " + url + " is not a valid true type font");
            f = new Font("Verdana", 0, 0);
        }
        return f.deriveFont(style, size);
    }
@NotNull
    private Properties loadProperties() {
        File file = new File(homeLocator.getHomeDir(), configFilename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e);
            }
        }
        if (!file.canRead() || !file.canWrite()) {
            throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath());
        }
        if (lastModifiedByUs < file.lastModified()) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("File \"" + file + "\" is newer on disk. Read it ...");
            }
            Properties properties = new Properties();
            try {
                FileInputStream in = new FileInputStream(file);
                try {
                    properties.loadFromXML(in);
                } catch (InvalidPropertiesFormatException e) {
                    FileOutputStream out = new FileOutputStream(file);
                    try {
                        properties.storeToXML(out, comment);
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e);
            }
            this.lastModifiedByUs = file.lastModified();
            this.properties = properties;
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("... read done.");
            }
        }
        assert this.properties != null;
        return this.properties;
    }
private String md5(String input) {
        MessageDigest md5Digest;
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new UserException("could not get a md5 message digest", e);
        }
        md5Digest.update(input.getBytes());
        return new String(md5Digest.digest());
    }
void readData(URL url) throws IOException {
        int i = 0, j = 0, k = 0;
        double xvalue, yvalue;
        double xindex, yindex;
        InputStream is = url.openStream();
        is.mark(0);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        int columnsize = 0;
        double temp_prev = 0;
        double temp_new = 0;
        int first = 0;
        s = br.readLine();
        StringTokenizer st = new StringTokenizer(s);
        columnsize = Integer.parseInt(st.nextToken());
        data = new double[columnsize][100][100];
        isize = 0;
        jsize = 0;
        while ((s = br.readLine()) != null) {
            st = new StringTokenizer(s);
            for (k = 0; k < columnsize; k++) {
                temp_new = Double.parseDouble(st.nextToken());
                if (first == 0) {
                    temp_prev = temp_new;
                    first = 1;
                }
                if (k == 0) {
                    if (temp_new != temp_prev) {
                        temp_prev = temp_new;
                        i++;
                        j = 0;
                    }
                }
                data[k][i][j] = temp_new;
            }
            j++;
        }
        isize = i + 1;
        jsize = j;
    }
@Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            final HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            final String contextPath = httpServletRequest.getContextPath() + "/";
            final String requestURI = httpServletRequest.getRequestURI();
            if (requestURI.startsWith(contextPath)) {
                final String filterURI = requestURI.substring(contextPath.length());
                final String filterPath = getFilterPath();
                if (filterURI.startsWith(filterPath)) {
                    final String targetURI = filterURI.substring(filterPath.length());
                    for (final Entry<String, String> entry : mapping.entrySet()) {
                        final String key = entry.getKey();
                        final String value = entry.getValue();
                        if (targetURI.startsWith(key) && (targetURI.length() > key.length())) {
                            final String resourceName = value + targetURI.substring(key.length());
                            InputStream is = null;
                            try {
                                is = getClass().getResourceAsStream("/" + resourceName);
                                if (is != null) {
                                    IOUtils.copy(is, httpServletResponse.getOutputStream());
                                    httpServletResponse.flushBuffer();
                                    break;
                                } else {
                                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                                    break;
                                }
                            } catch (final IOException ioex) {
                                throw new ServletException("Error serving resource [" + resourceName + "].", ioex);
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        }
                    }
                } else {
                    chain.doFilter(request, response);
                }
            } else {
                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
protected int deleteBitstreamInfo(int id, Connection conn) {
        PreparedStatement stmt = null;
        int numDeleted = 0;
        try {
            stmt = conn.prepareStatement(DELETE_BITSTREAM_INFO);
            stmt.setInt(1, id);
            numDeleted = stmt.executeUpdate();
            if (numDeleted > 1) {
                conn.rollback();
                throw new IllegalStateException("Too many rows deleted! Number of rows deleted: " + numDeleted + " only one row should be deleted for bitstream id " + id);
            }
        } catch (SQLException e) {
            LOG.error("Problem deleting bitstream. " + e.getMessage(), e);
            throw new RuntimeException("Problem deleting bitstream. " + e.getMessage(), e);
        } finally {
            cleanup(stmt);
        }
        return numDeleted;
    }
public static String hashMD5(String password) {
        String hashword = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            BigInteger hash = new BigInteger(1, md5.digest());
            hashword = hash.toString(16);
        } catch (NoSuchAlgorithmException nsae) {
        }
        return hashword;
    }
private static String fetchFile(String urlLocation) {
        try {
            URL url = new URL(urlLocation);
            URLConnection conn = url.openConnection();
            File tempFile = File.createTempFile("marla", ".jar");
            OutputStream os = new FileOutputStream(tempFile);
            IOUtils.copy(conn.getInputStream(), os);
            return tempFile.getAbsolutePath();
        } catch (IOException ex) {
            throw new MarlaException("Unable to fetch file '" + urlLocation + "' from server", ex);
        }
    }
public static String loadSite(String spec) throws IOException {
        URL url = new URL(spec);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String output = "";
        String str;
        while ((str = in.readLine()) != null) {
            output += str + "\n";
        }
        in.close();
        return output;
    }
@TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Tests Proxy functionality. Indirect test.", method = "Proxy", args = { java.net.Proxy.Type.class, java.net.SocketAddress.class })
    @BrokenTest("the host address isn't working anymore")
    public void test_openConnectionLjava_net_Proxy() throws IOException {
        SocketAddress addr1 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 808);
        SocketAddress addr2 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 1080);
        Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
        Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr2);
        Proxy proxyList[] = { proxy1, proxy2 };
        for (int i = 0; i < proxyList.length; ++i) {
            String posted = "just a test";
            URL u = new URL("http://" + Support_Configuration.ProxyServerTestHost + "/cgi-bin/test.pl");
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u.openConnection(proxyList[i]);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-length", String.valueOf(posted.length()));
            OutputStream out = conn.getOutputStream();
            out.write(posted.getBytes());
            out.close();
            conn.getResponseCode();
            InputStream is = conn.getInputStream();
            String response = "";
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = is.read(b)) > 0) {
                response += new String(b, 0, count);
            }
            assertTrue("Response to POST method invalid", response.equals(posted));
        }
        URL httpUrl = new URL("http://abc.com");
        URL jarUrl = new URL("jar:" + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp"));
        URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress + "/nettest.txt");
        URL fileUrl = new URL("file://abc");
        URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl };
        for (int i = 0; i < urlList.length; ++i) {
            try {
                urlList[i].openConnection(null);
            } catch (IllegalArgumentException iae) {
            }
        }
        fileUrl.openConnection(Proxy.NO_PROXY);
    }
public static KeyStore createKeyStore(final URL url, final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
        if (url == null) throw new IllegalArgumentException("Keystore url may not be null");
        LOG.debug("Initializing key store");
        KeyStore keystore = null;
        if (url.getFile().endsWith(".p12")) keystore = KeyStore.getInstance("pkcs12"); else keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
        return keystore;
    }
protected QName _getServiceName(String wsdlLocation) throws IOException, WSDLException {
        URL url = new URL(wsdlLocation);
        InputStream is = null;
        QName service = null;
        try {
            is = url.openStream();
            WSDLReader reader = WSDLFactory.newInstance().newWSDLReader();
            Definition def = reader.readWSDL(null, new InputSource(is));
            Map services = def.getServices();
            if (services.size() == 1) {
                javax.wsdl.Service se = (javax.wsdl.Service) services.values().iterator().next();
                service = se.getQName();
            }
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
        return service;
    }
public void extractSong(Song s, File dir) {
        FileInputStream fin = null;
        FileOutputStream fout = null;
        File dest = new File(dir, s.file.getName());
        if (dest.equals(s.file)) return;
        byte[] buf = new byte[COPY_BLOCKSIZE];
        try {
            fin = new FileInputStream(s.file);
            fout = new FileOutputStream(dest);
            int read = 0;
            do {
                read = fin.read(buf);
                if (read > 0) fout.write(buf, 0, read);
            } while (read > 0);
        } catch (IOException ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog("xtract.error");
        } finally {
            try {
                fin.close();
                fout.close();
            } catch (Exception ex) {
            }
        }
    }