semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void fetchCourses(String jsonurl) {
        if (jsonurl == null) {
            throw new NullPointerException("jsonurl");
        }
        InputStreamReader in = null;
        try {
            URL url = new URL(jsonurl);
            in = new InputStreamReader(url.openConnection().getInputStream());
            JSONObject root = (JSONObject) JSONValue.parse(in);
            JSONArray courseAr = (JSONArray) root.get("courses");
            ListIterator<JSONObject> it = courseAr.listIterator();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            while (it.hasNext()) {
                JSONObject obj = it.next();
                Course c;
                try {
                    c = new Course((String) obj.get("course"), df.parse((String) obj.get("start_date")), df.parse((String) obj.get("end_date")));
                    courses.add(c);
                } catch (ParseException pe) {
                }
            }
            in.close();
        } catch (IOException e) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
public void process() {
        try {
            update("Shutdown knowledge base ...", 0);
            DBHelper.shutdownDB();
            update("Shutdown knowledge base ...", 9);
            String zipDir = P.DIR.getPKBDataPath();
            update("Backup in progress ...", 10);
            List<String> fileList = getFilesToZip(zipDir);
            File file = new File(fileName);
            ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(file));
            byte[] readBuffer = new byte[2156];
            int bytesIn = 0;
            for (int i = 0; i < fileList.size(); i++) {
                String filePath = fileList.get(i);
                File f = new File(filePath);
                FileInputStream fis = new FileInputStream(f);
                String zipEntryName = f.getPath().substring(zipDir.length() + 1);
                ZipEntry anEntry = new ZipEntry(zipEntryName);
                zout.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zout.write(readBuffer, 0, bytesIn);
                }
                fis.close();
                int percentage = (int) Math.round((i + 1) * 80.0 / fileList.size());
                update("Backup in progress ...", 10 + percentage);
            }
            zout.close();
            update("Restart knowledge base ...", 91);
            DBHelper.startDB();
            update("Backup is done!", 100);
        } catch (Exception ex) {
            ex.printStackTrace();
            update("Error occurs during backup!", 100);
        }
    }
@Override
    public void close() throws IOException {
        super.close();
        byte[] signatureData = toByteArray();
        ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream);
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile));
        ZipEntry zipEntry;
        while (null != (zipEntry = zipInputStream.getNextEntry())) {
            if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) {
                ZipEntry newZipEntry = new ZipEntry(zipEntry.getName());
                zipOutputStream.putNextEntry(newZipEntry);
                LOG.debug("copying " + zipEntry.getName());
                IOUtils.copy(zipInputStream, zipOutputStream);
            }
        }
        zipInputStream.close();
        zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE);
        LOG.debug("writing " + zipEntry.getName());
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(signatureData, zipOutputStream);
        zipOutputStream.close();
    }
public void open(final String method, final java.net.URL url, boolean asyncFlag, final String userName, final String password) throws java.io.IOException {
        this.abort();
        Proxy proxy = this.proxy;
        URLConnection c = proxy == null || proxy == Proxy.NO_PROXY ? url.openConnection() : url.openConnection(proxy);
        synchronized (this) {
            this.connection = c;
            this.isAsync = asyncFlag;
            this.requestMethod = method;
            this.requestURL = url;
            this.requestUserName = userName;
            this.requestPassword = password;
        }
        this.changeState(HttpRequest.STATE_LOADING, 0, null, null);
    }
public Document load(java.net.URL url) throws DOMTestLoadException {
        Document doc = null;
        try {
            java.io.InputStream stream = url.openStream();
            Object tidyObj = tidyConstructor.newInstance(new Object[0]);
            doc = (Document) parseDOMMethod.invoke(tidyObj, new Object[] { stream, null });
        } catch (InvocationTargetException ex) {
            throw new DOMTestLoadException(ex.getTargetException());
        } catch (Exception ex) {
            throw new DOMTestLoadException(ex);
        }
        return doc;
    }
public static String doPost(String url, Map mapa) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> params = getParams(mapa);
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse httpresponse = httpclient.execute(httpPost);
            HttpEntity httpentity = httpresponse.getEntity();
            if (httpentity != null) {
                InputStream is = httpentity.getContent();
                return Funcoes.readString(is);
            }
        } catch (IOException e) {
            Log.e("HttpClientImpl.doPost", e.getMessage());
        }
        return url;
    }
private static InputStream download(String url) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse httpresponse = httpclient.execute(httpget);
            HttpEntity httpentity = httpresponse.getEntity();
            if (httpentity != null) {
                return httpentity.getContent();
            }
        } catch (Exception e) {
            Log.e("Android", e.getMessage());
        }
        return null;
    }
public static void copy(final String source, final String dest) {
        final File s = new File(source);
        final File w = new File(dest);
        try {
            final FileInputStream in = new FileInputStream(s);
            final FileOutputStream out = new FileOutputStream(w);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        } catch (IOException ioe) {
            System.out.println("Error reading/writing files!");
        }
    }
public TreeNode fetch(TreeNode owner, String pattern, String fetchChilds, String fetchAttributes, String flags, boolean updateOwner) throws Exception {
        builder.start(owner, updateOwner);
        parser.setDocumentHandler(builder);
        pattern = URLEncoder.encode(pattern);
        String arg = server + "?todo=fetch&db=" + db + "&document=" + document + "&pattern=" + pattern;
        if (fetchChilds != null) {
            arg += "&fetch-childs=" + URLEncoder.encode(fetchChilds);
        }
        if (fetchAttributes != null) {
            arg += "&fetch-attributes=" + URLEncoder.encode(fetchAttributes);
        }
        if (flags != null) {
            arg += "&flags=" + URLEncoder.encode(flags);
        }
        URL url = new URL(arg);
        URLConnection con = url.openConnection();
        con.setUseCaches(false);
        con.connect();
        InputSource xmlInput = new InputSource(new InputStreamReader(con.getInputStream(), "ISO-8859-1"));
        parser.parse(xmlInput);
        return owner;
    }
public TreeNode fetchArchive(TreeNode owner, int id) throws Exception {
        builder.start(owner, false);
        parser.setDocumentHandler(builder);
        String arg = server + "?todo=archive&db=" + db + "&document=" + document + "&id=" + id;
        URL url = new URL(arg);
        URLConnection con = url.openConnection();
        con.setUseCaches(false);
        con.connect();
        InputSource xmlInput = new InputSource(new InputStreamReader(con.getInputStream(), "ISO-8859-1"));
        parser.parse(xmlInput);
        return owner;
    }
public String getString(String arg) throws Exception {
        URL url = new URL(arg);
        URLConnection con = url.openConnection();
        con.setUseCaches(false);
        con.connect();
        InputStreamReader src = new InputStreamReader(con.getInputStream(), "ISO-8859-1");
        StringBuffer stb = new StringBuffer();
        char[] buf = new char[1024];
        int l;
        while ((l = src.read(buf, 0, 1024)) >= 0) {
            stb.append(buf, 0, l);
        }
        String res = stb.toString();
        if (res.startsWith("<pannenleiter-exception")) {
            builder.start(new TreeNode((TreeWidget) null, false), false);
            InputSource xmlInput = new InputSource(new StringReader(res));
            parser.setDocumentHandler(builder);
            parser.parse(xmlInput);
        }
        return res;
    }
private String fetch(URL url) {
        StringBuilder body = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                body.append(inputLine);
            }
            in.close();
            return body.toString();
        } catch (Exception e) {
            debug("Error: fetch: Exception reading URL: " + e);
        }
        return null;
    }
public synchronized String encrypt(String plaintext) throws Exception {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (Exception e) {
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }
@Override
    public void handle(HttpExchange http) throws IOException {
        Headers reqHeaders = http.getRequestHeaders();
        Headers respHeader = http.getResponseHeaders();
        respHeader.add("Content-Type", "text/plain");
        http.sendResponseHeaders(200, 0);
        PrintWriter console = new PrintWriter(System.err);
        PrintWriter web = new PrintWriter(http.getResponseBody());
        PrintWriter out = new PrintWriter(new YWriter(web, console));
        out.println("### " + new Date() + " ###");
        out.println("Method: " + http.getRequestMethod());
        out.println("Protocol: " + http.getProtocol());
        out.println("RemoteAddress.HostName: " + http.getRemoteAddress().getHostName());
        for (String key : reqHeaders.keySet()) {
            out.println("* \"" + key + "\"");
            for (String v : reqHeaders.get(key)) {
                out.println("\t" + v);
            }
        }
        InputStream in = http.getRequestBody();
        if (in != null) {
            out.println();
            IOUtils.copyTo(new InputStreamReader(in), out);
            in.close();
        }
        out.flush();
        out.close();
    }
private static final String getResult(String url, String postData) throws MalformedURLException, IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        if (!postData.equals("null")) {
            postData = postData.substring(1, postData.length() - 1);
            connection.setDoOutput(true);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            writer.write(postData);
            writer.flush();
        }
        InputStreamReader reader = new InputStreamReader(connection.getInputStream());
        int i;
        StringBuffer buffer = new StringBuffer();
        while ((i = reader.read()) != -1) {
            buffer.append((char) i);
        }
        reader.close();
        String response = buffer.toString().trim();
        response = StringUtilities.replaceAll(response, "\r\n", "\\r\\n");
        response = StringUtilities.replaceAll(response, "\"", "\\\"");
        return "\"" + response + "\"";
    }
private void saveFile(Folder folder, Object key, InputStream stream) throws FileManagerException {
        File file = new File(folder, key.toString());
        LOGGER.debug("Writing file: " + file.getAbsolutePath());
        Writer writer = null;
        Writer encodedWriter = null;
        try {
            encodedWriter = new OutputStreamWriter(new FileOutputStream(file), getEncodeCharset());
            IOUtils.copy(stream, encodedWriter, getDecodeCharset());
            LOGGER.info("saveFile(), decode charset: " + getDecodeCharset() + ", encode charset: " + getEncodeCharset());
        } catch (IOException e) {
            throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e);
        } finally {
            try {
                encodedWriter.close();
            } catch (IOException e) {
                throw new FileManagerException("Unable to write to file: " + file.getAbsolutePath(), e);
            }
        }
    }
public static HttpData postRequest(HttpPost postMethod, String xml) throws ClientProtocolException, SocketException, IOException, SocketTimeoutException {
        HttpData data = new HttpData();
        try {
            postMethod.addHeader("Content-Type", "text/xml; charset=utf-8");
            postMethod.addHeader("Connection", "Keep-Alive");
            postMethod.addHeader("User-Agent", "Openwave");
            StringEntity se = new StringEntity(xml, HTTP.UTF_8);
            postMethod.setEntity(se);
            printPostRequestHeader(postMethod);
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIMEOUT);
            HttpClient client = new DefaultHttpClient(httpParams);
            client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
            client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
            HttpResponse httpResponse = client.execute(postMethod);
            if (httpResponse == null) throw new SocketTimeoutException();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                byte bytearray[] = ImageInputStream(httpResponse.getEntity());
                data.setByteArray(bytearray);
            } else {
                data.setStatusCode(httpResponse.getStatusLine().getStatusCode() + "");
            }
        } catch (SocketException e) {
            throw new SocketException();
        } catch (SocketTimeoutException e) {
            throw new SocketTimeoutException();
        } catch (ClientProtocolException e) {
            throw new ClientProtocolException();
        } catch (IOException e) {
            throw new IOException();
        } finally {
            postMethod.abort();
        }
        return data;
    }
protected byte[] getTSAResponse(byte[] requestBytes) throws SinaduraCoreException {
        byte[] respBytes = null;
        try {
            URL url = new URL(this.tsaURL);
            URLConnection tsaConnection = null;
            if (this.proxy == null) tsaConnection = url.openConnection(); else tsaConnection = url.openConnection(this.proxy);
            tsaConnection.setDoInput(true);
            tsaConnection.setDoOutput(true);
            tsaConnection.setUseCaches(false);
            tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
            tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");
            if ((this.tsaUsername != null) && !this.tsaUsername.equals("")) {
                String userPassword = this.tsaUsername + ":" + this.tsaPassword;
                tsaConnection.setRequestProperty("Authorization", "Basic " + new String(new sun.misc.BASE64Encoder().encode(userPassword.getBytes())));
            }
            OutputStream out = tsaConnection.getOutputStream();
            out.write(requestBytes);
            out.close();
            InputStream inp = tsaConnection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
                baos.write(buffer, 0, bytesRead);
            }
            respBytes = baos.toByteArray();
            String encoding = tsaConnection.getContentEncoding();
            if (encoding != null && encoding.equalsIgnoreCase("base64")) {
                sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
                respBytes = dec.decodeBuffer(new String(respBytes));
            }
        } catch (MalformedURLException e) {
            throw new SinaduraCoreException("URL malformed " + e.getMessage(), e);
        } catch (IOException e) {
            throw new SinaduraCoreException("Connection Error " + e.getMessage(), e);
        }
        return respBytes;
    }
public static void copyFile(File src, File dst) throws IOException {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }
protected boolean exists(String filename) {
            try {
                URL url = new URL(base, filename);
                URLConnection conn = url.openConnection();
                conn.connect();
                conn.getInputStream().close();
                return true;
            } catch (IOException ex) {
                return false;
            }
        }
protected URLConnection openConnection(URL url) throws IOException {
        if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry));
        String bidString = url.getHost();
        if (bidString == null) {
            throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm()));
        }
        AbstractBundle bundle = null;
        long bundleID;
        try {
            bundleID = Long.parseLong(bidString);
        } catch (NumberFormatException nfe) {
            throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString));
        }
        bundle = (AbstractBundle) context.getBundle(bundleID);
        if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) {
            checkAdminPermission(bundle);
        }
        if (bundle == null) {
            throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm()));
        }
        return (new BundleURLConnection(url, findBundleEntry(url, bundle)));
    }
public boolean copy(String file, String path) {
        try {
            File file_in = new File(file);
            String tmp1, tmp2;
            tmp1 = file;
            tmp2 = path;
            while (tmp2.contains("\\")) {
                tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1);
                tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1);
            }
            tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\"));
            File file_out = new File(tmp1);
            File parent = file_out.getParentFile();
            parent.mkdirs();
            FileInputStream in1 = new FileInputStream(file_in);
            FileOutputStream out1 = new FileOutputStream(file_out);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c);
            in1.close();
            out1.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error!");
            return false;
        }
    }
public boolean copy(String file, String target, int tag) {
        try {
            File file_in = new File(file);
            File file_out = new File(target);
            File parent = file_out.getParentFile();
            parent.mkdirs();
            FileInputStream in1 = new FileInputStream(file_in);
            FileOutputStream out1 = new FileOutputStream(file_out);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c);
            in1.close();
            out1.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error!");
            return false;
        }
    }
public static boolean insert(final CelulaFinanceira objCelulaFinanceira) {
        int result = 0;
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            final String sql = "insert into celula_financeira " + "(descricao, id_orgao, id_gestao, " + "id_natureza_despesa, id_programa_trabalho, " + "id_unidade_orcamentaria, id_fonte_recursos, " + "valor_provisionado, gasto_previsto, gasto_real, " + "saldo_previsto, saldo_real)" + " values (?, ?, ?, ?, ?, ?, ?, TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2), TRUNCATE(?,2))";
            pst = c.prepareStatement(sql);
            pst.setString(1, objCelulaFinanceira.getDescricao());
            pst.setLong(2, (objCelulaFinanceira.getOrgao()).getCodigo());
            pst.setString(3, (objCelulaFinanceira.getGestao()).getCodigo());
            pst.setString(4, (objCelulaFinanceira.getNaturezaDespesa()).getCodigo());
            pst.setString(5, (objCelulaFinanceira.getProgramaTrabalho()).getCodigo());
            pst.setString(6, (objCelulaFinanceira.getUnidadeOrcamentaria()).getCodigo());
            pst.setString(7, (objCelulaFinanceira.getFonteRecursos()).getCodigo());
            pst.setDouble(8, objCelulaFinanceira.getValorProvisionado());
            pst.setDouble(9, objCelulaFinanceira.getGastoPrevisto());
            pst.setDouble(10, objCelulaFinanceira.getGastoReal());
            pst.setDouble(11, objCelulaFinanceira.getSaldoPrevisto());
            pst.setDouble(12, objCelulaFinanceira.getSaldoReal());
            result = pst.executeUpdate();
            c.commit();
        } catch (final SQLException e) {
            try {
                c.rollback();
            } catch (final SQLException e1) {
                System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[CelulaFinanceiraDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
private boolean canReadSource(String fileURL) {
        URL url;
        try {
            url = new URL(fileURL);
        } catch (MalformedURLException e) {
            log.error("Error accessing URL " + fileURL + ".");
            return false;
        }
        InputStream is;
        try {
            is = url.openStream();
        } catch (IOException e) {
            log.error("Error creating Input Stream from URL '" + fileURL + "'.");
            return false;
        }
        return true;
    }