semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Transactional(readOnly = false)
    public void saveOrUpdateProduct(Product product, File[] doc, String[] docFileName, String[] docContentType) throws IOException {
        logger.info("addOrUpdateProduct()");
        List<Images> imgList = new ArrayList<Images>();
        InputStream in = null;
        OutputStream out = null;
        String saveDirectory = ServletActionContext.getServletContext().getRealPath("common/userfiles/image/");
        if (doc != null && doc.length > 0) {
            File uploadPath = new File(saveDirectory);
            if (!uploadPath.exists()) uploadPath.mkdirs();
            for (int i = 0; i < doc.length; i++) {
                Images img = new Images();
                in = new FileInputStream(doc[i]);
                img.setName(docFileName[i].substring(0, docFileName[i].lastIndexOf(".")));
                img.setRenameAs(docFileName[i]);
                imgList.add(img);
                out = new FileOutputStream(saveDirectory + "/" + img.getRenameAs());
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
                out.flush();
            }
        }
        product.setImagesCollection(imgList);
        productDao.saveOrUpdateProduct(product);
        if (null != in) {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (null != out) {
            try {
                out.close();
            } catch (Exception e) {
                logger.info("addOrUpdateProduct() **********" + e.getStackTrace());
                e.printStackTrace();
            }
        }
    }
public void add(AddInterceptorChain chain, Entry entry, LDAPConstraints constraints) throws LDAPException {
        Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
        if (con == null) {
            throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection");
        }
        try {
            con.setAutoCommit(false);
            HashMap<String, String> db2ldap = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_DB2LDAP + this.dbInsertName);
            String uid = ((RDN) (new DN(entry.getEntry().getDN())).getRDNs().get(0)).getValue();
            PreparedStatement ps = con.prepareStatement(this.insertSQL);
            for (int i = 0; i < this.fields.size(); i++) {
                String field = this.fields.get(i);
                if (field.equals(this.rdnField)) {
                    ps.setString(i + 1, uid);
                } else {
                    ps.setString(i + 1, entry.getEntry().getAttribute(db2ldap.get(field)).getStringValue());
                }
            }
            ps.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e);
            }
            throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e);
        }
    }
public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException {
        Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
        if (con == null) {
            throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection");
        }
        try {
            con.setAutoCommit(false);
            String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
            PreparedStatement ps = con.prepareStatement(this.deleteSQL);
            ps.setString(1, uid);
            ps.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e);
            }
            throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e);
        }
    }
public void modify(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, LDAPConstraints constraints) throws LDAPException {
        Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
        if (con == null) {
            throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection");
        }
        try {
            con.setAutoCommit(false);
            HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName);
            Iterator<LDAPModification> it = mods.iterator();
            String sql = "UPDATE " + this.tableName + " SET ";
            while (it.hasNext()) {
                LDAPModification mod = it.next();
                if (mod.getOp() != LDAPModification.REPLACE) {
                    throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, "");
                }
                sql += ldap2db.get(mod.getAttribute().getName()) + "=? ";
            }
            sql += " WHERE " + this.rdnField + "=?";
            PreparedStatement ps = con.prepareStatement(sql);
            it = mods.iterator();
            int i = 1;
            while (it.hasNext()) {
                LDAPModification mod = it.next();
                ps.setString(i, mod.getAttribute().getStringValue());
                i++;
            }
            String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
            ps.setString(i, uid);
            ps.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e);
            }
            throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e);
        }
    }
public static void run(File targetFolder, URL url) throws UpdateException {
        try {
            run(targetFolder, new ZipInputStream(url.openStream()));
        } catch (Exception e) {
            if (e instanceof UpdateException) throw (UpdateException) e; else throw new UpdateException(e);
        }
    }
public static String generateDigest(String password, String saltHex, String alg) {
        try {
            MessageDigest sha = MessageDigest.getInstance(alg);
            byte[] salt = new byte[0];
            if (saltHex != null) {
                salt = fromHex(saltHex);
            }
            String label = null;
            if (alg.startsWith("SHA")) {
                label = (salt.length <= 0) ? "{SHA}" : "{SSHA}";
            } else if (alg.startsWith("MD5")) {
                label = (salt.length <= 0) ? "{MD5}" : "{SMD5}";
            }
            sha.reset();
            sha.update(password.getBytes());
            sha.update(salt);
            byte[] pwhash = sha.digest();
            StringBuffer digest = new StringBuffer(label);
            digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray());
            return digest.toString();
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae);
        }
    }
public static boolean verifyPassword(String digest, String password) {
        String alg = null;
        int size = 0;
        if (digest.regionMatches(true, 0, "{SHA}", 0, 5)) {
            digest = digest.substring(5);
            alg = "SHA-1";
            size = 20;
        } else if (digest.regionMatches(true, 0, "{SSHA}", 0, 6)) {
            digest = digest.substring(6);
            alg = "SHA-1";
            size = 20;
        } else if (digest.regionMatches(true, 0, "{MD5}", 0, 5)) {
            digest = digest.substring(5);
            alg = "MD5";
            size = 16;
        } else if (digest.regionMatches(true, 0, "{SMD5}", 0, 6)) {
            digest = digest.substring(6);
            alg = "MD5";
            size = 16;
        }
        try {
            MessageDigest sha = MessageDigest.getInstance(alg);
            if (sha == null) {
                return false;
            }
            byte[][] hs = split(Base64.decode(digest), size);
            byte[] hash = hs[0];
            byte[] salt = hs[1];
            sha.reset();
            sha.update(password.getBytes());
            sha.update(salt);
            byte[] pwhash = sha.digest();
            return MessageDigest.isEqual(hash, pwhash);
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae);
        }
    }
public static String executePost(String urlStr, String content) {
        StringBuffer result = new StringBuffer();
        try {
            Authentication.doIt();
            URL url = new URL(urlStr);
            System.out.println("Host: " + url.getHost());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            System.out.println("got connection ");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            connection.setRequestProperty("Content-Length", "" + content.length());
            connection.setRequestProperty("SOAPAction", "\"http://niki-bt.act.cmis.csiro.org/SMSService/SendText\"");
            connection.setRequestMethod("POST");
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(content);
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
            in.close();
            out.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String msg = result.toString();
        if (msg != null) {
            int beginCut = msg.indexOf('>');
            int endCut = msg.lastIndexOf('<');
            if (beginCut != -1 && endCut != -1) {
                return msg.substring(beginCut + 1, endCut);
            }
        }
        return null;
    }
private static String executeGet(String urlStr) {
        StringBuffer result = new StringBuffer();
        try {
            Authentication.doIt();
            URL url = new URL(urlStr);
            System.out.println("Host: " + url.getHost());
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
            in.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
@Test
    public void testWriteAndReadFirstLevel() throws Exception {
        JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0);
        JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort);
        try {
            server.start();
            RFile directory1 = new RFile("directory1");
            RFile file = new RFile(directory1, "testreadwrite1st.txt");
            RFileOutputStream out = new RFileOutputStream(file);
            out.write("test".getBytes("utf-8"));
            out.close();
            RFileInputStream in = new RFileInputStream(file);
            byte[] buffer = new byte[4];
            int readCount = in.read(buffer);
            in.close();
            assertEquals(4, readCount);
            String resultRead = new String(buffer, "utf-8");
            assertEquals("test", resultRead);
        } finally {
            server.stop();
        }
    }
@Test
    public void testWriteAndReadSecondLevel() throws Exception {
        JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0);
        JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort);
        try {
            server.start();
            RFile directory1 = new RFile("directory1");
            RFile directory2 = new RFile(directory1, "directory2");
            RFile file = new RFile(directory2, "testreadwrite2nd.txt");
            RFileOutputStream out = new RFileOutputStream(file);
            out.write("test".getBytes("utf-8"));
            out.close();
            RFileInputStream in = new RFileInputStream(file);
            byte[] buffer = new byte[4];
            int readCount = in.read(buffer);
            in.close();
            assertEquals(4, readCount);
            String resultRead = new String(buffer, "utf-8");
            assertEquals("test", resultRead);
        } finally {
            server.stop();
        }
    }
public void fetch(URL url, HTTPMethod method, String payload, WithResponse wr) throws IOException {
        System.out.println("fetchin' " + url.toString() + " with GAE fetch service");
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setReadTimeout(10000);
            connection.setRequestMethod(method.name());
            System.out.println(method.name().toString());
            connection.setRequestProperty("Connection", "close");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (wr != null) {
                connection.setDoOutput(true);
            }
            connection.connect();
            System.out.println(connection.toString());
            if (payload != null) {
                OutputStream out = null;
                OutputStreamWriter outWriter = null;
                try {
                    out = connection.getOutputStream();
                    outWriter = new OutputStreamWriter(out, "UTF-8");
                    outWriter.write(payload);
                    System.out.println(out.toString());
                } finally {
                    close(outWriter);
                    close(out);
                }
            }
            if (wr != null) {
                InputStream in = null;
                InputStreamReader reader = null;
                StringBuilder sb = new StringBuilder();
                try {
                    in = connection.getInputStream();
                    reader = new InputStreamReader(in);
                    BufferedReader bufReader = new BufferedReader(reader);
                    String line;
                    while ((line = bufReader.readLine()) != null) {
                        sb.append(line).append('\n');
                    }
                    System.out.println(line);
                } finally {
                    close(reader);
                    close(in);
                }
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
public void run() {
        try {
            Socket socket = getSocket();
            System.out.println("opening socket to " + address + " on " + port);
            InputStream in = socket.getInputStream();
            for (; ; ) {
                FileTransferHeader header = FileTransferHeader.readHeader(in);
                if (header == null) break;
                System.out.println("header: " + header);
                String[] parts = header.getFilename().getSegments();
                String filename;
                if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname();
                System.out.println("writing to file " + filename);
                long sum = 0;
                if (new File(filename).exists()) {
                    FileInputStream fis = new FileInputStream(filename);
                    byte[] block = new byte[10];
                    for (int i = 0; i < block.length; ) {
                        int count = fis.read(block);
                        if (count == -1) break;
                        i += count;
                    }
                    FileTransferChecksum summer = new FileTransferChecksum();
                    summer.update(block, 0, 10);
                    sum = summer.getValue();
                }
                FileChannel fileChannel = new FileOutputStream(filename).getChannel();
                FileTransferHeader outHeader = new FileTransferHeader(header);
                outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK);
                outHeader.setIcbmMessageId(cookie);
                outHeader.setBytesReceived(0);
                outHeader.setReceivedChecksum(sum);
                OutputStream socketOut = socket.getOutputStream();
                System.out.println("sending header: " + outHeader);
                outHeader.write(socketOut);
                for (int i = 0; i < header.getFileSize(); ) {
                    long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i);
                    System.out.println("transferred " + transferred);
                    if (transferred == -1) return;
                    i += transferred;
                }
                System.out.println("finished transfer!");
                fileChannel.close();
                FileTransferHeader doneHeader = new FileTransferHeader(header);
                doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED);
                doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE);
                doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1);
                doneHeader.setIcbmMessageId(cookie);
                doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1);
                doneHeader.write(socketOut);
                if (doneHeader.getFilesLeft() - 1 <= 0) {
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
public static void copyFile(File src, File dest, boolean notifyUserOnError) {
        if (src.exists()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
                byte[] read = new byte[128];
                int len = 128;
                while ((len = in.read(read)) > 0) out.write(read, 0, len);
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage();
                if (notifyUserOnError) {
                    Log.getInstance(SystemUtils.class).warnWithUserNotification(message);
                } else {
                    Log.getInstance(SystemUtils.class).warn(message);
                }
            }
        } else {
            String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath();
            if (notifyUserOnError) {
                Log.getInstance(SystemUtils.class).warnWithUserNotification(message);
            } else {
                Log.getInstance(SystemUtils.class).warn(message);
            }
        }
    }
private static String getVersion() {
        debug.print("");
        String version = null;
        String version_url = "http://kmttg.googlecode.com/svn/trunk/version";
        try {
            URL url = new URL(version_url);
            URLConnection con = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) version = inputLine;
            in.close();
        } catch (Exception ex) {
            version = null;
        }
        return version;
    }
public static final void main(String[] args) throws FileNotFoundException, IOException {
        ArrayList<String[]> result = new ArrayList<String[]>();
        IStream is = new StreamImpl();
        IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream());
        int count = loadExcel(result, is, 0, 0, -1, 16, 1);
        System.out.println(count);
        for (String[] rs : result) {
            for (String r : rs) {
                System.out.print(r + "\t");
            }
            System.out.println();
        }
    }
public String[][] getProjectTreeData() {
        String[][] treeData = null;
        String filename = dms_home + FS + "temp" + FS + username + "projects.xml";
        String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjects";
        try {
            String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "projects.xml";
            System.out.println(urldata);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            DocumentBuilder parser = factory.newDocumentBuilder();
            URL u = new URL(urldata);
            DataInputStream is = new DataInputStream(u.openStream());
            FileOutputStream os = new FileOutputStream(filename);
            int iBufSize = is.available();
            byte inBuf[] = new byte[20000 * 1024];
            int iNumRead;
            while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead);
            os.close();
            is.close();
            File f = new File(filename);
            InputStream inputstream = new FileInputStream(f);
            Document document = parser.parse(inputstream);
            NodeList nodelist = document.getElementsByTagName("j");
            int num = nodelist.getLength();
            treeData = new String[num][5];
            for (int i = 0; i < num; i++) {
                treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "i"));
                treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pi"));
                treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p"));
                treeData[i][3] = "";
                treeData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f"));
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
        } catch (ParserConfigurationException ex) {
            System.out.println(ex);
        } catch (NullPointerException e) {
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return treeData;
    }