semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType(req.getContentType());
            IOUtils.copy(req.getReader(), resp.getWriter());
        }
public static void downloadFile(String url, String filePath) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(new URL(url).openStream());
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        try {
            int i = 0;
            while ((i = inputStream.read()) != -1) {
                bos.write(i);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
private List<File> ungzipFile(File directory, File compressedFile) throws IOException {
        List<File> files = new ArrayList<File>();
        TarArchiveInputStream in = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(compressedFile)));
        try {
            TarArchiveEntry entry = in.getNextTarEntry();
            while (entry != null) {
                if (entry.isDirectory()) {
                    log.warn("TAR archive contains directories which are being ignored");
                    entry = in.getNextTarEntry();
                    continue;
                }
                String fn = new File(entry.getName()).getName();
                if (fn.startsWith(".")) {
                    log.warn("TAR archive contains a hidden file which is being ignored");
                    entry = in.getNextTarEntry();
                    continue;
                }
                File targetFile = new File(directory, fn);
                if (targetFile.exists()) {
                    log.warn("TAR archive contains duplicate filenames, only the first is being extracted");
                    entry = in.getNextTarEntry();
                    continue;
                }
                files.add(targetFile);
                log.debug("Extracting file: " + entry.getName() + " to: " + targetFile.getAbsolutePath());
                OutputStream fout = new BufferedOutputStream(new FileOutputStream(targetFile));
                InputStream entryIn = new FileInputStream(entry.getFile());
                IOUtils.copy(entryIn, fout);
                fout.close();
                entryIn.close();
            }
        } finally {
            in.close();
        }
        return files;
    }
private static String calcReturnKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        String text = new String();
        byte[] sha1hash = new byte[20];
        text = key + GUUI;
        md.update(text.getBytes(), 0, text.length());
        sha1hash = md.digest();
        return (Helper.getBASE64(sha1hash));
    }
public static URL[] getDirectoryListing(URL url) throws IOException, CancelledOperationException {
        FileSystem.logger.log(Level.FINER, "listing {0}", url);
        String file = url.getFile();
        if (file.charAt(file.length() - 1) != '/') {
            url = new URL(url.toString() + '/');
        }
        String userInfo = KeyChain.getDefault().getUserInfo(url);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setAllowUserInteraction(false);
        urlConnection.setConnectTimeout(FileSystem.settings().getConnectTimeoutMs());
        if (userInfo != null) {
            String encode = Base64.encodeBytes(userInfo.getBytes());
            urlConnection.setRequestProperty("Authorization", "Basic " + encode);
        }
        InputStream urlStream;
        urlStream = urlConnection.getInputStream();
        return getDirectoryListing(url, urlStream);
    }
private static Pair<URL, DTObject> loadRecruitersConf(URL url) throws ExternalConfigException, SyntaxException, IOException {
        Assert.notNullArg(url, "resourceName may not be null");
        InputStream is = url.openStream();
        try {
            Object value = ObjectParser.parse(is);
            if (!(value instanceof DTObject)) {
                throw new ExternalConfigException("The global value in " + url + " must be a DTObject");
            }
            return new Pair<URL, DTObject>(url, (DTObject) value);
        } finally {
            is.close();
        }
    }
public static String encodePassword(String password) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA");
            md.update(password.getBytes());
            String encodedPassword = new String(md.digest(), new Base64Provider().charsetForName("x-base64"));
            return encodedPassword;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
protected int doWork() {
        SAMFileReader reader = new SAMFileReader(IoUtil.openFileForReading(INPUT));
        reader.getFileHeader().setSortOrder(SORT_ORDER);
        SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), false, OUTPUT);
        Iterator<SAMRecord> iterator = reader.iterator();
        while (iterator.hasNext()) writer.addAlignment(iterator.next());
        reader.close();
        writer.close();
        return 0;
    }
static MenuListener openRecentHandler() {
        MenuListener handler = new MenuListener() {

            public void menuSelected(final MenuEvent event) {
                final JMenu menu = (JMenu) event.getSource();
                menu.removeAll();
                String[] recentURLSpecs = Application.getApp().getRecentURLSpecs();
                for (int index = 0; index < recentURLSpecs.length; index++) {
                    String urlSpec = recentURLSpecs[index];
                    JMenuItem menuItem = new JMenuItem(urlSpec);
                    menu.add(menuItem);
                    menuItem.setAction(openURLAction(urlSpec));
                    menuItem.setText(urlSpec);
                    try {
                        new java.net.URL(urlSpec).openStream();
                    } catch (java.io.IOException exception) {
                        menuItem.setEnabled(false);
                    }
                }
                menu.addSeparator();
                final JMenuItem clearItem = new JMenuItem("Clear");
                clearItem.setAction(new AbstractAction() {

                    public void actionPerformed(final ActionEvent event) {
                        Application.getApp().clearRecentItems();
                    }
                });
                clearItem.setText("Clear");
                menu.add(clearItem);
            }

            public void menuCanceled(final MenuEvent event) {
            }

            public void menuDeselected(final MenuEvent event) {
            }
        };
        return handler;
    }
@Override
        public InputStream getStream(String uri) throws IOException {
            debug.print("uri=" + uri);
            boolean isStreamFile = false;
            for (int i = 0; i < GLOBAL.extList.length; i++) {
                if (uri.toLowerCase().endsWith(GLOBAL.extList[i].toLowerCase())) {
                    isStreamFile = true;
                }
            }
            if (isStreamFile) {
                GLOBAL.streamFile = DIR + File.separator + uri;
                File file = new File(GLOBAL.streamFile);
                URL url = file.toURI().toURL();
                System.out.println("url=" + url);
                GLOBAL.cstream = new CountInputStream(url.openStream());
                if (GLOBAL.Resume && GLOBAL.positions.containsKey(GLOBAL.streamFile)) {
                    GLOBAL.Resume = false;
                    if (uri.toLowerCase().endsWith(".mpg") || uri.toLowerCase().endsWith(".vob") || uri.toLowerCase().endsWith(".mp2") || uri.toLowerCase().endsWith(".mpeg") || uri.toLowerCase().endsWith(".mpeg2")) {
                        System.out.println("--Skipping to last bookmark=" + GLOBAL.positions.get(GLOBAL.streamFile));
                        GLOBAL.cstream.skip(GLOBAL.positions.get(GLOBAL.streamFile));
                    }
                }
                return GLOBAL.cstream;
            }
            return super.getStream(uri);
        }
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) {
        File inputFile = new File(getInputFile());
        File outputFile = new File(getOutputFile());
        if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) {
            OpenOfficeConnection connection = new SocketOpenOfficeConnection();
            OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, outputFile);
            connection.disconnect();
        } else {
            FileChannel inputChannel = null;
            FileChannel outputChannel = null;
            try {
                inputChannel = new FileInputStream(inputFile).getChannel();
                outputChannel = new FileOutputStream(outputFile).getChannel();
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            } catch (FileNotFoundException e) {
                arg2.addError("File not found: " + e.getMessage());
            } catch (IOException e) {
                arg2.addError("Could not copy file: " + e.getMessage());
            } finally {
                if (inputChannel != null) {
                    try {
                        inputChannel.close();
                    } catch (IOException e) {
                        arg2.addError("Could not close input channel: " + e.getMessage());
                    }
                }
                if (outputChannel != null) {
                    try {
                        outputChannel.close();
                    } catch (IOException e) {
                        arg2.addError("Could not close input channel: " + e.getMessage());
                    }
                }
            }
        }
    }
public boolean deploy(MMedia[] media) {
        if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
            log.warning("You have not defined your own server, we will not really deploy to localhost!");
            return true;
        }
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(getIP_Address());
            if (ftp.login(getUserName(), getPassword())) log.info("Connected to " + getIP_Address() + " as " + getUserName()); else {
                log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
                return false;
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
            return false;
        }
        boolean success = true;
        String cmd = null;
        try {
            cmd = "cwd";
            ftp.changeWorkingDirectory(getFolder());
            cmd = "list";
            String[] fileNames = ftp.listNames();
            log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);
            cmd = "bin";
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            for (int i = 0; i < media.length; i++) {
                if (!media[i].isSummary()) {
                    log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                    MImage thisImage = media[i].getImage();
                    byte[] buffer = thisImage.getData();
                    ByteArrayInputStream is = new ByteArrayInputStream(buffer);
                    String fileName = media[i].get_ID() + media[i].getExtension();
                    cmd = "put " + fileName;
                    ftp.storeFile(fileName, is);
                    is.close();
                }
            }
        } catch (Exception e) {
            log.log(Level.WARNING, cmd, e);
            success = false;
        }
        try {
            cmd = "logout";
            ftp.logout();
            cmd = "disconnect";
            ftp.disconnect();
        } catch (Exception e) {
            log.log(Level.WARNING, cmd, e);
        }
        ftp = null;
        return success;
    }
@RequestMapping(value = "/image/{fileName}", method = RequestMethod.GET)
    public void getImage(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse res) throws Exception {
        File file = new File(STORAGE_PATH + fileName + ".jpg");
        res.setHeader("Cache-Control", "no-store");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", 0);
        res.setContentType("image/jpg");
        ServletOutputStream ostream = res.getOutputStream();
        IOUtils.copy(new FileInputStream(file), ostream);
        ostream.flush();
        ostream.close();
    }
private void stripOneFilex(File inFile, File outFile) throws IOException {
        StreamTokenizer reader = new StreamTokenizer(new FileReader(inFile));
        BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
        reader.slashSlashComments(false);
        reader.slashStarComments(false);
        reader.eolIsSignificant(true);
        int token;
        while ((token = reader.nextToken()) != StreamTokenizer.TT_EOF) {
            switch(token) {
                case StreamTokenizer.TT_NUMBER:
                    throw new IllegalStateException("didn't expect TT_NUMBER: " + reader.nval);
                case StreamTokenizer.TT_WORD:
                    System.out.print(reader.sval);
                    writer.write("WORD:" + reader.sval, 0, reader.sval.length());
                default:
                    char outChar = (char) reader.ttype;
                    System.out.print(outChar);
                    writer.write(outChar);
            }
        }
    }
public static void main(String args[]) {
        URL url = null;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {
            System.err.println(e.toString());
            System.exit(1);
        }
        try {
            InputStream ins = url.openStream();
            BufferedReader breader = new BufferedReader(new InputStreamReader(ins));
            String info = breader.readLine();
            while (info != null) {
                System.out.println(info);
                info = breader.readLine();
            }
        } catch (IOException e) {
            System.err.println(e.toString());
            System.exit(1);
        }
    }
public static void copy(File sourceFile, File destinationFile) throws IOException {
        FileChannel sourceFileChannel = (new FileInputStream(sourceFile)).getChannel();
        FileChannel destinationFileChannel = (new FileOutputStream(destinationFile)).getChannel();
        sourceFileChannel.transferTo(0, sourceFile.length(), destinationFileChannel);
        sourceFileChannel.close();
        destinationFileChannel.close();
    }
protected InputStream callApiGet(String apiUrl, int expected) {
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();
            if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
                request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
            }
            if (ApplicationConstants.READ_TIMEOUT > -1) {
                request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
            }
            for (String headerName : requestHeaders.keySet()) {
                request.setRequestProperty(headerName, requestHeaders.get(headerName));
            }
            request.connect();
            if (request.getResponseCode() != expected) {
                throw new BingMapsException(convertStreamToString(request.getErrorStream()));
            } else {
                return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
            }
        } catch (IOException e) {
            throw new BingMapsException(e);
        }
    }
protected InputStream callApiPost(String apiUrl, Map<String, List<String>> parameters, int expected) {
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();
            if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
                request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
            }
            if (ApplicationConstants.READ_TIMEOUT > -1) {
                request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
            }
            for (String headerName : requestHeaders.keySet()) {
                request.setRequestProperty(headerName, requestHeaders.get(headerName));
            }
            request.setRequestMethod("POST");
            request.setDoOutput(true);
            PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream()));
            out.print(getParametersString(parameters));
            out.flush();
            out.close();
            request.connect();
            if (request.getResponseCode() != expected) {
                throw new BingMapsException(convertStreamToString(request.getErrorStream()));
            } else {
                return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
            }
        } catch (IOException e) {
            throw new BingMapsException(e);
        }
    }
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) {
        try {
            URL url = new URL(apiUrl);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();
            if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
                request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
            }
            if (ApplicationConstants.READ_TIMEOUT > -1) {
                request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
            }
            for (String headerName : requestHeaders.keySet()) {
                request.setRequestProperty(headerName, requestHeaders.get(headerName));
            }
            request.setRequestMethod(method);
            request.setDoOutput(true);
            if (contentType != null) {
                request.setRequestProperty("Content-Type", contentType);
            }
            if (xmlContent != null) {
                PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream()));
                out.print(xmlContent);
                out.flush();
                out.close();
            }
            request.connect();
            if (request.getResponseCode() != expected) {
                throw new BingMapsException(convertStreamToString(request.getErrorStream()));
            } else {
                return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
            }
        } catch (IOException e) {
            throw new BingMapsException(e);
        }
    }
private static void ensure(File pFile) throws IOException {
        if (!pFile.exists()) {
            FileOutputStream fos = new FileOutputStream(pFile);
            String resourceName = "/" + pFile.getName();
            InputStream is = BaseTest.class.getResourceAsStream(resourceName);
            Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is);
            IOUtils.copy(is, fos);
            fos.close();
        }
    }
public void loadFromFile() {
        if (filename == null) return;
        try {
            BufferedReader reader;
            try {
                File file = new File(filename);
                if (!file.exists()) return;
                reader = new BufferedReader(new FileReader(file));
            } catch (java.security.AccessControlException e) {
                URL url = new URL(filename);
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
            }
            String line;
            while (true) {
                line = reader.readLine();
                if (line == null) break;
                String name = line.substring(0, line.indexOf("\t"));
                String rest1 = line.substring(line.indexOf("\t") + 1);
                String guiname = rest1.substring(0, rest1.indexOf("\t"));
                String rest2 = rest1.substring(rest1.indexOf("\t") + 1);
                String type = rest2.substring(0, rest2.indexOf("\t"));
                String value = rest2.substring(rest2.indexOf("\t") + 1);
                defineField(name, guiname, type);
                setField(name, value, true);
            }
            reader.close();
        } catch (IOException e) {
            throw new JGameError("Error reading file '" + filename + "'.", false);
        }
    }
public static void ExtraeArchivoJAR(String Archivo, String DirJAR, String DirDestino) {
        FileInputStream entrada = null;
        FileOutputStream salida = null;
        try {
            File f = new File(DirDestino + separador + Archivo);
            try {
                f.createNewFile();
            } catch (Exception sad) {
                sad.printStackTrace();
            }
            InputStream source = OP_Proced.class.getResourceAsStream(DirJAR + "/" + Archivo);
            BufferedInputStream in = new BufferedInputStream(source);
            FileOutputStream out = new FileOutputStream(f);
            int ch;
            while ((ch = in.read()) != -1) out.write(ch);
            in.close();
            out.close();
        } catch (IOException ex) {
            System.out.println(ex);
        } finally {
            if (entrada != null) {
                try {
                    entrada.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (salida != null) {
                try {
                    salida.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
public static URLConnection openRemoteDescriptionFile(String urlstr) throws MalformedURLException {
        URL url = new URL(urlstr);
        try {
            URLConnection conn = url.openConnection();
            conn.connect();
            return conn;
        } catch (Exception e) {
            Config conf = Config.loadConfig();
            SimpleSocketAddress localServAddr = conf.getLocalProxyServerAddress();
            Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(localServAddr.host, localServAddr.port));
            URLConnection conn;
            try {
                conn = url.openConnection(proxy);
                conn.connect();
                return conn;
            } catch (IOException e1) {
                logger.error("Failed to retrive desc file:" + url, e1);
            }
        }
        return null;
    }