semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public LogoutHandler(String username, String token) {
        try {
            URL url = new URL("http://eiffel.itba.edu.ar/hci/service/Security.groovy?method=LogOut&username=" + username + "&authentication_token=" + token);
            URLConnection urlc = url.openConnection();
            urlc.setDoOutput(false);
            urlc.setAllowUserInteraction(false);
            BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
            String str;
            StringBuffer sb = new StringBuffer();
            while ((str = br.readLine()) != null) {
                sb.append(str);
                sb.append("\n");
            }
            br.close();
            String response = sb.toString();
            if (response == null) {
                return;
            }
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(response));
            Document dom = db.parse(is);
            NodeList nl = dom.getElementsByTagName("response");
            String status = ((Element) nl.item(0)).getAttributes().item(0).getTextContent();
            if (status.toString().equals("fail")) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public MapInfo loadLocalMapData(String fileName) {
        MapInfo info = mapCacheLocal.get(fileName);
        if (info != null && info.getContent() == null) {
            try {
                BufferedReader bufferedreader;
                URL fetchUrl = new URL(localMapContextUrl, fileName);
                URLConnection urlconnection = fetchUrl.openConnection();
                if (urlconnection.getContentEncoding() != null) {
                    bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
                } else {
                    bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
                }
                String line;
                StringBuilder mapContent = new StringBuilder();
                while ((line = bufferedreader.readLine()) != null) {
                    mapContent.append(line);
                    mapContent.append("\n");
                }
                info.setContent(mapContent.toString());
                GameMapImplementation gameMap = GameMapImplementation.createFromMapInfo(info);
            } catch (IOException _ex) {
                System.err.println("HexTD::readFile:: Can't read from " + fileName);
            }
        }
        return info;
    }
@Override
    public MapInfo getMap(int mapId) {
        MapInfo info = mapCache.get(mapId);
        if (info != null && info.getContent() == null) {
            if (info.getInfo().get("fileName") == null) {
                if (mapId != lastRequestedMap) {
                    lastRequestedMap = mapId;
                    System.out.println("MapLoaderClient::getMap:requesting map from server " + mapId);
                    serverConnection.sendMessage(new MessageFetch(FetchType.map.name(), mapId));
                }
            } else {
                try {
                    System.out.println("MapLoaderClient::getMap:loading map from file " + info.getInfo().get("fileName"));
                    BufferedReader bufferedreader;
                    URL fetchUrl = new URL(localMapContextUrl, info.getInfo().get("fileName"));
                    URLConnection urlconnection = fetchUrl.openConnection();
                    if (urlconnection.getContentEncoding() != null) {
                        bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
                    } else {
                        bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
                    }
                    String line;
                    StringBuilder mapContent = new StringBuilder();
                    while ((line = bufferedreader.readLine()) != null) {
                        mapContent.append(line);
                        mapContent.append("\n");
                    }
                    info.setContent(mapContent.toString());
                    fireMapChanged(info);
                } catch (IOException _ex) {
                    System.err.println("MapLoaderClient::getMap:: Can't read from " + info.getInfo().get("fileName"));
                }
            }
        }
        return info;
    }
public static List<String> getLevelIndex(URL fetchUrl) {
        List<String> levelNames = new ArrayList<String>();
        BufferedReader bufferedreader;
        try {
            URLConnection urlconnection = fetchUrl.openConnection();
            urlconnection.setConnectTimeout(30000);
            if (urlconnection.getContentEncoding() != null) {
                bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
            } else {
                bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
            }
        } catch (IOException _ex) {
            System.err.println("HexTD::readFile:: Can't read from " + fetchUrl);
            return levelNames;
        }
        String sLine1;
        try {
            while ((sLine1 = bufferedreader.readLine()) != null) {
                if (sLine1.trim().length() != 0) {
                    levelNames.add(sLine1);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(MapLoaderClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        return levelNames;
    }
protected long incrementInDatabase(Object type) {
        long current_value;
        long new_value;
        String entry;
        if (global_entry != null) entry = global_entry; else throw new UnsupportedOperationException("Named key generators are not yet supported.");
        String lkw = (String) properties.get("net.ontopia.topicmaps.impl.rdbms.HighLowKeyGenerator.SelectSuffix");
        String sql_select;
        if (lkw == null && (database.equals("sqlserver"))) {
            sql_select = "select " + valcol + " from " + table + " with (XLOCK) where " + keycol + " = ?";
        } else {
            if (lkw == null) {
                if (database.equals("sapdb")) lkw = "with lock"; else lkw = "for update";
            }
            sql_select = "select " + valcol + " from " + table + " where " + keycol + " = ? " + lkw;
        }
        if (log.isDebugEnabled()) log.debug("KeyGenerator: retrieving: " + sql_select);
        Connection conn = null;
        try {
            conn = connfactory.requestConnection();
            PreparedStatement stm1 = conn.prepareStatement(sql_select);
            try {
                stm1.setString(1, entry);
                ResultSet rs = stm1.executeQuery();
                if (!rs.next()) throw new OntopiaRuntimeException("HIGH/LOW key generator table '" + table + "' not initialized (no rows).");
                current_value = rs.getLong(1);
                rs.close();
            } finally {
                stm1.close();
            }
            new_value = current_value + grabsize;
            String sql_update = "update " + table + " set " + valcol + " = ? where " + keycol + " = ?";
            if (log.isDebugEnabled()) log.debug("KeyGenerator: incrementing: " + sql_update);
            PreparedStatement stm2 = conn.prepareStatement(sql_update);
            try {
                stm2.setLong(1, new_value);
                stm2.setString(2, entry);
                stm2.executeUpdate();
            } finally {
                stm2.close();
            }
            conn.commit();
        } catch (SQLException e) {
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException e2) {
            }
            throw new OntopiaRuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    throw new OntopiaRuntimeException(e);
                }
            }
        }
        value = current_value + 1;
        max_value = new_value;
        return value;
    }
public int getUrl() {
        try {
            final URL url = new URL(this.url);
            conn = url.openConnection();
            if (cookies != null) {
                conn.setRequestProperty("Cookie", cookies);
            }
            InputStreamReader inputstream = new InputStreamReader(conn.getInputStream(), charset);
            charset = inputstream.getEncoding();
            BufferedReader input = new BufferedReader(inputstream);
            String line;
            while ((line = input.readLine()) != null) {
                content += line + "\n";
            }
            return 0;
        } catch (MalformedURLException e) {
            return 1;
        } catch (IOException e2) {
            return 2;
        }
    }
protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) {
		List<VideoSearchResult> resultsList = new ArrayList<>();
		try {
			// set up the HTTP request factory
			HttpTransport transport = new NetHttpTransport();
			HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() {

				@Override
				public void initialize(HttpRequest request) {
					// set the parser
					JsonCParser parser = new JsonCParser();
					parser.jsonFactory = JSON_FACTORY;
					request.addParser(parser);
					// set up the Google headers
					GoogleHeaders headers = new GoogleHeaders();
					headers.setApplicationName("OGLExplorer/1.0");
					headers.gdataVersion = "2";
					request.headers = headers;
				}
			});
			// build the YouTube URL
			YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos");
			url.maxResults = number;
			url.words = words;
			url.startIndex = offset + 1;
			// build
			HttpRequest request = factory.buildGetRequest(url);
			// execute
			HttpResponse response = request.execute();
			VideoFeed feed = response.parseAs(VideoFeed.class);
			if (feed.items == null) {
				return null;
			}
			// browse result and convert them to the local generic object model
			for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) {
				Video result = feed.items.get(i);
				VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1);
				modelResult.setTitle(result.title);
				modelResult.setDescription(result.description);
				modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL));
				modelResult.setPath(result.player.defaultUrl);
				resultsList.add(modelResult);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cancelMonitor.isCanceled()) {
			return null;
		}
		return resultsList;
	}
public String execute() {
        String dir = "E:\\ganymede_workspace\\training01\\web\\user_imgs\\";
        HomeMap map = new HomeMap();
        map.setDescription(description);
        Integer id = homeMapDao.saveHomeMap(map);
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(dir + id);
            IOUtils.copy(new FileInputStream(imageFile), fos);
            IOUtils.closeQuietly(fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list();
    }
private File magiaImagen(String titulo) throws MalformedURLException, IOException {
            titulo = URLEncoder.encode("\"" + titulo + "\"", "UTF-8");
            setMessage("Buscando portada en google...");
            URL url = new URL("http://images.google.com/images?q=" + titulo + "&imgsz=small|medium|large|xlarge");
            setMessage("Buscando portada en google: conectando...");
            URLConnection urlCon = url.openConnection();
            urlCon.setRequestProperty("User-Agent", "MyBNavigator");
            BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), Charset.forName("ISO-8859-1")));
            String inputLine;
            StringBuilder sb = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            inputLine = sb.toString();
            String busqueda = "<a href=/imgres?imgurl=";
            setMessage("Buscando portada en google: analizando...");
            while (inputLine.indexOf(busqueda) != -1) {
                int posBusqueda = inputLine.indexOf(busqueda) + busqueda.length();
                int posFinal = inputLine.indexOf("&", posBusqueda);
                String urlImagen = inputLine.substring(posBusqueda, posFinal);
                switch(confirmarImagen(urlImagen)) {
                    case JOptionPane.YES_OPTION:
                        setMessage("Descargando imagen...");
                        URL urlImg = new URL(urlImagen);
                        String ext = urlImagen.substring(urlImagen.lastIndexOf(".") + 1);
                        File f = File.createTempFile("Ignotus", "." + ext);
                        BufferedImage image = ImageIO.read(urlImg);
                        FileOutputStream outer = new FileOutputStream(f);
                        ImageIO.write(image, ext, outer);
                        outer.close();
                        in.close();
                        return f;
                    case JOptionPane.CANCEL_OPTION:
                        in.close();
                        return null;
                    default:
                        inputLine = inputLine.substring(posBusqueda + busqueda.length());
                }
            }
            return null;
        }
public static ContextInfo login(Context pContext, String pUsername, String pPwd, String pDeviceid) {
        HttpClient lClient = new DefaultHttpClient();
        StringBuilder lBuilder = new StringBuilder();
        ContextInfo lContextInfo = null;
        HttpPost lHttpPost = new HttpPost(new StringBuilder().append("http://").append(LoginActivity.mIpAddress.getText().toString()).append("/ZJWHServiceTest/GIS_Duty.asmx/PDALoginCheck").toString());
        List<NameValuePair> lNameValuePairs = new ArrayList<NameValuePair>(2);
        lNameValuePairs.add(new BasicNameValuePair("username", pUsername));
        lNameValuePairs.add(new BasicNameValuePair("password", pPwd));
        lNameValuePairs.add(new BasicNameValuePair("deviceid", pDeviceid));
        try {
            lHttpPost.setEntity(new UrlEncodedFormEntity(lNameValuePairs));
            HttpResponse lResponse = lClient.execute(lHttpPost);
            BufferedReader lHeader = new BufferedReader(new InputStreamReader(lResponse.getEntity().getContent()));
            for (String s = lHeader.readLine(); s != null; s = lHeader.readLine()) {
                lBuilder.append(s);
            }
            String lResult = lBuilder.toString();
            lResult = DataParseUtil.handleResponse(lResult);
            lContextInfo = LoginParseUtil.onlineParse(lResult);
            lContextInfo.setDeviceid(pDeviceid);
            if (0 == lContextInfo.getLoginFlag()) {
                lContextInfo.setLoginFlag(0);
            } else if (1 == lContextInfo.getLoginFlag()) {
                lContextInfo.setLoginFlag(1);
                updateUserInfo(pContext, lContextInfo);
            } else if (2 == lContextInfo.getLoginFlag()) {
                lContextInfo.setLoginFlag(2);
            } else if (3 == lContextInfo.getLoginFlag()) {
                lContextInfo.setLoginFlag(3);
            }
        } catch (Exception e) {
            return lContextInfo;
        }
        return lContextInfo;
    }
public void executaAlteracoes() {
        Album album = Album.getAlbum();
        Photo[] fotos = album.getFotos();
        Photo f;
        int ultimoFotoID = -1;
        int albumID = album.getAlbumID();
        sucesso = true;
        PainelWebFotos.setCursorWait(true);
        albumID = recordAlbumData(album, albumID);
        sucesso = recordFotoData(fotos, ultimoFotoID, albumID);
        String caminhoAlbum = Util.getFolder("albunsRoot").getPath() + File.separator + albumID;
        File diretorioAlbum = new File(caminhoAlbum);
        if (!diretorioAlbum.isDirectory()) {
            if (!diretorioAlbum.mkdir()) {
                Util.log("[AcaoAlterarAlbum.executaAlteracoes.7]/ERRO: diretorio " + caminhoAlbum + " n�o pode ser criado. abortando");
                return;
            }
        }
        for (int i = 0; i < fotos.length; i++) {
            f = fotos[i];
            if (f.getCaminhoArquivo().length() > 0) {
                try {
                    FileChannel canalOrigem = new FileInputStream(f.getCaminhoArquivo()).getChannel();
                    FileChannel canalDestino = new FileOutputStream(caminhoAlbum + File.separator + f.getFotoID() + ".jpg").getChannel();
                    canalDestino.transferFrom(canalOrigem, 0, canalOrigem.size());
                    canalOrigem = null;
                    canalDestino = null;
                } catch (Exception e) {
                    Util.log("[AcaoAlterarAlbum.executaAlteracoes.8]/ERRO: " + e);
                    sucesso = false;
                }
            }
        }
        prepareThumbsAndFTP(fotos, albumID, caminhoAlbum);
        prepareExtraFiles(album, caminhoAlbum);
        fireChangesToGUI(fotos);
        dispatchAlbum();
        PainelWebFotos.setCursorWait(false);
    }
public static String getStringHash(String fileName) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            digest.reset();
            digest.update(fileName.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < messageDigest.length; i++) builder.append(Integer.toHexString(0xFF & messageDigest[i]));
            String result = builder.toString();
            return result;
        } catch (NoSuchAlgorithmException ex) {
            return fileName;
        }
    }
public static void copyFile(File source, File destination) throws IOException {
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(destination).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }
@Override
    public List<WebSearchResult> search(String term) {
        List<GoogleResult> results = null;
        try {
            URL url = new URL(GoogleWebSearch.GOOGLE_URL + URLEncoder.encode(term, GoogleWebSearch.CHARSET));
            Reader reader = new InputStreamReader(url.openStream(), GoogleWebSearch.CHARSET);
            GoogleResponse jsonResults = new Gson().fromJson(reader, GoogleResponse.class);
            results = jsonResults.getResponseData().getResults();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<WebSearchResult> googleResults = new ArrayList<WebSearchResult>();
        if (results != null) {
            googleResults.addAll(results);
        }
        return googleResults;
    }
@Override
    public void connect() throws Exception {
        if (client != null) {
            _logger.warn("Already connected.");
            return;
        }
        try {
            _logger.debug("About to connect to ftp server " + server + " port " + port);
            client = new FTPClient();
            client.connect(server, port);
            if (!FTPReply.isPositiveCompletion(client.getReplyCode())) throw new Exception("Unable to connect to FTP server " + server + " port " + port + " got error [" + client.getReplyString() + "]");
            _logger.info("Connected to ftp server " + server + " port " + port);
            _logger.debug(client.getReplyString());
            if (!client.login(username, password)) throw new Exception("Invalid username / password combination for FTP server " + server + " port " + port);
            _logger.debug("Log in successful.");
            _logger.info("FTP server is [" + client.getSystemType() + "]");
            if (passiveMode) {
                client.enterLocalPassiveMode();
                _logger.info("Passive mode selected.");
            } else {
                client.enterLocalActiveMode();
                _logger.info("Active mode selected.");
            }
            if (binaryMode) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                _logger.info("BINARY mode selected.");
            } else {
                client.setFileType(FTP.ASCII_FILE_TYPE);
                _logger.info("ASCII mode selected.");
            }
            if (client.changeWorkingDirectory(remoteRootDir)) {
                _logger.info("Changed directory to " + remoteRootDir);
            } else {
                throw new Exception("Cannot change directory to [" + remoteRootDir + "] on FTP server " + server + " port " + port);
            }
        } catch (Exception e) {
            _logger.error("Failed to connect to the FTP server " + server + " on port " + port, e);
            disconnect();
            throw e;
        }
    }
protected String calcAuthResponse(String challenge) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(securityPolicy);
        md.update(challenge.getBytes());
        for (int i = 0, n = password.length; i < n; i++) {
            md.update((byte) password[i]);
        }
        byte[] digest = md.digest();
        StringBuffer digestText = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            int v = (digest[i] < 0) ? digest[i] + 256 : digest[i];
            String hex = Integer.toHexString(v);
            if (hex.length() == 1) {
                digestText.append("0");
            }
            digestText.append(hex);
        }
        return digestText.toString();
    }
public static void main(String arg[]) {
        try {
            String readFile = arg[0];
            String writeFile = arg[1];
            java.io.FileInputStream ss = new java.io.FileInputStream(readFile);
            ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true);
            javax.activation.DataHandler dh = new javax.activation.DataHandler(ms);
            java.io.InputStream is = dh.getInputStream();
            java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile);
            byte[] buf = new byte[512];
            int read = 0;
            do {
                read = is.read(buf);
                if (read > 0) {
                    fo.write(buf, 0, read);
                }
            } while (read > -1);
            fo.close();
            is.close();
        } catch (java.lang.Exception e) {
            log.error(Messages.getMessage("exception00"), e);
        }
    }
private void loadDynamically(File result, String extraPath) {
        URL url = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            url = new URL(homeServerUrl + extraPath);
            is = url.openStream();
            fos = new FileOutputStream(result);
            byte[] buff = new byte[8192];
            int nbRead;
            while ((nbRead = is.read(buff)) > 0) fos.write(buff, 0, nbRead);
        } catch (IOException e) {
            throw new StellariumException("Cannot dynamically load " + result + " from " + url);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace(System.out);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    }