semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void copyFile(File src, File dest, int bufSize, boolean force) throws IOException {
        logger.info("copyFile(File src=" + src + ", File dest=" + dest + ", int bufSize=" + bufSize + ", boolean force=" + force + ") - start");
        File f = new File(Configuration.getArchiveDir());
        if (!f.exists()) {
            f.mkdir();
        }
        if (dest.exists()) {
            if (force) {
                dest.delete();
            } else {
                throw new IOException("Cannot overwrite existing file: " + dest);
            }
        }
        byte[] buffer = new byte[bufSize];
        int read = 0;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(dest);
            while (true) {
                read = in.read(buffer);
                if (read == -1) {
                    break;
                }
                out.write(buffer, 0, read);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        }
        logger.debug("copyFile(File, File, int, boolean) - end");
    }
public InputStream start(String classname, String jarFileURI, String... params) throws IOException {
        Runtime.getRuntime().addShutdownHook(new Thread() {

            @Override
            public void run() {
                terminate();
            }
        });
        System.out.println("loading jar file " + jarFileURI + " ...");
        URL url = new URL(jarFileURI);
        InputStream is = url.openStream();
        jarFile = QAUtil.createTempfile();
        FileOutputStream fos = new FileOutputStream(jarFile);
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = is.read(buffer)) != -1) {
            fos.write(buffer, 0, bytes_read);
        }
        fos.close();
        is.close();
        String[] args = new String[params.length + 4];
        args[0] = "java";
        args[1] = "-cp";
        args[2] = jarFile.getAbsolutePath();
        args[3] = classname;
        System.arraycopy(params, 0, args, 4, params.length);
        StringBuilder sb = new StringBuilder();
        for (String arg : args) {
            sb.append(arg + " ");
        }
        System.out.println("execute " + sb);
        ProcessBuilder pb = new ProcessBuilder(args);
        p = pb.start();
        return p.getInputStream();
    }
public void testRelativeRedirect2() throws Exception {
        int port = this.localServer.getServicePort();
        String host = this.localServer.getServiceHostName();
        this.localServer.register("*", new RelativeRedirectService2());
        DefaultHttpClient client = new DefaultHttpClient();
        HttpContext context = new BasicHttpContext();
        client.getParams().setBooleanParameter(ClientPNames.REJECT_RELATIVE_REDIRECT, false);
        HttpGet httpget = new HttpGet("/test/oldlocation");
        HttpResponse response = client.execute(getServerHttp(), httpget, context);
        HttpEntity e = response.getEntity();
        if (e != null) {
            e.consumeContent();
        }
        HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        assertEquals("/test/relativelocation", reqWrapper.getRequestLine().getUri());
        assertEquals(host, targetHost.getHostName());
        assertEquals(port, targetHost.getPort());
    }
public void testRedirectWithCookie() throws Exception {
        String host = "localhost";
        int port = this.localServer.getServicePort();
        this.localServer.register("*", new BasicRedirectService(host, port));
        DefaultHttpClient client = new DefaultHttpClient();
        CookieStore cookieStore = new BasicCookieStore();
        client.setCookieStore(cookieStore);
        BasicClientCookie cookie = new BasicClientCookie("name", "value");
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
        HttpContext context = new BasicHttpContext();
        HttpGet httpget = new HttpGet("/oldlocation/");
        HttpResponse response = client.execute(getServerHttp(), httpget, context);
        HttpEntity e = response.getEntity();
        if (e != null) {
            e.consumeContent();
        }
        HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
        Header[] headers = reqWrapper.getHeaders(SM.COOKIE);
        assertEquals("There can only be one (cookie)", 1, headers.length);
    }
public void testDefaultHeadersRedirect() throws Exception {
        String host = "localhost";
        int port = this.localServer.getServicePort();
        this.localServer.register("*", new BasicRedirectService(host, port));
        DefaultHttpClient client = new DefaultHttpClient();
        HttpContext context = new BasicHttpContext();
        List<Header> defaultHeaders = new ArrayList<Header>(1);
        defaultHeaders.add(new BasicHeader(HTTP.USER_AGENT, "my-test-client"));
        client.getParams().setParameter(ClientPNames.DEFAULT_HEADERS, defaultHeaders);
        HttpGet httpget = new HttpGet("/oldlocation/");
        HttpResponse response = client.execute(getServerHttp(), httpget, context);
        HttpEntity e = response.getEntity();
        if (e != null) {
            e.consumeContent();
        }
        HttpRequest reqWrapper = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
        assertEquals("/newlocation/", reqWrapper.getRequestLine().getUri());
        Header header = reqWrapper.getFirstHeader(HTTP.USER_AGENT);
        assertEquals("my-test-client", header.getValue());
    }
public void load(URL url) throws IOException {
        if (url == null) {
            throw new IllegalArgumentException("URL cannot be null.");
        }
        isFileBased = false;
        this.url = url;
        InputStream in = null;
        try {
            in = url.openStream();
            load(in);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
public void render(ParagraphElement cnt, double x, double y, Graphics2D g, LayoutingContext layoutingContext, FlowContext flowContext) {
        InlineImageContent ic = (InlineImageContent) cnt;
        try {
            URLConnection urlConn = ic.getUrl().openConnection();
            urlConn.setConnectTimeout(15000);
            ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream());
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                System.out.println("loading image " + ic.getUrl());
                ImageReader reader = readers.next();
                reader.setInput(iis, true);
                if (flowContext.pdfContext == null) {
                    RenderedImage img = reader.readAsRenderedImage(0, null);
                    renderOnGraphics(img, x, y, ic, g, layoutingContext, flowContext);
                } else {
                    BufferedImage img = reader.read(0);
                    renderDirectPdf(img, x, y, ic, g, layoutingContext, flowContext);
                }
                reader.dispose();
            } else System.err.println("cannot render image " + ic.getUrl() + " - no suitable reader!");
        } catch (Exception exc) {
            System.err.println("cannot render image " + ic.getUrl() + " due to exception:");
            System.err.println(exc);
            exc.printStackTrace(System.err);
        }
    }
public static void download(String address, String localFileName, String rawClass, double newVer, int newStage) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        int totalBytes = 0;
        int dlBytes = 0;
        try {
            if (!Main.Updates.current.hasFile(rawClass)) {
                Main.Updates.current.addFile(newVer, newStage, rawClass);
            }
            Main.Updates.current.getFile(rawClass).downloading = true;
            Main.Updates.setImage(rawClass, "refresh.png");
            java.io.File folder = new java.io.File(localFileName);
            folder.createNewFile();
            URL url = new URL(address);
            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            conn = url.openConnection();
            in = conn.getInputStream();
            totalBytes = conn.getContentLength();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            double incr = java.lang.Math.floor(totalBytes / 1000);
            Main.Interface.Update.prgStatus.setMaximum(1000);
            Main.Interface.Update.prgStatus.setString("0.0%");
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
                dlBytes += numRead;
                int newVal = (dlBytes != totalBytes ? (int) java.lang.Math.floor(dlBytes / incr) : 1000);
                Main.Interface.Update.prgStatus.setValue(newVal);
                Main.Interface.Update.prgStatus.setString((newVal / 10) + "." + (newVal % 10) + "%");
            }
            Main.Updates.current.getFile(rawClass).downloading = false;
            Main.Updates.current.getFile(rawClass).version = newVer;
            Main.Updates.current.getFile(rawClass).stage = newStage;
            Main.Updates.setImage(rawClass, "updater.png");
            Main.Updates.updateTable();
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
            } catch (IOException ioe) {
            }
        }
    }
public final void run() {
        active = true;
        String s = findcachedir();
        uid = getuid(s);
        try {
            File file = new File(s + "main_file_cache.dat");
            if (file.exists() && file.length() > 0x3200000L) file.delete();
            cache_dat = new RandomAccessFile(s + "main_file_cache.dat", "rw");
            for (int j = 0; j < 5; j++) cache_idx[j] = new RandomAccessFile(s + "main_file_cache.idx" + j, "rw");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        for (int i = threadliveid; threadliveid == i; ) {
            if (socketreq != 0) {
                try {
                    socket = new Socket(socketip, socketreq);
                } catch (Exception _ex) {
                    socket = null;
                }
                socketreq = 0;
            } else if (threadreq != null) {
                Thread thread = new Thread(threadreq);
                thread.setDaemon(true);
                thread.start();
                thread.setPriority(threadreqpri);
                threadreq = null;
            } else if (dnsreq != null) {
                try {
                    dns = InetAddress.getByName(dnsreq).getHostName();
                } catch (Exception _ex) {
                    dns = "unknown";
                }
                dnsreq = null;
            } else if (savereq != null) {
                if (savebuf != null) try {
                    FileOutputStream fileoutputstream = new FileOutputStream(s + savereq);
                    fileoutputstream.write(savebuf, 0, savelen);
                    fileoutputstream.close();
                } catch (Exception _ex) {
                }
                if (waveplay) {
                    wave = s + savereq;
                    waveplay = false;
                }
                if (midiplay) {
                    midi = s + savereq;
                    midiplay = false;
                }
                savereq = null;
            } else if (urlreq != null) {
                try {
                    urlstream = new DataInputStream((new URL(mainapp.getCodeBase(), urlreq)).openStream());
                } catch (Exception _ex) {
                    urlstream = null;
                }
                urlreq = null;
            }
            try {
                Thread.sleep(50L);
            } catch (Exception _ex) {
            }
        }
    }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        URL url;
        URLConnection urlConn;
        DataOutputStream cgiInput;
        url = new URL("http://localhost:8080/ListeOnLine/Target");
        urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        cgiInput = new DataOutputStream(urlConn.getOutputStream());
        String content = "param1=" + URLEncoder.encode("first parameter") + "&param2=" + URLEncoder.encode("the second one...");
        cgiInput.writeBytes(content);
        cgiInput.flush();
        cgiInput.close();
        BufferedReader cgiOutput = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        PrintWriter servletOutput = response.getWriter();
        servletOutput.print("<html><body><h1>This is the Source Servlet</h1><p />");
        String line = null;
        while (null != (line = cgiOutput.readLine())) {
            servletOutput.println(line);
        }
        cgiOutput.close();
        servletOutput.print("</body></html>");
        servletOutput.close();
    }
public String getData() throws ValueFormatException, RepositoryException, IOException {
        InputStream is = getStream();
        StringWriter sw = new StringWriter();
        IOUtils.copy(is, sw, "UTF-8");
        IOUtils.closeQuietly(is);
        return sw.toString();
    }
public InputStream unZip(URL url) throws Exception {
        ZipInputStream zipped = new ZipInputStream(url.openStream());
        System.out.println("unzipping: " + url.getFile());
        ZipEntry zip = zipped.getNextEntry();
        byte[] b = new byte[4096];
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        for (int iRead = zipped.read(b); iRead != -1; iRead = zipped.read(b)) {
            bOut.write(b, 0, iRead);
        }
        zipped.close();
        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
        return (InputStream) bIn;
    }
public byte[] getFile(final String file) throws IOException {
        if (this.files.contains(file)) {
            ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes));
            ZipEntry entry = input.getNextEntry();
            while (entry != null) {
                entry = input.getNextEntry();
                if ((entry.getName().equals(file)) && (!entry.isDirectory())) {
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    IOUtils.copy(input, output);
                    output.close();
                    input.close();
                    return output.toByteArray();
                }
            }
            input.close();
        }
        return null;
    }
public void unzip(final File outDir) throws IOException {
        ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes));
        ZipEntry entry = input.getNextEntry();
        while (entry != null) {
            entry = input.getNextEntry();
            if (entry != null) {
                File file = this.createFile(outDir, entry.getName());
                if (!entry.isDirectory()) {
                    FileOutputStream output = new FileOutputStream(file);
                    IOUtils.copy(input, output);
                    output.close();
                }
            }
        }
        input.close();
    }
public static Pedido insert(Pedido objPedido) {
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        int result;
        if (c == null) {
            return null;
        }
        try {
            c.setAutoCommit(false);
            String sql = "";
            int idPedido;
            idPedido = PedidoDAO.getLastCodigo();
            if (idPedido < 1) {
                return null;
            }
            sql = "insert into pedido " + "(id_pedido, id_funcionario,data_pedido,valor) " + "values(?,?,now(),truncate(?,2))";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, objPedido.getFuncionario().getCodigo());
            pst.setString(3, new DecimalFormat("#0.00").format(objPedido.getValor()));
            result = pst.executeUpdate();
            pst = null;
            if (result > 0) {
                Iterator<ItemPedido> itItemPedido = (objPedido.getItemPedido()).iterator();
                while ((itItemPedido != null) && (itItemPedido.hasNext())) {
                    ItemPedido objItemPedido = (ItemPedido) itItemPedido.next();
                    sql = "";
                    sql = "insert into item_pedido " + "(id_pedido,id_produto,quantidade,subtotal) " + "values (?,?,?,truncate(?,2))";
                    pst = c.prepareStatement(sql);
                    pst.setInt(1, idPedido);
                    pst.setInt(2, (objItemPedido.getProduto()).getCodigo());
                    pst.setInt(3, objItemPedido.getQuantidade());
                    pst.setString(4, new DecimalFormat("#0.00").format(objItemPedido.getSubtotal()));
                    result = pst.executeUpdate();
                }
            }
            pst = null;
            sql = "";
            sql = "insert into pedido_situacao " + "(id_pedido,id_situacao, em, observacao, id_funcionario) " + "values (?,?,now(), ?, ?)";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, 1);
            pst.setString(3, "Inclus�o de pedido");
            pst.setInt(4, objPedido.getFuncionario().getCodigo());
            result = pst.executeUpdate();
            pst = null;
            sql = "";
            sql = "insert into tramitacao " + "(data_tramitacao, id_pedido, id_dep_origem, id_dep_destino) " + "values (now(),?,?, ?)";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idPedido);
            pst.setInt(2, 6);
            pst.setInt(3, 2);
            result = pst.executeUpdate();
            c.commit();
            objPedido.setCodigo(idPedido);
        } catch (final Exception e) {
            try {
                c.rollback();
            } catch (final Exception e1) {
                System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[PedidoDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        return objPedido;
    }
public Map load() throws IOException {
        rpdMap = new HashMap();
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xr = factory.newSAXParser().getXMLReader();
            ConfigHandler handler = new ConfigHandler();
            xr.setContentHandler(handler);
            xr.setErrorHandler(handler);
            InputStream is = url.openStream();
            xr.parse(new InputSource(is));
            is.close();
        } catch (SAXParseException e) {
            String msg = "Error while parsing line " + e.getLineNumber() + " of " + url + ": " + e.getMessage();
            throw new IOException(msg);
        } catch (SAXException e) {
            throw new IOException("Problem with XML: " + e);
        } catch (ParserConfigurationException e) {
            throw new IOException(e.getMessage());
        }
        return rpdMap;
    }
private String urlConnectionTranslate(String word) {
        try {
            URL url = new URL("http://ajax.googleapis.com/ajax/services/" + "language/translate?v=1.0&q=" + word + "&langpair=is%7Cen");
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", "http://www.hi.is");
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            JSONObject json = new JSONObject(builder.toString());
            return json.getJSONObject("responseData").getString("translatedText");
        } catch (Exception e) {
            Log.e(TranslatorApplication.tag, e.toString());
        }
        return null;
    }
protected boolean createFile(final IProject project, final IProgressMonitor monitor, final Template templ, final String sourceUrl, final String destFile, final boolean isBinary) throws IOException, CoreException {
        URL url;
        url = new URL(sourceUrl);
        final URLConnection con = url.openConnection();
        final IFile f = project.getFile(replaceVariables(templ.getVariables(), destFile));
        createParents(f, monitor);
        if (isBinary) {
            f.create(con.getInputStream(), true, monitor);
        } else {
            final StringWriter sw = new StringWriter();
            final InputStream in = con.getInputStream();
            for (; ; ) {
                final int c = in.read();
                if (-1 == c) {
                    break;
                }
                sw.write(c);
            }
            sw.close();
            final String fileText = replaceVariables(templ.getVariables(), sw.toString());
            f.create(new ByteArrayInputStream(fileText.getBytes()), true, monitor);
        }
        return true;
    }
int[] slowSort() {
        int[] values = getValues();
        int n = values.length;
        for (int pass = 1; pass < n; pass++) {
            for (int i = 0; i < n - pass; i++) {
                if (values[i] > values[i + 1]) {
                    int temp = values[i];
                    values[i] = values[i + 1];
                    values[i + 1] = temp;
                }
            }
        }
        return values;
    }
public File unpackResource(String resourceName) throws IOException {
        File file = null;
        URL url = getURL("/" + resourceName);
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof JarURLConnection) {
            file = handleJarFile((JarURLConnection) urlConn, resourceName);
        } else if (urlConn instanceof BundleURLConnection) {
            file = handleBundleFile((BundleURLConnection) urlConn);
        } else {
            file = handleClassicFile(resourceName);
        }
        return file;
    }
private static Properties load(URL url) {
        Properties props = new Properties();
        try {
            InputStream is = null;
            try {
                is = url.openStream();
                props.load(is);
            } finally {
                is.close();
            }
        } catch (IOException e) {
        }
        return props;
    }