semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void removeRecipe(Recipe recipe) throws Exception {
        PreparedStatement pst1 = null;
        PreparedStatement pst2 = null;
        PreparedStatement pst3 = null;
        ResultSet rs = null;
        try {
            int id = -1;
            conn = getConnection();
            pst1 = conn.prepareStatement("SELECT recipe_id FROM recipes WHERE name = ? AND instructions = ? ");
            pst1.setString(1, recipe.getName());
            pst1.setString(2, recipe.getInstructions());
            rs = pst1.executeQuery();
            if (rs.next()) {
                id = rs.getInt(1);
            }
            pst2 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ? ");
            pst3 = conn.prepareStatement("DELETE FROM recipes WHERE recipe_id = ? ");
            pst2.setInt(1, id);
            pst3.setInt(1, id);
            pst2.executeUpdate();
            if (pst3.executeUpdate() > 0) {
                MainFrame.appendStatusText("Resepti poistettu kannasta");
            } else {
                MainFrame.appendStatusText("Resepti� poistettaessa tietokannasta tapahtui virhe");
            }
            conn.commit();
            MainFrame.recipePanel.update();
            MainFrame.recipePanel.update();
        } catch (Exception e) {
            conn.rollback();
            MainFrame.appendStatusText("Can't remove 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;
                if (pst3 != null) pst3.close();
                pst3 = null;
            } catch (SQLException sqle) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
    }
public boolean setRecipeToTimetable(int recipeId, Timestamp time, int meal) {
        System.out.println("setRecipeToTimetable");
        PreparedStatement statement = null;
        StringBuffer query = new StringBuffer("insert into timetable (recipe_id, time, meal) values (?,?,?)");
        try {
            conn = getConnection();
            statement = conn.prepareStatement(query.toString());
            statement.setInt(1, recipeId);
            statement.setTimestamp(2, time);
            statement.setInt(3, meal);
            statement.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (Exception ex) {
            }
            MainFrame.appendStatusText("Error when trying to execute sql: " + e.getMessage());
        } finally {
            try {
                if (statement != null) statement.close();
                statement = null;
            } catch (Exception ex) {
                MainFrame.appendStatusText("Can't close database connection.");
            }
        }
        return true;
    }
@Override
    protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException {
        byte[] hash = new byte[DIGEST_SIZE];
        try {
            final MessageDigest md = MessageDigest.getInstance(passwordScheme);
            md.update(criteria.getCredential().getBytes());
            hash = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new LdapException(e);
        }
        final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes());
        final CompareOperation compare = new CompareOperation(c);
        final CompareRequest request = new CompareRequest(criteria.getDn(), la);
        request.setControls(getAuthenticationControls());
        final Response<Boolean> compareResponse = compare.execute(request);
        return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls());
    }
public static long checksum(IFile file) throws IOException {
        InputStream contents;
        try {
            contents = file.getContents();
        } catch (CoreException e) {
            throw new CausedIOException("Failed to calculate checksum.", e);
        }
        CheckedInputStream in = new CheckedInputStream(contents, new Adler32());
        try {
            IOUtils.copy(in, new NullOutputStream());
        } catch (IOException e) {
            throw new CausedIOException("Failed to calculate checksum.", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        return in.getChecksum().getValue();
    }
public static String encodePassword(String password) {
        try {
            MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1");
            messageDiegest.update(password.getBytes("UTF-8"));
            return Base64.encodeToString(messageDiegest.digest(), false);
        } catch (NoSuchAlgorithmException e) {
            log.error("Ha habido un error mientras se almacenaba la clave de acceso.");
            throw new Error(e);
        } catch (UnsupportedEncodingException e) {
            log.error("Ha habido un error mientras se almacenaba la clave de acceso.");
            throw new Error(e);
        }
    }
private Tuple execute(final HttpMethodBase method, int numTries) throws IOException {
        final Timer timer = Metric.newTimer("RestClientImpl.execute");
        try {
            final int sc = httpClient.executeMethod(method);
            if (sc < OK_MIN || sc > OK_MAX) {
                throw new RestException("Unexpected status code: " + sc + ": " + method.getStatusText() + " -- " + method, sc);
            }
            final InputStream in = method.getResponseBodyAsStream();
            try {
                final StringWriter writer = new StringWriter(2048);
                IOUtils.copy(in, writer, method.getResponseCharSet());
                return new Tuple(sc, writer.toString());
            } finally {
                in.close();
            }
        } catch (NullPointerException e) {
            if (numTries < 3) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ie) {
                    Thread.interrupted();
                }
                return execute(method, numTries + 1);
            }
            throw new IOException("Failed to connet to " + url + " [" + method + "]", e);
        } catch (SocketException e) {
            if (numTries < 3) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ie) {
                    Thread.interrupted();
                }
                return execute(method, numTries + 1);
            }
            throw new IOException("Failed to connet to " + url + " [" + method + "]", e);
        } catch (IOException e) {
            if (numTries < 3) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ie) {
                    Thread.interrupted();
                }
                return execute(method, numTries + 1);
            }
            throw e;
        } finally {
            method.releaseConnection();
            timer.stop();
        }
    }
public void createPartControl(Composite parent) {
        splitter = new FlyoutPaletteComposite(parent, SWT.NONE, getSite().getPage(), getPaletteViewerProvider(), new PaletteFlyoutPreferences());
        viewer = new ScrollingGraphicalViewer();
        viewer.createControl(splitter);
        editDomain.addViewer(viewer);
        viewer.getControl().setBackground(ColorConstants.listBackground);
        viewer.setProperty(SnapToGrid.PROPERTY_GRID_SPACING, new Dimension(45, 45));
        ScalableFreeformRootEditPart root = new CustomRootEditPart();
        viewer.setRootEditPart(root);
        viewer.setEditPartFactory(new CustomEditPartFactory());
        getSelectionSynchronizer().addViewer(viewer);
        getSite().setSelectionProvider(viewer);
        splitter.hookDropTargetListener(viewer);
        splitter.setGraphicalControl(viewer.getControl());
        configureViewerActions(root);
        configureKeyHandler();
        ContextMenuProvider comtextMenuProvider = new DiagramContextMenuProvider(viewer, actionRegistry, undoRedoGroup);
        viewer.setContextMenu(comtextMenuProvider);
        viewer.addDropTargetListener(DiagramDropTargetListener.forImport(viewer));
        viewer.addDropTargetListener(DiagramDropTargetListener.forModel(viewer));
        viewer.addSelectionChangedListener(new ISelectionChangedListener() {

            public void selectionChanged(SelectionChangedEvent event) {
                IStructuredSelection selection = (IStructuredSelection) event.getSelection();
                if (selection.size() == 1) {
                    EditPart selectedPart = (EditPart) selection.getFirstElement();
                    if (selectedPart instanceof TableEditPart) {
                        Table table = ((TableEditPart) selectedPart).getTable();
                        RMBenchPlugin.getEventManager().fireTableSelected(DiagramEditor.this, table);
                    } else if (selectedPart instanceof ColumnEditPart) {
                        Column column = ((ColumnEditPart) selectedPart).getColumn();
                        RMBenchPlugin.getEventManager().fireColumnSelected(DiagramEditor.this, column);
                    } else if (selectedPart instanceof ForeignKeyEditPart) {
                        ForeignKey key = ((ForeignKeyEditPart) selectedPart).getForeignKey();
                        RMBenchPlugin.getEventManager().fireForeignKeySelected(DiagramEditor.this, key);
                    } else {
                        RMBenchPlugin.getEventManager().fireTableSelected(DiagramEditor.this, null);
                    }
                }
                updateActions(selectionActionIDs);
            }
        });
        viewer.setContents(getDiagram());
        if (RMBenchPlugin.getModelManager().isDirty()) firePropertyChange(IWorkbenchPartConstants.PROP_DIRTY);
        pasteTablesAction.hookEvents();
    }
public void GetText(TextView content, String address) {
        String url = address;
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            content.setText(TextHelper.GetText(response));
        } catch (Exception ex) {
            content.setText("Welcome to Fluo. Failed to connect to intro server.");
        }
    }
public void onMessage(javax.jms.Message aMessage) {
        try {
            String urlStr = "http://203.197.20.2:8080/newgenlibctxt/oai2.0?verb=ListRecords&resumptionToken=100_marc";
            java.net.URL url = new java.net.URL(urlStr);
            java.net.URLConnection urlCon = url.openConnection();
            urlCon.setDoInput(true);
            urlCon.connect();
            InputStream is = urlCon.getInputStream();
            org.jdom.input.SAXBuilder sb = new org.jdom.input.SAXBuilder();
            org.jdom.Document doc = sb.build(is);
            String xmlstr = (new org.jdom.output.XMLOutputter()).outputString(doc);
            doc = null;
            sb = null;
            java.util.Vector vec = new java.util.Vector();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            TextMessage tm = (TextMessage) aMessage;
            String text = tm.getText() + "processed by: message bean on july 13" + hashCode();
            Queue dest = (Queue) aMessage.getJMSReplyTo();
            sendReply(text, dest);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
public HttpURLConnection connect() throws IOException {
        if (url == null) {
            return null;
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (previousETag != null) {
            connection.addRequestProperty("If-None-Match", previousETag);
        }
        if (previousLastModified != null) {
            connection.addRequestProperty("If-Modified-Since", previousLastModified);
        }
        return connection;
    }
@Override
    protected void handleCreateEditionForExport(File outputFile, int viewComponentIdWithUnit) throws Exception {
        log.info("createEditionForExport ");
        InputStream edition = null;
        if (viewComponentIdWithUnit <= 0) {
            edition = getContentServiceSpring().exportEditionFull();
        } else {
            edition = getContentServiceSpring().exportEditionUnit(Integer.valueOf(viewComponentIdWithUnit));
        }
        log.info("got answer... ");
        if (log.isDebugEnabled()) log.debug("tmpFile " + outputFile.getName());
        FileOutputStream fos = new FileOutputStream(outputFile);
        IOUtils.copyLarge(edition, fos);
        IOUtils.closeQuietly(edition);
        IOUtils.closeQuietly(fos);
        outputFile = null;
        System.gc();
    }
public static Set<String> getProteins(final String goCode, final Set<String> evCodes, final int taxon, final int limit) throws IOException {
        final Set<String> proteins = new HashSet<String>();
        HttpURLConnection connection = null;
        try {
            final String evCodeList = join(evCodes);
            final URL url = new URL(String.format(__urlTempl4, goCode, evCodeList, taxon, limit + 1));
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(__connTimeout);
            connection.setReadTimeout(__readTimeout);
            connection.setRequestProperty("Connection", "close");
            connection.connect();
            final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                proteins.add(line.trim());
            }
        } finally {
            if (connection != null) connection.disconnect();
        }
        return filter(proteins);
    }
public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException {
        if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!");
        if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs();
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)));
        out.setLevel(Deflater.BEST_COMPRESSION);
        InputStream in = null;
        try {
            for (InputStream inputStream : entries.keySet()) {
                in = inputStream;
                ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in)));
                out.putNextEntry(zipEntry);
                IOUtils.copy(in, out);
                out.closeEntry();
                in.close();
            }
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
public static void extract(final File destDir, final Collection<ZipEntryInfo> entryInfos) throws IOException {
        if (destDir == null || CollectionUtils.isEmpty(entryInfos)) throw new IllegalArgumentException("One or parameter is null or empty!");
        if (!destDir.exists()) destDir.mkdirs();
        for (ZipEntryInfo entryInfo : entryInfos) {
            ZipEntry entry = entryInfo.getZipEntry();
            InputStream in = entryInfo.getInputStream();
            File entryDest = new File(destDir, entry.getName());
            entryDest.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                OutputStream out = new FileOutputStream(new File(destDir, entry.getName()));
                try {
                    IOUtils.copy(in, out);
                    out.flush();
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                }
            }
        }
    }
private String unzip(TupleInput input) {
            boolean zipped = input.readBoolean();
            if (!zipped) {
                return input.readString();
            }
            int len = input.readInt();
            try {
                byte array[] = new byte[len];
                input.read(array);
                GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array));
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                IOUtils.copyTo(in, out);
                in.close();
                out.close();
                return new String(out.toByteArray());
            } catch (IOException err) {
                throw new RuntimeException(err);
            }
        }
private void zip(String object, TupleOutput output) {
            byte array[] = object.getBytes();
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream out = new GZIPOutputStream(baos);
                ByteArrayInputStream in = new ByteArrayInputStream(array);
                IOUtils.copyTo(in, out);
                in.close();
                out.close();
                byte array2[] = baos.toByteArray();
                if (array2.length + 4 < array.length) {
                    output.writeBoolean(true);
                    output.writeInt(array2.length);
                    output.write(array2);
                } else {
                    output.writeBoolean(false);
                    output.writeString(object);
                }
            } catch (IOException err) {
                throw new RuntimeException(err);
            }
        }
public InputStream getInputStream(String fName) throws IOException {
        InputStream result = null;
        int length = 0;
        if (isURL) {
            URL url = new URL(getFullFileNamePath(fName));
            URLConnection c = url.openConnection();
            length = c.getContentLength();
            result = c.getInputStream();
        } else {
            File f = new File(sysFn(getFullFileNamePath(fName)));
            if (!f.exists()) {
                String alt = (String) altFileNames.get(fName);
                if (alt != null) f = new File(sysFn(getFullFileNamePath(alt)));
            }
            length = (int) f.length();
            result = new FileInputStream(f);
        }
        if (result != null && rb != null) {
            result = rb.getProgressInputStream(result, length, fName);
        }
        return result;
    }
public void removerQuestaoMultiplaEscolha(QuestaoMultiplaEscolha multiplaEscolha) throws ClassNotFoundException, SQLException {
        this.criaConexao(false);
        String sql = "DELETE FROM \"Disciplina\"    " + "      WHERE ID_Disciplina =  ? )";
        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement(sql);
            stmt.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            throw e;
        } finally {
            try {
                stmt.close();
                this.fechaConexao();
            } catch (SQLException e) {
                throw e;
            }
        }
    }
public static String getContent(String url, String code) {
        HttpURLConnection connect = null;
        try {
            URL myurl = new URL(url);
            connect = (HttpURLConnection) myurl.openConnection();
            connect.setConnectTimeout(30000);
            connect.setReadTimeout(30000);
            connect.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB5; .NET CLR 1.1.4322; .NET CLR 2.0.50727; Alexa Toolbar; MAXTHON 2.0)");
            return StringUtil.convertStreamToString(connect.getInputStream(), code);
        } catch (Exception e) {
            slogger.warn(e.getMessage());
        } finally {
            if (connect != null) {
                connect.disconnect();
            }
        }
        slogger.warn("这个没找到" + url);
        return null;
    }
private String calculateMD5(String input) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.reset();
        digest.update(input.getBytes());
        byte[] md5 = digest.digest();
        String tmp = "";
        String res = "";
        for (int i = 0; i < md5.length; i++) {
            tmp = (Integer.toHexString(0xFF & md5[i]));
            if (tmp.length() == 1) {
                res += "0" + tmp;
            } else {
                res += tmp;
            }
        }
        return res;
    }
public static Document getDocument(URL url) {
        Document doc = null;
        try {
            InputStream i = url.openStream();
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            doc = docBuilder.parse(i);
            doc.getDocumentElement().normalize();
        } catch (Exception e) {
            LocalizedError.display(e);
        }
        return doc;
    }
public LocationResponse getResponse(LocationRequest lrq) throws UnregisteredComponentException {
        LocationResponse lrs = lrq.createResponse();
        try {
            String rqs, rss;
            rqs = encodeSkyhookRequest(lrq);
            if (null == rqs) {
                lrs.setError("No authentication was provided.");
                return lrs;
            }
            URL url = new URL(this.skyhookServerUri);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.addRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(rqs);
            wr.flush();
            BufferedReader rd;
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            rss = "";
            String line;
            while ((line = rd.readLine()) != null) rss += line;
            rd.close();
            decodeSkyhookResponse(rss, lrs);
        } catch (Exception e) {
            e.printStackTrace();
            lrs.setError("Error querying Skyhook");
        }
        return lrs;
    }