semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private String send(String method, String contentType, String urlStr, String body) throws MalformedURLException, IOException {
        HttpURLConnection postCon = (HttpURLConnection) new URL(getUrl(urlStr)).openConnection();
        postCon.setRequestMethod(method);
        postCon.setDoOutput(true);
        postCon.setDoInput(true);
        if (cookie != null) {
            postCon.setRequestProperty("Cookie", cookie);
            if (contentType != null) {
                postCon.setRequestProperty("Content-type", contentType);
            }
            postCon.setRequestProperty("Content-Length", body == null ? "0" : Integer.toString(body.length()));
        }
        if (body != null) {
            OutputStream os = postCon.getOutputStream();
            OutputStreamWriter out = new OutputStreamWriter(os);
            out.write(body);
            out.close();
        }
        InputStream is = null;
        try {
            is = postCon.getInputStream();
        } catch (IOException ioe) {
            is = postCon.getErrorStream();
        }
        int resCode = postCon.getResponseCode();
        if (resCode == 201 || resCode == 202) {
            String loc = postCon.getHeaderField("Location");
            System.out.println("loc:" + loc);
            return loc;
        }
        StringBuffer sb = StreamUtil.readStream(is);
        return sb.toString();
    }
@Override
    @RemoteMethod
    public synchronized boolean copy(int idAnexo) {
        try {
            Anexo anexo = selectById(idAnexo);
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Usuario usuario = (Usuario) auth.getPrincipal();
            if (anexo.getAssinado() == 1 && anexo.getIdAssinadoPor() != usuario.getIdUsuario()) {
                deleteAnexoFromTemp(anexo);
                return false;
            }
            Carteira carteiraUsuario = carteiraService.selectById(usuario.getIdCarteira());
            DocumentoDetalhes documentoDetalhes = anexo.getDocumentoDetalhes();
            Set<Documento> documentos = documentoDetalhes.getDocumentosByCarteira();
            boolean havePermission = false;
            for (Documento documento : documentos) {
                Carteira carteiraDocumento = documento.getCarteira();
                if (carteiraDocumento != null) {
                    if (carteiraDocumento.getIdCarteira() == carteiraUsuario.getIdCarteira()) {
                        havePermission = true;
                        System.out.println("tem permisssao: " + havePermission);
                        break;
                    }
                }
            }
            if (!havePermission) {
                System.out.println("Não tem permissao.");
                return false;
            }
            FileInputStream fis = new FileInputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho()));
            FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()));
            IOUtils.copy(fis, fos);
            String txtHistorico = "(Edição) -" + anexo.getAnexoNome() + "-";
            txtHistorico += usuario.getUsuLogin();
            Historico historico = new Historico();
            historico.setCarteira(carteiraUsuario);
            historico.setDataHoraHistorico(new Date());
            historico.setHistorico(txtHistorico);
            historico.setDocumentoDetalhes(documentoDetalhes);
            historico.setUsuario(usuario);
            historicoService.save(historico);
            return deleteAnexoFromTemp(anexo);
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException");
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            System.out.println("IOException");
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            System.out.println("AnexoServiceImpl.copy ERRO DESCONHECIDO");
            e.printStackTrace();
            return false;
        }
    }
public static Properties load(String classPath) throws IOException {
        AssertUtility.notNullAndNotSpace(classPath);
        Properties props = new Properties();
        URL url = ClassLoader.getSystemResource(classPath);
        props.load(url.openStream());
        return props;
    }
public static void fileDownload(String fAddress, String destinationDir) {
        int slashIndex = fAddress.lastIndexOf('/');
        int periodIndex = fAddress.lastIndexOf('.');
        String fileName = fAddress.substring(slashIndex + 1);
        URL url;
        try {
            url = new URL(fAddress);
            URLConnection uc = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            File file = new File(destinationDir + "/download.pdf");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
            int inputLine;
            while ((inputLine = in.read()) != -1) out.write(inputLine);
            in.close();
        } catch (Exception ex) {
            Logger.getLogger(UrlDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("At RandomGUID !!!", e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            logger.error("At RandomGUID !!!", e);
        }
    }
protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException {
        log("Retrieving url: " + urlString);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        if (this.archiveAccessSpecification.getUserID() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword()));
        }
        HttpGet httpget = new HttpGet(urlString);
        log("about to do request: " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        log("-------------- Request results --------------");
        log("Status line: " + response.getStatusLine());
        if (entity != null) {
            log("Response content length: " + entity.getContentLength());
        }
        log("contents");
        byte[] bytes = null;
        if (entity != null) {
            bytes = getBytesFromInputStream(entity.getContent());
            entity.consumeContent();
        }
        log("Status code :" + response.getStatusLine().getStatusCode());
        log(response.getStatusLine().getReasonPhrase());
        if (response.getStatusLine().getStatusCode() != 200) return null;
        return bytes;
    }
public static InputStream getInputStream(String path) throws ResourceException {
        URL url = getURL(path);
        if (url != null) {
            try {
                return url.openConnection().getInputStream();
            } catch (IOException e) {
                throw new ResourceException(e);
            }
        } else {
            throw new ResourceException("Error obtaining resource, invalid path: " + path);
        }
    }
public static OutputStream getOutputStream(String path) throws ResourceException {
        URL url = getURL(path);
        if (url != null) {
            try {
                return url.openConnection().getOutputStream();
            } catch (IOException e) {
                throw new ResourceException(e);
            }
        } else {
            throw new ResourceException("Error obtaining resource, invalid path: " + path);
        }
    }
private void getRandomGuid(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        long time = System.currentTimeMillis();
        long rand = 0;
        if (secure) {
            rand = secureRandom.nextLong();
        } else {
            rand = random.nextLong();
        }
        sbValueBeforeMD5.append(id);
        sbValueBeforeMD5.append(":");
        sbValueBeforeMD5.append(Long.toString(time));
        sbValueBeforeMD5.append(":");
        sbValueBeforeMD5.append(Long.toString(rand));
        String valueBeforeMD5 = sbValueBeforeMD5.toString();
        md5.update(valueBeforeMD5.getBytes());
        byte[] array = md5.digest();
        StringBuffer sb = new StringBuffer();
        for (int j = 0; j < array.length; ++j) {
            int b = array[j] & 0xFF;
            if (b < 0x10) sb.append('0');
            sb.append(Integer.toHexString(b));
        }
        guid = sb.toString();
    }
protected void downloadFile(String filename, java.io.File targetFile, File partFile, ProgressMonitor monitor) throws java.io.IOException {
        FileOutputStream out = null;
        InputStream is = null;
        try {
            filename = toCanonicalFilename(filename);
            URL url = new URL(root + filename.substring(1));
            URLConnection urlc = url.openConnection();
            int i = urlc.getContentLength();
            monitor.setTaskSize(i);
            out = new FileOutputStream(partFile);
            is = urlc.getInputStream();
            monitor.started();
            copyStream(is, out, monitor);
            monitor.finished();
            out.close();
            is.close();
            if (!partFile.renameTo(targetFile)) {
                throw new IllegalArgumentException("unable to rename " + partFile + " to " + targetFile);
            }
        } catch (IOException e) {
            if (out != null) out.close();
            if (is != null) is.close();
            if (partFile.exists() && !partFile.delete()) {
                throw new IllegalArgumentException("unable to delete " + partFile);
            }
            throw e;
        }
    }
public static void copy_file(String fromFileName, String toFileName) throws IOException {
        File fromFile = new File(fromFileName);
        File toFile = new File(toFileName);
        if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName);
        if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName);
        if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName);
        if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
        if (toFile.exists()) {
            if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName);
            System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): ");
            System.out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String response = in.readLine();
            if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten.");
        } else {
            String parent = toFile.getParent();
            if (parent == null) parent = System.getProperty("user.dir");
            File dir = new File(parent);
            if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
            if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
            if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
    }
public static Set<String> getServices(String url) {
        Set<String> services = new HashSet<String>();
        try {
            URL ws_url = new URL(url);
            URLConnection urlConn;
            DataInputStream dis;
            try {
                urlConn = ws_url.openConnection();
                urlConn.setDoInput(true);
                urlConn.setUseCaches(false);
                dis = new DataInputStream(urlConn.getInputStream());
                String s;
                int fpos = 0;
                int lpos;
                int lslash;
                String sn;
                while ((s = dis.readLine()) != null) {
                    if (s.contains("?wsdl")) {
                        fpos = s.indexOf("\"") + 1;
                        lpos = s.indexOf("?");
                        s = s.substring(fpos, lpos);
                        if (s.startsWith("http")) s = s.substring(7);
                        lslash = s.lastIndexOf('/');
                        sn = s.substring(lslash + 1);
                        if (!sn.equals("Version") && !sn.equals("AdminService")) services.add(url + "/" + sn);
                    }
                }
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }
        return services;
    }
@Override
    public void update(String mail, String email, String pwd, String firstname, String lastname) throws NamingException, NoSuchAlgorithmException, UnsupportedEncodingException {
        jndiManagerConnection connection = new jndiManagerConnection();
        Attributes attrs = new BasicAttributes();
        attrs.put("sn", lastname);
        attrs.put("givenName", firstname);
        attrs.put("cn", firstname + " " + lastname);
        if (!pwd.isEmpty()) {
            MessageDigest sha = MessageDigest.getInstance("md5");
            sha.reset();
            sha.update(pwd.getBytes("utf-8"));
            byte[] digest = sha.digest();
            String hash = Base64.encodeBase64String(digest);
            attrs.put("userPassword", "{MD5}" + hash);
        }
        DirContext ctx = connection.getLDAPDirContext();
        ctx.modifyAttributes("mail=" + mail + "," + dn, DirContext.REPLACE_ATTRIBUTE, attrs);
        if (!mail.equals(email)) {
            String newName = "mail=" + email + "," + dn;
            String oldName = "mail=" + mail + "," + dn;
            ctx.rename(oldName, newName);
        }
    }
public static InputStream gzip(final InputStream inputStream) throws IOException {
        Assert.notNull(inputStream, "inputStream");
        InputOutputStream inputOutputStream = new InputOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(inputOutputStream);
        IOUtils.copy(inputStream, gzipOutputStream);
        gzipOutputStream.close();
        return inputOutputStream.getInputStream();
    }
public static InputStream gunzip(final InputStream inputStream) throws IOException {
        Assert.notNull(inputStream, "inputStream");
        GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
        InputOutputStream inputOutputStream = new InputOutputStream();
        IOUtils.copy(gzipInputStream, inputOutputStream);
        return inputOutputStream.getInputStream();
    }
public void unsplit(String newFilename, File[] files) throws Exception {
        FileOutputStream stream = new FileOutputStream(new File(newFilename));
        for (int i = 0; i < files.length; i++) {
            FileInputStream fin = new FileInputStream(files[i].getAbsolutePath());
            DataInputStream din = new DataInputStream(fin);
            while (din.available() > 0) {
                stream.write(din.read());
            }
            din.close();
            fin.close();
        }
        stream.close();
    }
public static boolean isDicom(URL url) {
        assert url != null;
        boolean isDicom = false;
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(url.openStream());
            is.skip(DICOM_PREAMBLE_SIZE);
            byte[] buf = new byte[DICM.length];
            is.read(buf);
            if (buf[0] == DICM[0] && buf[1] == DICM[1] && buf[2] == DICM[2] && buf[3] == DICM[3]) {
                isDicom = true;
            }
        } catch (Exception exc) {
            System.out.println("ImageFactory::isDicom(): exc=" + exc);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception exc) {
                }
            }
        }
        return isDicom;
    }
public static BufferedImage readDicom(final URL url, final SourceImage src) {
        assert url != null;
        assert src != null;
        BufferedImage bi = null;
        try {
            DicomInputStream dis = new DicomInputStream(new BufferedInputStream(url.openStream()));
            src.read(dis);
            dis.close();
            bi = src.getBufferedImage();
        } catch (Exception exc) {
            System.out.println("ImageFactory::readDicom(): exc=" + exc);
        }
        return bi;
    }
@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        Object msg = e.getMessage();
        if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) {
            ctx.sendUpstream(e);
            return;
        }
        HttpMessage currentMessage = this.currentMessage;
        File localFile = this.file;
        if (currentMessage == null) {
            HttpMessage m = (HttpMessage) msg;
            if (m.isChunked()) {
                final String localName = UUID.randomUUID().toString();
                List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING);
                encodings.remove(HttpHeaders.Values.CHUNKED);
                if (encodings.isEmpty()) {
                    m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING);
                }
                this.currentMessage = m;
                this.file = new File(Play.tmpDir, localName);
                this.out = new FileOutputStream(file, true);
            } else {
                ctx.sendUpstream(e);
            }
        } else {
            final HttpChunk chunk = (HttpChunk) msg;
            if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) {
                currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded");
            } else {
                IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out);
                if (chunk.isLast()) {
                    this.out.flush();
                    this.out.close();
                    currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length()));
                    currentMessage.setContent(new FileChannelBuffer(localFile));
                    this.out = null;
                    this.currentMessage = null;
                    this.file = null;
                    Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress());
                }
            }
        }
    }
private void CopyTo(File dest) throws IOException {
        FileReader in = null;
        FileWriter out = null;
        int c;
        try {
            in = new FileReader(image);
            out = new FileWriter(dest);
            while ((c = in.read()) != -1) out.write(c);
        } finally {
            if (in != null) try {
                in.close();
            } catch (Exception e) {
            }
            if (out != null) try {
                out.close();
            } catch (Exception e) {
            }
        }
    }
@Override
    public void run() {
        URL url = null;
        FileOutputStream fos = null;
        FTPClient ftp = null;
        try {
            url = new URL(super.getAddress());
            String host = url.getHost();
            String folder = StringUtils.substringBeforeLast(url.getPath(), "/");
            String fileName = StringUtils.substringAfterLast(url.getPath(), "/");
            ftp = new FTPClient(host, 21);
            if (!ftp.connected()) {
                ftp.connect();
            }
            ftp.login("anonymous", "me@mymail.com");
            logger.info("Connected to " + host + ".");
            logger.info(ftp.getLastValidReply().getReplyText());
            logger.debug("changing dir to " + folder);
            ftp.chdir(folder);
            fos = new FileOutputStream(localFileName);
            logger.info("Downloading file " + fileName + "...");
            ftp.setType(FTPTransferType.BINARY);
            ftp.get(fos, fileName);
            logger.info("Done.");
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.debug(e.getStackTrace());
        } finally {
            try {
                ftp.quit();
                fos.close();
            } catch (Exception e) {
            }
        }
    }
public static String URLtoString(URL url) throws IOException {
        String xml = null;
        if (url != null) {
            URLConnection con = url.openConnection();
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestProperty("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            InputStream is = con.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];
            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {
                buffer.write(bytes, 0, i);
            }
            xml = new String(buffer.toByteArray());
            is.close();
            buffer.close();
        }
        return xml;
    }