semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static Document getDocument(String string, String defaultCharset) {
        DOMParser parser = new DOMParser();
        try {
            URL url = new URL(string);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(10000);
            con.setUseCaches(false);
            con.addRequestProperty("_", UUID.randomUUID().toString());
            String contentType = con.getContentType();
            if (contentType == null) {
                return null;
            }
            String charsetSearch = contentType.replaceFirst("(?i).*charset=(.*)", "$1");
            String contentTypeCharset = con.getContentEncoding();
            BufferedReader reader = null;
            if (!contentType.equals(charsetSearch)) {
                contentTypeCharset = charsetSearch;
            }
            if (contentTypeCharset == null) {
                reader = new BufferedReader(new InputStreamReader(con.getInputStream(), defaultCharset));
            } else {
                reader = new BufferedReader(new InputStreamReader(con.getInputStream(), contentTypeCharset));
            }
            InputSource source = new InputSource(reader);
            parser.setFeature("http://xml.org/sax/features/namespaces", false);
            parser.parse(source);
            Document document = parser.getDocument();
            String metaTagCharset = getMetaTagCharset(document);
            if (metaTagCharset != null && !metaTagCharset.equals(contentTypeCharset)) {
                HttpURLConnection reconnection = (HttpURLConnection) url.openConnection();
                reconnection.setConnectTimeout(10000);
                reconnection.setUseCaches(false);
                reconnection.addRequestProperty("_", UUID.randomUUID().toString());
                reader = new BufferedReader(new InputStreamReader(reconnection.getInputStream(), metaTagCharset));
                source = new InputSource(reader);
                parser.setFeature("http://xml.org/sax/features/namespaces", false);
                parser.parse(source);
                document = parser.getDocument();
            }
            reader.close();
            return document;
        } catch (DOMException e) {
            if (!"UTF-8".equals(defaultCharset)) {
                return getDocument(string, "UTF-8");
            }
            return null;
        } catch (Exception ex) {
            return null;
        }
    }
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }
        FileInputStream input = new FileInputStream(srcFile);
        try {
            FileOutputStream output = new FileOutputStream(destFile);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.close(output);
            }
        } finally {
            IOUtils.close(input);
        }
        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
public static void copyURLToFile(URL source, File destination) throws IOException {
        InputStream input = source.openStream();
        try {
            FileOutputStream output = openOutputStream(destination);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.close(output);
            }
        } finally {
            IOUtils.close(input);
        }
    }
public static Checksum checksum(File file, Checksum checksum) throws IOException {
        if (file.isDirectory()) {
            throw new IllegalArgumentException("Checksums can't be computed on directories");
        }
        InputStream in = null;
        try {
            in = new CheckedInputStream(new FileInputStream(file), checksum);
            IOUtils.copy(in, NULL_OUTPUT_STREAM);
        } finally {
            IOUtils.close(in);
        }
        return checksum;
    }
public BigInteger calculateMd5(String input) throws FileSystemException {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(input.getBytes());
            byte[] messageDigest = digest.digest();
            BigInteger bigInt = new BigInteger(1, messageDigest);
            return bigInt;
        } catch (Exception e) {
            throw new FileSystemException(e);
        }
    }
@SuppressWarnings("finally")
    @Override
    public String read(EnumSensorType sensorType, Map<String, String> stateMap) {
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(getUrl());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                result.append(str);
            }
        } catch (ConnectException ce) {
            logger.error("MockupStatusCommand excute fail: " + ce.getMessage());
        } catch (Exception e) {
            logger.error("MockupStatusCommand excute fail: " + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("BufferedReader could not be closed", e);
                }
            }
            return result.toString();
        }
    }
public static final long copyFile(final File srcFile, final File dstFile, final long cpySize) throws IOException {
        if ((null == srcFile) || (null == dstFile)) return (-1L);
        final File dstFolder = dstFile.getParentFile();
        if ((!dstFolder.exists()) && (!dstFolder.mkdirs())) throw new IOException("Failed to created destination folder(s)");
        FileChannel srcChannel = null, dstChannel = null;
        try {
            srcChannel = new FileInputStream(srcFile).getChannel();
            dstChannel = new FileOutputStream(dstFile).getChannel();
            final long srcLen = srcFile.length(), copyLen = dstChannel.transferFrom(srcChannel, 0, (cpySize < 0L) ? srcLen : cpySize);
            if ((cpySize < 0L) && (copyLen != srcLen)) return (-2L);
            return copyLen;
        } finally {
            FileUtil.closeAll(srcChannel, dstChannel);
        }
    }
public GetMessages(String messageType) {
        String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetMessages";
        String rvalue = "";
        String filename = dms_home + FS + "temp" + FS + username + "messages.xml";
        try {
            String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&messagetype=" + messageType + "&filename=" + URLEncoder.encode(username, "UTF-8") + "messages.xml";
            ;
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            URL u = new URL(urldata);
            DataInputStream is = new DataInputStream(u.openStream());
            FileOutputStream os = new FileOutputStream(filename);
            int iBufSize = is.available();
            byte inBuf[] = new byte[20000 * 1024];
            int iNumRead;
            while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead);
            os.close();
            is.close();
            File f = new File(filename);
            InputStream inputstream = new FileInputStream(f);
            Document document = parser.parse(inputstream);
            NodeList nodelist = document.getElementsByTagName("message");
            int num = nodelist.getLength();
            messages = new String[num][7];
            for (int i = 0; i < num; i++) {
                messages[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageid"));
                messages[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "subject"));
                messages[i][2] = (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "firstname"))) + " " + (new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "lastname")));
                messages[i][3] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagedatetime"));
                messages[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messagefrom"));
                messages[i][5] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "messageto"));
                messages[i][6] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "documentid"));
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
        } catch (ParserConfigurationException ex) {
            System.out.println(ex);
        } catch (NullPointerException e) {
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
public Parameters getParameters(HttpExchange http) throws IOException {
        ParametersImpl params = new ParametersImpl();
        String query = null;
        if (http.getRequestMethod().equalsIgnoreCase("GET")) {
            query = http.getRequestURI().getRawQuery();
        } else if (http.getRequestMethod().equalsIgnoreCase("POST")) {
            InputStream in = new MaxInputStream(http.getRequestBody());
            if (in != null) {
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                IOUtils.copyTo(in, bytes);
                query = new String(bytes.toByteArray());
                in.close();
            }
        } else {
            throw new IOException("Method not supported " + http.getRequestMethod());
        }
        if (query != null) {
            for (String s : query.split("[&]")) {
                s = s.replace('+', ' ');
                int eq = s.indexOf('=');
                if (eq > 0) {
                    params.add(URLDecoder.decode(s.substring(0, eq), "UTF-8"), URLDecoder.decode(s.substring(eq + 1), "UTF-8"));
                }
            }
        }
        return params;
    }
public File getAppHome() {
        if (appHome == null) {
            if (System.getProperty("app.home") != null) {
                appHome = new File(System.getProperty("app.home"));
            }
            if (appHome == null) {
                URL url = Main.class.getClassLoader().getResource("com/hs/mail/container/Main.class");
                if (url != null) {
                    try {
                        JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
                        url = jarConnection.getJarFileURL();
                        URI baseURI = new URI(url.toString()).resolve("..");
                        appHome = new File(baseURI).getCanonicalFile();
                        System.setProperty("app.home", appHome.getAbsolutePath());
                    } catch (Exception ignored) {
                    }
                }
            }
            if (appHome == null) {
                appHome = new File("../.");
                System.setProperty("app.home", appHome.getAbsolutePath());
            }
        }
        return appHome;
    }
public static String md5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("utf-8"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    }
protected static Certificate[] getCurrentCertificates() throws Exception {
        Certificate[] certificate = AppletLoader.class.getProtectionDomain().getCodeSource().getCertificates();
        if (certificate == null) {
            URL location = AppletLoader.class.getProtectionDomain().getCodeSource().getLocation();
            JarURLConnection jurl = (JarURLConnection) (new URL("jar:" + location.toString() + "!/org/lwjgl/util/applet/AppletLoader.class").openConnection());
            jurl.setDefaultUseCaches(true);
            certificate = jurl.getCertificates();
        }
        return certificate;
    }
public String getSHA256Checksum(String source) {
        String checksum = "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(source.getBytes());
            byte[] byteData = md.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            System.out.println("Hex format : " + sb.toString());
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < byteData.length; i++) {
                String hex = Integer.toHexString(0xff & byteData[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            checksum = hexString.toString();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        return checksum;
    }
public String SHA1(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            sha1hash = md.digest();
            return convToHex(sha1hash);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(CMessageDigestFile.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }
private String[] getHersheyFontNames() {
        String[] fontNames = null;
        URL url = HersheyFont.class.getResource("futural.jhf");
        String protocol = url.getProtocol();
        if (protocol.equals("file")) {
            File f = new File(url.getFile());
            f = f.getParentFile();
            FilenameFilter filter = new FilenameFilter() {

                public boolean accept(File dir, String name) {
                    return name.endsWith(".jhf");
                }
            };
            String[] children = f.list(filter);
            if (children == null) {
                return null;
            }
            fontNames = new String[children.length];
            for (int i = 0; i < children.length; i++) {
                fontNames[i] = children[i].substring(0, children[i].length() - 4);
            }
        } else if (protocol.equals("jar")) {
            try {
                JarURLConnection jarURL = (JarURLConnection) url.openConnection();
                ZipFile zf = new ZipFile(jarURL.getJarFile().getName());
                Enumeration e = zf.entries();
                Vector namesVector = new Vector();
                while (e.hasMoreElements()) {
                    ZipEntry ze = (ZipEntry) e.nextElement();
                    String name = ze.getName();
                    if (name.startsWith("visad/util/") && name.endsWith(".jhf")) {
                        namesVector.add(name.substring(11));
                    }
                }
                zf.close();
                if (namesVector.size() == 0) {
                    return null;
                }
                fontNames = new String[namesVector.size()];
                for (int i = 0; i < fontNames.length; i++) {
                    String name = (String) namesVector.elementAt(i);
                    fontNames[i] = name.substring(0, name.length() - 4);
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        } else {
            System.out.println("Cannot locate the HersheyFonts.");
        }
        return fontNames;
    }
protected static DynamicJasperDesign generateJasperDesign(DynamicReport dr) throws CoreException {
        DynamicJasperDesign jd = null;
        try {
            if (dr.getTemplateFileName() != null) {
                log.info("loading template file: " + dr.getTemplateFileName());
                log.info("Attemping to find the file directly in the file system...");
                File file = new File(dr.getTemplateFileName());
                if (file.exists()) {
                    JasperDesign jdesign = JRXmlLoader.load(file);
                    jd = DJJRDesignHelper.downCast(jdesign, dr);
                } else {
                    log.info("Not found: Attemping to find the file in the classpath...");
                    URL url = DynamicJasperHelper.class.getClassLoader().getResource(dr.getTemplateFileName());
                    JasperDesign jdesign = JRXmlLoader.load(url.openStream());
                    jd = DJJRDesignHelper.downCast(jdesign, dr);
                }
                JasperDesignHelper.populateReportOptionsFromDesign(jd, dr);
            } else {
                jd = DJJRDesignHelper.getNewDesign(dr);
            }
            registerParameters(jd, dr);
        } catch (JRException e) {
            throw new CoreException(e.getMessage(), e);
        } catch (IOException e) {
            throw new CoreException(e.getMessage(), e);
        }
        return jd;
    }
public static byte[] getSystemStateHash() {
        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
        } catch (Exception e) {
            throw new Error("Error in RandomSeed, no sha1 hash");
        }
        sha1.update((byte) System.currentTimeMillis());
        sha1.update((byte) Runtime.getRuntime().totalMemory());
        sha1.update((byte) Runtime.getRuntime().freeMemory());
        sha1.update(stackDump(new Throwable()));
        try {
            Properties props = System.getProperties();
            Enumeration names = props.propertyNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                sha1.update(name.getBytes());
                sha1.update(props.getProperty(name).getBytes());
            }
        } catch (Throwable t) {
            sha1.update(stackDump(t));
        }
        sha1.update((byte) System.currentTimeMillis());
        try {
            sha1.update(InetAddress.getLocalHost().toString().getBytes());
        } catch (Throwable t) {
            sha1.update(stackDump(t));
        }
        sha1.update((byte) System.currentTimeMillis());
        Runtime.getRuntime().gc();
        sha1.update((byte) Runtime.getRuntime().freeMemory());
        sha1.update((byte) System.currentTimeMillis());
        return sha1.digest();
    }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpClientInfo clientInfo = HttpUtil.parseClientInfo((HttpServletRequest) request);
        if (request.getParameter("_debug_") != null) {
            StringBuffer buffer = new StringBuffer();
            Enumeration iter = request.getHeaderNames();
            while (iter.hasMoreElements()) {
                String name = (String) iter.nextElement();
                buffer.append(name + "=" + request.getHeader(name)).append("\n");
            }
            buffer.append("\n");
            iter = request.getParameterNames();
            while (iter.hasMoreElements()) {
                String name = (String) iter.nextElement();
                String value = request.getParameter(name);
                if (!"ISO-8859-1".equalsIgnoreCase(clientInfo.getPreferCharset())) value = new String(value.getBytes("ISO-8859-1"), clientInfo.getPreferCharset());
                buffer.append(name).append("=").append(value).append("\n");
            }
            response.setContentType("text/plain; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(buffer.toString());
            return null;
        }
        Object resultObj = handleRequest(request);
        if (resultObj == null) {
            String requestException = (String) request.getAttribute("XSMP.handleRequest.Exception");
            if (requestException != null) response.sendError(500, requestException); else response.setContentLength(0);
        } else {
            if (resultObj instanceof DataHandler) {
                response.setContentType(((DataHandler) resultObj).getContentType());
                response.setContentLength(((DataHandler) resultObj).getInputStream().available());
                IOUtils.copy(((DataHandler) resultObj).getInputStream(), response.getOutputStream());
            } else {
                String temp = resultObj.toString();
                if (temp.startsWith("<") && temp.endsWith(">")) response.setContentType("text/html; charset=" + clientInfo.getPreferCharset()); else response.setContentType("text/plain; charset=" + clientInfo.getPreferCharset());
                byte[] buffer = temp.getBytes(clientInfo.getPreferCharset());
                response.setContentLength(buffer.length);
                response.getOutputStream().write(buffer);
            }
        }
        return null;
    }
public static String Md5By32(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
public static synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException nsae) {
                nsae.printStackTrace();
            }
        }
        try {
            digest.update(data.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            System.err.println(e);
        }
        return encodeHex(digest.digest());
    }
private static byte[] loadBytecodePrivileged() {
        URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz");
        try {
            InputStream in = url.openStream();
            try {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                for (; ; ) {
                    int r = in.read();
                    if (r == -1) {
                        return bout.toByteArray();
                    }
                    bout.write(r);
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new UndeclaredThrowableException(e);
        }
    }
public static byte[] computeMD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(s.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }