semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void unzipResource(final String resourceName, final File targetDirectory) throws IOException {
        assertTrue(resourceName.startsWith("/"));
        final URL resource = this.getClass().getResource(resourceName);
        assertNotNull("Expected '" + resourceName + "' not found.", resource);
        assertTrue(targetDirectory.isAbsolute());
        FileUtils.deleteDirectory(targetDirectory);
        assertTrue(targetDirectory.mkdirs());
        ZipInputStream in = null;
        boolean suppressExceptionOnClose = true;
        try {
            in = new ZipInputStream(resource.openStream());
            ZipEntry e;
            while ((e = in.getNextEntry()) != null) {
                if (e.isDirectory()) {
                    continue;
                }
                final File dest = new File(targetDirectory, e.getName());
                assertTrue(dest.isAbsolute());
                OutputStream out = null;
                try {
                    out = FileUtils.openOutputStream(dest);
                    IOUtils.copy(in, out);
                    suppressExceptionOnClose = false;
                } finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        suppressExceptionOnClose = true;
                    } catch (final IOException ex) {
                        if (!suppressExceptionOnClose) {
                            throw ex;
                        }
                    }
                }
                in.closeEntry();
            }
            suppressExceptionOnClose = false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                if (!suppressExceptionOnClose) {
                    throw e;
                }
            }
        }
    }
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ActionMessages errors = new ActionMessages();
        try {
            boolean isMultipart = FileUpload.isMultipartContent(request);
            Store storeInstance = getStoreInstance(request);
            if (isMultipart) {
                Map fields = new HashMap();
                Vector files = new Vector();
                List items = diskFileUpload.parseRequest(request);
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {
                        fields.put(item.getFieldName(), item.getString());
                    } else {
                        if (!StringUtils.isBlank(item.getName())) {
                            ByteArrayOutputStream baos = null;
                            try {
                                baos = new ByteArrayOutputStream();
                                IOUtils.copy(item.getInputStream(), baos);
                                MailPartObj part = new MailPartObj();
                                part.setAttachent(baos.toByteArray());
                                part.setContentType(item.getContentType());
                                part.setName(item.getName());
                                part.setSize(item.getSize());
                                files.addElement(part);
                            } catch (Exception ex) {
                            } finally {
                                IOUtils.closeQuietly(baos);
                            }
                        }
                    }
                }
                if (files.size() > 0) {
                    storeInstance.send(files, 0, Charset.defaultCharset().displayName());
                }
            } else {
                errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
                request.setAttribute("exception", "The form is null");
                request.setAttribute("newLocation", null);
                doTrace(request, DLog.ERROR, getClass(), "The form is null");
            }
        } catch (Exception ex) {
            String errorMessage = ExceptionUtilities.parseMessage(ex);
            if (errorMessage == null) {
                errorMessage = "NullPointerException";
            }
            errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
            request.setAttribute("exception", errorMessage);
            doTrace(request, DLog.ERROR, getClass(), errorMessage);
        } finally {
        }
        if (errors.isEmpty()) {
            doTrace(request, DLog.INFO, getClass(), "OK");
            return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
        } else {
            saveErrors(request, errors);
            return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
        }
    }
public static void copy(File file1, File file2) throws IOException {
        FileReader in = new FileReader(file1);
        FileWriter out = new FileWriter(file2);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }
private byte[] download(String URL) {
        byte[] result = null;
        HttpEntity httpEntity = null;
        try {
            HttpGet httpGet = new HttpGet(URL);
            httpGet.addHeader("Accept-Language", "zh-cn,zh,en");
            httpGet.addHeader("Accept-Encoding", "gzip,deflate");
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            Header header = response.getFirstHeader("content-type");
            if (header == null || header.getValue().indexOf("text/html") < 0) {
                return null;
            }
            int pos = header.getValue().indexOf("charset=");
            if (pos >= 0) {
                detectedEncoding = header.getValue().substring(pos + 8);
            }
            httpEntity = response.getEntity();
            InputStream in = null;
            in = httpEntity.getContent();
            header = response.getFirstHeader("Content-Encoding");
            if (null != header) {
                if (header.getValue().indexOf("gzip") >= 0) {
                    in = new GZIPInputStream(in);
                } else if (header.getValue().indexOf("deflate") >= 0) {
                    in = new InflaterInputStream(in, new Inflater(true));
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            result = out.toByteArray();
        } catch (IOException ex) {
            LOG.warn("downloading error,abandon");
            result = null;
        }
        return result;
    }
public static void encrypt(File plain, File symKey, File ciphered, String algorithm) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
        Key key = null;
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(symKey));
            key = (Key) in.readObject();
        } catch (IOException ioe) {
            KeyGenerator generator = KeyGenerator.getInstance(algorithm);
            key = generator.generateKey();
            ObjectOutputStream out = new ObjectOutputStream(new java.io.FileOutputStream(symKey));
            out.writeObject(key);
            out.close();
        }
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getEncoded(), algorithm));
        FileInputStream in = new FileInputStream(plain);
        CipherOutputStream out = new CipherOutputStream(new FileOutputStream(ciphered), cipher);
        byte[] buffer = new byte[4096];
        for (int read = in.read(buffer); read > -1; read = in.read(buffer)) {
            out.write(buffer, 0, read);
        }
        out.close();
    }
public static boolean copy(InputStream is, File file) {
        try {
            IOUtils.copy(is, new FileOutputStream(file));
            return true;
        } catch (Exception e) {
            logger.severe(e.getMessage());
            return false;
        }
    }
private void parseXMLFile() {
        String u = WeatherApplication.SERVER + location + ".xml";
        InputStream in = null;
        String str = null;
        try {
            URL url = new URL(u);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            in = url.openStream();
            ParserToolXML prt = new ParserToolXML(in);
            if (prt.doc == null) {
                System.err.println(FILE_NOT_FOUND_MSG + u);
                return;
            }
            NodeList ndl = prt.doc.getElementsByTagName("weather");
            for (int i = 0; i < ndl.getLength(); i++) {
                Forecast f = new Forecast();
                str = prt.searchElementValue(ndl.item(i), "date");
                f.setDate(str);
                str = prt.searchElementValue(ndl.item(i), "daycode");
                f.setDaycode(Integer.parseInt(str.trim()));
                str = prt.searchElementValue(ndl.item(i), "nightcode");
                f.setNightcode(Integer.parseInt(str.trim()));
                str = prt.searchElementValue(ndl.item(i), "maxtemp");
                f.setDaytemp(Integer.parseInt(str.trim()));
                str = prt.searchElementValue(ndl.item(i), "mintemp");
                f.setNighttemp(Integer.parseInt(str.trim()));
                str = prt.searchElementValue(ndl.item(i), "winddirectionday");
                f.setDaywinddir(str);
                str = prt.searchElementValue(ndl.item(i), "windspeedday");
                f.setDaywindspeed(Integer.parseInt(str.trim()));
                str = prt.searchElementValue(ndl.item(i), "winddirectionnight");
                f.setNightwinddir(str);
                str = prt.searchElementValue(ndl.item(i), "windspeednight");
                f.setNightwindspeed(Integer.parseInt(str.trim()));
                forecastlist.addElement(f);
            }
        } catch (MalformedURLException e) {
            System.err.println(MALFORMED_URL_MSG + u);
            System.err.println(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
        } catch (NumberFormatException e) {
            System.err.println(FILE_CORRUPT_MSG + u);
            System.err.println("-" + str + "-");
            System.err.println(e.getMessage());
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    System.err.println(COULD_NOT_CLOSE_FILE_MSG + u);
                    e.printStackTrace();
                }
            }
        }
    }
public void checkin(Object _document) {
        this.document = (Document) _document;
        synchronized (url) {
            OutputStream outputStream = null;
            try {
                if ("file".equals(url.getProtocol())) {
                    outputStream = new FileOutputStream(url.getFile());
                } else {
                    URLConnection connection = url.openConnection();
                    connection.setDoOutput(true);
                    outputStream = connection.getOutputStream();
                }
                new XMLOutputter("  ", true).output(this.document, outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
public String[][] getProjectTreeData() {
        String[][] treeData = null;
        String filename = dms_home + FS + "temp" + FS + username + "adminprojects.xml";
        String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetAdminProjects";
        try {
            String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "adminprojects.xml";
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            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("proj");
            int num = nodelist.getLength();
            treeData = new String[num][3];
            for (int i = 0; i < num; i++) {
                treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pid"));
                treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "ppid"));
                treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p"));
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
        } catch (ParserConfigurationException ex) {
            System.out.println(ex);
        } catch (NullPointerException e) {
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return treeData;
    }
private File download(String filename, URL url) {
		int size = -1;
		int received = 0;
		try {
			fireDownloadStarted(filename);
			File file = createFile(filename);
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
			System.out.println("下载资源：" + filename + ", url=" + url);
			// BufferedInputStream bis = new
			// BufferedInputStream(url.openStream());
			InputStream bis = url.openStream();
			byte[] buf = new byte[1024];
			int count = 0;
			long lastUpdate = 0;
			size = bis.available();
			while ((count = bis.read(buf)) != -1) {
				bos.write(buf, 0, count);
				received += count;
				long now = System.currentTimeMillis();
				if (now - lastUpdate > 500) {
					fireDownloadUpdate(filename, size, received);
					lastUpdate = now;
				}
			}
			bos.close();
			System.out.println("资源下载完毕：" + filename);
			fireDownloadCompleted(filename);
			return file;
		} catch (IOException e) {
			System.out.println("下载资源失败：" + filename + ", error=" + e.getMessage());
			fireDownloadInterrupted(filename);
			if (!(e instanceof FileNotFoundException)) {
				e.printStackTrace();
			}
		}
		return null;
	}
public String login(HttpSession callingSession, String username, String password) {
        String token = null;
        String customer = null;
        int timeoutInSeconds = 0;
        HashSet<Integer> tileProviderIds = new HashSet<Integer>();
        boolean bLoginOk = false;
        String dbPassword = (String) em.createNamedQuery("getCustomerPasswordByUsername").setParameter("username", username).getSingleResult();
        if (dbPassword.equals(password)) {
            CustomerElement ce = (CustomerElement) em.createNamedQuery("getCustomerByUsername").setParameter("username", username).getSingleResult();
            customer = ce.getName();
            timeoutInSeconds = ce.getTimeout();
            String[] tileProviderIdsArray = ce.getTileProvideridsArray();
            for (String tileProviderId : tileProviderIdsArray) tileProviderIds.add(Integer.parseInt(tileProviderId));
            bLoginOk = true;
        }
        if (bLoginOk) {
            token = SessionHandler.getInstance().alreadyGotValidSession(customer);
            if (token == null) {
                Random random = new Random();
                token = callingSession.getId() + new Date().getTime() + random.nextLong();
                MessageDigest md5 = null;
                try {
                    md5 = MessageDigest.getInstance("MD5");
                } catch (NoSuchAlgorithmException e) {
                    logger.error("Unable to digest the token.", e);
                }
                md5.update(token.getBytes());
                byte[] array = md5.digest();
                StringBuffer sb = new StringBuffer();
                for (int j = 0; j < array.length; ++j) {
                    int b = array[j] & 0xFF;
                    if (b < 0x10) sb.append('0');
                    sb.append(Integer.toHexString(b));
                }
                token = sb.toString();
                SessionHandler.getInstance().registerValidSession(token, customer, timeoutInSeconds, tileProviderIds);
            }
        }
        return token;
    }
public static DownloadedContent downloadContent(final InputStream is) throws IOException {
        if (is == null) {
            return new DownloadedContent.InMemory(new byte[] {});
        }
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[1024];
        int nbRead;
        try {
            while ((nbRead = is.read(buffer)) != -1) {
                bos.write(buffer, 0, nbRead);
                if (bos.size() > MAX_IN_MEMORY) {
                    final File file = File.createTempFile("htmlunit", ".tmp");
                    file.deleteOnExit();
                    final FileOutputStream fos = new FileOutputStream(file);
                    bos.writeTo(fos);
                    IOUtils.copyLarge(is, fos);
                    fos.close();
                    return new DownloadedContent.OnFile(file);
                }
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
        return new DownloadedContent.InMemory(bos.toByteArray());
    }
public void displayItems() throws IOException {
        URL url = new URL(SNIPPETS_FEED + "?bq=" + URLEncoder.encode(QUERY, "UTF-8") + "&key=" + DEVELOPER_KEY);
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = httpConnection.getInputStream();
        int ch;
        while ((ch = inputStream.read()) > 0) {
            System.out.print((char) ch);
        }
    }
public static String md5(String s) {
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            digester.update(s.getBytes());
            return new BigInteger(1, digester.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
public static String MD5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.update(str.getBytes(), 0, str.length());
            String sig = new BigInteger(1, md5.digest()).toString();
            return sig;
        } catch (NoSuchAlgorithmException e) {
            System.err.println("Can not use md5 algorithm");
        }
        return null;
    }
public static String sendRequest(String urlstring) {
        URL url;
        String line;
        Log.i("DVBMonitor", "Please wait while receiving data from dvb...");
        try {
            url = new URL(urlstring);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            if ((line = in.readLine()) != null) {
                return line;
            } else {
                return null;
            }
        } catch (Exception ex) {
            Log.e("DVBMonitor", ex.toString() + " while sending request to dvb");
            return null;
        }
    }
private ByteArrayInputStream fetchUrl(String urlString, Exception[] outException) {
        URL url;
        try {
            url = new URL(urlString);
            InputStream is = null;
            int inc = 65536;
            int curr = 0;
            byte[] result = new byte[inc];
            try {
                is = url.openStream();
                int n;
                while ((n = is.read(result, curr, result.length - curr)) != -1) {
                    curr += n;
                    if (curr == result.length) {
                        byte[] temp = new byte[curr + inc];
                        System.arraycopy(result, 0, temp, 0, curr);
                        result = temp;
                    }
                }
                return new ByteArrayInputStream(result, 0, curr);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } catch (Exception e) {
            if (outException != null) {
                outException[0] = e;
            }
        }
        return null;
    }
private List<String> readCredits() {
        URL url = SpriteStore.get().getResourceURL("games/midhedava/client/gui/credits.txt");
        List<String> res = new LinkedList<String>();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = br.readLine();
            while (line != null) {
                res.add(line);
                line = br.readLine();
            }
            br.close();
        } catch (IOException e) {
            res.add(0, "credits.txt not found");
        }
        return res;
    }
public ArrayList loadIndexes() {
        JSONObject job = new JSONObject();
        ArrayList al = new ArrayList();
        try {
            String req = job.put("OperationId", "1").toString();
            InputStream is = null;
            String result = "";
            JSONObject jArray = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.4:8080/newgenlibctxt/CarbonServlet");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("OperationId", "1"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                JSONObject jobres = new JSONObject(result);
                JSONArray jarr = jobres.getJSONArray("MobileIndexes");
                for (int i = 0; i < jarr.length(); i++) {
                    String indexname = jarr.getString(i);
                    al.add(indexname);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return al;
    }