semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public String fetchStockCompanyName(Stock stock) {
        String companyName = "";
        String symbol = StockUtil.getStock(stock);
        if (isStockCached(symbol)) {
            return getStockFromCache(symbol);
        }
        String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.stockInfo.url", new String[] { symbol, register.get("username", ""), register.get("password", "") });
        HttpContext context = new BasicHttpContext();
        HttpGet method = new HttpGet(url);
        try {
            HttpResponse response = ProxyManager.httpClient.execute(method, context);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                companyName = EntityUtils.toString(entity).split("\n")[1];
                cacheStock(symbol, companyName);
                EntityUtils.consume(entity);
            }
        } catch (Exception ex) {
            companyName = "";
        } finally {
            method.abort();
        }
        return companyName;
    }
public String[] fetchAutocomplete(String text) {
        String[] result = new String[0];
        String url = NbBundle.getMessage(MrSwingDataFeed.class, "MrSwingDataFeed.autocomplete.url", text);
        HttpContext context = new BasicHttpContext();
        HttpGet method = new HttpGet(url);
        try {
            HttpResponse response = ProxyManager.httpClient.execute(method, context);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity).split("\n");
                EntityUtils.consume(entity);
            }
        } catch (Exception ex) {
            result = new String[0];
        } finally {
            method.abort();
        }
        return result;
    }
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = null;
        md = MessageDigest.getInstance("SHA");
        md.update(plaintext.getBytes("UTF-8"));
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }
private void zipdir(File base, String zipname) throws IOException {
        FilenameFilter ff = new ExporterFileNameFilter();
        String[] files = base.list(ff);
        File zipfile = new File(base, zipname + ".zip");
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile));
        byte[] buf = new byte[10240];
        for (int i = 0; i < files.length; i++) {
            File f = new File(base, files[i]);
            FileInputStream fis = new FileInputStream(f);
            zos.putNextEntry(new ZipEntry(f.getName()));
            int len;
            while ((len = fis.read(buf)) > 0) zos.write(buf, 0, len);
            zos.closeEntry();
            fis.close();
            f.delete();
        }
        zos.close();
    }
private static List<String> loadServicesImplementations(final Class ofClass) {
        List<String> result = new ArrayList<String>();
        String override = System.getProperty(ofClass.getName());
        if (override != null) {
            result.add(override);
        }
        ClassLoader loader = ServiceLib.class.getClassLoader();
        URL url = loader.getResource("META-INF/services/" + ofClass.getName());
        if (url == null) {
            return result;
        }
        InputStream inStream = null;
        InputStreamReader reader = null;
        BufferedReader bReader = null;
        try {
            inStream = url.openStream();
            reader = new InputStreamReader(inStream);
            bReader = new BufferedReader(reader);
            String line;
            while ((line = bReader.readLine()) != null) {
                if (!line.matches("\\s*(#.*)?")) {
                    result.add(line.trim());
                }
            }
        } catch (IOException iox) {
            LOG.log(Level.WARNING, "Could not load services descriptor: " + url.toString(), iox);
        } finally {
            finalClose(bReader);
            finalClose(reader);
            finalClose(inStream);
        }
        return result;
    }
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            int id = 0;
            String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS";
            PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql);
            ResultSet rs = pStmt.executeQuery();
            if (rs.next()) {
                id = rs.getInt("MAX_ID") + 1;
            } else {
                id = 1;
            }
            Database.close(pStmt);
            sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)";
            pStmt = Database.getMyConnection().prepareStatement(sql);
            pStmt.setInt(1, id);
            pStmt.setString(2, txtGrpName.getText());
            pStmt.setString(3, txtGrpDesc.getText());
            pStmt.setDate(4, Utils.getTodaySql());
            pStmt.setDate(5, Date.valueOf("9999-12-31"));
            pStmt.setString(6, "A");
            pStmt.executeUpdate();
            Database.getMyConnection().commit();
            Database.close(pStmt);
            MessageBox.ok("New group added successfully", this);
            rs = getGroups();
            tblGroups.setModel(new GroupsTableModel(rs));
            Database.close(rs);
        } catch (SQLException e) {
            log.error("Failed with update operation \n" + e.getMessage());
            MessageBox.ok("Failed to create the new group in the database", this);
            try {
                Database.getMyConnection().rollback();
            } catch (Exception inner) {
            }
            ;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage());
            MessageBox.ok("Failed to create the new group in the database", this);
            try {
                Database.getMyConnection().rollback();
            } catch (Exception inner) {
            }
            ;
        } finally {
            txtGrpName.setEnabled(false);
            txtGrpDesc.setEnabled(false);
            btnOk.setEnabled(false);
            btnCancel.requestFocus();
        }
    }
private void initLogging() {
        File logging = new File(App.getHome(), "logging.properties");
        if (!logging.exists()) {
            InputStream input = getClass().getResourceAsStream("logging.properties-setup");
            OutputStream output = null;
            try {
                output = new FileOutputStream(logging);
                IOUtils.copy(input, output);
            } catch (Exception ex) {
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        }
        FileInputStream input = null;
        try {
            input = new FileInputStream(logging);
            LogManager.getLogManager().readConfiguration(input);
        } catch (Exception ex) {
        } finally {
            IOUtils.closeQuietly(input);
        }
    }
private Set read() throws IOException {
        URL url = new URL(urlPrefix + channelId + ".dat");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = in.readLine();
        Set programs = new HashSet();
        while (line != null) {
            String[] values = line.split("~");
            if (values.length != 23) {
                throw new RuntimeException("error: incorrect format for radiotimes information");
            }
            Program program = new RadioTimesProgram(values, channelId);
            programs.add(program);
            line = in.readLine();
        }
        return programs;
    }
public static void main(String[] args) throws Exception {
        String ftpHostIP = System.getProperty(RuntimeConstants.FTP_HOST_IP.toString());
        String ftpUsername = System.getProperty(RuntimeConstants.FTP_USERNAME.toString());
        String ftpPassword = System.getProperty(RuntimeConstants.FTP_PASSWORD.toString());
        String ftpWorkingDirectory = System.getProperty(RuntimeConstants.FTP_WORKING_DIRECTORY_PATH.toString());
        String ftpSenderDirectory = System.getProperty(RuntimeConstants.FTP_SENDER_DIRECTORY_FULL_PATH.toString());
        if (ftpHostIP == null) {
            System.err.println("The FTP_HOST_IP system property must be filled out.");
            System.exit(1);
        }
        if (ftpUsername == null) {
            System.err.println("The FTP_USERNAME system property must be filled out.");
            System.exit(1);
        }
        if (ftpPassword == null) {
            System.err.println("The FTP_PASSWORD system property must be filled out.");
            System.exit(1);
        }
        if (ftpWorkingDirectory == null) {
            System.err.println("The FTP_WORKING_DIRECTORY_PATH system property must be filled out.");
            System.exit(1);
        }
        if (ftpSenderDirectory == null) {
            System.err.println("The FTP_SENDER_DIRECTORY_FULL_PATH system property must be filled out.");
            System.exit(1);
        }
        FTPClient ftp = new FTPClient();
        ftp.connect(ftpHostIP);
        ftp.login(ftpUsername, ftpPassword);
        ftp.changeWorkingDirectory(ftpWorkingDirectory);
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[1024]);
        ftp.storeFile("sampleFile.txt", bais);
        IFileDescriptor fileDescriptor = FileTransferUtil.readAFile(ftpSenderDirectory);
        bais = new ByteArrayInputStream(fileDescriptor.getFileContent());
        long initTime = System.currentTimeMillis();
        ftp.storeFile(fileDescriptor.getFileName(), bais);
        long endTime = System.currentTimeMillis();
        System.out.println("File " + fileDescriptor.getFileName() + " transfer by FTP in " + (endTime - initTime) + " miliseconds.");
    }
public static Photo createPhoto(String title, String userLogin, String pathToPhoto, String basePathImage) throws NoSuchAlgorithmException, IOException {
        String id = CryptSHA1.genPhotoID(userLogin, title);
        String extension = pathToPhoto.substring(pathToPhoto.lastIndexOf("."));
        String destination = basePathImage + id + extension;
        FileInputStream fis = new FileInputStream(pathToPhoto);
        FileOutputStream fos = new FileOutputStream(destination);
        FileChannel fci = fis.getChannel();
        FileChannel fco = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int read = fci.read(buffer);
            if (read == -1) break;
            buffer.flip();
            fco.write(buffer);
            buffer.clear();
        }
        fci.close();
        fco.close();
        fos.close();
        fis.close();
        ImageIcon image;
        ImageIcon thumb;
        String destinationThumb = basePathImage + "thumb/" + id + extension;
        image = new ImageIcon(destination);
        int maxSize = 150;
        int origWidth = image.getIconWidth();
        int origHeight = image.getIconHeight();
        if (origWidth > origHeight) {
            thumb = new ImageIcon(image.getImage().getScaledInstance(maxSize, -1, Image.SCALE_SMOOTH));
        } else {
            thumb = new ImageIcon(image.getImage().getScaledInstance(-1, maxSize, Image.SCALE_SMOOTH));
        }
        BufferedImage bi = new BufferedImage(thumb.getIconWidth(), thumb.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.getGraphics();
        g.drawImage(thumb.getImage(), 0, 0, null);
        try {
            ImageIO.write(bi, "JPG", new File(destinationThumb));
        } catch (IOException ioe) {
            System.out.println("Error occured saving thumbnail");
        }
        Photo photo = new Photo(id);
        photo.setTitle(title);
        photo.basePathImage = basePathImage;
        return photo;
    }
public static Multimap<String, String> getProteins(final Set<String> queries, final int taxon) throws ParserConfigurationException, XPathExpressionException {
        final DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        final XPathExpression xpe = XPathFactory.newInstance().newXPath().compile(__xpath);
        final Multimap<String, String> proteins = HashMultimap.create();
        for (final String query : queries) {
            HttpURLConnection connection = null;
            try {
                final String encoded = URLEncoder.encode(query.trim(), "UTF-8");
                final URL url = new URL(String.format(__urlTempl2, encoded, taxon));
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(__connTimeout);
                connection.setReadTimeout(__readTimeout);
                connection.setRequestProperty("Connection", "close");
                connection.connect();
                final InputStream stream = connection.getInputStream();
                final Document doc = parser.parse(stream);
                final NodeList nodes = (NodeList) xpe.evaluate(doc, XPathConstants.NODESET);
                if (nodes != null) {
                    final int n = nodes.getLength();
                    for (int i = 0; i < n; i++) {
                        final Node node = nodes.item(i);
                        proteins.put(node.getTextContent().trim(), query.trim());
                    }
                }
            } catch (final Exception ex) {
                continue;
            } finally {
                if (connection != null) connection.disconnect();
            }
        }
        return proteins;
    }
private void copyPhoto(final IPhoto photo, final Map.Entry<String, Integer> size) {
        final File fileIn = new File(storageService.getPhotoPath(photo, storageService.getOriginalDir()));
        final File fileOut = new File(storageService.getPhotoPath(photo, size.getKey()));
        InputStream fileInputStream;
        OutputStream fileOutputStream;
        try {
            fileInputStream = new FileInputStream(fileIn);
            fileOutputStream = new FileOutputStream(fileOut);
            IOUtils.copy(fileInputStream, fileOutputStream);
            fileInputStream.close();
            fileOutputStream.close();
        } catch (final IOException e) {
            log.error("file io exception", e);
            return;
        }
    }
@SuppressWarnings("unused")
    private boolean copyAvecProgressNIO(File sRC2, File dEST2, JProgressBar progressEnCours) {
        boolean resultat = false;
        long PourcentEnCours = 0;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(sRC2);
        } catch (FileNotFoundException e) {
            try {
                Historique.ecrire("Erreur � la copie du fichier " + sRC2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(dEST2);
        } catch (FileNotFoundException e) {
            try {
                Historique.ecrire("Erreur � la creation du fichier " + dEST2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        java.nio.channels.FileChannel channelSrc = fis.getChannel();
        java.nio.channels.FileChannel channelDest = fos.getChannel();
        progressEnCours.setValue(0);
        progressEnCours.setString(sRC2 + " : 0 %");
        try {
            long tailleCopie = channelSrc.transferTo(0, channelSrc.size(), channelDest);
        } catch (IOException e) {
            try {
                Historique.ecrire("Erreur � la copie du fichier " + sRC2 + " vers la destination " + dEST2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        progressEnCours.setValue(100);
        progressEnCours.setString(sRC2 + " : 100 %");
        try {
            if (channelSrc.size() == channelDest.size()) {
                resultat = true;
            } else {
                resultat = false;
            }
        } catch (IOException e) {
            try {
                Historique.ecrire("Erreur � la copie du fichier " + sRC2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        try {
            fis.close();
        } catch (IOException e) {
            try {
                Historique.ecrire("Impossible de fermer le flux � la copie du fichier " + sRC2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        try {
            fos.close();
        } catch (IOException e) {
            try {
                Historique.ecrire("Impossible de fermer le flux � la copie du fichier " + dEST2 + " pour la raison suivante : " + e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return true;
        }
        return (resultat);
    }
public int addRecipe(Recipe recipe) throws Exception {
        PreparedStatement pst1 = null;
        PreparedStatement pst2 = null;
        ResultSet rs = null;
        int retVal = -1;
        try {
            conn = getConnection();
            pst1 = conn.prepareStatement("INSERT INTO recipes (name, instructions, category_id) VALUES (?, ?, ?)");
            pst1.setString(1, recipe.getName());
            pst1.setString(2, recipe.getInstructions());
            pst1.setInt(3, recipe.getCategoryId());
            if (pst1.executeUpdate() > 0) {
                pst2 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? AND category_id = ?");
                pst2.setString(1, recipe.getName());
                pst2.setString(2, recipe.getInstructions());
                pst2.setInt(3, recipe.getCategoryId());
                rs = pst2.executeQuery();
                conn.commit();
                if (rs.next()) {
                    int id = rs.getInt(1);
                    addIngredients(recipe, id);
                    MainFrame.recipePanel.update();
                    retVal = id;
                } else {
                    retVal = -1;
                }
            } else {
                retVal = -1;
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            MainFrame.appendStatusText("Can't add recipe, the exception was " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                rs = null;
                if (pst1 != null) pst1.close();
                pst1 = null;
                if (pst2 != null) pst2.close();
                pst2 = null;
            } catch (SQLException sqle) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
        return retVal;
    }
private void addIngredients(Recipe recipe, int id) throws Exception {
        PreparedStatement pst = null;
        try {
            conn = getConnection();
            pst = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)");
            IngredientContainer ings = recipe.getIngredients();
            Ingredient ingBean = null;
            Iterator it;
            for (it = ings.getIngredients().iterator(); it.hasNext(); ) {
                ingBean = (Ingredient) it.next();
                pst.setInt(1, id);
                pst.setString(2, ingBean.getName());
                pst.setDouble(3, ingBean.getAmount());
                pst.setInt(4, ingBean.getType());
                pst.setInt(5, ingBean.getShopFlag());
                pst.executeUpdate();
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage());
        } finally {
            try {
                if (pst != null) pst.close();
                pst = null;
            } catch (Exception ex) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
    }
public int editRecipe(int oldRecipeId, Recipe newRecipe) throws Exception {
        PreparedStatement pst1 = null;
        PreparedStatement pst2 = null;
        ResultSet rs = null;
        int retVal = -1;
        try {
            conn = getConnection();
            pst1 = conn.prepareStatement("UPDATE recipes SET name = ?, instructions = ?, category_id =? WHERE recipe_id = ?");
            pst1.setString(1, newRecipe.getName());
            pst1.setString(2, newRecipe.getInstructions());
            pst1.setInt(3, newRecipe.getCategoryId());
            pst1.setInt(4, oldRecipeId);
            int rsVal = pst1.executeUpdate();
            conn.commit();
            if (rsVal > 0) {
                updateIngredients(newRecipe, oldRecipeId);
                MainFrame.recipePanel.update();
                retVal = oldRecipeId;
            } else {
                retVal = -1;
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            throw new Exception("Can't edit recipe, the exception was " + e.getMessage());
        } finally {
            try {
                if (rs != null) rs.close();
                rs = null;
                if (pst1 != null) pst1.close();
                pst1 = null;
                if (pst2 != null) pst2.close();
                pst2 = null;
            } catch (SQLException sqle) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
        return retVal;
    }
private void updateIngredients(Recipe recipe, int id) throws Exception {
        PreparedStatement pst1 = null;
        PreparedStatement pst2 = null;
        try {
            conn = getConnection();
            pst1 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ?");
            pst1.setInt(1, id);
            if (pst1.executeUpdate() >= 0) {
                pst2 = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)");
                IngredientContainer ings = recipe.getIngredients();
                Ingredient ingBean = null;
                Iterator it;
                for (it = ings.getIngredients().iterator(); it.hasNext(); ) {
                    ingBean = (Ingredient) it.next();
                    pst2.setInt(1, id);
                    pst2.setString(2, ingBean.getName());
                    pst2.setDouble(3, ingBean.getAmount());
                    pst2.setInt(4, ingBean.getType());
                    pst2.setInt(5, ingBean.getShopFlag());
                    pst2.executeUpdate();
                }
            }
            conn.commit();
        } catch (Exception e) {
            conn.rollback();
            MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage());
        } finally {
            try {
                if (pst1 != null) pst1.close();
                pst1 = null;
                if (pst2 != null) pst2.close();
                pst2 = null;
            } catch (Exception ex) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
    }