semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public void connect() throws IOException {
        URL url = getLocator().getURL();
        if (url.getProtocol().equals("file")) {
            final String newUrlStr = URLUtils.createAbsoluteFileUrl(url.toExternalForm());
            if (newUrlStr != null) {
                if (!newUrlStr.toString().equals(url.toExternalForm())) {
                    logger.warning("Changing file URL to absolute for URL.openConnection, from " + url.toExternalForm() + " to " + newUrlStr);
                    url = new URL(newUrlStr);
                }
            }
        }
        conn = url.openConnection();
        if (!url.getProtocol().equals("ftp") && conn.getURL().getProtocol().equals("ftp")) {
            logger.warning("URL.openConnection() morphed " + url + " to " + conn.getURL());
            throw new IOException("URL.openConnection() returned an FTP connection for a non-ftp url: " + url);
        }
        if (conn instanceof HttpURLConnection) {
            final HttpURLConnection huc = (HttpURLConnection) conn;
            huc.connect();
            final int code = huc.getResponseCode();
            if (!(code >= 200 && code < 300)) {
                huc.disconnect();
                throw new IOException("HTTP response code: " + code);
            }
            logger.finer("URL: " + url);
            logger.finer("Response code: " + code);
            logger.finer("Full content type: " + conn.getContentType());
            boolean contentTypeSet = false;
            if (stripTrailer(conn.getContentType()).equals("text/plain")) {
                final String ext = PathUtils.extractExtension(url.getPath());
                if (ext != null) {
                    final String result = MimeManager.getMimeType(ext);
                    if (result != null) {
                        contentTypeStr = ContentDescriptor.mimeTypeToPackageName(result);
                        contentTypeSet = true;
                        logger.fine("Received content type " + conn.getContentType() + "; overriding based on extension, to: " + result);
                    }
                }
            }
            if (!contentTypeSet) contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType()));
        } else {
            conn.connect();
            contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType());
        }
        contentType = new ContentDescriptor(contentTypeStr);
        sources = new URLSourceStream[1];
        sources[0] = new URLSourceStream();
        connected = true;
    }
public static String getHash(String password) {
        if (password == null || password.length() == 0) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA");
            password = saltPassword(password);
            digest.update(password.getBytes());
            String result = getHexString(digest.digest());
            return result;
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {
        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }
        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        IOUtils.copy(inputStream, outputStream);
        outputStream.close();
        inputStream.close();
    }
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();
        }
    }
public static Collection<Class<? extends Page>> loadPages() throws IOException {
        ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        Collection<Class<? extends Page>> pages = new ArrayList<Class<? extends Page>>();
        Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName());
        while (e.hasMoreElements()) {
            URL url = e.nextElement();
            InputStream is = url.openStream();
            ;
            try {
                BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while (true) {
                    String line = r.readLine();
                    if (line == null) break;
                    int comment = line.indexOf('#');
                    if (comment >= 0) line = line.substring(0, comment);
                    String name = line.trim();
                    if (name.length() == 0) continue;
                    Class<?> clz = Class.forName(name, true, ldr);
                    Class<? extends Page> impl = clz.asSubclass(Page.class);
                    pages.add(impl);
                }
            } catch (Exception ex) {
                System.out.println(ex);
            } finally {
                try {
                    is.close();
                } catch (Exception ex) {
                }
            }
        }
        return pages;
    }
@Override
    public void parse() throws IOException {
        URL url = new URL(getDataUrl());
        URLConnection con = url.openConnection();
        BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String str;
        while ((str = bStream.readLine()) != null) {
            String[] tokens = str.split(",");
            CurrencyUnit unit = new CurrencyUnit(tokens[1], Float.valueOf(tokens[3]), Integer.valueOf(tokens[2]));
            this.set.add(unit);
        }
    }
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String realUrl = "http:/" + request.getPathInfo();
        if (request.getQueryString() != null) {
            realUrl += "?" + request.getQueryString();
        }
        URL url = new URL(realUrl);
        URLConnection connection = url.openConnection();
        HttpURLConnection http = null;
        if (connection instanceof HttpURLConnection) {
            http = (HttpURLConnection) connection;
            http.setRequestMethod(request.getMethod());
        }
        boolean hasContent = false;
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String header = (String) headers.nextElement();
            if ("content-type".equals(header.toLowerCase())) hasContent = true;
            Enumeration values = request.getHeaders(header);
            while (values.hasMoreElements()) {
                String value = (String) values.nextElement();
                if (value != null) {
                    connection.addRequestProperty(header, value);
                }
            }
        }
        try {
            connection.setDoInput(true);
            if (hasContent) {
                InputStream proxyRequest = request.getInputStream();
                connection.setDoOutput(true);
                IO.copy(proxyRequest, connection.getOutputStream());
            }
            connection.connect();
        } catch (Exception e) {
            context.log("proxy", e);
        }
        InputStream proxyResponse = null;
        int code = 500;
        if (http != null) {
            proxyResponse = http.getErrorStream();
            code = http.getResponseCode();
            response.setStatus(code);
        }
        if (proxyResponse == null) {
            try {
                proxyResponse = connection.getInputStream();
            } catch (Exception e) {
                if (http != null) proxyResponse = http.getErrorStream();
                context.log("stream", e);
            }
        }
        int i = 0;
        String header = connection.getHeaderFieldKey(i);
        String value = connection.getHeaderField(i);
        while (header != null || value != null) {
            if (header != null && value != null) {
                response.addHeader(header, value);
            }
            ++i;
            header = connection.getHeaderFieldKey(i);
            value = connection.getHeaderField(i);
        }
        if (proxyResponse != null) {
            IO.copy(proxyResponse, response.getOutputStream());
        }
    }
public void postProcess() throws StopWriterVisitorException {
        dbfWriter.postProcess();
        try {
            short originalEncoding = dbf.getDbaseHeader().getLanguageID();
            File dbfFile = fTemp;
            FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel();
            FileChannel fcoutDbf = new FileOutputStream(file).getChannel();
            DriverUtilities.copy(fcinDbf, fcoutDbf);
            fTemp.delete();
            close();
            RandomAccessFile fo = new RandomAccessFile(file, "rw");
            fo.seek(29);
            fo.writeByte(originalEncoding);
            fo.close();
            open(file);
        } catch (FileNotFoundException e) {
            throw new StopWriterVisitorException(getName(), e);
        } catch (IOException e) {
            throw new StopWriterVisitorException(getName(), e);
        } catch (CloseDriverException e) {
            throw new StopWriterVisitorException(getName(), e);
        } catch (OpenDriverException e) {
            throw new StopWriterVisitorException(getName(), e);
        }
    }
protected void refreshMods(String modsUrl) {
        while (true) {
            JMenuItem mi = mnMods.getItem(mnMods.getItemCount() - 1);
            if (mi == null) break;
            mnMods.remove(mnMods.getItemCount() - 1);
        }
        try {
            log.info("Loading mods from " + modsUrl);
            URL url = new URL(modsUrl);
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            SAXReader reader = new SAXReader();
            Document document = reader.read(conn.getInputStream());
            Element root = document.getRootElement();
            for (Iterator i = root.elementIterator("mod"); i.hasNext(); ) {
                final Element mod = (Element) i.next();
                JMenuItem mi = new JMenuItem(mod.element("name").getTextTrim());
                mi.setIcon(Application.icon("applications-other"));
                mi.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Application.getInstance().openUrl(mod.element("siteUrl").getTextTrim());
                    }
                });
                mnMods.add(mi);
            }
        } catch (Throwable t) {
            t.printStackTrace();
            log.warn("Failed to dynamically add mod links");
        }
    }
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) {
        LOG.info("copying [" + source + "] to [" + destination + "]");
        BufferedInputStream sourceStream = null;
        BufferedOutputStream destStream = null;
        try {
            File destinationFile = new File(destination);
            if (destinationFile.exists()) {
                destinationFile.delete();
            }
            sourceStream = new BufferedInputStream(new FileInputStream(source));
            destStream = new BufferedOutputStream(new FileOutputStream(destinationFile));
            int readByte;
            while ((readByte = sourceStream.read()) > 0) {
                destStream.write(readByte);
            }
            Object[] arg = { destinationFile.getName() };
            String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg);
            LOG.fine(msg);
        } catch (Exception e) {
            Object[] expArgs = { e.getMessage() };
            String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs);
            timeSlotTracker.errorLog(expMsg);
            timeSlotTracker.errorLog(e);
        } finally {
            try {
                if (destStream != null) {
                    destStream.close();
                }
                if (sourceStream != null) {
                    sourceStream.close();
                }
            } catch (Exception e) {
                Object[] expArgs = { e.getMessage() };
                String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs);
                timeSlotTracker.errorLog(expMsg);
                timeSlotTracker.errorLog(e);
            }
        }
    }
public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        int sec = 0;
        try {
            URL url = rep.getResource(request, resource);
            if (url == null) {
                return "Documento " + rep.dir + "/" + resource + " no encontrado";
            }
            br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding));
            String line = br.readLine();
            while (line != null) {
                int pos = line.indexOf("KAttach(");
                if (pos > -1) {
                    sb.append(attach(request, ++sec, line, pos, template));
                } else {
                    line = line.replaceAll("%20", "-");
                    sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n");
                }
                line = br.readLine();
            }
        } finally {
            if (br != null) br.close();
        }
        return sb.toString();
    }
public static boolean update(Orgao orgao) {
        int result = 0;
        Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            String sql = "update orgao set nome = (?) where id_orgao= ?";
            pst = c.prepareStatement(sql);
            pst.setString(1, orgao.getNome());
            pst.setInt(2, orgao.getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (SQLException e) {
            try {
                c.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("[OrgaoDAO.update] Erro ao atualizar -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        try {
            URL url = new URL("http://placekitten.com/g/500/250");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(5000);
            Bitmap kitten = BitmapFactory.decodeStream(conn.getInputStream());
            conn.disconnect();
            Bitmap frame = BitmapFactory.decodeResource(getResources(), R.drawable.frame500);
            Bitmap output = Bitmap.createBitmap(frame.getWidth(), frame.getHeight(), Bitmap.Config.ARGB_8888);
            output.eraseColor(Color.BLACK);
            Canvas canvas = new Canvas(output);
            canvas.drawBitmap(kitten, 125, 125, new Paint());
            canvas.drawBitmap(frame, 0, 0, new Paint());
            Paint textPaint = new Paint();
            textPaint.setColor(Color.WHITE);
            textPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD));
            textPaint.setTextAlign(Align.CENTER);
            textPaint.setAntiAlias(true);
            textPaint.setTextSize(36);
            canvas.drawText("Cute", output.getWidth() / 2, (output.getHeight() / 2) + 140, textPaint);
            textPaint.setTextSize(24);
            canvas.drawText("Some of us just haz it.", output.getWidth() / 2, (output.getHeight() / 2) + 180, textPaint);
            ImageView imageView = (ImageView) this.findViewById(R.id.imageView);
            imageView.setImageBitmap(output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public String accessURL_Post(String url, Map<String, String> keyValue, String encoding) throws Throwable {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (String key : keyValue.keySet()) {
            formparams.add(new BasicNameValuePair(key, keyValue.get(key)));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encoding);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        String entuity = EntityUtils.toString(response.getEntity());
        handleHeaders(response.getAllHeaders());
        return entuity;
    }
public String accessURL_Post(String url, String postStr, String encoding) throws Throwable {
        StringEntity entity = new StringEntity(postStr, encoding);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        String entuity = EntityUtils.toString(response.getEntity());
        handleHeaders(response.getAllHeaders());
        return entuity;
    }
public static void openFile(PublicHubList hublist, String url) {
        BufferedReader fichAl;
        String linha;
        try {
            if (url.startsWith("http://")) fichAl = new BufferedReader(new InputStreamReader((new java.net.URL(url)).openStream())); else fichAl = new BufferedReader(new FileReader(url));
            while ((linha = fichAl.readLine()) != null) {
                try {
                    hublist.addDCHub(new DCHub(linha, DCHub.hublistFormater));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
protected void initConnection() {
        connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=" + downloadedSize + "-");
            prepareConnectionBeforeConnect();
            connection.connect();
        } catch (IOException e) {
            status = STATUS_ERROR;
            Logger.getRootLogger().error("problem in connection", e);
        }
    }
public static void copyFile(String f_in, String f_out, boolean remove) throws FileNotFoundException, IOException {
        if (remove) {
            PogoString readcode = new PogoString(PogoUtil.readFile(f_in));
            readcode = PogoUtil.removeLogMessages(readcode);
            PogoUtil.writeFile(f_out, readcode.str);
        } else {
            FileInputStream fid = new FileInputStream(f_in);
            FileOutputStream fidout = new FileOutputStream(f_out);
            int nb = fid.available();
            byte[] inStr = new byte[nb];
            if (fid.read(inStr) > 0) fidout.write(inStr);
            fid.close();
            fidout.close();
        }
    }
private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException {
        File dirPath = new File(uploadDir);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        InputStream stream = file.getInputStream();
        OutputStream bos = new FileOutputStream(uploadDir + newFileName);
        IOUtils.copy(stream, bos);
    }
@Override
    public String addUser(UserInfoItem user) throws DatabaseException {
        if (user == null) throw new NullPointerException("user");
        if (user.getSurname() == null || "".equals(user.getSurname())) throw new NullPointerException("user.getSurname()");
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            LOGGER.warn("Unable to set autocommit off", e);
        }
        String retID = "exist";
        PreparedStatement insSt = null, updSt = null, seqSt = null;
        try {
            int modified = 0;
            if (user.getId() != null) {
                long id = Long.parseLong(user.getId());
                updSt = getConnection().prepareStatement(UPDATE_USER_STATEMENT);
                updSt.setString(1, user.getName());
                updSt.setString(2, user.getSurname());
                updSt.setLong(3, id);
                modified = updSt.executeUpdate();
            } else {
                insSt = getConnection().prepareStatement(INSERT_USER_STATEMENT);
                insSt.setString(1, user.getName());
                insSt.setString(2, user.getSurname());
                insSt.setBoolean(3, "m".equalsIgnoreCase(user.getSex()));
                modified = insSt.executeUpdate();
                seqSt = getConnection().prepareStatement(USER_CURR_VALUE);
                ResultSet rs = seqSt.executeQuery();
                while (rs.next()) {
                    retID = rs.getString(1);
                }
            }
            if (modified == 1) {
                getConnection().commit();
                LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\"");
            } else {
                getConnection().rollback();
                LOGGER.debug("DB has not been updated. -> rollback! Queries: \"" + seqSt + "\" and \"" + (user.getId() != null ? updSt : insSt) + "\"");
                retID = "error";
            }
        } catch (SQLException e) {
            LOGGER.error(e);
            retID = "error";
        } finally {
            closeConnection();
        }
        return retID;
    }
@Override
    public String addUserIdentity(OpenIDItem identity, long userId) throws DatabaseException {
        if (identity == null) throw new NullPointerException("identity");
        if (identity.getIdentity() == null || "".equals(identity.getIdentity())) throw new NullPointerException("identity.getIdentity()");
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            LOGGER.warn("Unable to set autocommit off", e);
        }
        String retID = "exist";
        PreparedStatement insSt = null, seqSt = null;
        try {
            int modified = 0;
            insSt = getConnection().prepareStatement(INSERT_IDENTITY_STATEMENT);
            insSt.setLong(1, userId);
            insSt.setString(2, identity.getIdentity());
            modified = insSt.executeUpdate();
            seqSt = getConnection().prepareStatement(USER_IDENTITY_VALUE);
            ResultSet rs = seqSt.executeQuery();
            while (rs.next()) {
                retID = rs.getString(1);
            }
            if (modified == 1) {
                getConnection().commit();
                LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + insSt + "\"");
            } else {
                getConnection().rollback();
                LOGGER.debug("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + insSt + "\"");
                retID = "error";
            }
        } catch (SQLException e) {
            LOGGER.error(e);
            retID = "error";
        } finally {
            closeConnection();
        }
        return retID;
    }