semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void addGames(List<Game> games) throws StadiumException, SQLException {
        Connection conn = ConnectionManager.getManager().getConnection();
        conn.setAutoCommit(false);
        PreparedStatement stm = null;
        ResultSet rs = null;
        try {
            for (Game game : games) {
                stm = conn.prepareStatement(Statements.SELECT_STADIUM);
                stm.setString(1, game.getStadiumName());
                stm.setString(2, game.getStadiumCity());
                rs = stm.executeQuery();
                int stadiumId = -1;
                while (rs.next()) {
                    stadiumId = rs.getInt("stadiumID");
                }
                if (stadiumId == -1) throw new StadiumException("No such stadium");
                stm = conn.prepareStatement(Statements.INSERT_GAME);
                stm.setInt(1, stadiumId);
                stm.setDate(2, game.getGameDate());
                stm.setTime(3, game.getGameTime());
                stm.setString(4, game.getTeamA());
                stm.setString(5, game.getTeamB());
                stm.executeUpdate();
                int gameId = getMaxId();
                List<SectorPrice> sectorPrices = game.getSectorPrices();
                for (SectorPrice price : sectorPrices) {
                    stm = conn.prepareStatement(Statements.INSERT_TICKET_PRICE);
                    stm.setInt(1, gameId);
                    stm.setInt(2, price.getSectorId());
                    stm.setInt(3, price.getPrice());
                    stm.executeUpdate();
                }
            }
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            rs.close();
            stm.close();
        }
        conn.commit();
        conn.setAutoCommit(true);
    }
public void removeGames(List<Game> games) throws SQLException {
        Connection conn = ConnectionManager.getManager().getConnection();
        PreparedStatement stm = null;
        conn.setAutoCommit(false);
        try {
            for (Game game : games) {
                stm = conn.prepareStatement(Statements.DELETE_GAME);
                stm.setInt(1, game.getGameID());
                stm.executeUpdate();
            }
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            if (stm != null) stm.close();
        }
        conn.commit();
        conn.setAutoCommit(true);
    }
public static Vector webService(String siteUrl, String login, String password, String table, String station, String element, String dayFrom, String dayTo, String filePath) throws Exception {
        Service service = new Service();
        Call call = (Call) service.createCall();
        if (login != null) {
            call.setUsername(login);
            if (password != null) {
                call.setPassword(password);
            }
            System.err.println("Info: authentication user=" + login + " passwd=" + password + " at " + siteUrl);
        }
        call.setTargetEndpointAddress(new URL(siteUrl));
        call.setOperationName("syncData");
        Vector exportList = (Vector) call.invoke(new Object[] { table, station, element, dayFrom, dayTo });
        if (exportList != null) {
            for (int k = 0; k < exportList.size(); k++) {
                HashMap exportDescr = (HashMap) exportList.get(k);
                String url = (String) exportDescr.get("fileName");
                log.debug("result URL is " + url);
                String fileName = null;
                URL dataurl = new URL(url);
                String filePart = dataurl.getFile();
                if (filePart == null) {
                    throw new Exception("Error: file part in the data URL is null");
                } else {
                    fileName = filePart.substring(filePart.lastIndexOf("/") < 0 ? 0 : filePart.lastIndexOf("/") + 1);
                    if (filePath != null) {
                        fileName = filePath + fileName;
                    }
                    log.debug("local file name is " + fileName);
                }
                FileOutputStream fos = new FileOutputStream(fileName);
                if (fos == null) {
                    throw new Exception("Error: file output stream is null");
                }
                InputStream strm = dataurl.openStream();
                if (strm == null) {
                    throw new Exception("Error: data input stream is null");
                } else {
                    int c;
                    while ((c = strm.read()) != -1) {
                        fos.write(c);
                    }
                }
                strm.close();
                fos.close();
                File file = new File(fileName);
                exportDescr.put("fileName", file.getCanonicalPath());
            }
        }
        return exportList;
    }
protected URLConnection openURLConnection() throws IOException {
        final String locator = getMediaLocator();
        if (locator == null) {
            return null;
        }
        final URL url;
        try {
            url = new URL(locator);
        } catch (MalformedURLException ex) {
            throw new IllegalArgumentException(ex);
        }
        final URLConnection connection = url.openConnection();
        connection.connect();
        return connection;
    }
public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) {
        Parser p = new Parser();
        javax.xml.parsers.DocumentBuilder db;
        try {
            db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            log.error("", e);
            throw new RuntimeException();
        }
        Document document = db.newDocument();
        InputStream is = htmlInputStream;
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream baos;
            baos = new ByteArrayOutputStream();
            try {
                IOUtils.copy(is, baos);
            } catch (IOException e) {
                log.error("Fail to make input stream copy.", e);
            }
            IOUtils.closeQuietly(is);
            ByteArrayInputStream byteArrayInputStream;
            byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray());
            try {
                IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8");
            } catch (IOException e) {
                log.error("", e);
            }
            IOUtils.closeQuietly(byteArrayInputStream);
            is = new ByteArrayInputStream(baos.toByteArray());
        }
        try {
            InputSource iSource = new InputSource(is);
            iSource.setEncoding(encoding);
            Source transformerSource = new SAXSource(p, iSource);
            Result result = new DOMResult(document);
            Transformer xslTransformer = getTransformerByName(classpathXsltResource, false);
            try {
                xslTransformer.transform(transformerSource, result);
            } catch (TransformerException e) {
                throw new RuntimeException(e);
            }
        } finally {
            try {
                is.close();
            } catch (Exception e) {
                log.warn("", e);
            }
        }
        return document;
    }
private static void copyFile(String src, String target) throws IOException {
        FileChannel ic = new FileInputStream(src).getChannel();
        FileChannel oc = new FileOutputStream(target).getChannel();
        ic.transferTo(0, ic.size(), oc);
        ic.close();
        oc.close();
    }
@Override
    protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
        if ((url == null) || (proxy == null)) {
            throw new IllegalArgumentException(Messages.getString("luni.1B"));
        }
        return new HttpsURLConnectionImpl(url, getDefaultPort(), proxy);
    }
FileCacheInputStreamFountain(FileCacheInputStreamFountainFactory factory, InputStream in) throws IOException {
        file = factory.createFile();
        OutputStream out = new FileOutputStream(file);
        IOUtils.copy(in, out);
        in.close();
        out.close();
    }
public static void copy(File from_file, File to_file) throws IOException {
        if (!from_file.exists()) {
            throw new IOException("FileCopy: no such source file: " + from_file.getPath());
        }
        if (!from_file.isFile()) {
            throw new IOException("FileCopy: can't copy directory: " + from_file.getPath());
        }
        if (!from_file.canRead()) {
            throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath());
        }
        if (to_file.isDirectory()) {
            to_file = new File(to_file, from_file.getName());
        }
        if (to_file.exists()) {
            if (!to_file.canWrite()) {
                throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath());
            }
            int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (choice != JOptionPane.YES_OPTION) {
                throw new IOException("FileCopy: existing file was not overwritten.");
            }
        } else {
            String parent = to_file.getParent();
            if (parent == null) {
                parent = Globals.getDefaultPath();
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("FileCopy: destination directory doesn't exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("FileCopy: destination is not a directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("FileCopy: destination directory is unwriteable: " + parent);
            }
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(from_file);
            to = new FileOutputStream(to_file);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytes_read);
            }
        } finally {
            if (from != null) {
                try {
                    from.close();
                } catch (IOException e) {
                }
            }
            if (to != null) {
                try {
                    to.close();
                } catch (IOException e) {
                }
            }
        }
    }
public void run() {
            try {
                IOUtils.copy(is, os);
                os.flush();
            } catch (IOException ioe) {
                logger.error("Unable to copy", ioe);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
            }
        }
public static int convertImage(InputStream is, OutputStream os, String command) throws IOException, InterruptedException {
        if (logger.isInfoEnabled()) {
            logger.info(command);
        }
        Process p = Runtime.getRuntime().exec(command);
        ByteArrayOutputStream errOut = new ByteArrayOutputStream();
        StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errOut, "Convert Thread (err gobbler): " + command);
        errGobbler.start();
        StreamGobbler outGobbler = new StreamGobbler(new BufferedInputStream(is), p.getOutputStream(), "Convert Thread (out gobbler): " + command);
        outGobbler.start();
        try {
            IOUtils.copy(p.getInputStream(), os);
            os.flush();
            if (p.waitFor() != 0) {
                logger.error("Unable to convert, stderr: " + new String(errOut.toByteArray(), "UTF-8"));
            }
            return p.exitValue();
        } finally {
            IOUtils.closeQuietly(os);
        }
    }
protected void unZip() throws PersistenceException {
        boolean newZip = false;
        try {
            if (null == backup) {
                mode = (String) context.get(Context.MODE);
                if (null == mode) mode = Context.MODE_NAME_RESTORE;
                backupDirectory = (File) context.get(Context.BACKUP_DIRECTORY);
                logger.debug("Got backup directory {" + backupDirectory.getAbsolutePath() + "}");
                if (!backupDirectory.exists() && mode.equals(Context.MODE_NAME_BACKUP)) {
                    newZip = true;
                    backupDirectory.mkdirs();
                } else if (!backupDirectory.exists()) {
                    throw new PersistenceException("Backup directory {" + backupDirectory.getAbsolutePath() + "} does not exist.");
                }
                backup = new File(backupDirectory + "/" + getBackupName() + ".zip");
                logger.debug("Got zip file {" + backup.getAbsolutePath() + "}");
            }
            File _explodedDirectory = File.createTempFile("exploded-" + backup.getName() + "-", ".zip");
            _explodedDirectory.mkdirs();
            _explodedDirectory.delete();
            backupDirectory = new File(_explodedDirectory.getParentFile(), _explodedDirectory.getName());
            backupDirectory.mkdirs();
            logger.debug("Created exploded directory {" + backupDirectory.getAbsolutePath() + "}");
            if (!backup.exists() && mode.equals(Context.MODE_NAME_BACKUP)) {
                newZip = true;
                backup.createNewFile();
            } else if (!backup.exists()) {
                throw new PersistenceException("Backup file {" + backup.getAbsolutePath() + "} does not exist.");
            }
            if (newZip) return;
            ZipFile zip = new ZipFile(backup);
            Enumeration zipFileEntries = zip.entries();
            while (zipFileEntries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
                String currentEntry = entry.getName();
                logger.debug("Inflating: " + entry);
                File destFile = new File(backupDirectory, currentEntry);
                File destinationParent = destFile.getParentFile();
                destinationParent.mkdirs();
                if (!entry.isDirectory()) {
                    InputStream in = null;
                    OutputStream out = null;
                    try {
                        in = zip.getInputStream(entry);
                        out = new FileOutputStream(destFile);
                        IOUtils.copy(in, out);
                    } finally {
                        if (null != out) out.close();
                        if (null != in) in.close();
                    }
                }
            }
        } catch (IOException e) {
            logger.error("Unable to unzip {" + backup + "}", e);
            throw new PersistenceException(e);
        }
    }
public void zipUp() throws PersistenceException {
        ZipOutputStream out = null;
        try {
            if (!backup.exists()) backup.createNewFile();
            out = new ZipOutputStream(new FileOutputStream(backup));
            out.setLevel(Deflater.DEFAULT_COMPRESSION);
            for (String file : backupDirectory.list()) {
                logger.debug("Deflating: " + file);
                FileInputStream in = null;
                try {
                    in = new FileInputStream(new File(backupDirectory, file));
                    out.putNextEntry(new ZipEntry(file));
                    IOUtils.copy(in, out);
                } finally {
                    out.closeEntry();
                    if (null != in) in.close();
                }
            }
            FileUtils.deleteDirectory(backupDirectory);
        } catch (Exception ex) {
            logger.error("Unable to ZIP the backup {" + backupDirectory.getAbsolutePath() + "}.", ex);
            throw new PersistenceException(ex);
        } finally {
            try {
                if (null != out) out.close();
            } catch (IOException e) {
                logger.error("Unable to close ZIP output stream.", e);
            }
        }
    }
public APIResponse delete(String id) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/variable/delete/" + id).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.setDone(true);
            response.setMessage("Variable Deleted!");
        } else {
            response.setDone(false);
            response.setMessage("Delete Variable Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }
public APIResponse update(Variable variable) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/variable/update").openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        connection.setUseCaches(false);
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        marshaller.marshal(variable, new MappedXMLStreamWriter(new MappedNamespaceConvention(new Configuration()), new OutputStreamWriter(connection.getOutputStream(), "utf-8")));
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            JSONObject obj = new JSONObject(new String(new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8")).readLine()));
            response.setDone(true);
            response.setMessage(unmarshaller.unmarshal(new MappedXMLStreamReader(obj, new MappedNamespaceConvention(new Configuration()))));
            connection.getInputStream().close();
        } else {
            response.setDone(false);
            response.setMessage("Update Variable Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }
private static URL searchForBundle(String name, String parent) throws MalformedURLException {
        URL url = null;
        File fileLocation = null;
        boolean reference = false;
        try {
            URL child = new URL(name);
            url = new URL(new File(parent).toURL(), name);
        } catch (MalformedURLException e) {
            File child = new File(name);
            fileLocation = child.isAbsolute() ? child : new File(parent, name);
            url = new URL(REFERENCE_PROTOCOL, null, fileLocation.toURL().toExternalForm());
            reference = true;
        }
        if (!reference) {
            URL baseURL = url;
            if (url.getProtocol().equals(REFERENCE_PROTOCOL)) {
                reference = true;
                String baseSpec = url.getFile();
                if (baseSpec.startsWith(FILE_SCHEME)) {
                    File child = new File(baseSpec.substring(5));
                    baseURL = child.isAbsolute() ? child.toURL() : new File(parent, child.getPath()).toURL();
                } else baseURL = new URL(baseSpec);
            }
            fileLocation = new File(baseURL.getFile());
            if (!fileLocation.isAbsolute()) fileLocation = new File(parent, fileLocation.toString());
        }
        if (reference) {
            String result = searchFor(fileLocation.getName(), new File(fileLocation.getParent()).getAbsolutePath());
            if (result != null) url = new URL(REFERENCE_PROTOCOL, null, FILE_SCHEME + result); else return null;
        }
        try {
            URLConnection result = url.openConnection();
            result.connect();
            return url;
        } catch (IOException e) {
            return null;
        }
    }
public static void main(String[] argv) throws IOException {
        int i;
        for (i = 0; i < argv.length; i++) {
            if (argv[i].charAt(0) != '-') break;
            ++i;
            switch(argv[i - 1].charAt(1)) {
                case 'b':
                    try {
                        flag_predict_probability = (atoi(argv[i]) != 0);
                    } catch (NumberFormatException e) {
                        exit_with_help();
                    }
                    break;
                default:
                    System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1));
                    exit_with_help();
                    break;
            }
        }
        if (i >= argv.length || argv.length <= i + 2) {
            exit_with_help();
        }
        BufferedReader reader = null;
        Writer writer = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET));
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET));
            Model model = Linear.loadModel(new File(argv[i + 1]));
            doPredict(reader, writer, model);
        } finally {
            closeQuietly(reader);
            closeQuietly(writer);
        }
    }
private static String getProviderName(URL url, PrintStream err) {
        InputStream in = null;
        try {
            in = url.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String result = null;
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                int commentPos = line.indexOf('#');
                if (commentPos >= 0) {
                    line = line.substring(0, commentPos);
                }
                line = line.trim();
                int len = line.length();
                if (len != 0) {
                    if (result != null) {
                        print(err, "checkconfig.multiproviders", url.toString());
                        return null;
                    }
                    result = line;
                }
            }
            if (result == null) {
                print(err, "checkconfig.missingprovider", url.toString());
                return null;
            }
            return result;
        } catch (IOException e) {
            print(err, "configconfig.read", url.toString(), e);
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
protected void onSubmit() {
            super.onSubmit();
            if (!this.hasError()) {
                final FileUpload upload = fileUploadField.getFileUpload();
                if (upload != null) {
                    try {
                        StringWriter xmlSourceWriter = new StringWriter();
                        IOUtils.copy(upload.getInputStream(), xmlSourceWriter);
                        processSubmittedDoap(xmlSourceWriter.toString());
                    } catch (IOException e) {
                        setResponsePage(new ErrorReportPage(new UserReportableException("Unable to add doap using RDF supplied", DoapFormPage.class, e)));
                    }
                }
            }
        }