semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public RoleItem addUserRole(RoleItem role, long userId) throws DatabaseException {
        if (role == null) throw new NullPointerException("role");
        if (role.getName() == null || "".equals(role.getName())) throw new NullPointerException("role.getName()");
        if (hasRole(role.getName(), userId)) {
            return new RoleItem(role.getName(), "", "exist");
        }
        RoleItem defaultRole = new RoleItem(role.getName(), "", "exist");
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            LOGGER.warn("Unable to set autocommit off", e);
        }
        String retID = "exist";
        String roleDesc = "";
        PreparedStatement seqSt = null, roleDescSt = null;
        try {
            int modified = 0;
            PreparedStatement insSt = getConnection().prepareStatement(INSERT_USER_IN_ROLE_STATEMENT);
            insSt.setLong(1, userId);
            insSt.setString(2, role.getName());
            modified = insSt.executeUpdate();
            seqSt = getConnection().prepareStatement(USER_ROLE_VALUE);
            ResultSet rs = seqSt.executeQuery();
            while (rs.next()) {
                retID = rs.getString(1);
            }
            roleDescSt = getConnection().prepareStatement(SELECT_ROLE_DESCRIPTION);
            roleDescSt.setString(1, role.getName());
            ResultSet rs2 = roleDescSt.executeQuery();
            while (rs2.next()) {
                roleDesc = rs2.getString(1);
            }
            if (modified == 1) {
                getConnection().commit();
                LOGGER.debug("DB has been updated. Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\"");
            } else {
                getConnection().rollback();
                LOGGER.error("DB has not been updated -> rollback! Queries: \"" + seqSt + "\" and \"" + roleDescSt + "\"");
                retID = "error";
            }
        } catch (SQLException e) {
            LOGGER.error(e);
            retID = "error";
        } finally {
            closeConnection();
        }
        defaultRole.setId(retID);
        defaultRole.setDescription(roleDesc);
        return defaultRole;
    }
protected void invoke(String path, Object request, Callback<Object> callback) throws IOException, ClassNotFoundException {
        Assert.notNull(callback, "callback cant be null");
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setDefaultUseCaches(false);
        connection.setRequestMethod("POST");
        connection.connect();
        try {
            ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
            try {
                output.writeObject(request);
                output.flush();
            } finally {
                output.close();
            }
            ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
            try {
                for (; ; ) {
                    Object result = input.readObject();
                    if (result == null) {
                        break;
                    }
                    callback.onSuccess(result);
                }
            } finally {
                input.close();
            }
        } finally {
            connection.disconnect();
        }
    }
public void putFullDirectory(final String ftpURL, final String remoteDir, final String userId, final String pwd, final String localDir) throws Exception {
        if (!Strings.isPopulated(ftpURL)) {
            Util.dspmsg("Need an FTP url.");
            return;
        }
        if (!Strings.isPopulated(remoteDir)) {
            Util.dspmsg("Need a remote directory.");
            return;
        }
        if (!Strings.isPopulated(userId)) {
            Util.dspmsg("Need a user ID.");
            return;
        }
        if (!Strings.isPopulated(pwd)) {
            Util.dspmsg("Need a password.");
            return;
        }
        if (!Strings.isPopulated(localDir)) {
            Util.dspmsg("Need a local directory.");
            return;
        }
        FTPClient c = new FTPClient();
        c.connect(ftpURL);
        int replyCode = c.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            Util.dspmsg("Could not connect, code: " + replyCode);
            c.disconnect();
            return;
        }
        if (!c.login(userId, pwd)) {
            Util.dspmsg("Could not log on, userId: " + userId + " pwd: " + pwd);
            return;
        }
        StringTokenizer st = new StringTokenizer(remoteDir, "/");
        while (st.hasMoreElements()) {
            if (!chgDir(c, st.nextToken())) {
                return;
            }
        }
        c.setFileType(FTP.BINARY_FILE_TYPE);
        File file = new File(localDir);
        if (file.isDirectory()) {
            FOR: for (File f : file.listFiles()) {
                if (!put(c, f)) {
                    break FOR;
                }
            }
        } else {
            put(c, file);
        }
        c.logout();
        c.disconnect();
    }
public static String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(password.getBytes());
            byte[] hash = md.digest();
            int hashLength = hash.length;
            StringBuffer hashStringBuf = new StringBuffer();
            String byteString;
            int byteLength;
            for (int index = 0; index < hashLength; index++) {
                byteString = String.valueOf(hash[index] + 128);
                byteLength = byteString.length();
                switch(byteLength) {
                    case 1:
                        byteString = "00" + byteString;
                        break;
                    case 2:
                        byteString = "0" + byteString;
                        break;
                }
                hashStringBuf.append(byteString);
            }
            return hashStringBuf.toString();
        } catch (NoSuchAlgorithmException nsae) {
            log.error("Error getting password hash: " + nsae.getMessage());
            return null;
        }
    }
public void execute(HttpServletRequest req, HttpServletResponse res, HttpServlet parent) throws Exception {
        String path = req.getParameter("path");
        path = URLDecoder.decode(path, "UTF-8");
        String name = req.getParameter("name");
        name = new String(name.getBytes(), "UTF-8");
        String contentType = req.getParameter("contentType");
        if (path == null) {
            NullPointerException e = new NullPointerException("The path attribute cannot be retrieved.");
            LOG.error(e);
            throw e;
        }
        URL url = new URL(path);
        InputStream inStream = null;
        try {
            inStream = URLUtils.getFileContent(url, req.getSession().getId());
            res.setContentType(contentType);
            res.addHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
            ServletOutputStream out = res.getOutputStream();
            IOUtils.copy(inStream, out);
            res.flushBuffer();
        } finally {
            if (inStream != null) {
                inStream.close();
            }
        }
    }
public MpegPresentation(URL url) throws IOException {
        File file = new File(url.getPath());
        InputStream input = url.openStream();
        DataInputStream ds = new DataInputStream(input);
        try {
            parseFile(ds);
            prepareTracks();
            if (audioTrackBox != null && audioHintTrackBox != null) {
                audioTrack = new AudioTrack(audioTrackBox, audioHintTrackBox, file);
            }
            if (videoTrackBox != null && videoHintTrackBox != null) {
                videoTrack = new VideoTrack(videoTrackBox, videoHintTrackBox, file);
            }
        } finally {
            ds.close();
            input.close();
        }
    }
public static String hash(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha1hash = md.digest();
        return SHA1.convertToHex(sha1hash);
    }
public static byte[] readUrl(URL url) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = url.openStream();
        try {
            IOUtils.copy(is, os);
            return os.toByteArray();
        } finally {
            is.close();
        }
    }
private int[] sortRows(int[] rows) {
        for (int i = 0; i < rows.length; i++) {
            for (int j = 0; j < rows.length - 1; j++) {
                if (rows[j] > rows[j + 1]) {
                    int temp = rows[j];
                    rows[j] = rows[j + 1];
                    rows[j + 1] = temp;
                }
            }
        }
        return rows;
    }
@Override
    public String encryptString(String passphrase, String message) throws Exception {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        md.update(passphrase.getBytes("UTF-8"));
        byte digest[] = md.digest();
        String digestString = base64encode(digest);
        System.out.println(digestString);
        SecureRandom sr = new SecureRandom(digestString.getBytes());
        KeyGenerator kGen = KeyGenerator.getInstance("AES");
        kGen.init(128, sr);
        Key key = kGen.generateKey();
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] bIn = cipher.doFinal(message.getBytes("UTF-8"));
        String base64Encoded = base64encode(bIn);
        return base64Encoded;
    }
@Override
    public String decryptString(String passphrase, String crypted) throws Exception {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        md.update(passphrase.getBytes("UTF-8"));
        byte digest[] = md.digest();
        String digestString = base64encode(digest);
        System.out.println(digestString);
        SecureRandom sr = new SecureRandom(digestString.getBytes());
        KeyGenerator kGen = KeyGenerator.getInstance("AES");
        kGen.init(128, sr);
        Key key = kGen.generateKey();
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] cryptString = base64decode(crypted);
        byte[] bOut = cipher.doFinal(cryptString);
        String outString = new String(bOut, "UTF-8");
        return outString;
    }
public String getLastReleaseVersion() throws TransferException {
        try {
            URL url = new URL("http://jtbdivelogbook.sourceforge.net/version.properties");
            URLConnection urlConn = url.openConnection();
            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);
            urlConn.setReadTimeout(20000);
            urlConn.setConnectTimeout(10000);
            Properties props = new Properties();
            InputStream is = urlConn.getInputStream();
            props.load(is);
            is.close();
            String lastVersion = props.getProperty(PROPERTY_LAST_RELEASE);
            if (lastVersion == null) {
                LOGGER.warn("Couldn't find property " + PROPERTY_LAST_RELEASE);
            }
            return lastVersion;
        } catch (MalformedURLException e) {
            LOGGER.error(e);
            throw new TransferException(e);
        } catch (IOException e) {
            LOGGER.error(e);
            throw new TransferException(e);
        }
    }
public void checkVersion(boolean showOnlyDiff) {
        try {
            DataInputStream di = null;
            byte[] b = new byte[1];
            URL url = new URL("http://lanslim.sourceforge.net/version.txt");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            di = new DataInputStream(con.getInputStream());
            StringBuffer lBuffer = new StringBuffer();
            while (-1 != di.read(b, 0, 1)) {
                lBuffer.append(new String(b));
            }
            String lLastStr = lBuffer.toString().trim();
            boolean equals = VERSION.equals(lLastStr);
            String lMessage = Externalizer.getString("LANSLIM.199", VERSION, lLastStr);
            if (!equals) {
                lMessage = lMessage + StringConstants.NEW_LINE + Externalizer.getString("LANSLIM.131") + StringConstants.NEW_LINE;
            }
            if (!equals || !showOnlyDiff) {
                JOptionPane.showMessageDialog(getRootPane().getParent(), lMessage, Externalizer.getString("LANSLIM.118"), JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(getRootPane().getParent(), Externalizer.getString("LANSLIM.200", SlimLogger.shortFormatException(e)), Externalizer.getString("LANSLIM.118"), JOptionPane.WARNING_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(getRootPane().getParent(), Externalizer.getString("LANSLIM.200", SlimLogger.shortFormatException(e)), Externalizer.getString("LANSLIM.118"), JOptionPane.WARNING_MESSAGE);
        }
    }
private static void stampaFoglioRisposte(HttpSession httpSess, Appelli appello, Elaborati el, StringBuffer retVal, boolean primaVolta, String url, boolean anonimo) {
        InputStream is = null;
        String html = null;
        final int MAX_RIGHE_PER_PAGINA = 25;
        long totaleDomande = EsamiDAO.trovaQuanteDomandeElaborato(el.getID());
        long numPagine = 0, totalePagine = (long) Math.ceil(totaleDomande / 50.0);
        String urlBarcode = null;
        while (numPagine < totalePagine) {
            try {
                urlBarcode = URLEncoder.encode(HtmlCodeForPrint.creaBarcode("" + appello.getID() + "-" + el.getID() + "-" + (numPagine + 1), url), "UTF-8");
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex);
            }
            String jsp = url + "jsp/StampaRisposte.jsp?base=" + (numPagine * MAX_RIGHE_PER_PAGINA) + "&urlbarcode=" + urlBarcode;
            try {
                URL urlJSP = new URL(jsp);
                is = urlJSP.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int letto = is.read();
                while (letto != -1) {
                    baos.write(letto);
                    letto = is.read();
                }
                html = baos.toString();
            } catch (IOException ex) {
                Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException ex) {
                    Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex);
                }
                numPagine++;
            }
        }
        retVal.append(html);
    }
@Test
    public void test01_ok_failed_500_no_logo() throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpPost post = new HttpPost(xlsURL);
            HttpResponse response = client.execute(post);
            assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
@Test
    public void test02_ok_200_logo() throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpPost post = new HttpPost(xlsURL);
            HttpResponse response = client.execute(post);
            assertEquals("failed code for ", 200, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException {
        if (log.isTraceEnabled()) log.trace("Read input stream with metadata=" + metadata);
        Integer resCode = (Integer) metadata.get(HTTPMetadataConstants.RESPONSE_CODE);
        String resMessage = (String) metadata.get(HTTPMetadataConstants.RESPONSE_CODE_MESSAGE);
        if (resCode != null && validResponseCodes.contains(resCode) == false) throw new RuntimeException("Invalid HTTP server response [" + resCode + "] - " + resMessage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        IOUtils.copyStream(baos, inputStream);
        String soapMessage = new String(baos.toByteArray(), charsetEncoding);
        if (isTraceEnabled) {
            String prettySoapMessage = DOMWriter.printNode(DOMUtils.parse(soapMessage), true);
            log.trace("Incoming Response SOAPMessage\n" + prettySoapMessage);
        }
        return soapMessage;
    }
public static void main(String[] argArray) {
        if (argArray.length == 0) {
            System.out.println("Usage: java  -jar doc-analyzer.jar  url | file");
        }
        List<URL> urlList = new LinkedList<URL>();
        for (String urlStr : argArray) {
            if (!(urlStr.startsWith("http") || urlStr.startsWith("file"))) {
                if (urlStr.indexOf("*") > -1) {
                    if (urlStr.indexOf("**") > -1) {
                    }
                    continue;
                } else {
                    if (!urlStr.startsWith("/")) {
                        File workDir = new File(System.getProperty("user.dir"));
                        urlStr = workDir.getPath() + "/" + urlStr;
                    }
                    urlStr = "file:" + urlStr;
                }
            }
            try {
                URL url = new URL(urlStr);
                urlList.add(url);
            } catch (MalformedURLException murle) {
                System.err.println(murle);
            }
        }
        for (URL url : urlList) {
            try {
                Document doc = builder.build(url.openStream());
                Element element = doc.getRootElement();
                Map<String, Long> numberOfElementMap = countElement(element);
                System.out.println("Overview of tags in '" + url + "':");
                for (String elementName : new TreeSet<String>(numberOfElementMap.keySet())) {
                    System.out.println("  " + elementName + ": " + numberOfElementMap.get(elementName));
                }
            } catch (JDOMException jdome) {
                System.err.println(jdome.getMessage());
            } catch (IOException ioe) {
                System.err.println(ioe.getMessage());
            }
        }
    }
public void copyFile(final File sourceFile, final File destinationFile) throws FileIOException {
        final FileChannel sourceChannel;
        try {
            sourceChannel = new FileInputStream(sourceFile).getChannel();
        } catch (FileNotFoundException exception) {
            final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile;
            LOGGER.fatal(message);
            throw fileIOException(message, sourceFile, exception);
        }
        final FileChannel destinationChannel;
        try {
            destinationChannel = new FileOutputStream(destinationFile).getChannel();
        } catch (FileNotFoundException exception) {
            final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile;
            LOGGER.fatal(message);
            throw fileIOException(message, destinationFile, exception);
        }
        try {
            destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (Exception exception) {
            final String message = COPY_FILE_FAILED + sourceFile + " -> " + destinationFile;
            LOGGER.fatal(message);
            throw fileIOException(message, null, exception);
        } finally {
            if (sourceChannel != null) {
                try {
                    sourceChannel.close();
                } catch (IOException exception) {
                    LOGGER.error("closing source", exception);
                }
            }
            if (destinationChannel != null) {
                try {
                    destinationChannel.close();
                } catch (IOException exception) {
                    LOGGER.error("closing destination", exception);
                }
            }
        }
    }
private static final String hash(String input, String algorithm) {
        try {
            MessageDigest dig = MessageDigest.getInstance(algorithm);
            dig.update(input.getBytes());
            StringBuffer result = new StringBuffer();
            byte[] digest = dig.digest();
            String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
            for (int i = 0; i < digest.length; i++) {
                int u = digest[i];
                u &= 0x000000FF;
                int highCount = u / 16;
                int lowCount = u - (highCount * 16);
                result.append(hex[highCount]);
                result.append(hex[lowCount]);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
public java.io.File gzip(java.io.File file) throws Exception {
        java.io.File tmp = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            tmp = java.io.File.createTempFile(file.getName(), ".gz");
            tmp.deleteOnExit();
            is = new BufferedInputStream(new FileInputStream(file));
            os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tmp)));
            byte[] buf = new byte[4096];
            int nread = -1;
            while ((nread = is.read(buf)) != -1) {
                os.write(buf, 0, nread);
            }
            os.flush();
        } finally {
            os.close();
            is.close();
        }
        return tmp;
    }
public RTUser getUserInfo(final String username) {
        getSession();
        Map<String, String> attributes = Collections.emptyMap();
        final HttpGet get = new HttpGet(m_baseURL + "/REST/1.0/user/" + username);
        try {
            final HttpResponse response = getClient().execute(get);
            int responseCode = response.getStatusLine().getStatusCode();
            if (responseCode != HttpStatus.SC_OK) {
                throw new RequestTrackerException("Received a non-200 response code from the server: " + responseCode);
            } else {
                if (response.getEntity() != null) {
                    attributes = parseResponseStream(response.getEntity().getContent());
                }
            }
        } catch (final Exception e) {
            LogUtils.errorf(this, e, "An exception occurred while getting user info for " + username);
            return null;
        }
        final String id = attributes.get("id");
        final String realname = attributes.get("realname");
        final String email = attributes.get("emailaddress");
        if (id == null || "".equals(id)) {
            LogUtils.errorf(this, "Unable to retrieve ID from user info.");
            return null;
        }
        return new RTUser(Long.parseLong(id.replace("user/", "")), username, realname, email);
    }