semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public String getCipherString(String source) throws CadenaNoCifradaException {
        String encryptedSource = null;
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(source.getBytes(encoding), 0, source.length());
            sha1hash = md.digest();
            encryptedSource = convertToHex(sha1hash);
        } catch (Exception e) {
            throw new CadenaNoCifradaException(e);
        }
        return encryptedSource;
    }
public static byte[] readResource(Class owningClass, String resourceName) {
        final URL url = getResourceUrl(owningClass, resourceName);
        if (null == url) {
            throw new MissingResourceException(owningClass.toString() + " key '" + resourceName + "'", owningClass.toString(), resourceName);
        }
        LOG.info("Loading resource '" + url.toExternalForm() + "' " + "from " + owningClass);
        final InputStream inputStream;
        try {
            inputStream = url.openStream();
        } catch (IOException e) {
            throw new RuntimeException("Should not happpen", e);
        }
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new RuntimeException("Should not happpen", e);
        }
        return outputStream.toByteArray();
    }
public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) {
        final byte[] resourceBytes = readResource(owningClass, resourceName);
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes);
        final File destinationFile = new File(destinationDir, resourceName);
        final FileOutputStream fileOutputStream;
        try {
            fileOutputStream = new FileOutputStream(destinationFile);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
private void addLine(AmazonItem coverAdress) {
        try {
            URL url = new URL("" + coverAdress.getMediumImageURL());
            TableItem ligne1 = new TableItem(table, SWT.DRAW_DELIMITER | SWT.DRAW_TAB | SWT.DRAW_MNEMONIC);
            url.openConnection();
            InputStream is = url.openStream();
            Image coverPicture = new Image(display, is);
            coverAvailable.add(url);
            ligne1.setImage(new Image[] { coverPicture, null });
            ligne1.setText(new String[] { null, coverAdress.getArtist() + "\n" + coverAdress.getCDTitle() + "\nTrack : " + coverAdress.getNbTrack() });
        } catch (MalformedURLException e) {
        } catch (IOException e) {
            System.err.println(e.toString());
        }
    }
public static boolean matchPassword(String prevPassStr, String newPassword) throws NoSuchAlgorithmException, java.io.IOException, java.io.UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] seed = new byte[12];
        byte[] prevPass = new sun.misc.BASE64Decoder().decodeBuffer(prevPassStr);
        System.arraycopy(prevPass, 0, seed, 0, 12);
        md.update(seed);
        md.update(newPassword.getBytes("UTF8"));
        byte[] digestNewPassword = md.digest();
        byte[] choppedPrevPassword = new byte[prevPass.length - 12];
        System.arraycopy(prevPass, 12, choppedPrevPassword, 0, prevPass.length - 12);
        boolean isMatching = Arrays.equals(digestNewPassword, choppedPrevPassword);
        return isMatching;
    }
public static String encodePassword(String password, byte[] seed) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (seed == null) {
            seed = new byte[12];
            secureRandom.nextBytes(seed);
        }
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(seed);
        md.update(password.getBytes("UTF8"));
        byte[] digest = md.digest();
        byte[] storedPassword = new byte[digest.length + 12];
        System.arraycopy(seed, 0, storedPassword, 0, 12);
        System.arraycopy(digest, 0, storedPassword, 12, digest.length);
        return new sun.misc.BASE64Encoder().encode(storedPassword);
    }
protected synchronized Class findClass(String className) {
        LOG.info("FIND class:" + className);
        String urlName = className.replace('.', '/');
        byte buf[];
        Class currentClass;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            int i = className.lastIndexOf('.');
            if (i >= 0) sm.checkPackageDefinition(className.substring(0, i));
        }
        buf = cache.get(urlName);
        if (buf != null) {
            LOG.info("Get class from cache:" + className);
            currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null);
            return currentClass;
        }
        try {
            URL url = new URL(urlBase, urlName + ".class");
            LOG.info("Loading " + url);
            InputStream is = url.openConnection().getInputStream();
            buf = getClassBytes(is);
            currentClass = defineClass(className, buf, 0, buf.length, (CodeSource) null);
            return currentClass;
        } catch (MalformedURLException mE) {
            LOG.warn("Bad url detected", mE);
            return null;
        } catch (IOException e) {
            buf = downloadClass(className);
            if (buf != null) {
                return defineClass(className, buf, 0, buf.length);
            } else {
                LOG.warn("no class found: " + className);
                return null;
            }
        }
    }
public static boolean insert(final Cargo cargo) {
        int result = 0;
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            final String sql = "insert into cargo (nome) values (?)";
            pst = c.prepareStatement(sql);
            pst.setString(1, cargo.getNome());
            result = pst.executeUpdate();
            c.commit();
        } catch (final SQLException e) {
            try {
                c.rollback();
            } catch (final SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
public static boolean update(Cargo cargo) {
        int result = 0;
        Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            String sql = "update cargo set nome = (?) where id_cargo= ?";
            pst = c.prepareStatement(sql);
            pst.setString(1, cargo.getNome());
            pst.setInt(2, cargo.getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (SQLException e) {
            try {
                c.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("[CargoDAO.update] Erro ao atualizar -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
public OperandToken evaluate(Token[] operands, GlobalValues globals) {
        String s = "";
        String lineFile = "";
        ;
        if (getNArgIn(operands) != 1) throwMathLibException("urlread: number of arguments < 1");
        if (!(operands[0] instanceof CharToken)) throwMathLibException("urlread: argument must be String");
        String urlString = ((CharToken) operands[0]).toString();
        URL url = null;
        try {
            url = new URL(urlString);
        } catch (Exception e) {
            throwMathLibException("urlread: malformed url");
        }
        try {
            BufferedReader inReader = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((lineFile = inReader.readLine()) != null) {
                s += lineFile + "\n";
            }
            inReader.close();
        } catch (Exception e) {
            throwMathLibException("urlread: error input stream");
        }
        return new CharToken(s);
    }
public void insertProfile() throws ClassNotFoundException, SQLException {
        Connection connection = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        PreparedStatement ps3 = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(this.url);
            connection.setAutoCommit(false);
            String query1 = "INSERT INTO customers(name,password) VALUES(?,?)";
            ps1 = connection.prepareStatement(query1);
            ps1.setString(1, this.name);
            ps1.setString(2, this.password);
            String query2 = "INSERT INTO customer_roles(name,role_name) VALUES(?,?)";
            ps2 = connection.prepareStatement(query2);
            ps2.setString(1, this.name);
            ps2.setString(2, "user");
            String query3 = "INSERT INTO customers_profile(name,first_name,middle_name,last_name,address1,address2,city,post_box,email,country)" + "VALUES(?,?,?,?,?,?,?,?,?,?)";
            ps3 = connection.prepareStatement(query3);
            ps3.setString(1, this.name);
            ps3.setString(2, this.firstName);
            ps3.setString(3, this.middleName);
            ps3.setString(4, this.lastName);
            ps3.setString(5, this.address1);
            ps3.setString(6, this.address2);
            ps3.setString(7, this.city);
            ps3.setString(8, this.postBox);
            ps3.setString(9, this.email);
            ps3.setString(10, this.country);
            ps1.executeUpdate();
            ps2.executeUpdate();
            ps3.executeUpdate();
            connection.commit();
        } catch (Exception ex) {
            connection.rollback();
        } finally {
            try {
                this.connection.close();
            } catch (Exception ex) {
            }
            try {
                ps1.close();
            } catch (Exception ex) {
            }
            try {
                ps2.close();
            } catch (Exception ex) {
            }
            try {
                ps3.close();
            } catch (Exception ex) {
            }
        }
    }
public void updateProfile() throws ClassNotFoundException, SQLException {
        Connection connection = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(this.url);
            connection.setAutoCommit(false);
            String query2 = "UPDATE customers SET password=? WHERE name=?";
            String query3 = "UPDATE customers_profile " + "SET first_name=?,middle_name=?,last_name=?,address1=?" + ",address2=?,city=?,post_box=?,email=?,country=? WHERE name=?";
            ps1 = connection.prepareStatement(query3);
            ps2 = connection.prepareStatement(query2);
            ps1.setString(1, this.firstName);
            ps1.setString(2, this.middleName);
            ps1.setString(3, this.lastName);
            ps1.setString(4, this.address1);
            ps1.setString(5, this.address2);
            ps1.setString(6, this.city);
            ps1.setString(7, this.postBox);
            ps1.setString(8, this.email);
            ps1.setString(9, this.country);
            ps1.setString(10, this.name);
            ps2.setString(1, this.password);
            ps2.setString(2, this.name);
            ps1.executeUpdate();
            ps2.executeUpdate();
        } catch (Exception ex) {
            connection.rollback();
        } finally {
            try {
                this.connection.close();
            } catch (Exception ex) {
            }
            try {
                ps1.close();
            } catch (Exception ex) {
            }
            try {
                ps2.close();
            } catch (Exception ex) {
            }
        }
    }
public void connect(String ftpHost, int ftpPort, String ftpUser, String ftpPwd) throws IOException {
        ftpClient = new FTPClient();
        ftpClient.setReaderThread(false);
        if (ftpPort == -1) ftpClient.connect(ftpHost); else ftpClient.connect(ftpHost, ftpPort);
        logger.info("FTP Connection Successful: " + ftpHost);
        ftpClient.login(ftpUser, ftpPwd);
    }
public int doCheck(URL url) throws IOException {
        long start = (System.currentTimeMillis());
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
        }
        in.close();
        long end = (System.currentTimeMillis());
        return (int) (end - start);
    }
public static void concatenateOutput(File[] inputFiles, File outputFile) {
        int numberOfInputFiles = inputFiles.length;
        byte lf = (byte) '\n';
        try {
            FileOutputStream fos = new FileOutputStream(outputFile);
            FileChannel outfc = fos.getChannel();
            System.out.println("Processing " + inputFiles[0].getPath());
            FileInputStream fis = new FileInputStream(inputFiles[0]);
            FileChannel infc = fis.getChannel();
            int bufferCapacity = 100000;
            ByteBuffer bb = ByteBuffer.allocate(bufferCapacity);
            bb.clear();
            while (infc.read(bb) > 0) {
                bb.flip();
                outfc.write(bb);
                bb.clear();
            }
            infc.close();
            for (int f = 1; f < numberOfInputFiles; f++) {
                System.out.println("Processing " + inputFiles[f].getPath());
                fis = new FileInputStream(inputFiles[f]);
                infc = fis.getChannel();
                bb.clear();
                int bytesread = infc.read(bb);
                bb.flip();
                byte b = bb.get();
                while (b != lf) {
                    b = bb.get();
                }
                outfc.write(bb);
                bb.clear();
                while (infc.read(bb) > 0) {
                    bb.flip();
                    outfc.write(bb);
                    bb.clear();
                }
                infc.close();
            }
            outfc.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
public static StreamSource getStreamSource(Item item, XQueryContext context) throws XPathException, MalformedURLException, IOException {
        StreamSource streamSource = new StreamSource();
        if (item.getType() == Type.JAVA_OBJECT) {
            LOG.debug("Streaming Java object");
            Object obj = ((JavaObjectValue) item).getObject();
            if (!(obj instanceof File)) {
                throw new XPathException("Passed java object should be a File");
            }
            File inputFile = (File) obj;
            InputStream is = new FileInputStream(inputFile);
            streamSource.setInputStream(is);
            streamSource.setSystemId(inputFile.toURI().toURL().toString());
        } else if (item.getType() == Type.ANY_URI) {
            LOG.debug("Streaming xs:anyURI");
            String url = item.getStringValue();
            if (url.startsWith("/")) {
                url = "xmldb:exist://" + url;
            }
            InputStream is = new URL(url).openStream();
            streamSource.setInputStream(is);
            streamSource.setSystemId(url);
        } else if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
            LOG.debug("Streaming element or document node");
            if (item instanceof NodeProxy) {
                NodeProxy np = (NodeProxy) item;
                String url = "xmldb:exist://" + np.getDocument().getBaseURI();
                LOG.debug("Document detected, adding URL " + url);
                streamSource.setSystemId(url);
            }
            Serializer serializer = context.getBroker().newSerializer();
            NodeValue node = (NodeValue) item;
            InputStream is = new NodeInputStream(serializer, node);
            streamSource.setInputStream(is);
        } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
            LOG.debug("Streaming base64 binary");
            BinaryValue binary = (BinaryValue) item;
            byte[] data = (byte[]) binary.toJavaObject(byte[].class);
            InputStream is = new ByteArrayInputStream(data);
            streamSource.setInputStream(is);
            if (item instanceof Base64BinaryDocument) {
                Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
                String url = "xmldb:exist://" + b64doc.getUrl();
                LOG.debug("Base64BinaryDocument detected, adding URL " + url);
                streamSource.setSystemId(url);
            }
        } else {
            LOG.error("Wrong item type " + Type.getTypeName(item.getType()));
            throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
        }
        return streamSource;
    }
private void copyFileToPhotoFolder(File photo, String personId) {
        try {
            FileChannel in = new FileInputStream(photo).getChannel();
            File dirServer = new File(Constants.PHOTO_DIR);
            if (!dirServer.exists()) {
                dirServer.mkdirs();
            }
            File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg");
            if (!fileServer.exists()) {
                fileServer.createNewFile();
            }
            in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public void writeTo(OutputStream out) throws IOException {
        if (!closed) {
            throw new IOException("Stream not closed");
        }
        if (isInMemory()) {
            memoryOutputStream.writeTo(out);
        } else {
            FileInputStream fis = new FileInputStream(outputFile);
            try {
                IOUtils.copy(fis, out);
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }
    }
private File uploadFile(InputStream inputStream, File file) {
        FileOutputStream fileOutputStream = null;
        try {
            File dir = file.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileUtils.touch(file);
            fileOutputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (IOException e) {
            throw new FileOperationException("Failed to save uploaded image", e);
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                LOGGER.warn("Failed to close resources on uploaded file", e);
            }
        }
        return file;
    }
public void requestConfirm() throws Exception {
        if (!this._c.checkProperty("directory.request", "request")) {
            throw new Exception("product has no active request");
        }
        if (!new File(WBSAgnitioConfiguration.getHARequestFile()).canWrite()) {
            throw new Exception("cannot remove request from system");
        }
        HashMap<String, String> values = getValues(WBSAgnitioConfiguration.getHARequestFile());
        if (!values.containsKey("address.virtual")) {
            throw new Exception("failed to determine the virtual address");
        }
        if (!values.containsKey("address.real")) {
            throw new Exception("failed to determine the remote address");
        }
        HTTPClient _hc = new HTTPClient(values.get("address.real"));
        if (TomcatConfiguration.checkHTTPS()) {
            _hc.setSecure(true);
        }
        _hc.load("/admin/Comm?type=" + CommResponse.TYPE_HA + "&command=" + CommResponse.COMMAND_REQUEST_CONFIRM + "&virtual=" + values.get("address.virtual"));
        String _reply = new String(_hc.getContent());
        if (_reply.isEmpty()) {
            throw new Exception("remote product has not sent any reply");
        } else if (_reply.indexOf("done") == -1) {
            throw new Exception(_reply);
        }
        HAConfiguration.setSlave(values.get("address.virtual"), values.get("address.real"));
        File _f = new File(WBSAgnitioConfiguration.getOptionalSchemaRequestFile());
        if (_f.exists()) {
            FileOutputStream _fos = new FileOutputStream(WBSAgnitioConfiguration.getOptionalSchemaFile());
            FileInputStream _fis = new FileInputStream(_f);
            while (_fis.available() > 0) {
                _fos.write(_fis.read());
            }
            _fis.close();
            _fos.close();
            _f.delete();
        }
        _f = new File(WBSAgnitioConfiguration.getSchemaObjectRequestFile());
        if (_f.exists()) {
            FileOutputStream _fos = new FileOutputStream(WBSAgnitioConfiguration.getSchemaObjectFile());
            FileInputStream _fis = new FileInputStream(_f);
            while (_fis.available() > 0) {
                _fos.write(_fis.read());
            }
            _fis.close();
            _fos.close();
            _f.delete();
        }
        new File(WBSAgnitioConfiguration.getHARequestFile()).delete();
        this._c.removeProperty("directory.request");
        this._c.setProperty("directory.virtual", values.get("address.virtual"));
        this._c.setProperty("directory.status", "slave");
        this._c.store();
    }
private File downloadPDB(String pdbId) {
        File tempFile = new File(path + "/" + pdbId + ".pdb.gz");
        File pdbHome = new File(path);
        if (!pdbHome.canWrite()) {
            System.err.println("can not write to " + pdbHome);
            return null;
        }
        String ftp = String.format("ftp://ftp.ebi.ac.uk/pub/databases/msd/pdb_uncompressed/pdb%s.ent", pdbId.toLowerCase());
        System.out.println("Fetching " + ftp);
        try {
            URL url = new URL(ftp);
            InputStream conn = url.openStream();
            System.out.println("writing to " + tempFile);
            FileOutputStream outPut = new FileOutputStream(tempFile);
            GZIPOutputStream gzOutPut = new GZIPOutputStream(outPut);
            PrintWriter pw = new PrintWriter(gzOutPut);
            BufferedReader fileBuffer = new BufferedReader(new InputStreamReader(conn));
            String line;
            while ((line = fileBuffer.readLine()) != null) {
                pw.println(line);
            }
            pw.flush();
            pw.close();
            outPut.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return tempFile;
    }