semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
private void saveMessage(String server, Message message, byte[] bytes) throws Exception {
            ConnectionProvider cp = null;
            Connection conn = null;
            PreparedStatement ps = null;
            try {
                SessionFactoryImplementor impl = (SessionFactoryImplementor) getPortalDao().getSessionFactory();
                cp = impl.getConnectionProvider();
                conn = cp.getConnection();
                conn.setAutoCommit(false);
                long orgId = 0;
                String className = "";
                long classId = 0;
                if (message.getBody() instanceof Entity) {
                    Entity entity = (Entity) message.getBody();
                    orgId = entity.getOrgId();
                    className = entity.getClass().getName();
                    classId = entity.getId();
                }
                ps = conn.prepareStatement("insert into light_replication_message (orgId,server,event,className,classId,message,createDate) values(?,?,?,?,?,?,?);");
                ps.setLong(1, orgId);
                ps.setString(2, server);
                ps.setString(3, message.getEvent().toString());
                ps.setString(4, className);
                ps.setLong(5, classId);
                ps.setBytes(6, bytes);
                ps.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
                ps.executeUpdate();
                conn.commit();
                ps.close();
                conn.close();
            } catch (Exception e) {
                conn.rollback();
                ps.close();
                conn.close();
                e.printStackTrace();
                throw new Exception(e);
            }
        }
public static void main(String[] args) {
        try {
            if (args.length < 2) {
                System.err.println("usage: test [src] [dest]");
                return;
            }
            FileInputStream in = new FileInputStream(args[0]);
            FileOutputStream out = new FileOutputStream(args[1]);
            FileChannel src = in.getChannel();
            FileChannel channel = out.getChannel();
            long pos = 0, len = src.size(), ret;
            while (len > 0) {
                if ((ret = channel.transferFrom(src, pos, len)) < 0) break;
                len -= ret;
                pos += ret;
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
public RandomGUID() {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage());
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            rand = myRand.nextLong();
            StringBuffer sb = new StringBuffer();
            sb.append(s_id);
            sb.append(":");
            sb.append(Long.toString(time));
            sb.append(":");
            sb.append(Long.toString(rand));
            md5.update(sb.toString().getBytes());
            byte[] array = md5.digest();
            sb.setLength(0);
            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) {
            throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage());
        }
    }
public Object construct() {
                Object result;
                try {
                    if (getParameter("data") != null && getParameter("data").length() > 0) {
                        NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), new StringReader(getParameter("data")));
                        result = domi.readObject(0);
                    } else if (getParameter("datafile") != null) {
                        InputStream in = null;
                        try {
                            URL url = new URL(getDocumentBase(), getParameter("datafile"));
                            in = url.openConnection().getInputStream();
                            NanoXMLDOMInput domi = new NanoXMLDOMInput(new UMLFigureFactory(), in);
                            result = domi.readObject(0);
                        } finally {
                            if (in != null) in.close();
                        }
                    } else {
                        result = null;
                    }
                } catch (Throwable t) {
                    result = t;
                }
                return result;
            }
public void bubbleSort(final int[] s) {
        source = s;
        if (source.length < 2) return;
        boolean go = true;
        while (go) {
            go = false;
            for (int i = 0; i < source.length - 1; i++) {
                int temp = source[i];
                if (temp > source[i + 1]) {
                    source[i] = source[i + 1];
                    source[i + 1] = temp;
                    go = true;
                }
            }
        }
    }
private void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(postURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("Filename", new StringBody(file.getName()));
        mpEntity.addPart("Filedata", new MonitoredFileBody(file, uploadProgress));
        httppost.setEntity(mpEntity);
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into sharesend.com");
        status = UploadStatus.UPLOADING;
        HttpResponse response = httpclient.execute(httppost);
        status = UploadStatus.GETTINGLINK;
        HttpEntity resEntity = response.getEntity();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (resEntity != null) {
            uploadresponse = EntityUtils.toString(resEntity);
        }
        NULogger.getLogger().log(Level.INFO, "Upload Response : {0}", uploadresponse);
        NULogger.getLogger().log(Level.INFO, "Download Link : http://sharesend.com/{0}", uploadresponse);
        downloadlink = "http://sharesend.com/" + uploadresponse;
        downURL = downloadlink;
        httpclient.getConnectionManager().shutdown();
        uploadFinished();
    }
public static final String MD5(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(value.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            String newValue = hash.toString(16);
            return newValue;
        } catch (NoSuchAlgorithmException ns) {
            ns.printStackTrace();
            return null;
        }
    }
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.addHeader("Cache-Control", "max-age=" + Constants.HTTP_CACHE_SECONDS);
        String uuid = req.getRequestURI().substring(req.getRequestURI().indexOf(Constants.SERVLET_THUMBNAIL_PREFIX) + Constants.SERVLET_THUMBNAIL_PREFIX.length() + 1);
        if (uuid != null && !"".equals(uuid)) {
            resp.setContentType("image/jpeg");
            StringBuffer sb = new StringBuffer();
            sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/IMG_THUMB/content");
            InputStream is = null;
            if (!Constants.MISSING.equals(uuid)) {
                is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), true);
            } else {
                is = new FileInputStream(new File("images/other/file_not_found.png"));
            }
            if (is == null) {
                return;
            }
            ServletOutputStream os = resp.getOutputStream();
            try {
                IOUtils.copyStreams(is, os);
            } catch (IOException e) {
            } finally {
                os.flush();
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    } finally {
                        is = null;
                    }
                }
            }
            resp.setStatus(200);
        } else {
            resp.setStatus(404);
        }
    }
public void execute(File tsvFile, File xmlFile) {
        BufferedReader reader = null;
        Writer writer = null;
        Boolean isFileSuccessfullyConverted = Boolean.TRUE;
        TableConfiguration tableConfig = null;
        try {
            xmlFile.getParentFile().mkdirs();
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(tsvFile), INPUT_ENCODING));
            writer = new OutputStreamWriter(new FileOutputStream(xmlFile), OUTPUT_ENCODING);
            tableConfig = Tsv2DocbookConverter.convert2(tableConfigManager, idScanner.extractIdentification(tsvFile), reader, writer, inputPolisher);
            isFileSuccessfullyConverted = (tableConfig != null);
        } catch (UnsupportedEncodingException e) {
            logger.error("Failed to create reader with UTF-8 encoding: " + e.getMessage(), e);
        } catch (FileNotFoundException fnfe) {
            logger.error("Failed to open tsv input file '" + tsvFile + "'. " + fnfe.getMessage());
        } catch (Throwable cause) {
            logger.error("Failed to convert input tsv file '" + tsvFile + "'.", cause);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    logger.warn("Unable to close input file.", ioe);
                }
            }
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ioe) {
                    logger.warn("Unable to close output file.", ioe);
                }
            }
        }
        if (isFileSuccessfullyConverted) {
            String newOutputFileName = tableConfig.getFileName(idScanner.extractIdentification(tsvFile));
            if (newOutputFileName != null) {
                File newOutputFile = new File(xmlFile.getParentFile(), newOutputFileName);
                if (!xmlFile.renameTo(newOutputFile)) {
                    logger.warn("Unable to rename '" + xmlFile + "' to '" + newOutputFile + "'.");
                    logger.info("Created successfully '" + xmlFile + "'.");
                } else {
                    logger.info("Created successfully '" + newOutputFileName + "'.");
                }
            } else {
                logger.info("Created successfully '" + xmlFile + "'.");
            }
        } else {
            logger.warn("Unable to convert input tsv file '" + Tsv2DocBookApplication.trimPath(sourceDir, tsvFile) + "' to docbook.");
            if (xmlFile.exists() && !xmlFile.delete()) {
                logger.warn("Unable to remove (empty) output file '" + xmlFile + "', which was created as target for the docbook table.");
            }
        }
    }
public static String MD5Encode(String password) {
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(password.getBytes());
            final byte[] digest = messageDigest.digest();
            final StringBuilder buf = new StringBuilder(digest.length * 2);
            final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            for (int j = 0; j < digest.length; j++) {
                buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]);
                buf.append(HEX_DIGITS[digest[j] & 0x0f]);
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            return password;
        }
    }
@Override
    protected String doInBackground(MarketData... market) {
        publishProgress(-1);
        InputStream input = null;
        OutputStream output = null;
        long lenghtOfFile = 0;
        int lengthRead = 0;
        try {
            HttpGet newReq = new HttpGet(market[0].apkURL);
            HttpResponse response = HttpManager.execute(newReq);
            Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode());
            while (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) {
                Log.i(Main.TAG, "redirect to:" + response.getFirstHeader("Location").getValue());
                newReq = new HttpGet(response.getFirstHeader("Location").getValue());
                response = HttpManager.execute(newReq);
                Log.i(Main.TAG, "req:" + response.getStatusLine().getStatusCode());
            }
            lenghtOfFile = response.getEntity().getContentLength();
            input = response.getEntity().getContent();
            output = new FileOutputStream(market[0].getFile());
            lengthRead = copy(input, output, lenghtOfFile);
        } catch (MalformedURLException e) {
            Log.w(Main.TAG, "error downloading " + market[0].apkURL, e);
        } catch (IOException e) {
            Log.w(Main.TAG, "error downloading " + market[0].apkURL, e);
        } finally {
            Log.v(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile);
            if (lenghtOfFile != 0 && lengthRead != lenghtOfFile) {
                Log.w(Main.TAG, "failed to download " + market[0].apkURL + " " + lengthRead + "/" + lenghtOfFile);
                try {
                    if (input != null) input.close();
                    if (output != null) output.close();
                    market[0].getFile().delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Log.v(Main.TAG, "copied " + market[0].apkURL + " to " + market[0].getFile());
        return null;
    }
public static String send(String ipStr, int port, String password, String command, InetAddress localhost, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty {
        StringBuffer response = new StringBuffer();
        try {
            rconSocket = new Socket();
            rconSocket.bind(new InetSocketAddress(localhost, localPort));
            rconSocket.connect(new InetSocketAddress(ipStr, port), RESPONSE_TIMEOUT);
            out = rconSocket.getOutputStream();
            in = rconSocket.getInputStream();
            BufferedReader buffRead = new BufferedReader(new InputStreamReader(in));
            rconSocket.setSoTimeout(RESPONSE_TIMEOUT);
            String digestSeed = "";
            boolean loggedIn = false;
            boolean keepGoing = true;
            while (keepGoing) {
                String receivedContent = buffRead.readLine();
                if (receivedContent.startsWith("### Digest seed: ")) {
                    digestSeed = receivedContent.substring(17, receivedContent.length());
                    try {
                        MessageDigest md5 = MessageDigest.getInstance("MD5");
                        md5.update(digestSeed.getBytes());
                        md5.update(password.getBytes());
                        String digestStr = "login " + digestedToHex(md5.digest()) + "\n";
                        out.write(digestStr.getBytes());
                    } catch (NoSuchAlgorithmException e1) {
                        response.append("MD5 algorithm not available - unable to complete RCON request.");
                        keepGoing = false;
                    }
                } else if (receivedContent.startsWith("error: not authenticated: you can only invoke 'login'")) {
                    throw new BadRcon();
                } else if (receivedContent.startsWith("Authentication failed.")) {
                    throw new BadRcon();
                } else if (receivedContent.startsWith("Authentication successful, rcon ready.")) {
                    keepGoing = false;
                    loggedIn = true;
                }
            }
            if (loggedIn) {
                String cmd = "exec " + command + "\n";
                out.write(cmd.getBytes());
                readResponse(buffRead, response);
                if (response.length() == 0) {
                    throw new ResponseEmpty();
                }
            }
        } catch (SocketTimeoutException timeout) {
            throw timeout;
        } catch (UnknownHostException e) {
            response.append("UnknownHostException: " + e.getMessage());
        } catch (IOException e) {
            response.append("Couldn't get I/O for the connection: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
                if (rconSocket != null) {
                    rconSocket.close();
                }
            } catch (IOException e1) {
            }
        }
        return response.toString();
    }
public Out(Article article) throws Exception {
            String body = article.meta(ARTICLE_BODY).getString();
            String url = find("a", "href", body);
            while (url.length() > 0 && url.startsWith("http://")) {
                System.out.println(url);
                conn = (HttpURLConnection) new URL(url).openConnection();
                conn.setRequestMethod("POST");
                int code = conn.getResponseCode();
                String ping = conn.getHeaderField("X-Pingback");
                System.out.println(ping);
                if (ping != null) {
                    conn = (HttpURLConnection) new URL(ping).openConnection();
                    conn.setDoOutput(true);
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("<?xml version=\"1.0\"?>\n");
                    buffer.append("<methodCall>\n");
                    buffer.append("  <methodName>pingback.ping</methodName>\n");
                    buffer.append("  <params>\n");
                    buffer.append("    <param><value><string>http://" + User.host + "/article?id=" + article.getId() + "</string></value></param>\n");
                    buffer.append("    <param><value><string>" + url + "</string></value></param>\n");
                    buffer.append("  </params>\n");
                    buffer.append("</methodCall>\n");
                    System.out.println(buffer.toString());
                    OutputStream out = conn.getOutputStream();
                    out.write(buffer.toString().getBytes("UTF-8"));
                    code = conn.getResponseCode();
                    InputStream in = null;
                    if (code == 200) {
                        in = conn.getInputStream();
                    } else if (code < 0) {
                        throw new IOException("HTTP response unreadable.");
                    } else {
                        in = conn.getErrorStream();
                    }
                    Deploy.pipe(in, System.out);
                    in.close();
                }
                url = find("a", "href", body);
            }
        }
public static void extractZipFile(String filename) {
        try {
            byte[] buf = new byte[1024];
            ZipInputStream zipinputstream = null;
            ZipEntry zipentry;
            zipinputstream = new ZipInputStream(new FileInputStream(filename));
            zipentry = zipinputstream.getNextEntry();
            while (zipentry != null) {
                String entryName = zipentry.getName();
                int n;
                FileOutputStream fileoutputstream;
                File newFile = new File(entryName);
                String directory = newFile.getParent();
                if (directory == null) {
                    if (newFile.isDirectory()) break;
                }
                fileoutputstream = new FileOutputStream(entryName);
                while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n);
                fileoutputstream.close();
                zipinputstream.closeEntry();
                zipentry = zipinputstream.getNextEntry();
            }
            zipinputstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
public Document index() throws CrawlingException {
        log.debug("BEGINIG indexing page [code=" + getCode() + "] ...");
        URL url = null;
        InputStream in = null;
        String contentType = null;
        try {
            url = new URL(getServer().getProtocol() + "://" + getServer().getHost() + ":" + getServer().getPort() + getPath());
            HttpURLConnection pageContent = (HttpURLConnection) url.openConnection();
            if (pageContent.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.debug("page pk[" + getCode() + "," + url.toExternalForm() + "] is invalid");
                return null;
            }
            String redireccion = pageContent.getHeaderField("location");
            if (redireccion != null) {
                log.debug("Page " + url.toExternalForm() + " redirected to " + redireccion);
                recordLink(redireccion);
                return null;
            }
            contentType = pageContent.getContentType();
            in = new BufferedInputStream(pageContent.getInputStream(), 32768);
        } catch (MalformedURLException e) {
            log.error("Invalid page address", e);
        } catch (ConnectException e) {
            if (getServer() != null) {
                log.error("Unable to connect to page: " + getServer().getProtocol() + "://" + getServer().getHost() + ":" + getServer().getPort() + getPath(), e);
            }
        } catch (UnknownHostException uhe) {
            log.warn("Unknow host indexing page " + getURL(), uhe);
        } catch (IOException e) {
            log.warn("Unable to index page " + getURL(), e);
        }
        Document doc = generateDocument(contentType, in);
        log.debug("END indexing page [code=" + getCode() + "]");
        return doc;
    }
public void testReadHelloWorldTxt() throws Exception {
        final InputStream helloWorldIS = this.getClass().getClassLoader().getResourceAsStream(BASE_DIR + "/HelloWorld.txt");
        FileUtils.forceMkdir(new File(this.testDir.getAbsolutePath() + "/org/settings4j/contentresolver"));
        final String helloWorldPath = this.testDir.getAbsolutePath() + "/org/settings4j/contentresolver/HelloWorld.txt";
        final FileOutputStream fileOutputStream = new FileOutputStream(new File(helloWorldPath));
        IOUtils.copy(helloWorldIS, fileOutputStream);
        IOUtils.closeQuietly(helloWorldIS);
        IOUtils.closeQuietly(fileOutputStream);
        LOG.info("helloWorldPath: " + helloWorldPath);
        final FSContentResolver contentResolver = new FSContentResolver();
        contentResolver.setRootFolderPath(this.testDir.getAbsolutePath());
        byte[] content = contentResolver.getContent("org/settings4j/contentresolver/HelloWorld.txt");
        assertNotNull(content);
        assertEquals("Hello World", new String(content, "UTF-8"));
        content = contentResolver.getContent("file:org/settings4j/contentresolver/HelloWorld.txt");
        assertNotNull(content);
        assertEquals("Hello World", new String(content, "UTF-8"));
        content = contentResolver.getContent("file:/org/settings4j/contentresolver/HelloWorld.txt");
        assertNotNull(content);
        assertEquals("Hello World", new String(content, "UTF-8"));
        content = contentResolver.getContent("file:laksjdhalksdhfa");
        assertNull(content);
        content = contentResolver.getContent("/org/settings4j/contentresolver/HelloWorld.txt");
        assertNotNull(content);
        assertEquals("Hello World", new String(content, "UTF-8"));
    }