semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
protected boolean checkLogin(String username, String password) {
        log.debug("Called checkLogin with " + username);
        String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.loginService + "?username=" + username + "&password=" + password;
        Element results = null;
        String cookieValue = null;
        try {
            URL url = new URL(urlIn);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(1000);
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            try {
                results = Xml.loadStream(in);
                log.debug("CheckLogin to GeoNetwork returned " + Xml.getString(results));
            } finally {
                in.close();
            }
            Map<String, List<String>> headers = conn.getHeaderFields();
            List<String> values = headers.get("Set-Cookie");
            for (Iterator iter = values.iterator(); iter.hasNext(); ) {
                String v = (String) iter.next();
                if (cookieValue == null) {
                    cookieValue = v;
                } else {
                    cookieValue = cookieValue + ";" + v;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("User login to GeoNetwork failed: ", e);
        }
        if (!results.getName().equals("ok")) return false;
        Session session = getConnection().getSession();
        session.removeAttribute("usercookie.object");
        session.setAttribute("usercookie.object", cookieValue);
        log.debug("Cookie set is " + cookieValue);
        return true;
    }
public void salva(UploadedFile imagem, Usuario usuario) {
        File destino = new File(pastaImagens, usuario.getId() + ".imagem");
        try {
            IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino));
        } catch (IOException e) {
            throw new RuntimeException("Erro ao copiar imagem", e);
        }
    }
public void copyToDir(File dir) {
        if (!dir.exists()) {
            dir.mkdirs();
        } else if (this.file.getParentFile() != null && this.file.getParentFile().equals(dir)) {
            return;
        }
        File file = getEstimatedFileName(dir);
        try {
            file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            FileInputStream fileInputStream = new FileInputStream(this.file);
            int read = 0;
            byte[] buffer = new byte[1024];
            while (read != -1) {
                fileOutputStream.write(buffer, 0, read);
                read = fileInputStream.read(buffer);
            }
            fileInputStream.close();
            fileOutputStream.close();
            this.file = file;
        } catch (IOException e) {
            Logger.log(e);
        }
    }
@SuppressWarnings("unchecked")
    private List getURLList(String request) throws IOException {
        List list = null;
        try {
            URL url = new URL(dbURL + request);
            URLConnection conn = url.openConnection();
            conn.connect();
            JSONParser parser = JSONParser.defaultJSONParser();
            InputStreamSource stream = new InputStreamSource(conn.getInputStream(), true);
            list = parser.parse(List.class, stream);
            stream.destroy();
        } catch (MalformedURLException mue) {
            System.err.println("Internal malformed url Exception: " + mue);
        }
        return list;
    }
@SuppressWarnings("unchecked")
    private Map getURLMap(String request) throws IOException {
        Map map = null;
        try {
            URL url = new URL(dbURL + request);
            URLConnection conn = url.openConnection();
            conn.connect();
            JSONParser parser = JSONParser.defaultJSONParser();
            InputStreamSource stream = new InputStreamSource(conn.getInputStream(), true);
            map = parser.parse(Map.class, stream);
            stream.destroy();
        } catch (MalformedURLException mue) {
            System.err.println("Internal malformed url Exception: " + mue);
        }
        return map;
    }
public static InputStream getResourceAsStream(final String name, final Class context) {
        final URL url = getResource(name, context);
        if (url == null) {
            return null;
        }
        try {
            return url.openStream();
        } catch (IOException e) {
            return null;
        }
    }
public static InputStream getResourceRelativeAsStream(final String name, final Class context) {
        final URL url = getResourceRelative(name, context);
        if (url == null) {
            return null;
        }
        try {
            return url.openStream();
        } catch (IOException e) {
            return null;
        }
    }
public void run() {
        String s;
        s = "";
        try {
            URL url = new URL("http://www.m-w.com/dictionary/" + word);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while (((str = in.readLine()) != null) && (!stopped)) {
                s = s + str;
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(s);
        java.io.StringWriter wr = new java.io.StringWriter();
        HTMLDocument doc = null;
        HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
        try {
            doc = (HTMLDocument) editor.getDocument();
        } catch (Exception e) {
        }
        System.out.println(wr);
        editor.setContentType("text/html");
        if (matcher.find()) try {
            kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } else try {
            kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        button.setEnabled(true);
    }
public String sendMessage(String message, boolean log) {
        StringBuilder ret;
        try {
            URL url = new URL(this.stringURL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestProperty("User-Agent", serverName);
            urlConnection.setRequestProperty("Host", ip);
            urlConnection.setRequestProperty("Content-type", "text/xml");
            urlConnection.setRequestProperty("Content-length", Integer.toString(message.length()));
            PrintWriter _out = new PrintWriter(urlConnection.getOutputStream());
            if (log) {
                CampaignData.mwlog.infoLog("Sending Message: " + MWCyclopsUtils.formatMessage(message));
            } else CampaignData.mwlog.infoLog("Sending Message: " + message);
            _out.println(message);
            _out.flush();
            _out.close();
            ret = new StringBuilder();
            if (log) {
                BufferedReader _in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String input;
                while ((input = _in.readLine()) != null) ret.append(input + "\n");
                CampaignData.mwlog.infoLog(ret.toString());
                _in.close();
            } else {
                BufferedReader _in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while (_in.readLine() != null) {
                }
                _in.close();
            }
            _out.close();
            urlConnection.disconnect();
            return ret.toString();
        } catch (Exception ex) {
            CampaignData.mwlog.errLog(ex);
        }
        return "";
    }
@SuppressWarnings("unchecked")
    private final D loadMeta(URL url) throws IOException {
        SAXParser saxParser;
        try {
            saxParser = SAX_PARSER_FACTORY.newSAXParser();
        } catch (ParserConfigurationException e) {
            throw new Error(e);
        } catch (SAXException e) {
            throw new Error(e);
        }
        try {
            saxParser.setProperty("http://xml.org/sax/features/validation", false);
        } catch (SAXNotRecognizedException e) {
            e.printStackTrace();
        } catch (SAXNotSupportedException e) {
            e.printStackTrace();
        }
        MetaParser handler = new MetaParser();
        try {
            saxParser.parse(url.openStream(), handler);
        } catch (SAXException e) {
            throw new ParsingException(e);
        }
        return ((D) handler.getMetaData());
    }
public String getMd5CodeOf16(String str) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();
            int i;
            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));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            return buf.toString().substring(8, 24);
        }
    }
public static void copyFile(String target, String source) {
        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(target).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (IOException e) {
            ExceptionHelper.showErrorDialog(e);
        }
    }
public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: GZip source");
            return;
        }
        String zipname = args[0] + ".gz";
        GZIPOutputStream zipout;
        try {
            FileOutputStream out = new FileOutputStream(zipname);
            zipout = new GZIPOutputStream(out);
        } catch (IOException e) {
            System.out.println("Couldn't create " + zipname + ".");
            return;
        }
        byte[] buffer = new byte[sChunk];
        try {
            FileInputStream in = new FileInputStream(args[0]);
            int length;
            while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length);
            in.close();
        } catch (IOException e) {
            System.out.println("Couldn't compress " + args[0] + ".");
        }
        try {
            zipout.close();
        } catch (IOException e) {
        }
    }
public static String crypt(String str) {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException("String to encript cannot be null or zero length");
        }
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hexString.toString();
    }
@Action(value = "ajaxFileUploads", results = {  })
    public void ajaxFileUploads() throws IOException {
        String extName = "";
        String newFilename = "";
        String nowTimeStr = "";
        String realpath = "";
        if (Validate.StrNotNull(this.getImgdirpath())) {
            realpath = "Uploads/" + this.getImgdirpath() + "/";
        } else {
            realpath = this.isexistdir();
        }
        SimpleDateFormat sDateFormat;
        Random r = new Random();
        String savePath = ServletActionContext.getServletContext().getRealPath("");
        savePath = savePath + realpath;
        HttpServletResponse response = ServletActionContext.getResponse();
        int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
        sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        nowTimeStr = sDateFormat.format(new Date());
        String filename = request.getHeader("X-File-Name");
        if (filename.lastIndexOf(".") >= 0) {
            extName = filename.substring(filename.lastIndexOf("."));
        }
        newFilename = nowTimeStr + rannum + extName;
        PrintWriter writer = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            log.debug(ImgTAction.class.getName() + "has thrown an exception:" + ex.getMessage());
        }
        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(savePath + newFilename));
            IOUtils.copy(is, fos);
            response.setStatus(response.SC_OK);
            writer.print("{success:'" + realpath + newFilename + "'}");
        } catch (FileNotFoundException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log.debug(ImgTAction.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                this.setImgdirpath(null);
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }
        writer.flush();
        writer.close();
    }
private void mergeOne(String level, char strand, String filename, Path outPath, FileSystem srcFS, FileSystem dstFS, Timer to) throws IOException {
        to.start();
        final OutputStream outs = dstFS.create(new Path(outPath, filename));
        final FileStatus[] parts = srcFS.globStatus(new Path(sorted ? getSortOutputDir(level, strand) : wrkDir, filename + "-[0-9][0-9][0-9][0-9][0-9][0-9]"));
        for (final FileStatus part : parts) {
            final InputStream ins = srcFS.open(part.getPath());
            IOUtils.copyBytes(ins, outs, getConf(), false);
            ins.close();
        }
        for (final FileStatus part : parts) srcFS.delete(part.getPath(), false);
        outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
        outs.close();
        System.out.printf("summarize :: Merged %s%c in %d.%03d s.\n", level, strand, to.stopS(), to.fms());
    }
@Override
    protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException {
        List<String> taxa = new Vector<String>();
        String domain = m_domain.getStringValue();
        String id = "";
        if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota";
        try {
            URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String link = "";
            String key = "";
            String name = "";
            int counter = 0;
            String line = "";
            while ((line = reader.readLine()) != null) {
                String[] st = line.split("\t");
                ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]);
                ENADataHolder.instance().put(ena.desc, ena);
                taxa.add(ena.desc);
            }
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output, String endpoint) throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
        String itemURI = doLookup(lni, itemHandle, null);
        URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager);
        System.err.println("DEBUG: GET from URL: " + url.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        fixBasicAuth(url, conn);
        conn.connect();
        int status = conn.getResponseCode();
        if (status < 200 || status >= 300) {
            die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
        }
        InputStream in = conn.getInputStream();
        OutputStream out = new FileOutputStream(output);
        copyStream(in, out);
        in.close();
        out.close();
        System.err.println("DEBUG: Created local file " + output);
        System.err.println("RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
    }
private String getCurrentUniprotAccession(String accession) throws Exception {
        URL url = new URL(String.format(UNIPROT_ENTRY_QUERY_STRING, accession));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        connection.setRequestMethod("HEAD");
        connection.connect();
        if (connection.getResponseCode() != 200) {
            logger.debug("{} seems to be no UniProt accession", accession);
            throw new Exception("Missing UniProt entry for " + accession);
        }
        String effectiveUrl = connection.getURL().toString();
        String confirmedAccession = effectiveUrl.substring(effectiveUrl.lastIndexOf('/') + 1);
        logger.debug("getCurrentUniprotAccession: {} -> {}", new Object[] { accession, confirmedAccession });
        return confirmedAccession;
    }
private String getPage(String urlString) throws Exception {
        if (pageBuffer.containsKey(urlString)) return pageBuffer.get(urlString);
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        BufferedReader in = null;
        StringBuilder page = new StringBuilder();
        try {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                page.append(line);
                page.append("\n");
            }
        } catch (IOException ioe) {
            logger.warn("Failed to read web page");
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return page.toString();
    }
protected String getTextResponse(String address, boolean ignoreResponseCode) throws Exception {
        URL url = new URL(address);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setUseCaches(false);
        BufferedReader in = null;
        try {
            con.connect();
            if (!ignoreResponseCode) {
                assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode());
            }
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                builder.append(inputLine);
            }
            return builder.toString();
        } finally {
            if (in != null) {
                in.close();
            }
            con.disconnect();
        }
    }
protected int getResponseCode(String address) throws Exception {
        URL url = new URL(address);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setUseCaches(false);
        try {
            con.connect();
            return con.getResponseCode();
        } finally {
            con.disconnect();
        }
    }
protected void testConnection(String address) throws Exception {
        URL url = new URL(address);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setUseCaches(false);
        try {
            con.connect();
            assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode());
        } finally {
            con.disconnect();
        }
    }
@Override
                public InputStream getInputStream() {
                    String url = resourceURL_;
                    try {
                        return new URL(url).openStream();
                    } catch (Exception e) {
                    }
                    try {
                        return new FileInputStream("/" + url);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }
public static void saveFileFromURL(URL url, File destinationFile) throws IOException {
        FileOutputStream fo = new FileOutputStream(destinationFile);
        InputStream is = url.openStream();
        byte[] data = new byte[1024];
        int bytecount = 0;
        do {
            fo.write(data, 0, bytecount);
            bytecount = is.read(data);
        } while (bytecount > 0);
        fo.flush();
        fo.close();
    }
Response doSend() throws IOException {
        HttpURLConnection connection;
        String str = this.headers.get("Authorization");
        if (str != null) {
            String hs[] = str.split(",");
            if (hs[0].startsWith("OAuth ")) {
                hs[0] = hs[0].substring("OAuth ".length());
            }
            String newUrl = url + "?";
            for (int i = 0; i < hs.length; i++) {
                hs[i] = hs[i].trim().replace("\"", "");
                if (i == hs.length - 1) {
                    newUrl += hs[i];
                } else {
                    newUrl += hs[i] + "&";
                }
            }
            System.out.println("newUrl=" + newUrl);
            connection = (HttpURLConnection) new URL(newUrl).openConnection();
            connection.setRequestMethod(this.verb.name());
            if (verb.equals(Verb.PUT) || verb.equals(Verb.POST)) {
                addBody(connection, getBodyContents());
            }
            return new Response(connection);
        }
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod(this.verb.name());
        addHeaders(connection);
        if (verb.equals(Verb.PUT) || verb.equals(Verb.POST)) {
            addBody(connection, getBodyContents());
        }
        return new Response(connection);
    }
public static List<String> getFiles(int year, int month, int day, String type) throws Exception {
        ArrayList<String> list = new ArrayList<String>();
        URL url = new URL(baseUrl + "/" + year + "/" + ((month > 9) ? month : ("0" + month)) + "/" + ((day > 9) ? day : ("0" + day)));
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        while ((line = br.readLine()) != null && line != "") {
            if (line.startsWith("<tr>") && line.indexOf("[TXT]") >= 0) {
                int i = line.indexOf("href=");
                i = i + 6;
                int j = line.indexOf("\"", i);
                String filename = line.substring(i, j);
                if (filename.matches(".*" + type + ".*")) {
                    list.add(filename);
                }
            }
        }
        br.close();
        return list;
    }