semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
protected BufferedReader getBufferedReader(InputSource input) throws IOException, SAXException {
        BufferedReader br = null;
        if (input.getCharacterStream() != null) {
            br = new BufferedReader(input.getCharacterStream());
        } else if (input.getByteStream() != null) {
            br = new BufferedReader(new InputStreamReader(input.getByteStream()));
        } else if (input.getSystemId() != null) {
            URL url = new URL(input.getSystemId());
            br = new BufferedReader(new InputStreamReader(url.openStream()));
        } else {
            throw new SAXException("Invalid InputSource!");
        }
        return br;
    }
private synchronized Frame addFrame(INSERT_TYPE type, File source) throws IOException {
        if (source == null) throw new NullPointerException("Parameter 'source' is null");
        if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath());
        if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath());
        File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(frames_.size()));
        if (newLocation.compareTo(source) != 0) {
            switch(type) {
                case MOVE:
                    source.renameTo(newLocation);
                    break;
                case COPY:
                    FileChannel inChannel = new FileInputStream(source).getChannel();
                    FileChannel outChannel = new FileOutputStream(newLocation).getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                    if (inChannel != null) inChannel.close();
                    if (outChannel != null) outChannel.close();
                    break;
            }
        }
        Frame f = new Frame(newLocation);
        f.createThumbNail();
        frames_.add(f);
        return f;
    }
private synchronized Frame insertFrame(int index, File source, INSERT_TYPE type) throws IOException {
        if (source == null) throw new NullPointerException("Parameter 'source' is null");
        if (!source.exists()) throw new IOException("File does not exist: " + source.getAbsolutePath());
        if (source.length() <= 0) throw new IOException("File is empty: " + source.getAbsolutePath());
        if (index < 0) throw new IndexOutOfBoundsException("index < 0");
        if (index >= frames_.size()) throw new IndexOutOfBoundsException("index >= frames_.size()");
        File tmp = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp.jpg");
        switch(type) {
            case MOVE:
                if (source.getParentFile().compareTo(new File(Settings.getPropertyString(ConstantKeys.project_dir))) == 0 && source.getName().matches("img_[0-9]{5}\\.jpg")) {
                    for (int i = 0; i < frames_.size(); i++) {
                        Frame f = frames_.get(i);
                        if (f.getFile().compareTo(source) == 0) {
                            frames_.remove(i);
                            break;
                        }
                    }
                }
                source.renameTo(tmp);
                break;
            case COPY:
                FileChannel inChannel = new FileInputStream(source).getChannel();
                FileChannel outChannel = new FileOutputStream(tmp).getChannel();
                inChannel.transferTo(0, inChannel.size(), outChannel);
                if (inChannel != null) inChannel.close();
                if (outChannel != null) outChannel.close();
                break;
        }
        for (int i = frames_.size() - 1; i >= index; i--) {
            Frame newFrame = new Frame(new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(i)));
            frames_.get(i).moveTo(newFrame);
            frames_.set(i, newFrame);
        }
        File newLocation = new File(Settings.getPropertyString(ConstantKeys.project_dir), formatFileName(index));
        tmp.renameTo(newLocation);
        Frame f = new Frame(newLocation);
        f.createThumbNail();
        frames_.set(index, f);
        return f;
    }
@Before
    public void setUp() throws Exception {
        connectionDigestHandler = new ConnectionDigestHandlerDefaultImpl();
        URL url = null;
        try {
            url = new URL("http://dev2dev.bea.com.cn/bbs/servlet/D2DServlet/download/64104-35000-204984-2890/webwork2guide.pdf");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            uc = url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public String parse(String term) throws OntologyAdaptorException {
        try {
            String sUrl = getUrl(term);
            if (sUrl.length() > 0) {
                URL url = new URL(sUrl);
                InputStream in = url.openStream();
                StringBuilder sb = new StringBuilder();
                BufferedReader r = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = r.readLine()) != null) {
                    if (sb.length() > 0) {
                        sb.append("\r\n");
                    }
                    sb.append(line);
                }
                return sb.toString();
            } else {
                return "";
            }
        } catch (Exception ex) {
            throw new OntologyAdaptorException("Convertion to lucene failed.", ex);
        }
    }
public String sendSMS(String host, String port, String username, String password, String from, String to, String text, String uhd, String charset, String coding, String validity, String deferred, String dlrmask, String dlrurl, String pid, String mclass, String mwi) throws SMSPushRequestException, Exception {
        StringBuffer res = new StringBuffer();
        if (!Utils.checkNonEmptyStringAttribute(coding) || coding.equals("0")) text = Utils.convertTextForGSMEncodingURLEncoded(text); else if (coding.equals("1")) text = Utils.convertTextForUTFEncodingURLEncoded(text, "UTF-8"); else text = Utils.convertTextForUTFEncodingURLEncoded(text, "UCS-2");
        String directives = "username=" + username;
        directives += "&password=" + password;
        directives += "&from=" + URLEncoder.encode(from, "UTF-8");
        directives += "&to=" + to;
        directives += "&text=" + text;
        if (Utils.checkNonEmptyStringAttribute(uhd)) directives += "&uhd=" + uhd;
        if (Utils.checkNonEmptyStringAttribute(charset)) directives += "&charset=" + charset;
        if (Utils.checkNonEmptyStringAttribute(coding)) directives += "&coding=" + coding;
        if (Utils.checkNonEmptyStringAttribute(validity)) directives += "&validity=" + validity;
        if (Utils.checkNonEmptyStringAttribute(deferred)) directives += "&deferred=" + deferred;
        if (Utils.checkNonEmptyStringAttribute(dlrmask)) directives += "&dlrmask=" + dlrmask;
        if (Utils.checkNonEmptyStringAttribute(dlrurl)) directives += "&dlrurl=" + dlrurl;
        if (Utils.checkNonEmptyStringAttribute(pid)) directives += "&pid=" + pid;
        if (Utils.checkNonEmptyStringAttribute(mclass)) directives += "&mclass=" + mclass;
        if (Utils.checkNonEmptyStringAttribute(mwi)) directives += "&mwi=" + mwi;
        URL url = new URL("http://" + host + ":" + port + "/cgi-bin/sendsms?" + directives);
        URLConnection conn = url.openConnection();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response;
        while ((response = rd.readLine()) != null) res.append(response);
        rd.close();
        String resultCode = res.substring(0, res.indexOf(":"));
        if (!resultCode.equals(SMS_PUSH_RESPONSE_SUCCESS_CODE)) throw new SMSPushRequestException(resultCode);
        return res.toString();
    }
public void searchEntity(HttpServletRequest req, HttpServletResponse resp, SearchCommand command) {
        setHeader(resp);
        logger.debug("Search: Looking for the entity with the id:" + command.getSearchedid());
        String login = command.getLogin();
        String password = command.getPassword();
        SynchronizableUser currentUser = userAccessControl.authenticate(login, password);
        if (currentUser != null) {
            try {
                File tempFile = File.createTempFile("medoo", "search");
                OutputStream fos = new FileOutputStream(tempFile);
                syncServer.searchEntity(currentUser, command.getSearchedid(), fos);
                InputStream fis = new FileInputStream(tempFile);
                resp.setContentLength(fis.available());
                while (fis.available() > 0) {
                    resp.getOutputStream().write(fis.read());
                }
                resp.getOutputStream().flush();
                resp.flushBuffer();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
            } catch (ImogSerializationException ex) {
                logger.error(ex.getMessage(), ex);
            }
        } else {
            try {
                OutputStream out = resp.getOutputStream();
                out.write("-ERROR-".getBytes());
                out.flush();
                out.close();
                logger.debug("Search: user " + login + " has not been authenticated");
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
public void reqservmodif(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) {
        setHeader(resp);
        try {
            logger.debug("SeMo: Requesting server modification for session " + command.getSession());
            File tempFile = new File(getSyncWorkDirectory(req), command.getSession() + ".smodif");
            OutputStream fos = new FileOutputStream(tempFile);
            syncServer.getServerModifications(command.getSession(), fos);
            InputStream fis = new FileInputStream(tempFile);
            resp.setContentLength(fis.available());
            while (fis.available() > 0) {
                resp.getOutputStream().write(fis.read());
            }
            resp.getOutputStream().flush();
            resp.flushBuffer();
        } catch (IOException ioe) {
            logger.error(ioe.getMessage());
        } catch (ImogSerializationException ex) {
            logger.error(ex.getMessage());
        }
    }
public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) {
        setHeader(resp);
        try {
            logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes");
            File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif");
            if (!tempFile.exists()) {
                logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities");
                try {
                    OutputStream fos = new FileOutputStream(tempFile);
                    syncServer.getServerModifications(command.getSession(), fos);
                    fos.close();
                } catch (ImogSerializationException mse) {
                    logger.error(mse.getMessage(), mse);
                }
            }
            InputStream fis = new FileInputStream(tempFile);
            fis.skip(command.getLen());
            resp.setContentLength(fis.available());
            while (fis.available() > 0) {
                resp.getOutputStream().write(fis.read());
            }
            resp.getOutputStream().flush();
            resp.flushBuffer();
            fis.close();
        } catch (IOException ioe) {
            logger.error(ioe.getMessage());
        }
    }
protected Properties loadFile(String fileName) {
        Properties prop = new Properties();
        try {
            String packageName = getClass().getName();
            packageName = packageName.substring(0, packageName.lastIndexOf("."));
            String src = "src";
            if (mavenBuild) {
                src = src + File.separator + "test" + File.separator + "resources";
            }
            packageName = src + File.separator + packageName.replace('.', File.separatorChar);
            packageName += File.separator;
            packageName += fileName;
            URL url0 = new File(packageName).toURI().toURL();
            final InputStream input = url0.openStream();
            prop.load(input);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop;
    }
private void download(String address, String localFileName, String host, int porta) {
        InputStream in = null;
        URLConnection conn = null;
        OutputStream out = null;
        System.out.println("Update.download() BAIXANDO " + address);
        try {
            URL url = new URL(address);
            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            if (host != "" && host != null) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, porta));
                conn = url.openConnection(proxy);
            } else {
                conn = url.openConnection();
            }
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }
            System.out.println(localFileName + "\t" + numWritten);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
public static String post(String strUrl, String data) throws Exception {
        URL url = new URL(strUrl);
        final String method = "POST";
        final String host = url.getHost();
        final String contentType = "application/x-www-form-urlencoded";
        final int contentLength = getContentLength(data);
        final String encoding = "UTF-8";
        final String connection = "Close";
        Config.log(DEBUG, "Sending data to: " + url + " (host=" + host + ", encoding=" + encoding + ", method=" + method + ", Content-Type=" + contentType + ", Content-Length=" + contentLength + ", Connection=" + connection + "):" + "\r\n" + data);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method);
        conn.setRequestProperty("host", host);
        conn.setRequestProperty("content-type", contentType);
        conn.setRequestProperty("Content-Encoding", encoding);
        conn.setRequestProperty("content-length", contentLength + "");
        conn.setRequestProperty("connection", connection);
        if (tools.valid(Config.JSON_RPC_WEBSERVER_USERNAME) && tools.valid(Config.JSON_RPC_WEBSERVER_PASSWORD)) {
            String authString = Config.JSON_RPC_WEBSERVER_USERNAME + ":" + Config.JSON_RPC_WEBSERVER_PASSWORD;
            String authStringEnc = new sun.misc.BASE64Encoder().encode(authString.getBytes());
            conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }
        conn.setReadTimeout((int) (Config.JSON_RPC_TIMEOUT_SECONDS * 1000));
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
        writer.close();
        int responseCode = 400;
        try {
            responseCode = conn.getResponseCode();
        } catch (Exception x) {
            Config.log(ERROR, "Failed to get response code from HTTP Server. Check your URL and username/password.", x);
        }
        String response = readStream(responseCode == 200 ? conn.getInputStream() : conn.getErrorStream());
        if (response == null) {
            return null;
        }
        Config.log(DEBUG, "Raw response from POST. Response Code = " + conn.getResponseCode() + " (" + conn.getResponseMessage() + "):\r\n" + response);
        return response.toString();
    }
private void convertFile() {
        final File fileToConvert = filePanel.getInputFile();
        final File convertedFile = filePanel.getOutputFile();
        if (fileToConvert == null || convertedFile == null) {
            Main.showMessage("Select valid files for both input and output");
            return;
        }
        if (fileToConvert.getName().equals(convertedFile.getName())) {
            Main.showMessage("Input and Output files are same.. select different files");
            return;
        }
        final int len = (int) fileToConvert.length();
        progressBar.setMinimum(0);
        progressBar.setMaximum(len);
        progressBar.setValue(0);
        try {
            fileCopy(fileToConvert, fileToConvert.getAbsolutePath() + ".bakup");
        } catch (IOException e) {
            Main.showMessage("Unable to Backup input file");
            return;
        }
        final BufferedReader bufferedReader;
        try {
            bufferedReader = new BufferedReader(new FileReader(fileToConvert));
        } catch (FileNotFoundException e) {
            Main.showMessage("Unable to create reader - file not found");
            return;
        }
        final BufferedWriter bufferedWriter;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(convertedFile));
        } catch (IOException e) {
            Main.showMessage("Unable to create writer for output file");
            return;
        }
        String input;
        try {
            while ((input = bufferedReader.readLine()) != null) {
                if (stopRequested) {
                    break;
                }
                bufferedWriter.write(parseLine(input));
                bufferedWriter.newLine();
                progressBar.setValue(progressBar.getValue() + input.length());
            }
        } catch (IOException e) {
            Main.showMessage("Unable to convert " + e.getMessage());
            return;
        } finally {
            try {
                bufferedReader.close();
                bufferedWriter.close();
            } catch (IOException e) {
                Main.showMessage("Unable to close reader/writer " + e.getMessage());
                return;
            }
        }
        if (!stopRequested) {
            filePanel.readOutputFile();
            progressBar.setValue(progressBar.getMaximum());
            Main.setStatus("Transliterate Done.");
        }
        progressBar.setValue(progressBar.getMinimum());
    }
public void execute() {
        checkInput();
        try {
            client = new FTPClient();
            log("Connecting to " + ftpServer, Project.MSG_INFO);
            client.connect(ftpServer, ftpPort);
            checkFtpCode(client, "FTP server refused connection:");
            log("Connected", Project.MSG_INFO);
            log("Logging in", Project.MSG_INFO);
            if (!client.login(username, password)) {
                log("Login failed: " + client.getReplyString(), Project.MSG_ERR);
            }
            log("Login successful", Project.MSG_INFO);
            client.enterLocalPassiveMode();
            checkFtpCode(client, "Couldn't change connection type to passive: ");
            log("Changed to passive mode.", Project.MSG_VERBOSE);
            client.changeWorkingDirectory(remoteDir);
            checkFtpCode(client, "Can't change to directory: " + remoteDir);
            log("Listing FTP files", Project.MSG_INFO);
            for (int i = 0; i < remoteFileStrings.length; i++) {
                remoteFilePatterns = makePattern(remoteFileStrings[i]);
                numDir = remoteFilePatterns.length - 1;
                log("Setting number of directories to: " + numDir, Project.MSG_VERBOSE);
                FTPFile[] files = client.listFiles(remoteDir);
                files = followSymLink(client, files);
                log("# of files in " + remoteDir + " is " + files.length, Project.MSG_VERBOSE);
                scanDir(0, numDir, files, null);
            }
            bw.flush();
            bw.close();
        } catch (IOException ioe) {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                } catch (IOException iof) {
                }
            }
            log("Could not connect to " + ftpServer + " " + ioe.getMessage(), Project.MSG_ERR);
        }
    }
public WebResponse getResponse(WebRequest webRequest, String charset) throws IOException {
        initHttpClient();
        switch(webRequest.getRequestMethod()) {
            case GET:
                httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpGet(webRequest.getUrl())));
                break;
            case HEAD:
                httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpHead(webRequest.getUrl())));
                break;
            case OPTIONS:
                httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpOptions(webRequest.getUrl())));
                break;
            case TRACE:
                httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpTrace(webRequest.getUrl())));
                break;
            case DELETE:
                httpRequest.set(populateHttpRequestBaseMethod(webRequest, new HttpDelete(webRequest.getUrl())));
                break;
            case POST:
                httpRequest.set(populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPost(webRequest.getUrl())));
                break;
            case PUT:
                httpRequest.set(populateHttpEntityEnclosingRequestBaseMethod(webRequest, new HttpPut(webRequest.getUrl())));
                break;
            default:
                throw new RuntimeException("Method not yet supported: " + webRequest.getRequestMethod());
        }
        WebResponse resp;
        HttpResponse response = executeMethod(httpRequest.get());
        if (response == null) {
            throw new IOException("LIGHTHTTP. An empty response received from server. Possible reason: host is offline");
        }
        resp = processResponse(response, httpRequest.get(), charset);
        httpRequest.set(null);
        return resp;
    }
protected void initGame() {
        try {
            for (File fonte : files) {
                String absolutePath = outputDir.getAbsolutePath();
                String separator = System.getProperty("file.separator");
                String name = fonte.getName();
                String destName = name.substring(0, name.length() - 3);
                File destino = new File(absolutePath + separator + destName + "jme");
                FileInputStream reader = new FileInputStream(fonte);
                OutputStream writer = new FileOutputStream(destino);
                conversor.setProperty("mtllib", fonte.toURL());
                conversor.convert(reader, writer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.finish();
    }
public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new ServiceUnavailableException(e.getMessage());
        }
        try {
            md.update(p_plainText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new ServiceUnavailableException(e.getMessage());
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }