semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void filter(File source, File destination, MNamespace mNamespace) throws Exception {
        BufferedReader reader = new BufferedReader(new FileReader(source));
        BufferedWriter writer = new BufferedWriter(new FileWriter(destination));
        int line = 0;
        int column = 0;
        Stack parseStateStack = new Stack();
        parseStateStack.push(new ParseState(mNamespace));
        for (Iterator i = codePieces.iterator(); i.hasNext(); ) {
            NamedCodePiece cp = (NamedCodePiece) i.next();
            while (line < cp.getStartLine()) {
                line++;
                column = 0;
                writer.write(reader.readLine());
                writer.newLine();
            }
            while (column < cp.getStartPosition()) {
                writer.write(reader.read());
                column++;
            }
            cp.write(writer, parseStateStack, column);
            while (line < cp.getEndLine()) {
                line++;
                column = 0;
                reader.readLine();
            }
            while (column < cp.getEndPosition()) {
                column++;
                reader.read();
            }
        }
        String data;
        while ((data = reader.readLine()) != null) {
            writer.write(data);
            writer.newLine();
        }
        reader.close();
        writer.close();
    }
public Font(String path, String fontName) {
        this();
        StringTokenizer tok = new StringTokenizer(path, ";");
        NybbleInputStream str = null;
        while (str == null & tok.hasMoreTokens()) {
            try {
                URL url = new URL(tok.nextToken() + "/");
                url = new URL(url, fontName);
                System.out.println(url.toString());
                str = new NybbleInputStream(url.openStream());
                parsePkStream(str);
                str.close();
                name = fontName;
            } catch (java.io.IOException e) {
            }
        }
    }
public static synchronized Font loadFont(String path, String fontName) {
        Font f = null;
        StringTokenizer tok = new StringTokenizer(path, ";");
        NybbleInputStream str = null;
        if (tok.hasMoreTokens()) tok.nextToken();
        while (str == null && tok.hasMoreTokens()) {
            try {
                String bla = tok.nextToken();
                URL url = new URL(bla);
                url = new URL("file", "localhost", url.getFile() + fontName);
                str = new NybbleInputStream(url.openStream());
            } catch (java.io.IOException e) {
                Frame1.writelog(e.toString());
            }
        }
        if (str == null) {
            f = new Font();
            InputStream istr = f.getClass().getResourceAsStream(fontName + ".123");
            if (istr != null) str = new NybbleInputStream(istr);
        }
        if (str != null) {
            if (f == null) f = new Font();
            try {
                f.parsePkStream(str);
                str.close();
            } catch (java.io.IOException e) {
            }
            return f;
        }
        return null;
    }
public void adjustPadding(File file, int paddingSize, long audioStart) throws FileNotFoundException, IOException {
        logger.finer("Need to move audio file to accomodate tag");
        FileChannel fcIn;
        FileChannel fcOut;
        ByteBuffer paddingBuffer = ByteBuffer.wrap(new byte[paddingSize]);
        File paddedFile = File.createTempFile("temp", ".mp3", file.getParentFile());
        fcOut = new FileOutputStream(paddedFile).getChannel();
        fcIn = new FileInputStream(file).getChannel();
        long written = (long) fcOut.write(paddingBuffer);
        logger.finer("Copying:" + (file.length() - audioStart) + "bytes");
        long audiolength = file.length() - audioStart;
        if (audiolength <= MAXIMUM_WRITABLE_CHUNK_SIZE) {
            long written2 = fcIn.transferTo(audioStart, audiolength, fcOut);
            logger.finer("Written padding:" + written + " Data:" + written2);
            if (written2 != audiolength) {
                throw new RuntimeException("Problem adjusting padding, expecting to write:" + audiolength + ":only wrote:" + written2);
            }
        } else {
            long noOfChunks = audiolength / MAXIMUM_WRITABLE_CHUNK_SIZE;
            long lastChunkSize = audiolength % MAXIMUM_WRITABLE_CHUNK_SIZE;
            long written2 = 0;
            for (int i = 0; i < noOfChunks; i++) {
                written2 += fcIn.transferTo(audioStart + (i * MAXIMUM_WRITABLE_CHUNK_SIZE), MAXIMUM_WRITABLE_CHUNK_SIZE, fcOut);
                Runtime.getRuntime().gc();
            }
            written2 += fcIn.transferTo(audioStart + (noOfChunks * MAXIMUM_WRITABLE_CHUNK_SIZE), lastChunkSize, fcOut);
            logger.finer("Written padding:" + written + " Data:" + written2);
            if (written2 != audiolength) {
                throw new RuntimeException("Problem adjusting padding in large file, expecting to write:" + audiolength + ":only wrote:" + written2);
            }
        }
        long lastModified = file.lastModified();
        fcIn.close();
        fcOut.close();
        file.delete();
        paddedFile.renameTo(file);
        paddedFile.setLastModified(lastModified);
    }
public void write(URL output, String model, String mainResourceClass) throws InfoUnitIOException {
        InfoUnitXMLData iur = new InfoUnitXMLData(STRUCTURE_RDF);
        rdf = iur.load("rdf");
        rdfResource = rdf.ft("resource");
        rdfParseType = rdf.ft("parse type");
        try {
            PrintWriter outw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output.getFile()), "UTF-8"));
            URL urlModel = new URL(model);
            BufferedReader inr = new BufferedReader(new InputStreamReader(urlModel.openStream()));
            String finalTag = "</" + rdf.ft("main") + ">";
            String line = inr.readLine();
            while (line != null && !line.equalsIgnoreCase(finalTag)) {
                outw.println(line);
                line = inr.readLine();
            }
            inr.close();
            InfoNode nodeType = infoRoot.path(rdf.ft("constraint"));
            String type = null;
            if (nodeType != null) {
                type = nodeType.getValue().toString();
                try {
                    infoRoot.removeChildNode(nodeType);
                } catch (InvalidChildInfoNode error) {
                }
            } else if (mainResourceClass != null) type = mainResourceClass; else type = rdf.ft("description");
            outw.println("   <" + type + " " + rdf.ft("about") + "=\"" + ((infoNamespaces == null) ? infoRoot.getLabel() : infoNamespaces.convertEntity(infoRoot.getLabel().toString())) + "\">");
            Set<InfoNode> nl = infoRoot.getChildren();
            writeNodeList(nl, outw, 5);
            outw.println("   </" + type + ">");
            if (line != null) outw.println(finalTag);
            outw.close();
        } catch (IOException error) {
            throw new InfoUnitIOException(error.getMessage());
        }
    }
public void run() {
            try {
                if (useStream || inputStream != null) {
                    InputStream inputStream = null;
                    if (LoadDocumentOperation.this.inputStream != null) inputStream = LoadDocumentOperation.this.inputStream; else inputStream = url.openStream();
                    if (frame != null) document = officeApplication.getDocumentService().loadDocument(frame, inputStream, documentDescriptor); else document = officeApplication.getDocumentService().loadDocument(inputStream, documentDescriptor);
                    try {
                        inputStream.close();
                    } catch (Throwable throwable) {
                    }
                } else {
                    if (frame != null) document = officeApplication.getDocumentService().loadDocument(frame, url.toString(), documentDescriptor); else document = officeApplication.getDocumentService().loadDocument(url.toString(), documentDescriptor);
                }
                done = true;
            } catch (Exception exception) {
                this.exception = exception;
            } catch (ThreadDeath threadDeath) {
            }
        }
private static String md5(String text) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(text.getBytes("UTF-8"));
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < messageDigest.length; i++) {
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
protected String downloadURLtoString(URL url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer sb = new StringBuffer(100 * 1024);
        String str;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        in.close();
        return sb.toString();
    }
@ActionMethod
    public void list() throws IOException {
        final URL url = new URL("http://127.0.0.1:" + testPort + "/list?version=1000");
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\"");
        final InputStream in = con.getInputStream();
        final byte[] buf = new byte[4096];
        textArea.setText("");
        for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) {
            textArea.append(new String(buf, 0, bytesRead));
        }
    }
@ActionMethod
    public void mirror() throws IOException {
        final URL url = new URL("http://127.0.0.1:" + testPort + "/mirror");
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\"");
        final InputStream in = con.getInputStream();
        final byte[] buf = new byte[4096];
        textArea.setText("");
        for (int bytesRead; (bytesRead = in.read(buf)) != -1; ) {
            textArea.append(new String(buf, 0, bytesRead));
        }
    }
@ActionMethod
    public void download() throws IOException {
        final JPanel message = new JPanel(new GridBagLayout());
        final GridBagConstraints gbcLabel = new GridBagConstraints();
        final GridBagConstraints gbcField = new GridBagConstraints();
        gbcLabel.weightx = 0.0;
        gbcField.weightx = 1.0;
        gbcField.fill = GridBagConstraints.HORIZONTAL;
        gbcField.insets = new Insets(2, 2, 2, 2);
        final JTextField deviceField, fullnameField, versionField;
        deviceField = new JTextField();
        fullnameField = new JTextField();
        versionField = new JTextField();
        gbcField.gridwidth = GridBagConstraints.REMAINDER;
        message.add(new JLabel("device"), gbcLabel);
        message.add(deviceField, gbcField);
        message.add(new JLabel("fullname"), gbcLabel);
        message.add(fullnameField, gbcField);
        message.add(new JLabel("version"), gbcLabel);
        message.add(versionField, gbcField);
        final int result = JOptionPane.showConfirmDialog(frame, message, "Download parameters", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (result != JOptionPane.OK_OPTION) {
            return;
        }
        final String device = deviceField.getText();
        final String fullname = fullnameField.getText();
        final String version = versionField.getText();
        final URL url = new URL("http://127.0.0.1:" + testPort + "/databases/" + fullname + "?device=" + device + "&version=" + version);
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\"");
        final InputStream in = con.getInputStream();
        try {
            final int fileResult = fileChooser.showSaveDialog(frame);
            if (fileResult != JFileChooser.APPROVE_OPTION) {
                return;
            }
            final OutputStream out = new FileOutputStream(fileChooser.getSelectedFile());
            try {
                Util.copy(in, out);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }
@ActionMethod
    public void upload() throws IOException {
        final int fileResult = fileChooser.showOpenDialog(frame);
        if (fileResult != JFileChooser.APPROVE_OPTION) {
            return;
        }
        final InputStream in = new FileInputStream(fileChooser.getSelectedFile());
        try {
            final URL url = new URL("http://127.0.0.1:" + testPort + "/databases/" + fileChooser.getSelectedFile().getName());
            final HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("PUT");
            con.setDoOutput(true);
            con.setRequestProperty(Http11Header.AUTHORIZATION, "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
            con.setRequestProperty(Http11Header.WWW_AUTHENTICATE, "Basic realm=\"karatasi\"");
            con.setRequestProperty(Http11Header.CONTENT_LENGTH, Long.toString(fileChooser.getSelectedFile().length()));
            con.setRequestProperty(Http11Header.CONTENT_TYPE, "application/octet-stream");
            final OutputStream out = con.getOutputStream();
            try {
                Util.copy(in, out);
                con.connect();
                final InputStream in2 = con.getInputStream();
                try {
                    textArea.setText("");
                    final byte[] buf = new byte[4096];
                    for (int bytesRead; (bytesRead = in2.read(buf)) != -1; ) {
                        textArea.append(new String(buf, 0, bytesRead));
                    }
                } finally {
                    in2.close();
                }
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }
private void copy(String imgPath, String path) {
        try {
            File input = new File(imgPath);
            File output = new File(path, input.getName());
            if (output.exists()) {
                if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return;
            }
            byte[] data = new byte[1024];
            FileInputStream fis = new FileInputStream(imgPath);
            BufferedInputStream bis = new BufferedInputStream(fis);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));
            int length;
            while ((length = bis.read(data)) > 0) {
                bos.write(data, 0, length);
                bos.flush();
            }
            bos.close();
            fis.close();
            IJavaProject ijp = VisualSwingPlugin.getCurrentProject();
            if (ijp != null) {
                ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
                view.refresh();
                view.expandAll();
            }
        } catch (Exception e) {
            VisualSwingPlugin.getLogger().error(e);
        }
    }
public void checkAndDownload(String statsUrl, RDFStatsUpdatableModelExt stats, Date lastDownload, boolean onlyIfNewer) throws DataSourceMonitorException {
        if (log.isInfoEnabled()) log.info("Checking if update required for statistics of " + ds + "...");
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(statsUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
            urlConnection.setReadTimeout(READ_TIMEOUT);
            int statusCode = urlConnection.getResponseCode();
            if (statusCode / 100 != 2) {
                String msg = urlConnection.getResponseMessage();
                throw new DataSourceMonitorException(statsUrl + " returned HTTP " + statusCode + (msg != null ? msg : "") + ".");
            }
        } catch (Exception e) {
            throw new DataSourceMonitorException("Failed to connect to " + statsUrl + ".", e);
        }
        long lastModified = urlConnection.getLastModified();
        boolean newer = lastDownload == null || lastModified == 0 || lastModified - TIMING_GAP > lastDownload.getTime();
        if (newer || !onlyIfNewer) {
            Model newStats = retrieveModelData(urlConnection, ds);
            Date retrievedTimestamp = Calendar.getInstance().getTime();
            Date modifiedTimestamp = (urlConnection.getLastModified() > 0) ? new Date(urlConnection.getLastModified()) : null;
            if (log.isInfoEnabled()) log.info("Attempt to import up-to-date " + ((modifiedTimestamp != null) ? "(from " + modifiedTimestamp + ") " : "") + "statistics for " + ds + ".");
            try {
                if (stats.updateFrom(RDFStatsModelFactory.create(newStats), onlyIfNewer)) stats.setLastDownload(ds.getSPARQLEndpointURL(), retrievedTimestamp);
            } catch (Exception e) {
                throw new DataSourceMonitorException("Failed to import statistics and set last download for " + ds + ".", e);
            }
        } else {
            if (log.isInfoEnabled()) log.info("Statistics for " + ds + " are up-to-date" + ((lastDownload != null) ? " (" + lastDownload + ")" : ""));
        }
    }
public static byte[] getBytes(String s) throws Exception {
        java.security.MessageDigest d = null;
        d = java.security.MessageDigest.getInstance("SHA-1");
        d.reset();
        d.update(s.getBytes());
        return d.digest();
    }
public synchronized String encrypt(String plaintext) {
        if (plaintext == null || plaintext.equals("")) {
            return plaintext;
        }
        String hash = null;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
            byte raw[] = md.digest();
            hash = Base64.encodeBase64String(raw).replaceAll("\r\n", "");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.getMessage());
        }
        return hash;
    }
public void open(Input input) throws IOException, ResolverException {
            if (!input.isUriDefinitive()) return;
            URI uri;
            try {
                uri = new URI(input.getUri());
            } catch (URISyntaxException e) {
                throw new ResolverException(e);
            }
            if (!uri.isAbsolute()) throw new ResolverException("cannot open relative URI: " + uri);
            URL url = new URL(uri.toASCIIString());
            input.setByteStream(url.openStream());
        }
private String readTwitterFead() {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://twitter.com/statuses/user_timeline/vogella.json");
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e(AndroidJsonTestingActivity.class.getName(), "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
public String encrypt(String password) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(password.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        String hashword = hash.toString(16);
        return hashword;
    }
private byte[] getBytes(String resource) throws IOException {
        InputStream is = HttpServletFileDownloadTest.class.getResourceAsStream(resource);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(is, out);
        IOUtils.closeQuietly(is);
        return out.toByteArray();
    }
private CachedQuery loadQuery(String path) throws CacheException, IOException, XQueryException {
        final URL url;
        final long lastModified;
        final InputStream is;
        try {
            url = getServletContext().getResource(path);
            assert (url != null);
            lastModified = url.openConnection().getLastModified();
            is = url.openStream();
        } catch (IOException e) {
            log(PrintUtils.prettyPrintStackTrace(e, -1));
            throw e;
        }
        _lock.readLock().lock();
        CachedQuery cached = _caches.get(path);
        if (cached == null || cached.loadTimeStamp < lastModified) {
            if (cached == null) {
                cached = new CachedQuery();
            }
            XQueryParser parser = new XQueryParser(is);
            StaticContext staticEnv = parser.getStaticContext();
            try {
                URI baseUri = url.toURI();
                staticEnv.setBaseURI(baseUri);
            } catch (URISyntaxException e) {
                log(PrintUtils.prettyPrintStackTrace(e, -1));
            }
            final XQueryModule module;
            try {
                module = parser.parse();
            } catch (XQueryException e) {
                log(PrintUtils.prettyPrintStackTrace(e, -1));
                _lock.readLock().unlock();
                throw e;
            }
            _lock.readLock().unlock();
            _lock.writeLock().lock();
            cached.queryObject = module;
            cached.staticEnv = staticEnv;
            cached.loadTimeStamp = System.currentTimeMillis();
            _caches.put(path, cached);
            _lock.writeLock().unlock();
            _lock.readLock().lock();
            try {
                module.staticAnalysis(staticEnv);
            } catch (XQueryException e) {
                log(PrintUtils.prettyPrintStackTrace(e, -1));
                _lock.readLock().unlock();
                throw e;
            }
        }
        _lock.readLock().unlock();
        return cached;
    }
private static boolean copyFile(File srcFile, File tagFile) throws IOException {
        if (srcFile == null || tagFile == null) {
            return false;
        }
        int length = 2097152;
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(tagFile);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        int i = 0;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                break;
            }
            if ((inC.size() - inC.position()) < 20971520) length = (int) (inC.size() - inC.position()); else length = 20971520;
            inC.transferTo(inC.position(), length, outC);
            inC.position(inC.position() + length);
            i++;
        }
        return true;
    }