semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static String SHA1(String password) throws BusinessException {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(password.getBytes());
            BigInteger hash = new BigInteger(1, digest.digest());
            return hash.toString(16);
        } catch (java.security.NoSuchAlgorithmException e) {
            throw new BusinessException();
        }
    }
public static void copy(File src, File dest) throws IOException {
        log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath());
        if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath());
        if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath());
        if (src.isDirectory()) {
            if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath());
            String children[] = src.list();
            for (String child : children) {
                File src1 = new File(src, child);
                File dst1 = new File(dest, child);
                copy(src1, dst1);
            }
        } else {
            FileInputStream fin = null;
            FileOutputStream fout = null;
            byte[] buffer = new byte[4096];
            int bytesRead;
            fin = new FileInputStream(src);
            fout = new FileOutputStream(dest);
            while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead);
            if (fin != null) {
                fin.close();
            }
            if (fout != null) {
                fout.close();
            }
        }
    }
public void fileUpload() throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(postURL);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("fff", new MonitoredFileBody(file, uploadProgress));
        httppost.setEntity(reqEntity);
        NULogger.getLogger().info("Now uploading your file into 2shared.com. Please wait......................");
        status = UploadStatus.UPLOADING;
        HttpResponse response = httpclient.execute(httppost);
        status = UploadStatus.GETTINGLINK;
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            String page = EntityUtils.toString(resEntity);
            NULogger.getLogger().log(Level.INFO, "PAGE :{0}", page);
        }
    }
public static String sha1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("UTF-8"), 0, text.length());
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
public static void copyTo(File source, File dest) {
        if (source.isHidden()) ; else if (source.isDirectory()) {
            File temp = new File(dest.getPath() + "/" + source.getName());
            temp.mkdir();
            for (File sel : source.listFiles()) copyTo(sel, temp);
        } else {
            try {
                File tempDest = new File(dest.getPath() + "/" + source.getName());
                tempDest.createNewFile();
                FileChannel sourceCh = new FileInputStream(source).getChannel();
                FileChannel destCh = new FileOutputStream(tempDest).getChannel();
                sourceCh.transferTo(0, sourceCh.size(), destCh);
                sourceCh.close();
                destCh.close();
            } catch (IOException ex) {
                Logger.getLogger(EditorUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
public static void zip() throws Exception {
        System.out.println("zip()");
        ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip")));
        ZipEntry entry = new ZipEntry("asdf.script");
        zipout.putNextEntry(entry);
        byte buffer[] = new byte[BLOCKSIZE];
        FileInputStream in = new FileInputStream(new File("/zip/asdf.script"));
        for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length);
        in.close();
        zipout.closeEntry();
        zipout.close();
    }
public static void gzip() throws Exception {
        System.out.println("gzip()");
        GZIPOutputStream zipout = new GZIPOutputStream(new FileOutputStream("/zip/myzip.gz"));
        byte buffer[] = new byte[BLOCKSIZE];
        File dir = new File("/zip/covers");
        System.out.println("Dir '" + dir.getAbsolutePath() + "' exists: " + dir.exists());
        FileInputStream in = new FileInputStream(dir);
        for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length);
        in.close();
        zipout.close();
    }
public static void gunzip() throws Exception {
        System.out.println("gunzip()");
        GZIPInputStream zipin = new GZIPInputStream(new FileInputStream("/zip/myzip.gz"));
        byte buffer[] = new byte[BLOCKSIZE];
        FileOutputStream out = new FileOutputStream("/zip/covers");
        for (int length; (length = zipin.read(buffer, 0, BLOCKSIZE)) != -1; ) out.write(buffer, 0, length);
        out.close();
        zipin.close();
    }
public void setUp() {
        configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml");
        getProject().executeTarget("setup");
        tmpDir = getProject().getProperty("tmp.dir");
        ftp = new FTPClient();
        ftpFileSep = getProject().getProperty("ftp.filesep");
        myFTPTask.setSeparator(ftpFileSep);
        myFTPTask.setProject(getProject());
        remoteTmpDir = myFTPTask.resolveFile(tmpDir);
        String remoteHost = getProject().getProperty("ftp.host");
        int port = Integer.parseInt(getProject().getProperty("ftp.port"));
        String remoteUser = getProject().getProperty("ftp.user");
        String password = getProject().getProperty("ftp.password");
        try {
            ftp.connect(remoteHost, port);
        } catch (Exception ex) {
            connectionSucceeded = false;
            loginSuceeded = false;
            System.out.println("could not connect to host " + remoteHost + " on port " + port);
        }
        if (connectionSucceeded) {
            try {
                ftp.login(remoteUser, password);
            } catch (IOException ioe) {
                loginSuceeded = false;
                System.out.println("could not log on to " + remoteHost + " as user " + remoteUser);
            }
        }
    }
public void save() {
        final JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileFilter() {

            public String getDescription() {
                return "PDF File";
            }

            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".pdf");
            }
        });
        if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
            return;
        }
        File targetFile = fc.getSelectedFile();
        if (!targetFile.getName().toLowerCase().endsWith(".pdf")) {
            targetFile = new File(targetFile.getParentFile(), targetFile.getName() + ".pdf");
        }
        if (targetFile.exists()) {
            if (JOptionPane.showConfirmDialog(this, "Do you want to overwrite the file?") != JOptionPane.YES_OPTION) {
                return;
            }
        }
        try {
            final InputStream is = new FileInputStream(filename);
            try {
                final OutputStream os = new FileOutputStream(targetFile);
                try {
                    final byte[] buffer = new byte[32768];
                    for (int read; (read = is.read(buffer)) != -1; ) {
                        os.write(buffer, 0, read);
                    }
                } finally {
                    os.close();
                }
            } finally {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
@Override
    protected Control createDialogArea(final Composite parent) {
        this.area = new Composite((Composite) super.createDialogArea(parent), SWT.NONE);
        this.area.setLayout(new FillLayout());
        this.area.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        this.scrolledComposite = new ScrolledComposite(this.area, SWT.V_SCROLL | SWT.H_SCROLL);
        this.scrolledComposite.setLayout(new FillLayout());
        this.scrolledComposite.setExpandVertical(true);
        this.scrolledComposite.setExpandHorizontal(true);
        ViewForm vf = new ViewForm(this.scrolledComposite, SWT.BORDER | SWT.FLAT);
        vf.horizontalSpacing = 0;
        vf.verticalSpacing = 0;
        ToolBarManager tbm = new ToolBarManager(SWT.FLAT | SWT.HORIZONTAL | SWT.RIGHT);
        long width = InformationUtil.getChildByType(this.image, ImagePlugin.NODE_NAME_WIDTH).getLongValue();
        long height = InformationUtil.getChildByType(this.image, ImagePlugin.NODE_NAME_HEIGHT).getLongValue();
        this.graphicalViewer = new ScrollingGraphicalViewer();
        ScalableRootEditPart root = new ScalableRootEditPart();
        this.graphicalViewer.setRootEditPart(root);
        this.graphicalViewer.setEditDomain(new EditDomain());
        this.graphicalViewer.setEditPartFactory(new ImageLinkEditPartFactory(this.editingDomain));
        this.canvas = (FigureCanvas) this.graphicalViewer.createControl(vf);
        this.canvas.getHorizontalBar().setVisible(true);
        this.canvas.getVerticalBar().setVisible(true);
        this.graphicalViewer.setContents(this.image);
        DeleteCommentAction deleteLinkAction = new DeleteCommentAction(this.image);
        deleteLinkAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE));
        CreateCommentAction createLinkAction = new CreateCommentAction(this.image);
        createLinkAction.setEditingDomain(this.editingDomain);
        deleteLinkAction.setEditingDomain(this.editingDomain);
        tbm.add(createLinkAction);
        tbm.add(deleteLinkAction);
        this.scrolledComposite.setContent(vf);
        this.graphicalViewer.addSelectionChangedListener(deleteLinkAction);
        vf.setTopLeft(tbm.createControl(vf));
        vf.setContent(this.canvas);
        GridData gd = new GridData(SWT.BEGINNING, SWT.TOP);
        gd.widthHint = (int) width;
        gd.heightHint = (int) height;
        this.canvas.setLayoutData(gd);
        vf.addControlListener(new ControlAdapter() {

            @Override
            public void controlResized(final ControlEvent e) {
                CommentImageDialog.this.canvas.redraw();
                super.controlResized(e);
            }
        });
        setTitle(Messages.CommentImageDialog_Title);
        setMessage(Messages.CommentImageDialog_Message);
        setTitleImage(ResourceManager.getPluginImage(ImagePlugin.getDefault(), "icons/iconexperience/comment_wizard_title.png"));
        return this.area;
    }
public static synchronized String encrypt(String plaintext) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(plaintext.getBytes("UTF-8"));
        byte raw[] = md.digest();
        return (new BASE64Encoder()).encode(raw);
    }
public static String toMd5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }
public int saveRoom(String name, String icon, String stringid) {
        DBConnection con = null;
        int categoryId = -1;
        try {
            con = DBServiceManager.allocateConnection();
            con.setAutoCommit(false);
            String query = "INSERT INTO cafe_Chat_Category " + "(cafe_Chat_Category_pid,cafe_Chat_Category_name, cafe_Chat_Category_icon) " + "VALUES (null,?,?) ";
            PreparedStatement ps = con.prepareStatement(query);
            ps.setString(1, name);
            ps.setString(2, icon);
            ps.executeUpdate();
            query = "SELECT cafe_Chat_Category_id FROM cafe_Chat_Category " + "WHERE cafe_Chat_Category_name=? ";
            ps = con.prepareStatement(query);
            ps.setString(1, name);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                query = "INSERT INTO cafe_Chatroom (cafe_chatroom_category, cafe_chatroom_name, cafe_chatroom_stringid) " + "VALUES (?,?,?) ";
                ps = con.prepareStatement(query);
                ps.setInt(1, rs.getInt("cafe_Chat_Category_id"));
                categoryId = rs.getInt("cafe_Chat_Category_id");
                ps.setString(2, name);
                ps.setString(3, stringid);
                ps.executeUpdate();
            }
            con.commit();
            con.setAutoCommit(true);
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException sqle) {
            }
        } finally {
            if (con != null) con.release();
        }
        return categoryId;
    }
public void removeRoom(int thisRoom) {
        DBConnection con = null;
        try {
            con = DBServiceManager.allocateConnection();
            con.setAutoCommit(false);
            String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? ";
            PreparedStatement ps = con.prepareStatement(query);
            ps.setInt(1, thisRoom);
            ps.executeUpdate();
            query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? ";
            ps = con.prepareStatement(query);
            ps.setInt(1, thisRoom);
            ps.executeUpdate();
            con.commit();
            con.setAutoCommit(true);
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException sqle) {
            }
        } finally {
            if (con != null) con.release();
        }
    }
private IProject createJavaProject() {
        IProject proj = ResourcesPlugin.getWorkspace().getRoot().getProject("DefaultFolderPropertiesTest");
        if (!proj.exists()) {
            try {
                proj.create(null);
                proj.open(null);
                IProjectDescription desc = proj.getDescription();
                desc.setNatureIds(new String[] { JavaCore.NATURE_ID });
                proj.setDescription(desc, null);
                IJavaProject javaProject = JavaCore.create(proj);
                javaProject.open(null);
                IFolder srcFolder1 = proj.getFolder(new Path("src"));
                srcFolder1.create(true, true, null);
                IFolder srcFolder2 = proj.getFolder(new Path("custom_src"));
                srcFolder2.create(true, true, null);
                IClasspathEntry[] classpathEntries = new IClasspathEntry[] { JavaCore.newSourceEntry(srcFolder1.getFullPath()), JavaCore.newSourceEntry(srcFolder2.getFullPath()), JavaRuntime.getDefaultJREContainerEntry() };
                javaProject.setRawClasspath(classpathEntries, null);
                IFolder binFolder = proj.getFolder(new Path("bin"));
                if (!binFolder.exists()) {
                    binFolder.create(true, true, null);
                }
                javaProject.setOutputLocation(binFolder.getFullPath(), null);
                IFolder testFolder = proj.getFolder(new Path("test"));
                testFolder.create(true, true, null);
                IFolder resultFolder = proj.getFolder(new Path("result"));
                resultFolder.create(true, true, null);
            } catch (CoreException e) {
                fail(e.getMessage());
            }
        }
        return proj;
    }
public InputStream loadDriver(String id) throws IOException {
        Hashtable drivers = loadDriverDB();
        DriverInfo di = (DriverInfo) drivers.get(id);
        InputStream stream = null;
        if (di == null) {
            log.warn("No id" + id);
            throw new IOException("No driver id '" + id + "'");
        }
        try {
            String strURL = di.url;
            if (strURL.indexOf(":") == -1) {
                strURL = jarbase + strURL;
            }
            URL url = new URL(strURL);
            stream = url.openStream();
        } catch (MalformedURLException e) {
            log.error("bad URL for in " + di, e);
            throw new IOException("Bad driver URL " + e);
        } catch (IOException e) {
            log.error("can't connect to URL in " + di, e);
            throw e;
        }
        return stream;
    }
Hashtable loadDriverDB() {
        Hashtable d = new Hashtable();
        InputStream instream = null;
        try {
            String dbURL = System.getProperty("org.osgi.service.basicdriverlocator.dburl");
            if (dbURL != null && !dbURL.equals("")) {
                if (dbURL.indexOf(":") == -1) {
                    dbURL = jarbase + dbURL;
                }
                URL url = new URL(dbURL);
                log.info("read external props file: " + dbURL);
                instream = url.openStream();
            } else {
                log.info("read internal props file: " + dbResourceName);
                instream = getClass().getResourceAsStream(dbResourceName);
            }
            Properties db = new Properties();
            db.load(instream);
            int nCount = Integer.parseInt((String) db.get("count"));
            for (int i = 0; i < nCount; i++) {
                try {
                    DriverInfo di = new DriverInfo(db, i);
                    d.put(di.id, di);
                } catch (Exception e) {
                    log.error("Failed to initialize driver entry " + i, e);
                }
            }
        } catch (Exception e) {
            log.error("Can't load driverDB: ", e);
            e.printStackTrace();
        } finally {
            try {
                if (instream != null) instream.close();
            } catch (IOException e2) {
            }
        }
        return d;
    }
static InputStream getFileAsStream(Class clazz, HandlerChain chain) {
        URL url = clazz.getResource(chain.file());
        if (url == null) {
            url = Thread.currentThread().getContextClassLoader().getResource(chain.file());
        }
        if (url == null) {
            String tmp = clazz.getPackage().getName();
            tmp = tmp.replace('.', '/');
            tmp += "/" + chain.file();
            url = Thread.currentThread().getContextClassLoader().getResource(tmp);
        }
        if (url == null) {
            throw new UtilException("util.failed.to.find.handlerchain.file", clazz.getName(), chain.file());
        }
        try {
            return url.openStream();
        } catch (IOException e) {
            throw new UtilException("util.failed.to.parse.handlerchain.file", clazz.getName(), chain.file());
        }
    }
public String loadFileContent(final String _resourceURI) {
        final Lock readLock = this.fileLock.readLock();
        final Lock writeLock = this.fileLock.writeLock();
        boolean hasReadLock = false;
        boolean hasWriteLock = false;
        try {
            readLock.lock();
            hasReadLock = true;
            if (!this.cachedResources.containsKey(_resourceURI)) {
                readLock.unlock();
                hasReadLock = false;
                writeLock.lock();
                hasWriteLock = true;
                if (!this.cachedResources.containsKey(_resourceURI)) {
                    final InputStream resourceAsStream = this.getClass().getResourceAsStream(_resourceURI);
                    final StringWriter writer = new StringWriter();
                    try {
                        IOUtils.copy(resourceAsStream, writer);
                    } catch (final IOException ex) {
                        throw new IllegalStateException("Resource not read-able", ex);
                    }
                    final String loadedResource = writer.toString();
                    this.cachedResources.put(_resourceURI, loadedResource);
                }
                writeLock.unlock();
                hasWriteLock = false;
                readLock.lock();
                hasReadLock = true;
            }
            return this.cachedResources.get(_resourceURI);
        } finally {
            if (hasReadLock) {
                readLock.unlock();
            }
            if (hasWriteLock) {
                writeLock.unlock();
            }
        }
    }
private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException {
        log("Creating launch profile package " + destfile);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile)));
        ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME);
        e.setMethod(ZipEntry.STORED);
        e.setSize(tmpFile.length());
        e.setCompressedSize(tmpFile.length());
        e.setCrc(calcChecksum(tmpFile, new CRC32()));
        out.putNextEntry(e);
        InputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.closeEntry();
        out.finish();
        out.close();
    }
public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException {
        PreparedStatement stmt = null;
        String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getIdQuestao());
            stmt.setInt(2, q.getDisciplina().getIdDisciplina());
            stmt.setInt(3, idTopico);
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }
private void criarQuestaoMultiplaEscolha(QuestaoMultiplaEscolha q) throws SQLException {
        PreparedStatement stmt = null;
        String sql = "INSERT INTO multipla_escolha (id_questao, texto, gabarito) VALUES (?,?,?)";
        try {
            for (Alternativa alternativa : q.getAlternativa()) {
                stmt = conexao.prepareStatement(sql);
                stmt.setInt(1, q.getIdQuestao());
                stmt.setString(2, alternativa.getTexto());
                stmt.setBoolean(3, alternativa.getGabarito());
                stmt.executeUpdate();
                conexao.commit();
            }
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }
@Override
    public void alterar(QuestaoMultiplaEscolha q) throws Exception {
        PreparedStatement stmt = null;
        String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getDisciplina().getIdDisciplina());
            stmt.setString(2, q.getEnunciado());
            stmt.setString(3, q.getDificuldade().name());
            stmt.setInt(4, q.getIdQuestao());
            stmt.executeUpdate();
            conexao.commit();
            alterarQuestaoMultiplaEscolha(q);
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }