semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public boolean register(String username, String password) {
        this.getLogger().info(DbUserServiceImpl.class, ">>>rigister " + username + "<<<");
        try {
            if (this.getDbServ().queryFeelerUser(username) != null) {
                return false;
            }
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            String passwordMd5 = new String(md5.digest());
            this.getDbServ().addFeelerUser(username, passwordMd5);
            return this.identification(username, password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        }
    }
@Override
    public boolean identification(String username, String password) {
        this.getLogger().info(DbUserServiceImpl.class, ">>>identification " + username + "<<<");
        try {
            IFeelerUser user = this.getDbServ().queryFeelerUser(username);
            if (user == null) {
                return false;
            }
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            if (user.getPassword().equals(new String(md5.digest()))) {
                if (!this.localUUIDList.contains(user.getUuid())) {
                    this.localUUIDList.add(user.getUuid());
                }
                return true;
            } else {
                return false;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        String pathInfo = httpServletRequest.getPathInfo();
        log.info("PathInfo: " + pathInfo);
        if (pathInfo == null || pathInfo.equals("") || pathInfo.equals("/")) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String fileName = pathInfo.charAt(0) == '/' ? pathInfo.substring(1) : pathInfo;
        log.info("FileName: " + fileName);
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = getDataSource().getConnection();
            ps = con.prepareStatement("select file, size from files where name=?");
            ps.setString(1, fileName);
            rs = ps.executeQuery();
            if (rs.next()) {
                httpServletResponse.setContentType(getServletContext().getMimeType(fileName));
                httpServletResponse.setContentLength(rs.getInt("size"));
                OutputStream os = httpServletResponse.getOutputStream();
                org.apache.commons.io.IOUtils.copy(rs.getBinaryStream("file"), os);
                os.flush();
            } else {
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        } finally {
            if (rs != null) try {
                rs.close();
            } catch (SQLException e) {
            }
            if (ps != null) try {
                ps.close();
            } catch (SQLException e) {
            }
            if (con != null) try {
                con.close();
            } catch (SQLException e) {
            }
        }
    }
public static synchronized Document readRemoteDocument(URL url, boolean validate) throws IOException, SAXParseException {
        if (DEBUG) System.out.println("DocumentUtilities.readDocument( " + url + ")");
        Document document = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setCoalescing(true);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDefaultUseCaches(false);
            connection.setUseCaches(false);
            connection.setRequestProperty("User-Agent", "eXchaNGeR/" + System.getProperty("xngr.version") + " (http://xngr.org/)");
            connection.connect();
            InputStream stream = connection.getInputStream();
            document = factory.newDocumentBuilder().parse(stream);
            stream.close();
            connection.disconnect();
        } catch (SAXException e) {
            if (e instanceof SAXParseException) {
                throw (SAXParseException) e;
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        if (DEBUG) System.out.println("DocumentUtilities.readDocument( " + url + ") [" + document + "]");
        return document;
    }
private static String makeTempTraceFile(String base) throws IOException {
        File temp = File.createTempFile(base, ".trace");
        temp.deleteOnExit();
        FileChannel dstChannel = new FileOutputStream(temp).getChannel();
        FileChannel srcChannel = new FileInputStream(base + ".key").getChannel();
        long size = dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        srcChannel = new FileInputStream(base + ".data").getChannel();
        dstChannel.transferFrom(srcChannel, size, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
        return temp.getPath();
    }
public void run() throws Exception {
        logger.debug("#run enter");
        logger.debug("#run lineId : " + lineId);
        logger.debug("#run quantityNew : " + quantityNew);
        logger.debug("#run priceNew : " + priceNew);
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            connection.setAutoCommit(false);
            Integer itemId = null;
            Integer quantity = null;
            ps = connection.prepareStatement(SQL_SELECT_ORDER_LINE);
            ps.setInt(1, lineId);
            rs = ps.executeQuery();
            while (rs.next()) {
                itemId = rs.getInt("ITEM_ID");
                quantity = rs.getInt("QUANTITY");
            }
            rs.close();
            ps.close();
            ps = connection.prepareStatement(SQL_UPDATE_ITEM_BALANCE);
            ps.setInt(1, quantityNew - quantity);
            ps.setInt(2, itemId);
            ps.executeUpdate();
            ps = connection.prepareStatement(SQL_UPDATE_ORDER_LINE);
            ps.setDouble(1, priceNew);
            ps.setInt(2, quantityNew);
            ps.setInt(3, lineId);
            ps.executeUpdate();
            ps.close();
            ps.close();
            connection.commit();
        } catch (SQLException ex) {
            logger.error("SQLException", ex);
            connection.rollback();
            throw new Exception("Не удалось обновить позицию в заказе. Ошибка : " + ex.getMessage());
        } finally {
            connection.setAutoCommit(true);
        }
        logger.debug("#run exit");
    }
@Override
    public URLConnection getResourceConnection(String name) throws ResourceException {
        try {
            URLConnection c = super.getResourceConnection(name);
            return c;
        } catch (ResourceException e) {
            while (name.startsWith(ServletHelpers.SCRIPT_DIR.getAbsolutePath())) name = name.substring(ServletHelpers.SCRIPT_DIR.getAbsolutePath().length());
            name = name.replaceAll("\\\\", "/");
            if (name.startsWith("/")) name = name.substring(1);
            File script = new File(ServletHelpers.SCRIPT_DIR, name);
            if (script.canRead()) {
                try {
                    URL url = new URL("file", "", script.getAbsolutePath());
                    return url.openConnection();
                } catch (IOException x) {
                    throw new ResourceException("IOError", x);
                }
            } else throw new ResourceException(String.format("Script not found! [%s]", script.getAbsolutePath()));
        }
    }
protected static String stringOfUrl(String addr) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        URLConnection c = url.openConnection();
        c.setConnectTimeout(2000);
        IOUtils.copy(c.getInputStream(), output);
        return output.toString();
    }
protected Object insertSingle(Object name, Object fact) throws SQLException {
        DFAgentDescription dfd = (DFAgentDescription) fact;
        AID agentAID = dfd.getName();
        String agentName = agentAID.getName();
        DFAgentDescription dfdToReturn = null;
        String batchErrMsg = "";
        Connection conn = getConnectionWrapper().getConnection();
        PreparedStatements pss = getPreparedStatements();
        try {
            dfdToReturn = (DFAgentDescription) removeSingle(dfd.getName());
            Date leaseTime = dfd.getLeaseTime();
            long lt = (leaseTime != null ? leaseTime.getTime() : -1);
            String descrId = getGUID();
            pss.stm_insAgentDescr.setString(1, descrId);
            pss.stm_insAgentDescr.setString(2, agentName);
            pss.stm_insAgentDescr.setString(3, String.valueOf(lt));
            pss.stm_insAgentDescr.executeUpdate();
            saveAID(agentAID);
            Iterator iter = dfd.getAllLanguages();
            if (iter.hasNext()) {
                pss.stm_insLanguage.clearBatch();
                while (iter.hasNext()) {
                    pss.stm_insLanguage.setString(1, descrId);
                    pss.stm_insLanguage.setString(2, (String) iter.next());
                    pss.stm_insLanguage.addBatch();
                }
                pss.stm_insLanguage.executeBatch();
            }
            iter = dfd.getAllOntologies();
            if (iter.hasNext()) {
                pss.stm_insOntology.clearBatch();
                while (iter.hasNext()) {
                    pss.stm_insOntology.setString(1, descrId);
                    pss.stm_insOntology.setString(2, (String) iter.next());
                    pss.stm_insOntology.addBatch();
                }
                pss.stm_insOntology.executeBatch();
            }
            iter = dfd.getAllProtocols();
            if (iter.hasNext()) {
                pss.stm_insProtocol.clearBatch();
                while (iter.hasNext()) {
                    pss.stm_insProtocol.setString(1, descrId);
                    pss.stm_insProtocol.setString(2, (String) iter.next());
                    pss.stm_insProtocol.addBatch();
                }
                pss.stm_insProtocol.executeBatch();
            }
            saveServices(descrId, dfd.getAllServices());
            regsCnt++;
            if (regsCnt > MAX_REGISTER_WITHOUT_CLEAN) {
                regsCnt = 0;
                clean();
            }
            conn.commit();
        } catch (SQLException sqle) {
            try {
                conn.rollback();
            } catch (SQLException se) {
                logger.log(Logger.SEVERE, "Rollback for incomplete insertion of DFD for agent " + dfd.getName() + " failed.", se);
            }
            throw sqle;
        }
        return dfdToReturn;
    }
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
            System.out.println("newBundle");
            if (baseName == null || locale == null || format == null || loader == null) throw new NullPointerException();
            ResourceBundle bundle = null;
            if (format.equals("xml")) {
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, format);
                System.out.println(resourceName);
                InputStream stream = null;
                if (reload) {
                    URL url = loader.getResource(resourceName);
                    System.out.println(url.toExternalForm());
                    if (url != null) {
                        URLConnection connection = url.openConnection();
                        if (connection != null) {
                            connection.setUseCaches(false);
                            stream = connection.getInputStream();
                        }
                    }
                } else {
                    stream = loader.getResourceAsStream(resourceName);
                }
                if (stream != null) {
                    InputSource source = new InputSource(stream);
                    try {
                        bundle = new XMLResourceBundle(source);
                    } catch (SAXException saxe) {
                        throw new IOException(saxe);
                    }
                }
            }
            return bundle;
        }
private static void readIzvestiyaArticles() throws IOException {
        CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';');
        reader.setTrimWhitespace(true);
        try {
            while (reader.readRecord()) {
                String id = reader.get(0);
                String filename = reader.get(1);
                StringTokenizer st = new StringTokenizer(filename, "-.");
                String name = st.nextToken();
                String volume = st.nextToken();
                String year = st.nextToken();
                String extension = st.nextToken();
                String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension);
                id2filename.put(id, filepath);
            }
        } finally {
            reader.close();
        }
        for (Map.Entry<String, String> entry : id2filename.entrySet()) {
            String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue());
            filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX");
            if (new File(filepath).exists()) {
                InputStream in = new FileInputStream(filepath);
                FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false);
                try {
                    org.apache.commons.io.IOUtils.copy(in, out);
                } catch (Exception e) {
                    org.apache.commons.io.IOUtils.closeQuietly(in);
                    org.apache.commons.io.IOUtils.closeQuietly(out);
                }
            } else {
                logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist");
            }
        }
    }
public static String md5(String plain) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            PApplet.println("[ERROR]: md5()   " + e);
            return "";
        }
        md5.reset();
        md5.update(plain.getBytes());
        byte[] result = md5.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < result.length; i += 1) {
            hexString.append(Integer.toHexString(0xFF & result[i]));
        }
        return hexString.toString();
    }
protected String readUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String response = "";
        String inputLine;
        while ((inputLine = in.readLine()) != null) response += inputLine;
        in.close();
        return response;
    }
public static IEntity readFromFile(File resourceName) {
        InputStream inputStream = null;
        try {
            URL urlResource = ModelLoader.solveResource(resourceName.getPath());
            if (urlResource != null) {
                inputStream = urlResource.openStream();
                return (IEntity) new ObjectInputStream(inputStream).readObject();
            }
        } catch (IOException e) {
        } catch (ClassNotFoundException e) {
        } finally {
            if (inputStream != null) try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
        return null;
    }
public boolean connect(String host, String userName, String password) throws IOException, UnknownHostException {
        try {
            if (ftpClient != null) {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
            ftpClient = new FTPClient();
            boolean success = false;
            ftpClient.connect(host);
            int reply = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                success = ftpClient.login(userName, password);
            }
            if (!success) {
                ftpClient.disconnect();
            }
            return success;
        } catch (Exception ex) {
            throw new IOException(ex.getMessage());
        }
    }
@Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        TextView tv = new TextView(this);
        try {
            URL url = new URL("");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            ExampleHandler myExampleHandler = new ExampleHandler();
            xr.setContentHandler(myExampleHandler);
            xr.parse(new InputSource(url.openStream()));
            ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
            tv.setText(parsedExampleDataSet.toString());
        } catch (Exception e) {
            tv.setText("Error: " + e.getMessage());
            Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
        }
        this.setContentView(tv);
    }
public void service(TranslationRequest request, TranslationResponse response) {
        try {
            Thread.sleep((long) Math.random() * 250);
        } catch (InterruptedException e1) {
        }
        hits.incrementAndGet();
        String key = getKey(request);
        RequestResponse cachedResponse = cache.get(key);
        if (cachedResponse == null) {
            response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key));
            return;
        }
        response.addHeaders(cachedResponse.getExpectedResponse().getHeaders());
        response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount());
        response.setFailCount(cachedResponse.getExpectedResponse().getFailCount());
        if (cachedResponse.getExpectedResponse().getLastModified() != -1) {
            response.setLastModified(cachedResponse.getExpectedResponse().getLastModified());
        }
        try {
            OutputStream output = response.getOutputStream();
            InputStream input = cachedResponse.getExpectedResponse().getInputStream();
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(input);
                IOUtils.closeQuietly(output);
            }
        } catch (IOException e) {
            response.setEndState(new ResponseStateException(e));
            return;
        }
        response.setEndState(cachedResponse.getExpectedResponse().getEndState());
    }
private Image getIcon(Element e) {
        if (!addIconsToButtons) {
            return null;
        } else {
            NodeList nl = e.getElementsByTagName("rc:iconURL");
            if (nl.getLength() > 0) {
                String urlString = nl.item(0).getTextContent();
                try {
                    Image img = new Image(Display.getCurrent(), new URL(urlString).openStream());
                    return img;
                } catch (Exception exception) {
                    logger.warn("Can't read " + urlString + " using default icon instead.");
                }
            }
            return new Image(Display.getCurrent(), this.getClass().getResourceAsStream("/res/default.png"));
        }
    }
protected static String encodePassword(String raw_password) throws DatabaseException {
        String clean_password = validatePassword(raw_password);
        try {
            MessageDigest md = MessageDigest.getInstance(DEFAULT_PASSWORD_DIGEST);
            md.update(clean_password.getBytes(DEFAULT_PASSWORD_ENCODING));
            String digest = new String(Base64.encodeBase64(md.digest()));
            if (log.isDebugEnabled()) log.debug("encodePassword: digest=" + digest);
            return digest;
        } catch (UnsupportedEncodingException e) {
            throw new DatabaseException("encoding-problem with password", e);
        } catch (NoSuchAlgorithmException e) {
            throw new DatabaseException("digest-problem encoding password", e);
        }
    }
private void createScript(File scriptsLocation, String relativePath, String scriptContent) {
        Writer fileWriter = null;
        try {
            File scriptFile = new File(scriptsLocation.getAbsolutePath() + "/" + relativePath);
            scriptFile.getParentFile().mkdirs();
            fileWriter = new FileWriter(scriptFile);
            IOUtils.copy(new StringReader(scriptContent), fileWriter);
        } catch (IOException e) {
            throw new UnitilsException(e);
        } finally {
            IOUtils.closeQuietly(fileWriter);
        }
    }
private void doUpdate(final boolean notifyOnChange) {
        if (!validServerUrl) {
            return;
        }
        boolean tempBuildClean = true;
        List failedBuilds = new ArrayList();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                Matcher matcher = ROW_PARSER_PATTERN.matcher(line);
                if (matcher.matches() && checkAllProjects) {
                    String project = matcher.group(GROUP_PROJECT);
                    String status = matcher.group(GROUP_STATUS);
                    if (status.equals(MessageUtils.getString("ccOutput.status.failed"))) {
                        tempBuildClean = false;
                        failedBuilds.add(project);
                    }
                }
            }
        } catch (IOException e) {
            serverReachable = false;
            if (notifyOnChange) {
                monitor.notifyServerUnreachable(MessageUtils.getString("error.readError", new String[] { url.toString() }));
            }
            return;
        }
        if (notifyOnChange && buildClean && !tempBuildClean) {
            monitor.notifyBuildFailure(MessageUtils.getString("message.buildFailed", new Object[] { failedBuilds.get(0) }));
        }
        if (notifyOnChange && !buildClean && tempBuildClean) {
            monitor.notifyBuildFixed(MessageUtils.getString("message.allBuildsClean"));
        }
        buildClean = tempBuildClean;
        monitor.setStatus(buildClean);
        serverReachable = true;
    }
public void insert(IIDGenerator idGenerators, AIDADocument item) throws SQLException {
        AIDAActivityObjectDB.getManager(token).insert(idGenerators, item);
        Connection con = getConnection();
        try {
            PreparedStatement ps = con.prepareStatement(DOC_INSERT);
            ps.setLong(1, item.getId());
            ps.setString(2, item.getName());
            ps.setString(3, item.getRelativeLink());
            ps.executeUpdate();
            ps.close();
            insertDescriptions(con, item);
        } catch (SQLException sqlEx) {
            con.rollback();
            throw sqlEx;
        } finally {
            con.close();
        }
        return;
    }