semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void salvarCategoria(Categoria cat) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "insert into categoria VALUES (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setNull(1, Types.INTEGER);
            ps.setString(2, cat.getNome());
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }
@Override
    public void delCategoria(Integer codigo) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "delete from categoria where id_categoria = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, codigo);
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }
private void alterarArtista(Artista artista) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "UPDATE artista SET nome = ?,sexo = ?,email = ?,obs = ?,telefone = ? where numeroinscricao = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, artista.getNome());
            ps.setBoolean(2, artista.isSexo());
            ps.setString(3, artista.getEmail());
            ps.setString(4, artista.getObs());
            ps.setString(5, artista.getTelefone());
            ps.setInt(6, artista.getNumeroInscricao());
            ps.executeUpdate();
            alterarEndereco(conn, ps, artista);
            delObras(conn, ps, artista.getNumeroInscricao());
            sql = "insert into obra VALUES (?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            for (Obra obra : artista.getListaObras()) {
                salvarObra(conn, ps, obra, artista.getNumeroInscricao());
            }
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }
private void salvarArtista(Artista artista) throws Exception {
        System.out.println("GerenteMySQL.salvarArtista()" + artista.toString2());
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "insert into artista VALUES (?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, artista.getNumeroInscricao());
            ps.setString(2, artista.getNome());
            ps.setBoolean(3, artista.isSexo());
            ps.setString(4, artista.getEmail());
            ps.setString(5, artista.getObs());
            ps.setString(6, artista.getTelefone());
            ps.setNull(7, Types.INTEGER);
            ps.executeUpdate();
            salvarEndereco(conn, ps, artista);
            sql = "insert into obra VALUES (?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            for (Obra obra : artista.getListaObras()) {
                salvarObra(conn, ps, obra, artista.getNumeroInscricao());
            }
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }
@Override
    public void delArtista(Integer numeroInscricao) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "delete from artista where numeroinscricao = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, numeroInscricao);
            ps.executeUpdate();
            delEndereco(conn, ps, numeroInscricao);
            delObras(conn, ps, numeroInscricao);
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }
public static JSONObject fromUrl(String url) throws Throwable {
        Validate.notEmpty(url);
        InputStream stream = null;
        HttpClient httpclient = null;
        try {
            httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try {
                        stream = entity.getContent();
                        return fromStream(stream);
                    } finally {
                        try {
                            if (stream != null) stream.close();
                        } catch (Exception ex) {
                        }
                    }
                }
            }
        } catch (Throwable tr) {
            Logger.e(TAG, "fromUrl", tr);
            throw tr;
        } finally {
            if (httpclient != null) httpclient.getConnectionManager().shutdown();
        }
        return null;
    }
public Wget2(URL url, File f) throws IOException {
        System.out.println("bajando: " + url);
        if (f == null) {
            by = new ByteArrayOutputStream();
        } else {
            by = new FileOutputStream(f);
        }
        URLConnection uc = url.openConnection();
        if (uc instanceof HttpURLConnection) {
            leerHttp((HttpURLConnection) uc);
        } else {
            throw new IOException("solo se pueden descargar url http");
        }
    }
public TVRageShowInfo(String xmlShowName) {
        String[] tmp, tmp2;
        String line = "";
        this.usrShowName = xmlShowName;
        try {
            URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20"));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((line = in.readLine()) != null) {
                tmp = line.split("@");
                if (tmp[0].equals("Show Name")) showName = tmp[1];
                if (tmp[0].equals("Show URL")) showURL = tmp[1];
                if (tmp[0].equals("Latest Episode")) {
                    StringTokenizer st = new StringTokenizer(tmp[1], "^");
                    for (int i = 0; st.hasMoreTokens(); i++) {
                        if (i == 0) {
                            tmp2 = st.nextToken().split("x");
                            latestSeasonNum = tmp2[0];
                            latestEpisodeNum = tmp2[1];
                            if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1);
                        } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken();
                    }
                }
                if (tmp[0].equals("Next Episode")) {
                    StringTokenizer st = new StringTokenizer(tmp[1], "^");
                    for (int i = 0; st.hasMoreTokens(); i++) {
                        if (i == 0) {
                            tmp2 = st.nextToken().split("x");
                            nextSeasonNum = tmp2[0];
                            nextEpisodeNum = tmp2[1];
                            if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1);
                        } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken();
                    }
                }
                if (tmp[0].equals("Status")) status = tmp[1];
                if (tmp[0].equals("Airtime")) airTime = tmp[1];
            }
            if (airTime.length() != 0) {
                tmp = airTime.split(",");
                airTimeHour = tmp[1];
            }
            in.close();
            url = new URL(showURL);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((line = in.readLine()) != null) {
                if (line.indexOf("<b>Latest Episode: </b>") > -1) {
                    tmp = line.split("'>");
                    if (tmp[2].indexOf(':') > -1) {
                        tmp = tmp[2].split(":");
                        latestSeriesNum = tmp[0];
                    }
                } else if (line.indexOf("<b>Next Episode: </b>") > -1) {
                    tmp = line.split("'>");
                    if (tmp[2].indexOf(':') > -1) {
                        tmp = tmp[2].split(":");
                        nextSeriesNum = tmp[0];
                    }
                }
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }
public void performUpdates(List<PackageDescriptor> downloadList, ProgressListener progressListener) throws IOException, UpdateServiceException_Exception {
        int i = 0;
        try {
            for (PackageDescriptor desc : downloadList) {
                String urlString = service.getDownloadURL(desc.getPackageId(), desc.getVersion(), desc.getPlatformName());
                int minProgress = 20 + 80 * i / downloadList.size();
                int maxProgress = 20 + 80 * (i + 1) / downloadList.size();
                boolean incremental = UpdateManager.isIncrementalUpdate();
                if (desc.getPackageTypeName().equals("RAPIDMINER_PLUGIN")) {
                    ManagedExtension extension = ManagedExtension.getOrCreate(desc.getPackageId(), desc.getName(), desc.getLicenseName());
                    String baseVersion = extension.getLatestInstalledVersionBefore(desc.getVersion());
                    incremental &= baseVersion != null;
                    URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(baseVersion, "UTF-8") : "")).toURL();
                    if (incremental) {
                        LogService.getRoot().info("Updating " + desc.getPackageId() + " incrementally.");
                        try {
                            updatePluginIncrementally(extension, openStream(url, progressListener, minProgress, maxProgress), baseVersion, desc.getVersion());
                        } catch (IOException e) {
                            LogService.getRoot().warning("Incremental Update failed. Trying to fall back on non incremental Update...");
                            incremental = false;
                        }
                    }
                    if (!incremental) {
                        LogService.getRoot().info("Updating " + desc.getPackageId() + ".");
                        updatePlugin(extension, openStream(url, progressListener, minProgress, maxProgress), desc.getVersion());
                    }
                    extension.addAndSelectVersion(desc.getVersion());
                } else {
                    URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(RapidMiner.getLongVersion(), "UTF-8") : "")).toURL();
                    LogService.getRoot().info("Updating RapidMiner core.");
                    updateRapidMiner(openStream(url, progressListener, minProgress, maxProgress), desc.getVersion());
                }
                i++;
                progressListener.setCompleted(20 + 80 * i / downloadList.size());
            }
        } catch (URISyntaxException e) {
            throw new IOException(e);
        } finally {
            progressListener.complete();
        }
    }
private InputStream openStream(URL url, ProgressListener listener, int minProgress, int maxProgress) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(false);
        String lengthStr = con.getHeaderField("Content-Length");
        InputStream urlIn;
        try {
            urlIn = con.getInputStream();
        } catch (IOException e) {
            throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(), e);
        }
        if (lengthStr == null || lengthStr.isEmpty()) {
            LogService.getRoot().warning("Server did not send content length.");
            return urlIn;
        } else {
            try {
                long length = Long.parseLong(lengthStr);
                return new ProgressReportingInputStream(urlIn, listener, minProgress, maxProgress, length);
            } catch (NumberFormatException e) {
                LogService.getRoot().log(Level.WARNING, "Server sent illegal content length: " + lengthStr, e);
                return urlIn;
            }
        }
    }
protected File downloadUpdate(String resource) throws AgentException {
        RESTCall call = makeRESTCall(resource);
        call.invoke();
        File tmpFile;
        try {
            tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath));
        } catch (IOException e) {
            throw new AgentException("Failed to create temporary file", e);
        }
        InputStream is;
        try {
            is = call.getInputStream();
        } catch (IOException e) {
            throw new AgentException("Failed to open input stream", e);
        }
        try {
            FileOutputStream os;
            try {
                os = new FileOutputStream(tmpFile);
            } catch (FileNotFoundException e) {
                throw new AgentException("Failed to open temporary file for writing", e);
            }
            boolean success = false;
            try {
                IOUtils.copy(is, os);
                success = true;
            } catch (IOException e) {
                throw new AgentException("Failed to download update", e);
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    if (!success) throw new AgentException("Failed to flush to disk", e);
                }
            }
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("Failed to close input stream", e);
            }
            call.disconnect();
        }
        return tmpFile;
    }
private String fazHttpRequest(String u) {
        StringBuilder str = new StringBuilder();
        URL url = null;
        URLConnection urlC = null;
        try {
            url = new URL(u.toString());
            urlC = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                str.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            System.out.println("[fazHttpRequest]" + e);
        }
        return (str.length() > 0) ? str.toString() : null;
    }
public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception {
        if (file != null) {
            try {
                HttpServletRequest request = ServletActionContext.getRequest();
                HttpSession session = request.getSession();
                String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName;
                File outfile = new File(pathFile);
                String[] nomPhotoTab = fileName.split("\\.");
                String extension = nomPhotoTab[nomPhotoTab.length - 1];
                StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]);
                for (int i = 1; i < nomPhotoTab.length - 1; i++) {
                    pathResBuff.append(".").append(nomPhotoTab[i]);
                }
                String pathRes = pathResBuff.toString();
                String nomPhoto = fileName;
                for (int i = 0; !outfile.createNewFile(); i++) {
                    nomPhoto = pathRes + "_" + +i + "." + extension;
                    pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto;
                    outfile = new File(pathFile);
                }
                logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile);
                FileChannel in = null;
                FileChannel out = null;
                try {
                    in = new FileInputStream(file).getChannel();
                    out = new FileOutputStream(outfile).getChannel();
                    in.transferTo(0, in.size(), out);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                    }
                }
                return outfile;
            } catch (IOException e) {
                logger.error("Erreur lors de l'enregistrement de l'image ", e);
                throw new Exception("Erreur lors de l'enregistrement de l'image ");
            }
        }
        return null;
    }
static final void saveStatus(JWAIMStatus status, DBConnector connector) throws IOException {
        Connection con = null;
        PreparedStatement ps = null;
        Statement st = null;
        try {
            con = connector.getDB();
            con.setAutoCommit(false);
            st = con.createStatement();
            st.executeUpdate("DELETE FROM status");
            ps = con.prepareStatement("INSERT INTO status VALUES (?, ?)");
            ps.setString(1, "jwaim.status");
            ps.setBoolean(2, status.getJWAIMStatus());
            ps.addBatch();
            ps.setString(1, "logging.status");
            ps.setBoolean(2, status.getLoggingStatus());
            ps.addBatch();
            ps.setString(1, "stats.status");
            ps.setBoolean(2, status.getStatsStatus());
            ps.addBatch();
            ps.executeBatch();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new IOException(e.getMessage());
        } finally {
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException ignore) {
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException ignore) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
protected JSONObject doJSONRequest(JSONObject jsonRequest) throws JSONRPCException {
        HttpPost request = new HttpPost(serviceUri);
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(params, getSoTimeout());
        HttpProtocolParams.setVersion(params, PROTOCOL_VERSION);
        request.setParams(params);
        request.addHeader("Authorization", "Basic " + Base64Coder.encodeString(serviceUser + ":" + servicePass));
        HttpEntity entity;
        try {
            entity = new JSONEntity(jsonRequest);
        } catch (UnsupportedEncodingException e1) {
            throw new JSONRPCException("Unsupported encoding", e1);
        }
        request.setEntity(entity);
        try {
            long t = System.currentTimeMillis();
            HttpResponse response = httpClient.execute(request);
            t = System.currentTimeMillis() - t;
            Log.d("json-rpc", "Request time :" + t);
            String responseString = EntityUtils.toString(response.getEntity());
            responseString = responseString.trim();
            JSONObject jsonResponse = new JSONObject(responseString);
            if (jsonResponse.has("error")) {
                Object jsonError = jsonResponse.get("error");
                if (!jsonError.equals(null)) throw new JSONRPCException(jsonResponse.get("error"));
                return jsonResponse;
            } else {
                return jsonResponse;
            }
        } catch (ClientProtocolException e) {
            throw new JSONRPCException("HTTP error", e);
        } catch (IOException e) {
            throw new JSONRPCException("IO error", e);
        } catch (JSONException e) {
            throw new JSONRPCException("Invalid JSON response", e);
        }
    }
public String encryptPassword(String clearPassword) throws NullPointerException {
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new NullPointerException("NoSuchAlgorithmException: " + e.toString());
        }
        sha.update(clearPassword.getBytes());
        byte encryptedPassword[] = sha.digest();
        sha = null;
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < encryptedPassword.length; i++) {
            result.append(Byte.toString(encryptedPassword[i]));
        }
        return (result.toString());
    }
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
        if (format != null && "gif".equals(format.toLowerCase())) {
            resize(originalFile, resizedFile, width, 1);
            return;
        }
        FileInputStream fis = new FileInputStream(originalFile);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int readLength = -1;
        int bufferSize = 1024;
        byte bytes[] = new byte[bufferSize];
        while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
            byteStream.write(bytes, 0, readLength);
        }
        byte[] in = byteStream.toByteArray();
        fis.close();
        byteStream.close();
        Image inputImage = Toolkit.getDefaultToolkit().createImage(in);
        waitForImage(inputImage);
        int imageWidth = inputImage.getWidth(null);
        if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
        int imageHeight = inputImage.getHeight(null);
        if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range");
        int height = -1;
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (double) height;
        if (scaleW >= 0 && scaleY >= 0) {
            if (scaleW > scaleY) {
                height = -1;
            } else {
                width = -1;
            }
        }
        Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT);
        checkImage(outputImage);
        encode(new FileOutputStream(resizedFile), outputImage, format);
    }
public InputStream sendReceive(String trackerURL) throws TorrentException {
        try {
            URL url = new URL(trackerURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            in = conn.getInputStream();
        } catch (MalformedURLException e) {
            throw new TorrentException(e);
        } catch (IOException e) {
            throw new TorrentException(e);
        }
        return in;
    }