semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void retrieveClasses(URL url, Map<String, T> cmds) {
        try {
            String resource = URLDecoder.decode(url.getPath(), "UTF-8");
            File directory = new File(resource);
            if (directory.exists()) {
                String[] files = directory.list();
                for (String file : files) {
                    if (file.endsWith(".class")) {
                        addInstanceIfCommand(pckgname + '.' + file.substring(0, file.length() - 6), cmds);
                    }
                }
            } else {
                JarURLConnection con = (JarURLConnection) url.openConnection();
                String starts = con.getEntryName();
                Enumeration<JarEntry> entriesEnum = con.getJarFile().entries();
                while (entriesEnum.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entriesEnum.nextElement();
                    String entryname = entry.getName();
                    if (entryname.startsWith(starts) && (entryname.lastIndexOf('/') <= starts.length()) && entryname.endsWith(".class")) {
                        String classname = entryname.substring(0, entryname.length() - 6);
                        if (classname.startsWith("/")) {
                            classname = classname.substring(1);
                        }
                        classname = classname.replace('/', '.');
                        addInstanceIfCommand(classname, cmds);
                    }
                }
            }
        } catch (IOException ioe) {
            LOG.warning("couldn't retrieve classes of " + url + ". Reason: " + ioe);
        }
    }
public String postEvent(EventDocument eventDoc, Map attachments) {
        if (eventDoc == null || eventDoc.getEvent() == null) return null;
        if (jmsTemplate == null) {
            sendEvent(eventDoc, attachments);
            return eventDoc.getEvent().getEventId();
        }
        if (attachments != null) {
            Iterator iter = attachments.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                if (entry.getValue() instanceof DataHandler) {
                    File file = new File(attachmentStorge + "/" + GuidUtil.generate() + entry.getKey());
                    try {
                        IOUtils.copy(((DataHandler) entry.getValue()).getInputStream(), new FileOutputStream(file));
                        entry.setValue(file);
                    } catch (IOException err) {
                        err.printStackTrace();
                    }
                }
            }
        }
        InternalEventObject eventObj = new InternalEventObject();
        eventObj.setEventDocument(eventDoc);
        eventObj.setAttachments(attachments);
        eventObj.setSessionContext(SessionContextUtil.getCurrentContext());
        eventDoc.getEvent().setEventId(GuidUtil.generate());
        if (destinationName != null) jmsTemplate.convertAndSend(destinationName, eventObj); else jmsTemplate.convertAndSend(eventObj);
        return eventDoc.getEvent().getEventId();
    }
public synchronized String getEncryptedPassword(String plaintext, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance(algorithm);
            md.update(plaintext.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException nsae) {
            throw nsae;
        } catch (UnsupportedEncodingException uee) {
            throw uee;
        }
        return (new BigInteger(1, md.digest())).toString(16);
    }
public static String loadUrlContentAsString(URL url) throws IOException {
        char[] buf = new char[2048];
        StringBuffer ret = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        for (int chars = reader.read(buf); chars != -1; chars = reader.read(buf)) {
            ret.append(buf, 0, chars);
        }
        reader.close();
        return ret.toString();
    }
public static boolean copyFile(File from, File to) {
        try {
            FileChannel fromChannel = new FileInputStream(from).getChannel();
            FileChannel toChannel = new FileOutputStream(to).getChannel();
            toChannel.transferFrom(fromChannel, 0, fromChannel.size());
            fromChannel.close();
            toChannel.close();
        } catch (IOException e) {
            log.error("failed to copy " + from.getAbsolutePath() + " to " + to.getAbsolutePath() + ": caught exception", e);
            return false;
        }
        return true;
    }
private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException {
        try {
            final MessageDigest hash = MessageDigest.getInstance("SHA1");
            hash.update(new String(password).getBytes());
            hash.update(GGUtils.intToByte(seed));
            return hash.digest();
        } catch (final NoSuchAlgorithmException e) {
            LOG.error("SHA1 algorithm not usable", e);
            throw new GGException("SHA1 algorithm not usable!", e);
        }
    }
private void gzip(FileHolder fileHolder) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File destFile = new File(fileHolder.destFiles[0]);
        try {
            OutputStream outStream = new FileOutputStream(destFile);
            outStream = new GZIPOutputStream(outStream);
            File selectedFile = fileHolder.selectedFileList.get(0);
            super.currentObjBeingProcessed = selectedFile;
            this.inStream = new FileInputStream(selectedFile);
            while ((bytes_read = this.inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytes_read);
            }
            outStream.close();
            this.inStream.close();
        } catch (IOException e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("gzip()");
            errEntry.setAppMessage("Error gzip'ing: " + destFile);
            logger.logError(errEntry);
        }
    }
private void zip(FileHolder fileHolder, int zipCompressionLevel) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File zipDestFile = new File(fileHolder.destFiles[0]);
        try {
            ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipDestFile));
            for (int i = 0; i < fileHolder.selectedFileList.size(); i++) {
                File selectedFile = fileHolder.selectedFileList.get(i);
                super.currentObjBeingProcessed = selectedFile;
                this.inStream = new FileInputStream(selectedFile);
                ZipEntry entry = new ZipEntry(selectedFile.getName());
                outStream.setLevel(zipCompressionLevel);
                outStream.putNextEntry(entry);
                while ((bytes_read = this.inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytes_read);
                }
                outStream.closeEntry();
                this.inStream.close();
            }
            outStream.close();
        } catch (IOException e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("gzip()");
            errEntry.setAppMessage("Error zipping: " + zipDestFile);
            logger.logError(errEntry);
        }
        return;
    }
private void tar(FileHolder fileHolder, boolean gzipIt) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        if (fileHolder.selectedFileList.size() == 0) {
            return;
        }
        File tarDestFile = new File(fileHolder.destFiles[0]);
        try {
            OutputStream outStream = new FileOutputStream(tarDestFile);
            if (gzipIt) {
                outStream = new GZIPOutputStream(outStream);
            }
            TarOutputStream tarOutStream = new TarOutputStream(outStream);
            for (int i = 0; i < fileHolder.selectedFileList.size(); i++) {
                File selectedFile = fileHolder.selectedFileList.get(i);
                super.currentObjBeingProcessed = selectedFile;
                this.inStream = new FileInputStream(selectedFile);
                TarEntry tarEntry = null;
                try {
                    tarEntry = new TarEntry(selectedFile, selectedFile.getName());
                } catch (InvalidHeaderException e) {
                    errEntry.setThrowable(e);
                    errEntry.setAppContext("tar()");
                    errEntry.setAppMessage("Error tar'ing: " + selectedFile);
                    logger.logError(errEntry);
                }
                tarOutStream.putNextEntry(tarEntry);
                while ((bytes_read = inStream.read(buffer)) != -1) {
                    tarOutStream.write(buffer, 0, bytes_read);
                }
                tarOutStream.closeEntry();
                inStream.close();
                super.processorSyncFlag.restartWaitUntilFalse();
            }
            tarOutStream.close();
        } catch (Exception e) {
            errEntry.setThrowable(e);
            errEntry.setAppContext("tar()");
            errEntry.setAppMessage("Error tar'ing: " + tarDestFile);
            logger.logError(errEntry);
        }
    }
List<String> options(String path) throws TwinException {
        try {
            BasicHttpRequest request = new BasicHttpRequest("OPTIONS", url + path);
            HttpClient client = getClient();
            HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
            Header hdr = response.getFirstHeader("Allow");
            if (hdr == null || hdr.getValue().isEmpty()) return Collections.emptyList();
            return Arrays.asList(hdr.getValue().split("\\s*,\\s*"));
        } catch (IOException e) {
            throw TwinError.UnknownError.create("IOException when accessing RC", e);
        }
    }
@SuppressWarnings("unchecked")
    private Map<String, Object> _request(String method, String path, Map<String, Object> body, JSONRecognizer... recognizers) throws IOException, TwinException {
        String uri = url + path;
        HttpRequest request;
        if (body == null) {
            BasicHttpRequest r = new BasicHttpRequest(method, uri);
            request = r;
        } else {
            BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, uri);
            StringEntity entity;
            try {
                entity = new StringEntity(JSON.encode(body), "utf-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            entity.setContentType("application/json; charset=utf-8");
            r.setEntity(entity);
            request = r;
        }
        HttpClient client = getClient();
        try {
            HttpResponse response = client.execute(new HttpHost(url.getHost(), url.getPort()), request);
            HttpEntity entity = response.getEntity();
            if (entity == null) return null;
            String contentType = entity.getContentType().getValue();
            boolean isJson = (contentType != null) && ("application/json".equals(contentType) || contentType.startsWith("application/json;"));
            String result = null;
            InputStream in = entity.getContent();
            try {
                Reader r = new InputStreamReader(in, "UTF-8");
                StringBuilder sb = new StringBuilder();
                char[] buf = new char[256];
                int read;
                while ((read = r.read(buf, 0, buf.length)) >= 0) sb.append(buf, 0, read);
                r.close();
                result = sb.toString();
            } finally {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
            int code = response.getStatusLine().getStatusCode();
            if (code >= 400) {
                if (isJson) {
                    try {
                        throw deserializeException((Map<String, Object>) JSON.decode(result));
                    } catch (IllegalArgumentException e) {
                        throw TwinError.UnknownError.create("Couldn't parse error response: \n" + result, e);
                    }
                }
                if (code == 404) throw TwinError.UnknownCommand.create("Got server response " + code + " for request " + uri); else throw TwinError.UnknownError.create("Got server response " + code + " for request " + uri + "\nBody is " + result);
            }
            if (!isJson) throw TwinError.UnknownError.create("Got wrong content type " + contentType + " for request " + uri + "\nBody is " + result);
            try {
                return (Map<String, Object>) JSON.decode(result, recognizers);
            } catch (Exception e) {
                throw TwinError.UnknownError.create("Malformed JSON result for request " + uri + ": \nBody is " + result, e);
            }
        } catch (ClientProtocolException e) {
            throw new IOException(e);
        }
    }
public static File copy(String fromFileName, String toFileName) throws IOException {
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);
        System.out.println("AbsolutePath fromFile: " + fromFile.getAbsolutePath());
        System.out.println("AbsolutePath toFile: " + toFile.getAbsolutePath());
        if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
        if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
        if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);
        if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
        if (toFile.exists()) {
            if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
        } else {
            String parent = toFile.getParent();
            if (parent == null) parent = System.getProperty("user.dir");
            File dir = new File(parent);
            if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
            if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
            if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
        return toFile;
    }
static JSONObject executeMethod(HttpClient httpClient, HttpMethod method, int timeout) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException {
        try {
            method.getParams().setSoTimeout(timeout * 1000);
            int status = -1;
            JSONObject result = null;
            for (int i = 0; i < RETRY; i++) {
                System.out.println("Execute method[" + method.getURI() + "](try " + (i + 1) + ")");
                status = httpClient.executeMethod(method);
                if (status == HttpStatus.SC_OK) {
                    InputStream inputStream = method.getResponseBodyAsStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(inputStream, baos);
                    String response = new String(baos.toByteArray(), "UTF-8");
                    System.out.println(response);
                    result = JSONObject.fromString(response);
                    if (result.has("status")) {
                        String lingrStatus = result.getString("status");
                        if ("ok".equals(lingrStatus)) {
                            break;
                        } else {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                } else {
                    throw new HttpRequestFailureException(status);
                }
            }
            return result;
        } catch (SocketTimeoutException e) {
            throw new HttpRequestTimeoutException(e);
        } finally {
            method.releaseConnection();
        }
    }
private static synchronized void calcLocalFileHash() {
        long startTime = System.currentTimeMillis();
        if (currentFileHash != null) return;
        List fileList = getAllFiles("/", new AllFilesFilter());
        int len = 0;
        byte[] buf = new byte[1024];
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA");
            for (Iterator i = fileList.iterator(); i.hasNext(); ) {
                String path = (String) i.next();
                LocalFileResource lfr = new LocalFileResource(path);
                if (lfr.isDirectory()) {
                    digest.update(path.getBytes("UTF-8"));
                    continue;
                }
                InputStream stream = lfr.getFileAsInputStream();
                while ((len = stream.read(buf)) != -1) {
                    digest.update(buf, 0, len);
                }
                stream.close();
            }
            currentFileHash = new String(Hex.encodeHex(digest.digest()));
        } catch (Exception e) {
            log.error("No SHA found ...?", e);
            currentFileHash = "unknown" + System.currentTimeMillis();
        } finally {
            if (log.isDebugEnabled()) log.debug("Needed " + (System.currentTimeMillis() - startTime) + "ms for hash calculation");
        }
    }
public String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception {
        long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L);
        BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user);
        response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"');
        String contentType = binaryAttribute.getContentType();
        if (contentType != null) {
            if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) {
                response.setContentType("application/octet-stream");
            } else {
                response.setContentType(contentType);
            }
        } else {
            response.setContentType("application/octet-stream");
        }
        IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream());
        return null;
    }
public boolean load() {
        if (getFilename() != null && getFilename().length() > 0) {
            try {
                File file = new File(PreferencesManager.loadDirectoryLocation("macros") + File.separator + getFilename());
                URL url = file.toURL();
                InputStreamReader isr = new InputStreamReader(url.openStream());
                BufferedReader br = new BufferedReader(isr);
                String line = br.readLine();
                String macro_text = "";
                while (line != null) {
                    macro_text = macro_text.concat(line);
                    line = br.readLine();
                    if (line != null) {
                        macro_text = macro_text.concat(System.getProperty("line.separator"));
                    }
                }
                code = macro_text;
            } catch (Exception e) {
                System.err.println("Exception at StoredMacro.load(): " + e.toString());
                return false;
            }
        }
        return true;
    }
public String readReferenceText(final String ident) throws NoContentException {
        try {
            String name = getFilename(ident);
            URL url = new URL(FreqAnalysisPlugin.getDefault().getBundle().getEntry("/"), name);
            InputStream in = url.openStream();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String line = br.readLine();
            while (null != line) {
                buffer.append(line + "\n");
                line = br.readLine();
            }
            return buffer.toString();
        } catch (MalformedURLException muEx) {
            logError(muEx);
        } catch (UnsupportedEncodingException ueEx) {
            logError(ueEx);
        } catch (IOException ioEx) {
            logError(ioEx);
        }
        throw new NoContentException("Unable to find or read reference text.");
    }
public String getPassword(URI uri) {
        if (_getPassword(uri) != null) return _getPassword(uri);
        String result = null;
        try {
            String sUri = scrubURI(uri);
            URL url = new URL(TEMP_PASSWORD_SERVICE_URL + "?SID=" + sessionId + "&ruri=" + URLEncoder.encode(sUri, "UTF-8"));
            JSONObject jsonObject = null;
            URLConnection conn = url.openConnection();
            InputStream istream = conn.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(istream));
            if ((result = in.readLine()) != null) {
                jsonObject = new JSONObject(result);
            }
            if (jsonObject.has("success")) {
                if (jsonObject.get("success").toString().equals("false")) {
                    if (jsonObject.has("error")) {
                        logger.log("Returned error message from temporary password service is: " + jsonObject.get("error"));
                    }
                    return null;
                }
            }
            if (jsonObject.has("temppass")) {
                result = (String) jsonObject.get("temppass");
            }
        } catch (java.io.FileNotFoundException fe) {
            logger.log("Could not find temporary password service. " + fe);
            fe.printStackTrace();
        } catch (Exception e) {
            logger.log("Exception getting temporary password. " + e);
            e.printStackTrace();
        }
        if (result == null) return null;
        return result;
    }
public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException {
        try {
            Socket s = new Socket(host, port);
            try {
                ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
                ObjectInputStream in = new ObjectInputStream(s.getInputStream());
                int protocolVersion = in.readInt();
                if (protocolVersion > 220) {
                    throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected.");
                }
                byte[] challenge = (byte[]) in.readObject();
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(password.getBytes("UTF-8"));
                md.update(challenge);
                out.writeObject(md.digest());
                return new LocalDebuggerProxy((Debugger) in.readObject());
            } finally {
                s.close();
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new UndeclaredThrowableException(e);
        }
    }