semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public Bitmap getImage() throws IOException {
        int recordBegin = 78 + 8 * mCount;
        Bitmap result = null;
        FileChannel channel = new FileInputStream(mFile).getChannel();
        channel.position(mRecodeOffset[mPage]);
        ByteBuffer bodyBuffer;
        if (mPage + 1 < mCount) {
            int length = mRecodeOffset[mPage + 1] - mRecodeOffset[mPage];
            bodyBuffer = channel.map(MapMode.READ_ONLY, mRecodeOffset[mPage], length);
            byte[] tmpCache = new byte[bodyBuffer.capacity()];
            bodyBuffer.get(tmpCache);
            FileOutputStream o = new FileOutputStream("/sdcard/test.bmp");
            o.write(tmpCache);
            o.flush();
            o.getFD().sync();
            o.close();
            result = BitmapFactory.decodeByteArray(tmpCache, 0, length);
        } else {
        }
        channel.close();
        return result;
    }
private void checkLogin(String email, String password) throws JspTagException {
        String cryptedPassword;
        try {
            MessageDigest crypt = MessageDigest.getInstance("MD5");
            crypt.update(password.getBytes());
            byte digest[] = crypt.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < digest.length; i++) {
                hexString.append(hexDigit(digest[i]));
            }
            cryptedPassword = hexString.toString();
            crypt.reset();
            InitialContext context = new InitialContext();
            java.lang.Object homeRef = context.lookup("java:comp/env/ejb/Value");
            ValueHome valueHome = (ValueHome) PortableRemoteObject.narrow(homeRef, ValueHome.class);
            Value value = valueHome.findByPasswordCheck(email, cryptedPassword);
            pageContext.setAttribute("validLogin", new Boolean(true));
            HttpSession session = pageContext.getSession();
            session.setAttribute("jspShop.userID", value.getObjectID());
        } catch (NoSuchAlgorithmException e) {
            System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage());
            e.printStackTrace();
            throw new JspTagException("Error crypting password!: " + e.getMessage());
        } catch (ObjectNotFoundException e) {
            pageContext.setAttribute("validLogin", new Boolean(false));
        } catch (NamingException e) {
            System.err.println("jspShop: Could not initialise context in LoginTag");
            e.printStackTrace();
        } catch (RemoteException e) {
            System.err.println("jspShop: Could not connect to container in LoginTag");
        } catch (FinderException e) {
            System.err.println("jspShop: Error using finderQuery in LoginTag");
        }
    }
public void logging() throws Fault {
        final InterceptorWrapper wrap = new InterceptorWrapper(message);
        final LoggingMessage buffer = new LoggingMessage("Inbound Message\n----------------------------");
        String encoding = (String) wrap.getEncoding();
        if (encoding != null) {
            buffer.getEncoding().append(encoding);
        }
        Object headers = wrap.getProtocolHeaders();
        if (headers != null) {
            buffer.getHeader().append(headers);
        }
        InputStream is = (InputStream) wrap.getContent(InputStream.class);
        if (is != null) {
            CachedOutputStream bos = new CachedOutputStream();
            try {
                IOUtils.copy(is, bos);
                bos.flush();
                is.close();
                this.message.setContent(InputStream.class, bos.getInputStream());
                if (bos.getTempFile() != null) {
                    logger.error("\nMessage (saved to tmp file):\n");
                    logger.error("Filename: " + bos.getTempFile().getAbsolutePath() + "\n");
                }
                if (bos.size() > limit) {
                    logger.error("(message truncated to " + limit + " bytes)\n");
                }
                bos.writeCacheTo(buffer.getPayload(), limit);
                bos.close();
            } catch (IOException e) {
                throw new Fault(e);
            }
        }
        logger.debug("Message received :\n" + buffer.getPayload().toString());
    }
@Override
    public void sendErrorMessage(String message) throws EntriesException, StatementNotExecutedException, NotConnectedException, MessagingException {
        if (query == null) {
            throw new NotConnectedException();
        }
        ArrayList<String> recipients = query.getUserManager().getTecMail();
        Mail mail = new Mail(recipients);
        try {
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("log/ossobooklog.zip"));
            FileInputStream fis = new FileInputStream("log/ossobook.log");
            ZipEntry entry = new ZipEntry("ossobook.log");
            zos.putNextEntry(entry);
            byte[] buffer = new byte[8192];
            int read = 0;
            while ((read = fis.read(buffer, 0, 1024)) != -1) {
                zos.write(buffer, 0, read);
            }
            zos.closeEntry();
            fis.close();
            zos.close();
            mail.sendErrorMessage(message, new File("log/ossobooklog.zip"), getUserName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setHeader("Content-type", "application/force-download");
        response.setHeader("Content-disposition", "attachment");
        response.setHeader("filename", "export.txt");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        InputStream x = baseRequest.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(x, writer);
        String theString = writer.toString();
        System.out.println(theString);
        response.getWriter().println(request.getParameter("file").replace("*", "\n"));
    }
private OSD downloadList() throws IOException, IllegalStateException, ParseException, URISyntaxException {
        OSD osd = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet getMethod = new HttpGet(new URI(listUri));
        try {
            HttpResponse response = client.execute(getMethod);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream stream = entity.getContent();
                String charset = null;
                if (entity.getContentType() != null) {
                    HeaderElement values[] = entity.getContentType().getElements();
                    if (values.length > 0) {
                        NameValuePair param = values[0].getParameterByName("charset");
                        if (param != null) {
                            charset = param.getValue();
                        }
                    }
                }
                if (charset == null) {
                    charset = HTTP.DEFAULT_CONTENT_CHARSET;
                }
                osd = OSD.parse(stream, charset);
            }
        } finally {
            getMethod.abort();
        }
        return osd;
    }
private static void copyContent(final File srcFile, final File dstFile, final boolean gzipContent) throws IOException {
        final File dstFolder = dstFile.getParentFile();
        dstFolder.mkdirs();
        if (!dstFolder.exists()) {
            throw new RuntimeException("Unable to create the folder " + dstFolder.getAbsolutePath());
        }
        final InputStream in = new FileInputStream(srcFile);
        OutputStream out = new FileOutputStream(dstFile);
        if (gzipContent) {
            out = new GZIPOutputStream(out);
        }
        try {
            final byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
        } finally {
            in.close();
            out.close();
        }
    }
public static boolean isUrlAvailable(String url) {
        boolean flag = true;
        try {
            URLConnection conn = (new URL(url)).openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();
            if (conn.getDate() == 0) {
                flag = false;
            }
        } catch (IOException e) {
            log.error(e);
            flag = false;
        }
        return flag;
    }
public Mappings read() {
        Mappings result = null;
        InputStream stream = null;
        try {
            XMLParser parser = new XMLParser();
            stream = url.openStream();
            result = parser.parse(stream);
        } catch (Throwable e) {
            log.error("Error in loading dozer mapping file url: [" + url + "] : " + e);
            MappingUtils.throwMappingException(e);
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                MappingUtils.throwMappingException(e);
            }
        }
        return result;
    }
public static String encrypt(String txt) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(txt.getBytes("UTF-8"));
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }
private static void process(String urlstring) {
        try {
            URL url = new URL(urlstring);
            System.out.println("Connecting to " + url);
            URLConnection connection = url.openConnection();
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            for (String line; (line = in.readLine()) != null; ) if (line.startsWith(MARKER)) {
                System.out.println(TAG.matcher(line).replaceAll(""));
            }
            in.close();
        } catch (IOException ioe) {
            System.err.println("" + ioe);
        }
    }
public void exportFile() {
        String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY);
        File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc");
        File f = new File(absPath);
        try {
            FileOutputStream fout = new FileOutputStream(out);
            FileInputStream fin = new FileInputStream(f);
            int read = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((read = fin.read(buffer)) > 0) {
                fout.write(buffer, 0, read);
            }
            fin.close();
            fout.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
@Override
    public CheckAvailabilityResult execute(final CheckAvailabilityAction action, final ExecutionContext context) throws ActionException {
        if (LOGGER.isDebugEnabled()) {
            String serverName = null;
            if (action.getServerId() == CheckAvailability.FEDORA_ID) {
                serverName = "fedora";
            } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) {
                serverName = "kramerius";
            }
            LOGGER.debug("Processing action: CheckAvailability: " + serverName);
        }
        ServerUtils.checkExpiredSession(httpSessionProvider);
        boolean status = true;
        String url = null;
        String usr = "";
        String pass = "";
        if (action.getServerId() == CheckAvailability.FEDORA_ID) {
            url = configuration.getFedoraHost();
            usr = configuration.getFedoraLogin();
            pass = configuration.getFedoraPassword();
        } else if (action.getServerId() == CheckAvailability.KRAMERIUS_ID) {
            url = configuration.getKrameriusHost() + SOME_STATIC_KRAMERIUS_PAGE;
        } else {
            throw new ActionException("Unknown server id");
        }
        try {
            URLConnection con = RESTHelper.openConnection(url, usr, pass, false);
            if (con instanceof HttpURLConnection) {
                HttpURLConnection httpConnection = (HttpURLConnection) con;
                int resp = httpConnection.getResponseCode();
                if (resp < 200 || resp >= 308) {
                    status = false;
                    LOGGER.info("Server " + url + " answered with HTTP code " + httpConnection.getResponseCode());
                }
            } else {
                status = false;
            }
        } catch (MalformedURLException e) {
            status = false;
            e.printStackTrace();
        } catch (IOException e) {
            status = false;
            e.printStackTrace();
        }
        return new CheckAvailabilityResult(status, url);
    }
public static void main(String[] args) {
        log.info("Passage paramètres " + args);
        try {
            URL url = new URL("http://localhost:8082/HomeAutomateCore/ListenerServlet/");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            out.write("username = JavaWorld \r \n ");
            out.flush();
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String reponse = "";
            while ((reponse = in.readLine()) != null) {
                System.out.println(reponse);
            }
            System.out.println("Fin");
            in.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            System.out.println("Fin1 " + ex.getMessage() + " " + ex.getCause());
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("Fin2 " + ex.getMessage() + " " + ex.getCause());
        }
    }
protected void writePage(final CacheItem entry, final TranslationResponse response, ModifyTimes times) throws IOException {
        if (entry == null) {
            return;
        }
        Set<ResponseHeader> headers = new TreeSet<ResponseHeader>();
        for (ResponseHeader h : entry.getHeaders()) {
            if (TranslationResponse.ETAG.equals(h.getName())) {
                if (!times.isFileLastModifiedKnown()) {
                    headers.add(new ResponseHeaderImpl(h.getName(), doETagStripWeakMarker(h.getValues())));
                }
            } else {
                headers.add(h);
            }
        }
        response.addHeaders(headers);
        if (!times.isFileLastModifiedKnown()) {
            response.setLastModified(entry.getLastModified());
        }
        response.setTranslationCount(entry.getTranslationCount());
        response.setFailCount(entry.getFailCount());
        OutputStream output = response.getOutputStream();
        try {
            InputStream input = entry.getContentAsStream();
            try {
                IOUtils.copy(input, output);
            } finally {
                input.close();
            }
        } finally {
            response.setEndState(ResponseStateOk.getInstance());
        }
    }
public static FileChannel getFileChannel(Object o) throws IOException {
        Class c = o.getClass();
        try {
            Method m = c.getMethod("getChannel", null);
            return (FileChannel) m.invoke(o, null);
        } catch (IllegalAccessException x) {
        } catch (NoSuchMethodException x) {
        } catch (InvocationTargetException x) {
            if (x.getTargetException() instanceof IOException) throw (IOException) x.getTargetException();
        }
        if (o instanceof FileInputStream) return new MyFileChannelImpl((FileInputStream) o);
        if (o instanceof FileOutputStream) return new MyFileChannelImpl((FileOutputStream) o);
        if (o instanceof RandomAccessFile) return new MyFileChannelImpl((RandomAccessFile) o);
        Assert.UNREACHABLE(o.getClass().toString());
        return null;
    }
public static String generatePassword(String userKey, int applicationId, String applicationKey) {
        String nonce = generateNonce();
        String createDate = fmtDate.format(new Date());
        String keyDigest = null;
        MessageDigest sha1 = null;
        try {
            sha1 = MessageDigest.getInstance("SHA1");
            sha1.update(nonce.getBytes("UTF-8"));
            sha1.update(createDate.getBytes("UTF-8"));
            sha1.update(userKey.getBytes("UTF-8"));
            sha1.update(applicationKey.getBytes("UTF-8"));
            keyDigest = getHexaDecimal(sha1.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(applicationId);
        sb.append(',');
        sb.append(nonce);
        sb.append(',');
        sb.append(createDate);
        sb.append(',');
        sb.append(keyDigest);
        return sb.toString();
    }
static void invalidSlave(String msg, Socket sock) throws IOException {
        BufferedReader _sinp = null;
        PrintWriter _sout = null;
        try {
            _sout = new PrintWriter(sock.getOutputStream(), true);
            _sinp = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            _sout.println(msg);
            logger.info("NEW< " + msg);
            String txt = SocketSlaveListener.readLine(_sinp, 30);
            String sname = "";
            String spass = "";
            String shash = "";
            try {
                String[] items = txt.split(" ");
                sname = items[1].trim();
                spass = items[2].trim();
                shash = items[3].trim();
            } catch (Exception e) {
                throw new IOException("Slave Inititalization Faailed");
            }
            String pass = sname + spass + _pass;
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(pass.getBytes());
            String hash = SocketSlaveListener.hash2hex(md5.digest()).toLowerCase();
            if (!hash.equals(shash)) {
                throw new IOException("Slave Inititalization Faailed");
            }
        } catch (Exception e) {
        }
        throw new IOException("Slave Inititalization Faailed");
    }
public static void fastBackup(File file) {
        FileChannel in = null;
        FileChannel out = null;
        FileInputStream fin = null;
        FileOutputStream fout = null;
        try {
            in = (fin = new FileInputStream(file)).getChannel();
            out = (fout = new FileOutputStream(file.getAbsolutePath() + ".bak")).getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            Logging.getErrorLog().reportError("Fast backup failure (" + file.getAbsolutePath() + "): " + e.getMessage());
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                    Logging.getErrorLog().reportException("Failed to close file input stream", e);
                }
            }
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    Logging.getErrorLog().reportException("Failed to close file output stream", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Logging.getErrorLog().reportException("Failed to close file channel", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    Logging.getErrorLog().reportException("Failed to close file channel", e);
                }
            }
        }
    }
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException {
        long mgr = Constants.MANAGER;
        Data data, response;
        try {
            response = sendAndWait(new Request(mgr)).get(0);
            MessageDigest md;
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("MD5 hash not supported.");
            }
            byte[] challenge = response.getBytes();
            md.update(challenge);
            md.update(password.getBytes(Data.STRING_ENCODING));
            try {
                data = Data.valueOf(md.digest());
                response = sendAndWait(new Request(mgr).add(0, data)).get(0);
            } catch (ExecutionException ex) {
                throw new IncorrectPasswordException();
            }
            loginMessage = response.getString();
            response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0);
            ID = response.getWord();
        } catch (InterruptedException ex) {
            throw new LoginFailedException(ex);
        } catch (ExecutionException ex) {
            throw new LoginFailedException(ex);
        } catch (IOException ex) {
            throw new LoginFailedException(ex);
        }
    }
public static String encrypt(String data) throws IOException, NoSuchAlgorithmException {
        Properties props = Configuration.getInstance().getProperties();
        String algorithm = props.getProperty("com.makeabyte.jhosting.server.persistence.security.algorithm");
        String encryptedData = data;
        boolean encrypt = Boolean.parseBoolean(props.getProperty("com.makeabyte.jhosting.server.persistence.security.encrypt"));
        if (encrypt) {
            if (algorithm.equalsIgnoreCase("UTF-16LE")) return encryptActiveDirectory(data);
            MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
            md.reset();
            md.update(data.getBytes());
            encryptedData = md.digest().toString();
        }
        return encryptedData;
    }
public String getDigest(String algorithm, String data) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = java.security.MessageDigest.getInstance(algorithm);
        md.reset();
        md.update(data.getBytes());
        return md.digest().toString();
    }
private Document parseResponse(String url) throws IOException, MalformedURLException, ParserConfigurationException, SAXException {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputStream stream = null;
        try {
            stream = new URL(url).openStream();
            return db.parse(stream);
        } finally {
            PetstoreUtil.closeIgnoringException(stream);
        }
    }
public static String md5(String plainText) {
        String ret = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            ret = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return ret;
    }