semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public Object invoke(MethodInvocation invocation, int retryTimes) throws Throwable {
        retryTimes--;
        try {
            String url = getServiceUrl() + "/" + invocation.getMethod().getName();
            HttpPost postMethod = new HttpPost(url);
            if (invocation.getMethod().getParameterTypes().length > 0) postMethod.setEntity(new StringEntity(JsonUtils.toJson(invocation.getArguments())));
            HttpResponse rsp = HttpClientUtils.getDefaultInstance().execute(postMethod);
            StatusLine sl = rsp.getStatusLine();
            if (sl.getStatusCode() >= 300) {
                throw new RuntimeException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]");
            }
            HttpEntity entity = rsp.getEntity();
            StringBuilder sb = new StringBuilder();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line;
            while ((line = reader.readLine()) != null) sb.append(line).append("\n");
            reader.close();
            is.close();
            String responseBody = null;
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
                responseBody = sb.toString();
            }
            Type t = invocation.getMethod().getGenericReturnType();
            if (t.equals(Void.class) || responseBody == null) return null;
            return JsonUtils.fromJson(responseBody, t);
        } catch (ConnectTimeoutException e) {
            if (retryTimes < 0) throw e;
            if (urlFromDiscovery) {
                String serviceUrl = discoverServiceUrl(getServiceInterface().getName());
                if (!serviceUrl.equals(getServiceUrl())) {
                    setServiceUrl(serviceUrl);
                    log.info("relocate service url:" + serviceUrl);
                }
            }
            return invoke(invocation, retryTimes);
        }
    }
public static final InputStream getConfigStream(final String path) {
        final URL url = ConfigHelper.locateConfig(path);
        if (url == null) {
            String msg = "Unable to locate config file: " + path;
            log.error(msg);
            return null;
        }
        try {
            return url.openStream();
        } catch (IOException e) {
            log.error("Unable to open config file: " + path, e);
        }
        return null;
    }
@Test
    public void testAuthorizedMirror() throws IOException {
        final URL url = new URL("http://127.0.0.1:" + testPort + "/mirror?version=5&direction=just+right");
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        con.setRequestProperty("WWW-Authenticate", "Basic realm=\"karatasi\"");
        con.setRequestProperty("testline1", "1234567890");
        assertEquals("Expecting resource to exist.", HttpURLConnection.HTTP_OK, con.getResponseCode());
        assertEquals("mirror responds with Content-Type text/plain.", "text/plain", con.getContentType());
        assertNull("The server does not use any special encoding.", con.getContentEncoding());
        int bytesRemaining = con.getContentLength();
        final InputStream err = con.getErrorStream();
        assertNull("Expecting no error stream.", err);
        final InputStream in = con.getInputStream();
        final byte[] buf = new byte[bytesRemaining];
        for (int bytesRead; bytesRemaining > 0 && (bytesRead = in.read(buf, buf.length - bytesRemaining, bytesRemaining)) != -1; bytesRemaining -= bytesRead) {
        }
        assertEquals("Expecting server to send not fewer bytes as indicated.", 0, bytesRemaining);
        final String testResult = new String(buf, "ASCII");
        assertContains("Response has to contain this line.", testResult, "url direction::just right\r\n");
        assertContains("Response has to contain this line.", testResult, "url version::5\r\n");
        assertContains("Response has to contain this line.", testResult, "body authorization::Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n");
        assertContains("Response has to contain this line.", testResult, "body www-authenticate::Basic realm=\"karatasi\"\r\n");
        assertContains("Response has to contain this line.", testResult, "body testline1::1234567890\r\n");
    }
public void close() {
        try {
            if (writer != null) {
                BufferedReader reader;
                writer.close();
                writer = new BufferedWriter(new FileWriter(fileName));
                for (int i = 0; i < headers.size(); i++) writer.write(headers.get(i) + ",");
                writer.write("\n");
                reader = new BufferedReader(new FileReader(file));
                while (reader.ready()) writer.write(reader.readLine() + "\n");
                reader.close();
                writer.close();
                file.delete();
            }
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
    }
@Test
    @JUnitHttpServer(port = 10342, https = false, webapps = { @Webapp(context = "/fmpm", path = "src/test/resources/test-webapp") })
    public void testTestServlet() throws Exception {
        TestServlet.reset();
        HttpClient client = new DefaultHttpClient();
        HttpEntity entity = new StringEntity(xml);
        HttpPost method = new HttpPost("http://localhost:10342/fmpm/restful/NotificationMessageRelay");
        method.setEntity(entity);
        HttpResponse response = client.execute(method);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals(xml, TestServlet.getPosted());
    }
public static void invokeServlet(String op, String user) throws Exception {
        boolean isSayHi = true;
        try {
            if (!"sayHi".equals(op)) {
                isSayHi = false;
            }
            URL url = new URL("http://localhost:9080/helloworld/*.do");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            out.write("Operation=" + op);
            if (!isSayHi) {
                out.write("&User=" + user);
            }
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            boolean correctReturn = false;
            String response;
            if (isSayHi) {
                while ((response = in.readLine()) != null) {
                    if (response.contains("Bonjour")) {
                        System.out.println(" sayHi server return: Bonjour");
                        correctReturn = true;
                        break;
                    }
                }
            } else {
                while ((response = in.readLine()) != null) {
                    if (response.contains("Hello CXF")) {
                        System.out.println(" greetMe server return: Hello CXF");
                        correctReturn = true;
                        break;
                    }
                }
            }
            if (!correctReturn) {
                System.out.println("Can't got correct return from server.");
            }
            in.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
@Override
    public String getFeedFeed(String sUrl) {
        try {
            URL url = new URL(sUrl);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String result = "";
            String line;
            for (; (line = reader.readLine()) != null; result += line) {
            }
            reader.close();
            return result;
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return null;
    }
public void Sort(int a[]) {
        for (int i = a.length; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
private boolean keysMatch(String keyNMinusOne, String keyN) {
        boolean match = false;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.reset();
            digest.update(keyNMinusOne.getBytes());
            byte[] hashedBytes = digest.digest();
            String encodedHashedKey = new String(com.Ostermiller.util.Base64.encode(hashedBytes));
            match = encodedHashedKey.equals(keyN);
        } catch (NoSuchAlgorithmException e) {
        }
        return match;
    }
private String getData(String method, String arg) {
        try {
            URL url;
            String str;
            StringBuilder strBuilder;
            BufferedReader stream;
            url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8"));
            stream = new BufferedReader(new InputStreamReader(url.openStream()));
            strBuilder = new StringBuilder();
            while ((str = stream.readLine()) != null) {
                strBuilder.append(str);
            }
            stream.close();
            return strBuilder.toString();
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }
public static final byte[] getBytesFromUrl(final String urlString) throws BT747Exception {
        byte[] result = null;
        try {
            final URL url = new URL(urlString);
            final URLConnection urlc = url.openConnection();
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
            final InputStream ins = urlc.getInputStream();
            final ByteArrayOutputStream bout = new ByteArrayOutputStream(120 * 1024);
            final byte[] buf = new byte[1024];
            while (true) {
                final int n = ins.read(buf);
                if (n == -1) {
                    break;
                }
                bout.write(buf, 0, n);
            }
            result = bout.toByteArray();
            bout.close();
        } catch (final Exception e) {
            throw new BT747Exception(I18N.i18n("Problem downloading AGPS data."), e);
        }
        return result;
    }
public static void unzip(File file, ZipFile zipFile, File targetDirectory) throws BusinessException {
        LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory '" + targetDirectory.getAbsolutePath() + "'.");
        assert (file.exists() && file.isFile());
        if (targetDirectory.exists() == false) {
            LOG.debug("Creating target directory.");
            if (targetDirectory.mkdirs() == false) {
                throw new BusinessException("Could not create target directory at '" + targetDirectory.getAbsolutePath() + "'!");
            }
        }
        ZipInputStream zipin = null;
        try {
            zipin = new ZipInputStream(new FileInputStream(file));
            ZipEntry entry = null;
            while ((entry = zipin.getNextEntry()) != null) {
                LOG.debug("Unzipping entry '" + entry.getName() + "'.");
                if (entry.isDirectory()) {
                    LOG.debug("Skipping directory.");
                    continue;
                }
                final File targetFile = new File(targetDirectory, entry.getName());
                final File parentTargetFile = targetFile.getParentFile();
                if (parentTargetFile.exists() == false) {
                    LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'.");
                    if (parentTargetFile.mkdirs() == false) {
                        throw new BusinessException("Could not create target directory at '" + parentTargetFile.getAbsolutePath() + "'!");
                    }
                }
                InputStream input = null;
                FileOutputStream output = null;
                try {
                    input = zipFile.getInputStream(entry);
                    if (targetFile.createNewFile() == false) {
                        throw new BusinessException("Could not create target file '" + targetFile.getAbsolutePath() + "'!");
                    }
                    output = new FileOutputStream(targetFile);
                    int readBytes = 0;
                    byte[] buffer = new byte[BUFFER_SIZE];
                    while ((readBytes = input.read(buffer, 0, buffer.length)) > 0) {
                        output.write(buffer, 0, readBytes);
                    }
                } finally {
                    FileUtil.closeCloseable(input);
                    FileUtil.closeCloseable(output);
                }
            }
        } catch (IOException e) {
            throw new BusinessException("Could not unzip file '" + file.getAbsolutePath() + "'!", e);
        } finally {
            FileUtil.closeCloseable(zipin);
        }
    }
@Test
    public void testGetJarInformation() throws Exception {
        final URL url1 = getClass().getResource("/fakejars/something");
        final URL url2 = getClass().getResource("/fakejars/something-else");
        final URL url3 = getClass().getResource("/fakejars/another-thing");
        final Map<String, Date> paths = new HashMap<String, Date>();
        paths.put(SOMETHING_JAR, new Date(url1.openConnection().getLastModified()));
        paths.put(SOMETHING_ELSE_JAR, new Date(url2.openConnection().getLastModified()));
        paths.put(ANOTHER_THING_JAR, new Date(url3.openConnection().getLastModified()));
        paths.put(NOT_A_JAR, null);
        context.checking(new Expectations() {

            {
                one(servletContext).getResourcePaths(WEB_INF_LIB_PATH);
                will(returnValue(paths.keySet()));
                one(servletContext).getResource(SOMETHING_JAR);
                will(returnValue(url1));
                one(servletContext).getResource(SOMETHING_ELSE_JAR);
                will(returnValue(url2));
                one(servletContext).getResource(ANOTHER_THING_JAR);
                will(returnValue(url3));
            }
        });
        final Map<URL, Date> output = new ModulesImpl(servletContext, null, new LoggerProvider()).getJarInformation();
        assertThat(output.size(), is(3));
        for (final URL url : output.keySet()) {
            final String jarName = url.toString();
            final String key = WEB_INF_LIB_PATH + jarName.substring(jarName.lastIndexOf("/") + 1) + ".jar";
            assertThat(output.get(url), is(paths.get(key)));
        }
    }
private void bokActionPerformed(java.awt.event.ActionEvent evt) {
        if (this.seriesstatementpanel.getEnteredvalues().get(0).toString().trim().equals("")) {
            this.showWarningMessage("Enter Series Title");
        } else {
            String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds();
            String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveSeriesName("2", seriesstatementpanel.getEnteredvalues(), patlib);
            try {
                java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SeriesNameServlet");
                java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection();
                urlconn.setDoOutput(true);
                java.io.OutputStream dos = urlconn.getOutputStream();
                dos.write(xmlreq.getBytes());
                java.io.InputStream ios = urlconn.getInputStream();
                SAXBuilder saxb = new SAXBuilder();
                Document retdoc = saxb.build(ios);
                Element rootelement = retdoc.getRootElement();
                if (rootelement.getChild("Error") == null) {
                    this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase"));
                } else {
                    this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor"));
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
private static InputStream getResourceAsStream(String pResourcePath, Object pResourceLoader, boolean pThrow) {
        URL url = getResource(pResourcePath, pResourceLoader, pThrow);
        InputStream stream = null;
        if (url != null) {
            try {
                stream = url.openStream();
            } catch (IOException e) {
                LOGGER.warn(null, e);
            }
        }
        return stream;
    }
public Graph getGraph(URL urlFilename) throws MraldException {
            try {
                System.out.print("DBGraphReader: gettingGraph using url");
                InputStream inUrl = urlFilename.openStream();
                XMLGraphReader gr = new XMLGraphReader();
                gr.setNodeType(DefaultTreeNode.class);
                Graph graph = gr.loadGraph(inUrl);
                return graph;
            } catch (java.io.FileNotFoundException e) {
                throw new MraldException(e.getMessage());
            } catch (java.io.IOException e) {
                throw new MraldException(e.getMessage());
            }
        }
public List<Template> getTemplates(boolean fromPrivate) {
        String shared = fromPrivate ? "private" : "public";
        List<Template> templates = new ArrayList<Template>();
        String restURL = configuration.getBeehiveRESTRootUrl() + "account/" + userService.getAccount().getOid() + "/templates/" + shared;
        HttpGet httpGet = new HttpGet(restURL);
        httpGet.setHeader("Accept", "application/json");
        this.addAuthentication(httpGet);
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
                if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
                    throw new NotAuthenticatedException("User " + userService.getCurrentUser().getUsername() + " not authenticated! ");
                }
                throw new BeehiveNotAvailableException("Beehive is not available right now! ");
            }
            InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
            BufferedReader buffReader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = buffReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            String result = sb.toString();
            TemplateList templateList = buildTemplateListFromJson(result);
            List<TemplateDTO> dtoes = templateList.getTemplates();
            for (TemplateDTO dto : dtoes) {
                templates.add(dto.toTemplate());
            }
        } catch (IOException e) {
            throw new BeehiveNotAvailableException("Failed to get template list, The beehive is not available right now ", e);
        }
        return templates;
    }
public List<Template> getTemplatesByKeywordsAndPage(String keywords, int page) {
        String newKeywords = keywords;
        if (keywords == null || keywords.trim().length() == 0) {
            newKeywords = TemplateService.NO_KEYWORDS;
        }
        List<Template> templates = new ArrayList<Template>();
        String restURL = configuration.getBeehiveRESTRootUrl() + "templates/keywords/" + newKeywords + "/page/" + page;
        HttpGet httpGet = new HttpGet(restURL);
        httpGet.setHeader("Accept", "application/json");
        this.addAuthentication(httpGet);
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
                if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
                    throw new NotAuthenticatedException("User " + userService.getCurrentUser().getUsername() + " not authenticated! ");
                }
                throw new BeehiveNotAvailableException("Beehive is not available right now! ");
            }
            InputStreamReader reader = new InputStreamReader(response.getEntity().getContent());
            BufferedReader buffReader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = buffReader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            String result = sb.toString();
            TemplateList templateList = buildTemplateListFromJson(result);
            List<TemplateDTO> dtoes = templateList.getTemplates();
            for (TemplateDTO dto : dtoes) {
                templates.add(dto.toTemplate());
            }
        } catch (IOException e) {
            throw new BeehiveNotAvailableException("Failed to get template list, The beehive is not available right now ", e);
        }
        return templates;
    }
@Override
    public Template updateTemplate(Template template) {
        template.setContent(getTemplateContent(template.getScreen()));
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", template.getName()));
        params.add(new BasicNameValuePair("content", template.getContent()));
        params.add(new BasicNameValuePair("shared", template.isShared() + ""));
        params.add(new BasicNameValuePair("keywords", template.getKeywords()));
        try {
            String saveRestUrl = configuration.getBeehiveRESTRootUrl() + "account/" + userService.getAccount().getOid() + "/template/" + template.getOid();
            HttpPut httpPut = new HttpPut(saveRestUrl);
            addAuthentication(httpPut);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPut.setEntity(formEntity);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(httpPut);
            if (HttpServletResponse.SC_OK == response.getStatusLine().getStatusCode()) {
                resourceService.saveTemplateResourcesToBeehive(template);
            } else if (HttpServletResponse.SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                return null;
            } else {
                throw new BeehiveNotAvailableException("Failed to update template:" + template.getName() + ", Status code: " + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            throw new BeehiveNotAvailableException("Failed to save screen as a template: " + (e.getMessage() == null ? "" : e.getMessage()), e);
        }
        return template;
    }
List<String> HttpGet(URL url) throws IOException {
        List<String> responseList = new ArrayList<String>();
        Logger.getInstance().logInfo("HTTP GET: " + url, null, null);
        URLConnection con = url.openConnection();
        con.setAllowUserInteraction(false);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) responseList.add(inputLine);
        in.close();
        return responseList;
    }