semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException {
        final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name"));
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            final FileChannel outChannel = fos.getChannel();
            try {
                final int numOfFaceObjects = faceObjects.size();
                progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects);
                final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                final Charset charset = Charset.forName("ISO-8859-1");
                int i = 0;
                for (final FaceObject faceObject : faceObjects) {
                    final String face = faceObject.getFaceName();
                    final String path = archFaceProvider.getFilename(face);
                    try {
                        final FileInputStream fin = new FileInputStream(path);
                        try {
                            final FileChannel inChannel = fin.getChannel();
                            final long imageSize = inChannel.size();
                            byteBuffer.clear();
                            byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset));
                            byteBuffer.flip();
                            outChannel.write(byteBuffer);
                            inChannel.transferTo(0L, imageSize, outChannel);
                        } finally {
                            fin.close();
                        }
                    } catch (final FileNotFoundException ignored) {
                        ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path);
                        return;
                    } catch (final IOException e) {
                        ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e);
                        return;
                    }
                    if (i++ % 100 == 0) {
                        progress.setValue(i);
                    }
                }
                progress.setValue(faceObjects.size());
            } finally {
                outChannel.close();
            }
        } finally {
            fos.close();
        }
    }
public void run() throws Exception {
        logger.debug("#run enter");
        logger.debug("#run orderId = " + orderId);
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE);
            ps.setInt(1, orderId);
            rs = ps.executeQuery();
            DeleteOrderLineAction action = new DeleteOrderLineAction();
            while (rs.next()) {
                Integer lineId = rs.getInt("ID");
                Integer itemId = rs.getInt("ITEM_ID");
                Integer quantity = rs.getInt("QUANTITY");
                action.execute(connection, lineId, itemId, quantity);
            }
            rs.close();
            ps.close();
            ps = connection.prepareStatement(SQL_DELETE_ORDER);
            ps.setInt(1, orderId);
            ps.executeUpdate();
            ps.close();
            logger.info("#run order delete OK");
            connection.commit();
        } catch (SQLException ex) {
            logger.error("SQLException", ex);
            connection.rollback();
            throw new Exception("Не удалось удалить заказ. Ошибка : " + ex.getMessage());
        } finally {
            connection.setAutoCommit(true);
        }
        logger.debug("#run exit");
    }
private static boolean copyFile(File src, File dest) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            for (int c = fis.read(); c != -1; c = fis.read()) fos.write(c);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fis != null) try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fos != null) try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
public boolean login() {
        if (super.isAuthenticated()) return true;
        try {
            if (client == null) {
                client = new FTPClient();
                FTPClientConfig config = new FTPClientConfig();
                client.configure(config);
            }
            if (!client.isConnected()) {
                client.connect(super.getStoreConfig().getServerName(), new Integer(super.getStoreConfig().getServerPort()).intValue());
            }
            if (client.login(super.getStoreConfig().getUserName(), super.getStoreConfig().getPassword(), super.getStoreConfig().getServerName())) {
                super.setAuthenticated(true);
                return true;
            }
            log.error("Login ftp server error");
        } catch (Exception e) {
            log.info("FTPStore.login", e);
        }
        return false;
    }
protected void givenTestRepository(String repositoryId) throws Exception {
        HttpResponse response = executeDeleteWithResponse("/repositories/" + repositoryId);
        consume(response.getEntity());
        response = executePost("/repositories", createRepositoryXml(repositoryId));
        assertEquals(content(response), SC_CREATED, statusCode(response));
    }
protected void givenGroupRepository(String repoId, String providerId, Repository... memberRepos) throws AuthenticationException, UnsupportedEncodingException, IOException, ClientProtocolException {
        HttpResponse response = executeDeleteWithResponse(format("/repo_groups/%s", repoId));
        consume(response.getEntity());
        final StringEntity content = new StringEntity(format("{data:{id: '%s', name: '%s', provider: '%s', exposed: true, repositories: [%s]}}", repoId, repoId, providerId, render(memberRepos)));
        response = executePost("/repo_groups", content, new BasicHeader("Content-Type", "application/json"));
        consume(response.getEntity());
        assertThat(response.getStatusLine().getStatusCode(), is(201));
    }
public static File createTempFile(InputStream contentStream, String ext) throws IOException {
        ExceptionUtils.throwIfNull(contentStream, "contentStream");
        File file = File.createTempFile("test", ext);
        FileOutputStream fos = new FileOutputStream(file);
        try {
            IOUtils.copy(contentStream, fos, false);
        } finally {
            fos.close();
        }
        return file;
    }
public void copy(final File source, final File dest) throws IOException {
        final FileInputStream in = new FileInputStream(source);
        try {
            final FileOutputStream out = new FileOutputStream(dest);
            try {
                final FileChannel inChannel = in.getChannel();
                final FileChannel outChannel = out.getChannel();
                inChannel.transferTo(0, inChannel.size(), outChannel);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }
public boolean updateLOB(String sql, int displayType, Object value, String trxName, SecurityToken token) {
        validateSecurityToken(token);
        if (sql == null || value == null) {
            log.fine("No sql or data");
            return false;
        }
        log.fine(sql);
        Trx trx = null;
        if (trxName != null && trxName.trim().length() > 0) {
            trx = Trx.get(trxName, false);
            if (trx == null) throw new RuntimeException("Transaction lost - " + trxName);
        }
        m_updateLOBCount++;
        boolean success = true;
        Connection con = trx != null ? trx.getConnection() : DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED);
        PreparedStatement pstmt = null;
        try {
            pstmt = con.prepareStatement(sql);
            if (displayType == DisplayType.TextLong) pstmt.setString(1, (String) value); else pstmt.setBytes(1, (byte[]) value);
            int no = pstmt.executeUpdate();
        } catch (Exception e) {
            log.log(Level.FINE, sql, e);
            success = false;
        } finally {
            DB.close(pstmt);
            pstmt = null;
        }
        if (success && trx == null) {
            try {
                con.commit();
            } catch (Exception e) {
                log.log(Level.SEVERE, "commit", e);
                success = false;
            } finally {
                try {
                    con.close();
                } catch (SQLException e) {
                }
                con = null;
            }
        }
        if (!success) {
            log.severe("rollback");
            if (trx == null) {
                try {
                    con.rollback();
                } catch (Exception ee) {
                    log.log(Level.SEVERE, "rollback", ee);
                } finally {
                    try {
                        con.close();
                    } catch (SQLException e) {
                    }
                    con = null;
                }
            } else {
                trx.rollback();
            }
        }
        return success;
    }
@Override
    public boolean updateProductIfAvailable(Map<String, Integer> carro, HttpServletRequest request, Map<Producto, Integer> listado) {
        Connection conexion = null;
        PreparedStatement select = null;
        PreparedStatement update = null;
        ResultSet rs = null;
        boolean exito = false;
        try {
            conexion = pool.getConnection();
            conexion.setAutoCommit(false);
            select = conexion.prepareStatement("SELECT* FROM " + nameBD + ".Productos WHERE Codigo=?");
            update = conexion.prepareStatement("UPDATE " + nameBD + ".Productos SET Stock=? WHERE Codigo=?");
            String codigoProd;
            int filasAfectadas = 0;
            Iterator<String> iterador = carro.keySet().iterator();
            while (iterador.hasNext()) {
                codigoProd = iterador.next();
                select.setString(1, codigoProd);
                rs = select.executeQuery();
                if (rs.next() == false) {
                    Tools.anadirMensaje(request, "No existe el producto con codigo: " + codigoProd + "(producto eliminado de la cesta)");
                    iterador.remove();
                    conexion.rollback();
                } else {
                    Producto prod = new Producto(rs.getString("Codigo"), rs.getString("Nombre"), rs.getDouble("Precio"), rs.getInt("Stock"), rs.getString("Descripcion"), rs.getString("Detalles"));
                    select.clearParameters();
                    if (carro.get(codigoProd) > prod.getStock()) {
                        Tools.anadirMensaje(request, "No hay unidades suficientes de: " + prod.getNombre() + "(producto eliminado de la cesta)");
                        iterador.remove();
                        conexion.rollback();
                    } else {
                        update.setInt(1, prod.getStock() - carro.get(codigoProd));
                        update.setString(2, codigoProd);
                        filasAfectadas = update.executeUpdate();
                        if (filasAfectadas != 1) {
                            Tools.anadirMensaje(request, "Ocurrio un error en el catalogo");
                            conexion.rollback();
                        }
                        update.clearParameters();
                        listado.put(prod, carro.get(codigoProd));
                    }
                }
            }
            conexion.commit();
            exito = true;
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error actualizando unidades de productos en compra", ex);
            try {
                conexion.rollback();
            } catch (SQLException ex1) {
                logger.log(Level.SEVERE, "Error haciendo rolback de la transacción que ha dado error en la actualización de unidades por compra", ex1);
            }
        } finally {
            cerrarConexionYStatement(conexion, select, update);
            cerrarResultSet(rs);
        }
        return exito;
    }
@Override
    public boolean saveCart(Carrito cart, boolean completado, String date, String formPago) {
        Connection conexion = null;
        PreparedStatement insertHistorial = null;
        PreparedStatement insertCarrito = null;
        boolean exito = false;
        try {
            conexion = pool.getConnection();
            conexion.setAutoCommit(false);
            insertHistorial = conexion.prepareStatement("INSERT INTO " + nameBD + ".HistorialCarritos VALUES (?,?,?,?,?,?)");
            insertHistorial.setString(1, cart.getUser());
            insertHistorial.setString(2, cart.getCodigo());
            insertHistorial.setString(3, date);
            insertHistorial.setDouble(4, cart.getPrecio());
            insertHistorial.setString(5, formPago);
            insertHistorial.setBoolean(6, completado);
            int filasAfectadas = insertHistorial.executeUpdate();
            if (filasAfectadas != 1) {
                conexion.rollback();
            } else {
                insertCarrito = conexion.prepareStatement("INSERT INTO " + nameBD + ".Carritos VALUES (?,?,?,?,?)");
                Iterator<String> iteradorProductos = cart.getArticulos().keySet().iterator();
                while (iteradorProductos.hasNext()) {
                    String key = iteradorProductos.next();
                    Producto prod = getProduct(key);
                    int cantidad = cart.getArticulos().get(key);
                    insertCarrito.setString(1, cart.getCodigo());
                    insertCarrito.setString(2, prod.getCodigo());
                    insertCarrito.setString(3, prod.getNombre());
                    insertCarrito.setDouble(4, prod.getPrecio());
                    insertCarrito.setInt(5, cantidad);
                    filasAfectadas = insertCarrito.executeUpdate();
                    if (filasAfectadas != 1) {
                        conexion.rollback();
                        break;
                    }
                    insertCarrito.clearParameters();
                }
                conexion.commit();
                exito = true;
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error añadiendo carrito al registro", ex);
            try {
                conexion.rollback();
            } catch (SQLException ex1) {
                logger.log(Level.SEVERE, "Error haciendo rollback de la transacción para insertar carrito en el registro", ex1);
            }
        } finally {
            cerrarConexionYStatement(conexion, insertCarrito, insertHistorial);
        }
        return exito;
    }
public List<String> addLine(String username, String URL, int page) {
        List<String> rss = new ArrayList<String>();
        try {
            URL url = new URL(URL + page);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            System.out.println(reader.readLine());
            while ((line = reader.readLine()) != null) {
                String string = "<text>";
                String string1 = "</text>";
                if (line.contains(string) && !line.contains("@") && !line.contains("http")) {
                    String tweet = line.replace(string, "").replace(string1, "").replace("'", "").trim();
                    final Tweets tweets = new Tweets(username, tweet, page, false);
                    int save = tweets.save();
                    tweets.setId((long) save);
                    Thread thread = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            Main.addRow(tweets);
                        }
                    });
                    thread.start();
                    System.out.println(tweet);
                }
            }
            reader.close();
        } catch (MalformedURLException e) {
            Log.put(e.toString());
            System.out.println(e.toString());
        } catch (IOException e) {
            Log.put(e.toString());
            System.out.println(e.toString());
        } catch (Exception e) {
            Log.put(e.toString());
            System.out.println(e.toString());
        }
        return rss;
    }
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" })
    public static String md5Encode(String val) {
        String output = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(val.getBytes());
            byte[] digest = md.digest();
            output = base64Encode(digest);
        } catch (Exception e) {
        }
        return output;
    }
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" })
    public static String shaEncode(String val) {
        String output = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(val.getBytes());
            byte[] digest = md.digest();
            output = base64Encode(digest);
        } catch (Exception e) {
        }
        return output;
    }
public static void copyResource(String src, File dest) throws IOException {
        InputStream fin = ResourceLoader.openResource(src);
        if (fin == null) {
            LogFactory.getLog(ResourceLoader.class).error("Failed to load resource '" + src + "'");
            LogFactory.getLog(ResourceLoader.class).info("Attempting to open file from from file system");
            fin = new FileInputStream(src);
        }
        if (fin == null) {
            LogFactory.getLog(ResourceLoader.class).warn("Giving up on copy operation, can't find source '" + src + "'");
            return;
        }
        BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(dest));
        byte[] buffer = new byte[COPY_BUFFER_SIZE];
        int readBytes = fin.read(buffer);
        while (readBytes > -1) {
            fout.write(buffer, 0, readBytes);
            readBytes = fin.read(buffer);
        }
        fout.close();
        fin.close();
    }
public String postData(String url, List<NameValuePair> nameValuePairs) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        StringBuilder sb = new StringBuilder();
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.i(TAG, "HEADER: " + headers[i].getName() + " - " + headers[i].getValue());
            }
            InputStream is = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println("Parsing line... " + line);
                sb.append(line);
                if (line.contains("<html xmlns:fn")) {
                    String gtinCode = line.substring(line.indexOf("GLN:") + 165, line.indexOf("GLN:") + 176);
                    Log.i(TAG, "OUT: " + gtinCode);
                    break;
                }
            }
            Log.i(TAG, "Post Communication OK");
        } catch (ClientProtocolException e) {
            Log.e(TAG, "ClientProtocolException ", e);
        } catch (IOException e) {
            Log.e(TAG, "HTTP Not Available", e);
        }
        return sb.toString();
    }
@Override
        @SuppressWarnings("empty-statement")
        public void run() {
            String server = System.getProperty("server.downsampler");
            if (server == null) server = FALLBACK;
            String url = server + "cgi-bin/downsample.cgi?" + this._uri.toString();
            url = url.replaceAll("\\?#$", "");
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setDoInput(true);
                this._input_stream = connection.getInputStream();
                while (this._input_stream.read() != '\n') ;
                this._complete = true;
            } catch (Exception e) {
                new ErrorEvent().send(e);
            }
        }
public static void copyFile(String original, String destination) throws Exception {
        File original_file = new File(original);
        File destination_file = new File(destination);
        if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist.");
        if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists.");
        FileReader in = new FileReader(original_file);
        FileWriter out = new FileWriter(destination_file);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }
public static boolean copy(final File from, final File to) {
        if (from.isDirectory()) {
            to.mkdirs();
            for (final String name : Arrays.asList(from.list())) {
                if (!copy(from, to, name)) {
                    if (COPY_DEBUG) {
                        System.out.println("Failed to copy " + name + " from " + from + " to " + to);
                    }
                    return false;
                }
            }
        } else {
            try {
                final FileInputStream is = new FileInputStream(from);
                final FileChannel ifc = is.getChannel();
                final FileOutputStream os = makeFile(to);
                if (USE_NIO) {
                    final FileChannel ofc = os.getChannel();
                    ofc.transferFrom(ifc, 0, from.length());
                } else {
                    pipe(is, os, false);
                }
                is.close();
                os.close();
            } catch (final IOException ex) {
                if (COPY_DEBUG) {
                    System.out.println("Failed to copy " + from + " to " + to + ": " + ex);
                }
                return false;
            }
        }
        final long time = from.lastModified();
        setLastModified(to, time);
        final long newtime = to.lastModified();
        if (COPY_DEBUG) {
            if (newtime != time) {
                System.out.println("Failed to set timestamp for file " + to + ": tried " + new Date(time) + ", have " + new Date(newtime));
                to.setLastModified(time);
                final long morenewtime = to.lastModified();
                return false;
            } else {
                System.out.println("Timestamp for " + to + " set successfully.");
            }
        }
        return time == newtime;
    }
private void callService() {
        try {
            URL url = new URL(baseUrl + servicePath + attributes);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            StringBuffer buf = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                buf.append(inputLine);
            }
            in.close();
            answer = buf.toString();
        } catch (MalformedURLException e) {
            answer = "Malformed Url:" + e.getMessage();
            return;
        } catch (IOException e) {
            answer = "I/O exception: " + e.getMessage();
            return;
        }
    }