semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public void actionPerformed(ActionEvent e) {
                int returnVal = chooser.showSaveDialog(jd);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    String fileName = file.getPath();
                    String ext = StringUtil.getLowerExtension(fileName);
                    if (!"png".equals(ext)) {
                        fileName += ".png";
                        file = new File(fileName);
                    }
                    boolean doIt = true;
                    if (file.exists()) {
                        int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist"));
                        if (i != JOptionPane.YES_OPTION) doIt = false;
                    } else if (!file.getParentFile().exists()) {
                        doIt = file.getParentFile().mkdirs();
                    }
                    if (doIt) {
                        FileChannel src = null;
                        FileChannel dest = null;
                        try {
                            src = new FileInputStream(imageURL.getPath()).getChannel();
                            dest = new FileOutputStream(fileName).getChannel();
                            src.transferTo(0, src.size(), dest);
                        } catch (FileNotFoundException e1) {
                            warn(jd, getMessage("err_no_source_file"));
                        } catch (IOException e2) {
                            warn(jd, getMessage("err_output_target"));
                        } finally {
                            try {
                                if (src != null) src.close();
                            } catch (IOException e1) {
                            }
                            try {
                                if (dest != null) dest.close();
                            } catch (IOException e1) {
                            }
                            src = null;
                            dest = null;
                        }
                    }
                }
            }
public void test2() throws Exception {
        SpreadsheetDocument document = new SpreadsheetDocument();
        Sheet sheet = new Sheet("Planilha 1");
        sheet.setLandscape(true);
        Row row = new Row();
        row.setHeight(20);
        sheet.getMerges().add(new IntegerCellMerge(0, 0, 0, 5));
        sheet.getImages().add(new Image(new FileInputStream("D:/image001.jpg"), 0, 0, ImageType.JPEG, 80, 60));
        for (int i = 0; i < 10; i++) {
            Cell cell = new Cell();
            cell.setValue("Celula " + i);
            cell.setBackgroundColor(new Color(192, 192, 192));
            cell.setUnderline(true);
            cell.setBold(true);
            cell.setItalic(true);
            cell.setFont("Times New Roman");
            cell.setFontSize(10);
            cell.setFontColor(new Color(255, 0, 0));
            Border border = new Border();
            border.setWidth(1);
            border.setColor(new Color(0, 0, 0));
            cell.setLeftBorder(border);
            cell.setTopBorder(border);
            cell.setRightBorder(border);
            cell.setBottomBorder(border);
            row.getCells().add(cell);
            sheet.getColumnsWith().put(new Integer(i), new Integer(25));
        }
        sheet.getRows().add(row);
        document.getSheets().add(sheet);
        FileOutputStream fos = new FileOutputStream("D:/teste2.xls");
        SpreadsheetDocumentWriter writer = HSSFSpreadsheetDocumentWriter.getInstance();
        writer.write(document, fos);
        fos.close();
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/png");
        OutputStream outStream;
        outStream = resp.getOutputStream();
        InputStream is;
        String name = req.getParameter("name");
        if (name == null) {
            is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
        } else {
            ImageRecord imageRecord = imageBean.getFile(name);
            if (imageRecord != null) {
                is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile()));
            } else {
                is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
            }
        }
        IOUtils.copy(is, outStream);
        outStream.close();
        outStream.flush();
    }
@Override
    public void setDocumentSpace(DocumentSpace space) {
        for (Document doc : space) {
            if (doc instanceof XMLDOMDocument) {
                writer.writeDocument(doc);
            } else if (doc instanceof BinaryDocument) {
                BinaryDocument bin = (BinaryDocument) doc;
                try {
                    ManagedFile result = resolveFileFor(folder, (BinaryDocument) doc);
                    IOUtils.copy(bin.getContent().getInputStream(), result.getContent().getOutputStream());
                } catch (IOException e) {
                    throw ManagedIOException.manage(e);
                }
            } else {
                System.err.println("Unkown Document type");
            }
        }
    }
public static void copyFile(File source, File destination) throws IOException {
        if (!source.isFile()) {
            throw new IOException(source + " is not a file.");
        }
        if (destination.exists()) {
            throw new IOException("Destination file " + destination + " is already exist.");
        }
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(destination).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            inChannel.close();
            outChannel.close();
        }
    }
public void test() throws Exception {
        File temp = File.createTempFile("test", ".test");
        temp.deleteOnExit();
        StorageFile s = new StorageFile(temp, "UTF-8");
        s.addText("Test");
        s.getOutputStream().write("ing is important".getBytes("UTF-8"));
        s.getWriter().write(" but overrated");
        assertEquals("Testing is important but overrated", s.getText());
        s.close(ResponseStateOk.getInstance());
        assertEquals("Testing is important but overrated", s.getText());
        InputStream input = s.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(input, writer, "UTF-8");
        assertEquals("Testing is important but overrated", writer.toString());
        try {
            s.getOutputStream();
            fail("Should thow an IOException as it is closed.");
        } catch (IOException e) {
        }
    }
private boolean copyToFile(String folder, String fileName) throws StorageException {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(folder + "/" + fileName);
        if (in == null) {
            return false;
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(new File(path, fileName));
            IOUtils.copy(in, out);
            in.close();
            out.flush();
        } catch (Exception e) {
            throw new StorageException(e);
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
        }
        return true;
    }
public static String getMD5(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte[] b = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte aB : b) {
            sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3));
        }
        return sb.toString();
    }
private boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) {
        try {
            String ret;
            String xml;
            String moviehash = getHash(movieFile);
            String moviebytesize = String.valueOf(movieFile.length());
            xml = generateXMLRPCSS(moviehash, moviebytesize);
            ret = sendRPC(xml);
            String subDownloadLink = getValue("SubDownloadLink", ret);
            if (subDownloadLink.equals("")) {
                String moviefilename = movieFile.getName();
                if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) {
                    String subfilename = subtitleFile.getName();
                    int index = subfilename.lastIndexOf(".");
                    String query = subfilename.substring(0, index);
                    xml = generateXMLRPCSS(query);
                    ret = sendRPC(xml);
                    subDownloadLink = getValue("SubDownloadLink", ret);
                }
            }
            if (subDownloadLink.equals("")) {
                logger.finer("OpenSubtitles Plugin: Subtitle not found for " + movie.getBaseName());
                return false;
            }
            logger.finer("OpenSubtitles Plugin: Download subtitle for " + movie.getBaseName());
            URL url = new URL(subDownloadLink);
            HttpURLConnection connection = (HttpURLConnection) (url.openConnection());
            connection.setRequestProperty("Connection", "Close");
            InputStream inputStream = connection.getInputStream();
            int code = connection.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                logger.severe("OpenSubtitles Plugin: Download Failed");
                return false;
            }
            GZIPInputStream a = new GZIPInputStream(inputStream);
            OutputStream out = new FileOutputStream(subtitleFile);
            byte buf[] = new byte[1024];
            int len;
            while ((len = a.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            movie.setSubtitles(true);
            return true;
        } catch (Exception e) {
            logger.severe("OpenSubtitles Plugin: Download Exception (Movie Not Found)");
            return false;
        }
    }
private static String sendRPC(String xml) throws MalformedURLException, IOException {
        String str = "";
        String strona = OSdbServer;
        String logowanie = xml;
        URL url = new URL(strona);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Connection", "Close");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setDoOutput(true);
        connection.getOutputStream().write(logowanie.getBytes("UTF-8"));
        Scanner in;
        in = new Scanner(connection.getInputStream());
        while (in.hasNextLine()) {
            str += in.nextLine();
        }
        ;
        return str;
    }
@Test
    public void testWrite() throws Exception {
        MrstkXmlFileReader reader = new MrstkXmlFileReader();
        reader.setFileName("..//data//MrstkXML//prototype3.xml");
        reader.read();
        SpectrumArray sp = reader.getOutput();
        File tmp = File.createTempFile("mrstktest", ".xml");
        System.out.println("Writing temp file: " + tmp.getAbsolutePath());
        MrstkXmlFileWriter writer = new MrstkXmlFileWriter(sp);
        writer.setFile(tmp);
        writer.write();
        MrstkXmlFileReader reader2 = new MrstkXmlFileReader();
        reader2.setFileName(writer.getFile().getAbsolutePath());
        reader2.read();
        SpectrumArray sp2 = reader2.getOutput();
        assertTrue(sp.equals(sp2));
    }
public static void compressAll(File dir, File file) throws IOException {
        if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory");
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        out.setLevel(0);
        String[] entries = dir.list();
        byte[] buffer = new byte[4096];
        int bytesRead;
        for (int i = 0; i < entries.length; i++) {
            File f = new File(dir, entries[i]);
            if (f.isDirectory()) continue;
            FileInputStream in = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(f.getName());
            out.putNextEntry(entry);
            while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();
    }
public static String plainStringToMD5(String input) {
        if (input == null) {
            throw new NullPointerException("Input cannot be null");
        }
        MessageDigest md = null;
        byte[] byteHash = null;
        StringBuffer resultString = new StringBuffer();
        try {
            md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(input.getBytes());
            byteHash = md.digest();
            for (int i = 0; i < byteHash.length; i++) {
                resultString.append(Integer.toHexString(0xFF & byteHash[i]));
            }
            return (resultString.toString());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
@Override
    protected URLConnection openConnection(URL url) throws IOException {
        final String urlPath = url.getPath();
        final int status;
        final String path;
        String statusAsString = extractValue(urlPath, STATUS_REGEX, STATUS_CAPTURE);
        status = statusAsString == null ? 200 : Integer.parseInt(statusAsString);
        path = extractPath(urlPath);
        if (saved.get(url.toString()) == null) {
            saved.put(url.toString(), new ArrayList<ByteArrayOutputStream>());
        }
        return new HttpsURLConnection(url) {

            @Override
            public int getResponseCode() throws IOException {
                return status;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                if (errorStatus()) throw new IOException("fake server returned a fake error");
                if (path == null) {
                    return new ByteArrayInputStream(new byte[0]);
                } else {
                    return new FileInputStream(path);
                }
            }

            @Override
            public InputStream getErrorStream() {
                if (errorStatus()) {
                    try {
                        return new FileInputStream(path);
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    return null;
                }
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                Handler.saved.get(url.toString()).add(out);
                return out;
            }

            @Override
            public String getContentType() {
                return "test/plain";
            }

            @Override
            public void connect() throws IOException {
            }

            @Override
            public boolean usingProxy() {
                return false;
            }

            @Override
            public void disconnect() {
            }

            private boolean errorStatus() {
                return status >= 500 && status <= 599;
            }

            @Override
            public String getCipherSuite() {
                return null;
            }

            @Override
            public Certificate[] getLocalCertificates() {
                return null;
            }

            @Override
            public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
                return null;
            }
        };
    }
public SessionManager(String username) {
        try {
            url = new URL("http://" + username + ".bebo.com");
            conn = url.openConnection();
        } catch (MalformedURLException ex) {
            Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
public void salva(UploadedFile imagem, Usuario usuario) {
        File destino;
        if (usuario.getId() == null) {
            destino = new File(pastaImagens, usuario.hashCode() + ".jpg");
        } else {
            destino = new File(pastaImagens, usuario.getId() + ".jpg");
        }
        try {
            IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino));
        } catch (Exception e) {
            throw new RuntimeException("Erro ao copiar imagem", e);
        }
        redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110);
    }
private String computeHash(String str) {
        StringBuffer hexBuffer = new StringBuffer();
        byte[] bytes;
        int i;
        try {
            MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName);
            hashAlgorithm.reset();
            hashAlgorithm.update(str.getBytes());
            bytes = hashAlgorithm.digest();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF));
        return hexBuffer.toString();
    }
private void redirect(TargetApp app, HttpServletRequest request, HttpServletResponse response) throws IOException {
        URL url = new URL(app.getUrl() + request.getRequestURI());
        s_log.debug("Redirecting to " + url);
        URLConnection urlConnection = url.openConnection();
        Map<String, List<String>> fields = urlConnection.getHeaderFields();
        for (String key : fields.keySet()) {
            StringBuffer values = new StringBuffer();
            boolean comma = false;
            for (String value : fields.get(key)) {
                if (comma) {
                    values.append(", ");
                }
                values.append(value);
                comma = true;
            }
            if (key != null) {
                response.setHeader(key, values.toString());
            } else {
                response.setStatus(Integer.parseInt(values.toString().split(" ")[1]));
            }
        }
        InputStream in = urlConnection.getInputStream();
        try {
            ServletOutputStream out = response.getOutputStream();
            byte[] buff = new byte[1024];
            int len;
            while ((len = in.read(buff)) != -1) {
                out.write(buff, 0, len);
            }
        } finally {
            in.close();
        }
    }
static void copyFile(File in, File outDir, String outFileName) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        outDir.mkdirs();
        File outFile = new File(outDir, outFileName);
        FileChannel outChannel = new FileOutputStream(outFile).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }
@Override
    public String getURL(String name) {
        String r;
        try {
            URL url = new URL(NIFHandler.URL_BASE + name.replaceAll(" ", "+"));
            Document d = new SAXBuilder().build(url.openStream());
            Element e = d.getRootElement().descendTo("url");
            r = e.getText().trim();
        } catch (Throwable t) {
            r = "unknown";
        }
        return r;
    }
public static String generateHash(final String sText, final String sAlgo) throws NoSuchAlgorithmException {
        final MessageDigest md = MessageDigest.getInstance(sAlgo);
        md.update(sText.getBytes());
        final Formatter formatter = new Formatter();
        for (final Byte curByte : md.digest()) formatter.format("%x", curByte);
        return formatter.toString();
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cacheName = req.getParameter("cacheName");
        if (cacheName == null || cacheName.equals("")) {
            resp.getWriter().println("parameter cacheName required");
            return;
        } else {
            StringBuffer urlStr = new StringBuffer();
            urlStr.append(BASE_URL);
            urlStr.append("?");
            urlStr.append("cacheName=");
            urlStr.append("rpcwc.bo.cache.");
            urlStr.append(cacheName);
            URL url = new URL(urlStr.toString());
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            StringBuffer output = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                output.append(line);
                output.append(System.getProperty("line.separator"));
            }
            reader.close();
            resp.getWriter().println(output.toString());
        }
    }
@Override
    public void convert() throws Exception {
        URL url = new URL("http://qsardb.jrc.it/qmrf/download.jsp?filetype=xml&id=" + Integer.parseInt(this.id));
        InputStream is = url.openStream();
        try {
            QMRF qmrf = QmrfUtil.loadQmrf(is);
            Qmrf2Qdb.convert(getQdb(), qmrf);
        } finally {
            is.close();
        }
    }
public FTPFile[] connect() {
        if (ftpe == null) {
            ftpe = new FTPEvent(this);
        }
        if (ftp == null) {
            ftp = new FTPClient();
        } else if (ftp.isConnected()) {
            path = "";
            try {
                ftp.disconnect();
            } catch (IOException e1) {
                log.error("could not disconnect -" + e1.getMessage());
            }
        }
        currentDir = new FTPFile[0];
        log.debug("try to connect");
        try {
            int reply;
            ftp.connect(ftpsite);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                log.error("FTP server refused connection.");
            }
        } catch (IOException e) {
            log.error("FTPConnection error: " + e.getMessage());
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
        }
        try {
            if (!ftp.login(user, password)) {
                log.error("could not login with: " + user);
                ftp.logout();
            }
            log.debug("Remote system is " + ftp.getSystemName());
            ftp.enterLocalPassiveMode();
            currentDir = ftp.listFiles();
        } catch (FTPConnectionClosedException e) {
            log.error("FTPConnectionClosedException: " + e.getMessage());
        } catch (IOException e) {
            log.error("IOException: " + e.getMessage());
        }
        ftpe.setType(FTPEvent.CONNECT);
        fireFTPEvent(ftpe);
        return currentDir;
    }