semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception {
        String fileName = destination.getPath();
        File f = new File(getFtpServerHome(), "" + System.currentTimeMillis());
        f.deleteOnExit();
        org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f));
        remoteHostClient.setAscii(isAscii());
        remoteHostClient.setPromptOn(isPrompt());
        remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName);
    }
protected String getHashCode(String value) {
        if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin");
        String retVal = null;
        try {
            MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
            mdAlgorithm.update(value.getBytes());
            byte[] digest = mdAlgorithm.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < digest.length; i++) {
                sb.append(this.toHexString(digest[i]));
            }
            retVal = sb.toString();
            if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal);
        } catch (Exception e) {
            log.error("getHashCode(...) -> error occured generating hashcode ", e);
        }
        if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end");
        return retVal;
    }
private void doLogin() {
        try {
            println("Logging in as '" + username.getText() + "'");
            URL url = new URL("http://" + hostname + "/migrate");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(URLEncoder.encode("login", "UTF-8") + "=" + encodeCredentials());
            wr.flush();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(in);
            Element root = doc.getDocumentElement();
            in.close();
            if (root.getAttribute("success").equals("false")) {
                println("Login Failed: " + getTextContent(root));
                JOptionPane.showMessageDialog(this, "Login Failed: " + getTextContent(root), "Login Failed", JOptionPane.ERROR_MESSAGE);
            } else {
                token = root.hasAttribute("token") ? root.getAttribute("token") : null;
                if (token != null) {
                    startImport();
                }
            }
        } catch (Exception e) {
            ErrorReporter.showError(e, this);
            println(e.toString());
        }
    }
public boolean addTextGroup(String key, URL url) {
        if (_textGroups.contains(key)) return false;
        String s;
        Hashtable tg = new Hashtable();
        String sGroupKey = "default";
        String sGroup[];
        Vector vGroup = new Vector();
        int cntr;
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((s = in.readLine()) != null) {
                if (s.startsWith("[")) {
                    if (vGroup.size() > 0) {
                        sGroup = new String[vGroup.size()];
                        for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr);
                        tg.put(sGroupKey, sGroup);
                        vGroup.removeAllElements();
                    }
                    sGroupKey = s.substring(1, s.indexOf(']'));
                } else {
                    vGroup.addElement(s);
                }
            }
            if (vGroup.size() > 0) {
                sGroup = new String[vGroup.size()];
                for (cntr = 0; cntr < vGroup.size(); ++cntr) sGroup[cntr] = (String) vGroup.elementAt(cntr);
                tg.put(sGroupKey, sGroup);
            }
            in.close();
        } catch (IOException ioe) {
            System.err.println("Error reading file for " + key);
            System.err.println(ioe.getMessage());
            return false;
        }
        _textGroups.put(key, tg);
        return true;
    }
private IMolecule readMolecule() throws Exception {
        String xpath = "";
        if (index.equals("ichi")) {
            xpath = URLEncoder.encode("//molecule[./identifier/basic='" + query + "']", UTF8);
        } else if (index.equals("kegg")) {
            xpath = URLEncoder.encode("//molecule[./@name='" + query + "' and ./@dictRef='KEGG']", UTF8);
        } else if (index.equals("nist")) {
            xpath = URLEncoder.encode("//molecule[../@id='" + query + "']", UTF8);
        } else {
            logger.error("Did not recognize index type: " + index);
            return null;
        }
        String colname = URLEncoder.encode("/" + this.collection, UTF8);
        logger.info("Doing query: " + xpath + " in collection " + colname);
        URL url = new URL("http://" + server + "/Bob/QueryXindice");
        logger.info("Connection to server: " + url.toString());
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        PrintWriter out = new PrintWriter(connection.getOutputStream());
        out.print("detailed=on");
        out.print("&");
        out.print("xmlOnly=on");
        out.print("&");
        out.print("colName=" + colname);
        out.print("&");
        out.print("xpathString=" + xpath);
        out.print("&");
        out.println("query=Query");
        out.close();
        InputStream stream = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(stream));
        in.mark(1000000);
        in.readLine();
        String comment = in.readLine();
        logger.debug("The comment is: " + comment);
        Pattern p = Pattern.compile("<!-- There are (\\d{1,6}) results! -->");
        Matcher match = p.matcher(comment);
        if (match.find()) {
            resultNum = match.group(1);
        } else {
            resultNum = "0";
        }
        logger.debug("The number of result is " + resultNum);
        in.reset();
        CMLReader reader = new CMLReader(stream);
        ChemFile cf = (ChemFile) reader.read((ChemObject) new ChemFile());
        logger.debug("#sequences: " + cf.getChemSequenceCount());
        IMolecule m = null;
        if (cf.getChemSequenceCount() > 0) {
            org.openscience.cdk.interfaces.IChemSequence chemSequence = cf.getChemSequence(0);
            logger.debug("#models in sequence: " + chemSequence.getChemModelCount());
            if (chemSequence.getChemModelCount() > 0) {
                org.openscience.cdk.interfaces.IChemModel chemModel = chemSequence.getChemModel(0);
                org.openscience.cdk.interfaces.IMoleculeSet setOfMolecules = chemModel.getMoleculeSet();
                logger.debug("#mols in model: " + setOfMolecules.getMoleculeCount());
                if (setOfMolecules.getMoleculeCount() > 0) {
                    m = setOfMolecules.getMolecule(0);
                } else {
                    logger.warn("No molecules in the model");
                }
            } else {
                logger.warn("No models in the sequence");
            }
        } else {
            logger.warn("No sequences in the file");
        }
        in.close();
        return m;
    }
Object onSuccess() {
        this.mErrorExist = true;
        this.mErrorMdp = true;
        if (this.mNewMail.equals(mClient.getEmail()) || !this.mNewMail.equals(mClient.getEmail()) && !mClientManager.exists(this.mNewMail)) {
            this.mErrorExist = false;
            if (mNewMdp != null && mNewMdpConfirm != null) {
                if (this.mNewMdp.equals(this.mNewMdpConfirm)) {
                    this.mErrorMdp = false;
                    MessageDigest sha1Instance;
                    try {
                        sha1Instance = MessageDigest.getInstance("SHA1");
                        sha1Instance.reset();
                        sha1Instance.update(this.mNewMdp.getBytes());
                        byte[] digest = sha1Instance.digest();
                        BigInteger bigInt = new BigInteger(1, digest);
                        String vHashPassword = bigInt.toString(16);
                        mClient.setMdp(vHashPassword);
                    } catch (NoSuchAlgorithmException e) {
                        mLogger.error(e.getMessage(), e);
                    }
                }
            } else {
                this.mErrorMdp = false;
            }
            if (!this.mErrorMdp) {
                mClient.setAdresse(this.mNewAdresse);
                mClient.setEmail(this.mNewMail);
                mClient.setNom(this.mNewNom);
                mClient.setPrenom((this.mNewPrenom != null ? this.mNewPrenom : ""));
                Client vClient = new Client(mClient);
                mClientManager.save(vClient);
                mComponentResources.discardPersistentFieldChanges();
                return "Client/List";
            }
        }
        return errorZone.getBody();
    }
public void testCodingBeyondContentLimitFromFile() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel channel = newChannel(baos);
        HttpParams params = new BasicHttpParams();
        SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);
        File tmpFile = File.createTempFile("testFile", "txt");
        FileOutputStream fout = new FileOutputStream(tmpFile);
        OutputStreamWriter wrtout = new OutputStreamWriter(fout);
        wrtout.write("stuff;");
        wrtout.write("more stuff; and a lot more stuff");
        wrtout.flush();
        wrtout.close();
        FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
        encoder.transfer(fchannel, 0, 20);
        String s = baos.toString("US-ASCII");
        assertTrue(encoder.isCompleted());
        assertEquals("stuff;more stuff", s);
        tmpFile.delete();
    }
public void testCodingEmptyFile() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel channel = newChannel(baos);
        HttpParams params = new BasicHttpParams();
        SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);
        encoder.write(wrap("stuff;"));
        File tmpFile = File.createTempFile("testFile", "txt");
        FileOutputStream fout = new FileOutputStream(tmpFile);
        OutputStreamWriter wrtout = new OutputStreamWriter(fout);
        wrtout.flush();
        wrtout.close();
        FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
        encoder.transfer(fchannel, 0, 20);
        encoder.write(wrap("more stuff"));
        String s = baos.toString("US-ASCII");
        assertTrue(encoder.isCompleted());
        assertEquals("stuff;more stuff", s);
        tmpFile.delete();
    }
public void testCodingCompletedFromFile() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel channel = newChannel(baos);
        HttpParams params = new BasicHttpParams();
        SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 5);
        encoder.write(wrap("stuff"));
        File tmpFile = File.createTempFile("testFile", "txt");
        FileOutputStream fout = new FileOutputStream(tmpFile);
        OutputStreamWriter wrtout = new OutputStreamWriter(fout);
        wrtout.write("more stuff");
        wrtout.flush();
        wrtout.close();
        try {
            FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
            encoder.transfer(fchannel, 0, 10);
            fail("IllegalStateException should have been thrown");
        } catch (IllegalStateException ex) {
        } finally {
            tmpFile.delete();
        }
    }
public void testCodingFromFileSmaller() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel channel = newChannel(baos);
        HttpParams params = new BasicHttpParams();
        SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
        HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
        LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16);
        File tmpFile = File.createTempFile("testFile", "txt");
        FileOutputStream fout = new FileOutputStream(tmpFile);
        OutputStreamWriter wrtout = new OutputStreamWriter(fout);
        wrtout.write("stuff;");
        wrtout.write("more stuff;");
        wrtout.flush();
        wrtout.close();
        FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
        encoder.transfer(fchannel, 0, 20);
        String s = baos.toString("US-ASCII");
        assertTrue(encoder.isCompleted());
        assertEquals("stuff;more stuff", s);
        tmpFile.delete();
    }
protected void sort(double[] a) throws Exception {
        for (int i = a.length - 1; i >= 0; i--) {
            boolean swapped = false;
            for (int j = 0; j < i; j++) {
                if (a[j] > a[j + 1]) {
                    double d = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = d;
                    swapped = true;
                }
            }
            if (!swapped) return;
        }
    }
public static ObjectID[] sortDecending(ObjectID[] oids) {
        for (int i = 1; i < oids.length; i++) {
            ObjectID iId = oids[i];
            for (int j = 0; j < oids.length - i; j++) {
                if (oids[j].getTypePrefix() > oids[j + 1].getTypePrefix()) {
                    ObjectID temp = oids[j];
                    oids[j] = oids[j + 1];
                    oids[j + 1] = temp;
                }
            }
        }
        return oids;
    }
public static String getMD5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] digest = md.digest();
            String out = "";
            for (int i = 0; i < digest.length; i++) {
                out += digest[i];
            }
            return out;
        } catch (NoSuchAlgorithmException e) {
            System.err.println("Manca l'MD5 (piuttosto strano)");
        }
        return "";
    }
private static int get(URL url, byte[] content) throws IOException {
        int len = -1;
        InputStream in = null;
        try {
            in = new BufferedInputStream(url.openStream());
            String type = URLConnection.guessContentTypeFromStream(in);
            if (type == null || type.compareTo("text/html") != 0) {
                return -1;
            }
            len = read(in, content);
        } catch (IOException e) {
            throw e;
        } finally {
            close(in);
        }
        return len;
    }
static ConversionMap create(String file) {
        ConversionMap out = new ConversionMap();
        URL url = ConversionMap.class.getResource("data/" + file);
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = in.readLine();
            while (line != null) {
                if (line.length() > 0) {
                    String[] arr = line.split("\t");
                    try {
                        double value = Double.parseDouble(arr[1]);
                        out.put(translate(lowercase(arr[0].getBytes())), value);
                        out.defaultValue += value;
                        out.length = arr[0].length();
                    } catch (NumberFormatException e) {
                        throw new RuntimeException("Something is wrong with in conversion file: " + e);
                    }
                }
                line = in.readLine();
            }
            in.close();
            out.defaultValue /= Math.pow(4, out.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Their was an error while reading the conversion map: " + e);
        }
        return out;
    }
public boolean parseResults(URL url, String analysis_type, CurationI curation, Date analysis_date, String regexp) throws OutputMalFormatException {
        boolean parsed = false;
        try {
            InputStream data_stream = url.openStream();
            parsed = parseResults(data_stream, analysis_type, curation, analysis_date, regexp);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return parsed;
    }
private String readHtmlFile(String htmlFileName) {
        StringBuffer buffer = new StringBuffer();
        java.net.URL url = getClass().getClassLoader().getResource("freestyleLearning/homeCore/help/" + htmlFileName);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String string = " ";
            while (string != null) {
                string = reader.readLine();
                if (string != null) buffer.append(string);
            }
        } catch (Exception exc) {
            System.out.println(exc);
        }
        return new String(buffer);
    }
private void copyTemplates(ProjectPath pPath) {
        String sourceAntPath = pPath.sourceAntPath();
        final String moduleName = projectOperations.getFocusedTopLevelPackage().toString();
        logger.info("Module Name: " + moduleName);
        String targetDirectory = pPath.canonicalFileSystemPath(projectOperations);
        logger.info("Moving into target Directory: " + targetDirectory);
        if (!targetDirectory.endsWith("/")) {
            targetDirectory += "/";
        }
        if (!fileManager.exists(targetDirectory)) {
            fileManager.createDirectory(targetDirectory);
        }
        System.out.println("Target Directory: " + pPath.sourceAntPath());
        String path = TemplateUtils.getTemplatePath(getClass(), sourceAntPath);
        Set<URL> urls = UrlFindingUtils.findMatchingClasspathResources(context.getBundleContext(), path);
        Assert.notNull(urls, "Could not search bundles for resources for Ant Path '" + path + "'");
        if (urls.isEmpty()) {
            logger.info("URLS are empty stopping...");
        }
        for (URL url : urls) {
            logger.info("Stepping into " + url.toExternalForm());
            String fileName = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
            fileName = fileName.replace("-template", "");
            String targetFilename = targetDirectory + fileName;
            logger.info("Handling " + targetFilename);
            if (!fileManager.exists(targetFilename)) {
                try {
                    logger.info("Copied file");
                    String input = FileCopyUtils.copyToString(new InputStreamReader(url.openStream()));
                    logger.info("TopLevelPackage: " + projectOperations.getFocusedTopLevelPackage());
                    logger.info("SegmentPackage: " + pPath.canonicalFileSystemPath(projectOperations));
                    String topLevelPackage = projectOperations.getFocusedTopLevelPackage().toString();
                    input = input.replace("__TOP_LEVEL_PACKAGE__", topLevelPackage);
                    input = input.replace("__SEGMENT_PACKAGE__", pPath.segmentPackage());
                    input = input.replace("__PROJECT_NAME__", projectOperations.getFocusedProjectName());
                    input = input.replace("__ENTITY_NAME__", entityName);
                    MutableFile mutableFile = fileManager.createFile(targetFilename);
                    FileCopyUtils.copy(input.getBytes(), mutableFile.getOutputStream());
                } catch (IOException ioe) {
                    throw new IllegalStateException("Unable to create '" + targetFilename + "'", ioe);
                }
            }
        }
    }
public static void copyFile(final File sourceFile, final File destFile) throws IOException {
        if (destFile.getParentFile() != null && !destFile.getParentFile().mkdirs()) {
            LOG.error("GeneralHelper.copyFile(): Cannot create parent directories from " + destFile);
        }
        FileInputStream fIn = null;
        FileOutputStream fOut = null;
        FileChannel source = null;
        FileChannel destination = null;
        try {
            fIn = new FileInputStream(sourceFile);
            source = fIn.getChannel();
            fOut = new FileOutputStream(destFile);
            destination = fOut.getChannel();
            long transfered = 0;
            final long bytes = source.size();
            while (transfered < bytes) {
                transfered += destination.transferFrom(source, 0, source.size());
                destination.position(transfered);
            }
        } finally {
            if (source != null) {
                source.close();
            } else if (fIn != null) {
                fIn.close();
            }
            if (destination != null) {
                destination.close();
            } else if (fOut != null) {
                fOut.close();
            }
        }
    }
private void saveFile(File destination) {
        InputStream in = null;
        OutputStream out = null;
        try {
            if (fileScheme) in = new BufferedInputStream(new FileInputStream(source.getPath())); else in = new BufferedInputStream(getContentResolver().openInputStream(source));
            out = new BufferedOutputStream(new FileOutputStream(destination));
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) out.write(buffer);
            Toast.makeText(this, R.string.saveas_file_saved, Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(this, R.string.saveas_error, Toast.LENGTH_SHORT).show();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }
public static InputStream getResourceAsStreamIfAny(String resPath) {
        URL url = findResource(resPath);
        try {
            return url == null ? null : url.openStream();
        } catch (IOException e) {
            ZMLog.warn(e, " URL open Connection got an exception!");
            return null;
        }
    }