semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static void httpOnLoad(String fileName, String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int responseCode = conn.getResponseCode();
        System.err.println("Code : " + responseCode);
        System.err.println("getResponseMessage : " + conn.getResponseMessage());
        if (responseCode >= 400) {
            return;
        }
        int threadSize = 3;
        int fileLength = conn.getContentLength();
        System.out.println("fileLength:" + fileLength);
        int block = fileLength / threadSize;
        int lastBlock = fileLength - (block * (threadSize - 1));
        conn.disconnect();
        File file = new File(fileName);
        RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
        randomFile.setLength(fileLength);
        randomFile.close();
        for (int i = 2; i < 3; i++) {
            int startPosition = i * block;
            if (i == threadSize - 1) {
                block = lastBlock;
            }
            RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
            threadFile.seek(startPosition);
            new TestDownFile(url, startPosition, threadFile, block).start();
        }
    }
private void copyDirContent(String fromDir, String toDir) throws Exception {
        String fs = System.getProperty("file.separator");
        File[] files = new File(fromDir).listFiles();
        if (files == null) {
            throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!");
        }
        for (int i = 0; i < files.length; i++) {
            File dir = new File(toDir);
            dir.mkdirs();
            if (files[i].isFile()) {
                try {
                    FileChannel srcChannel = new FileInputStream(files[i]).getChannel();
                    FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (Exception e) {
                    Logger.ERROR("Error during file copy: " + e.getMessage());
                    throw e;
                }
            }
        }
    }
public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (lsm.isSelectionEmpty()) {
            } else {
                int selectedRow = lsm.getMinSelectionIndex();
                ChemModel model = modelContent.getValueAt(sortedModelContent.getSortedIndex(selectedRow));
                DADMLResult resource = (DADMLResult) model.getProperty("org.openscience.cdk.internet.DADMLResult");
                URL url = resource.getURL();
                try {
                    URLConnection connection = url.openConnection();
                    InputStreamReader input = new InputStreamReader(connection.getInputStream());
                    if (APIVersionTester.isBiggerOrEqual("1.8", editBus.getAPIVersion())) {
                        try {
                            editBus.showChemFile(input);
                            return;
                        } catch (Exception exception) {
                            logger.error("EditBus error: ", exception.getMessage());
                            logger.debug(exception);
                        }
                    }
                    IChemObjectReader reader = readerFactory.createReader(input);
                    ChemFile chemFile = (ChemFile) reader.read(new ChemFile());
                    editBus.showChemFile(chemFile);
                } catch (FileNotFoundException exception) {
                    String error = "Resource not found: " + url;
                    logger.error(error);
                    JOptionPane.showMessageDialog(null, error);
                    return;
                } catch (Exception exception) {
                    String error = "Error while reading file: " + exception.getMessage();
                    logger.error(error);
                    logger.debug(exception);
                    JOptionPane.showMessageDialog(null, error);
                    return;
                }
                logger.warn("Not displaying model with unknown content");
            }
        }
public void testServletTesterClient() throws Exception {
        String base_url = tester.createSocketConnector(true);
        URL url = new URL(base_url + "/context/hello/info");
        String result = IO.toString(url.openStream());
        assertEquals("<h1>Hello Servlet</h1>", result);
    }
protected BufferedReader getDataReader() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            String line;
            URL url = new URL(this.catalog.getCatalogURL());
            Debug.output("Catalog URL:" + url.toString());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir");
            File temp = new File(dir, TEMP);
            Debug.output("Temp file:" + temp.toString());
            out = new PrintWriter(new BufferedWriter(new FileWriter(temp)));
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
            Debug.output("Temp file size:" + temp.length());
            return new BufferedReader(new FileReader(temp));
        } catch (IOException e) {
            throw new SeismoException(e);
        } finally {
            Util.close(in);
            Util.close(out);
        }
    }
public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException {
        Validate.notNull(reader, "CSVReader");
        Validate.notNull(writer, "Writer");
        Writer bufferedWriter = new BufferedWriter(writer);
        File fileForColsDef = createTempFileForCss();
        BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef));
        File fileForTable = createTempFileForTable();
        BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable));
        try {
            int currentRow = 0;
            String[] nextLine = reader.readNext();
            if (nextLine != null) {
                int[] colsCharCount = new int[nextLine.length];
                writeTableRowHeader(tableWriter, nextLine);
                while ((nextLine = reader.readNext()) != null) {
                    currentRow++;
                    if (progress != null) {
                        float percent = ((float) currentRow / (float) nbTotalRows) * 100f;
                        progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent);
                    }
                    writeTableRow(tableWriter, nextLine, colsCharCount);
                }
                writeTableStart(colsDefWriter, colsCharCount);
                writeColsDefinitions(colsDefWriter, colsCharCount);
            }
            writeConverterInfos(bufferedWriter);
            writeTableEnd(tableWriter);
            flushAndClose(tableWriter);
            flushAndClose(colsDefWriter);
            BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef));
            BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable));
            mergeFiles(bufferedWriter, colsDefReader, tableReader);
        } finally {
            closeQuietly(tableWriter);
            closeQuietly(colsDefWriter);
            fileForTable.delete();
            fileForColsDef.delete();
        }
    }
protected FTPClient openFTP() throws CruiseControlException {
        LOG.info("Opening FTP connection to " + targetHost);
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(targetHost, targetPort);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new CruiseControlException("FTP connection failed: " + ftp.getReplyString());
            }
            LOG.info("logging in to FTP server");
            if (!ftp.login(targetUser, targetPasswd)) {
                throw new CruiseControlException("Could not login to FTP server");
            }
            LOG.info("login succeeded");
            if (passive) {
                setPassive(ftp);
            }
        } catch (IOException ioe) {
            LOG.error(ioe);
            throw new CruiseControlException(ioe.getMessage());
        }
        return ftp;
    }
public Resource get(String serviceUrl, String resourceId, String svcId, boolean appendProfile) throws Exception {
        Resource resource = new Resource();
        String openurl = getURL(serviceUrl, resourceId, svcId, appendProfile);
        logger.debug("OpenURL Request: " + openurl);
        URL url;
        try {
            url = new URL(openurl);
            HttpURLConnection huc = (HttpURLConnection) (url.openConnection());
            int code = huc.getResponseCode();
            if (code == 200) {
                InputStream is = huc.getInputStream();
                resource.setBytes(IOUtils.getByteArray(is));
                resource.setContentType(huc.getContentType());
            } else if (code == 404) {
                return null;
            } else {
                logger.error("An error of type " + code + " occurred for " + url.toString());
                throw new Exception("Cannot get " + url.toString());
            }
        } catch (MalformedURLException e) {
            throw new Exception("A MalformedURLException occurred for " + openurl);
        } catch (IOException e) {
            throw new Exception("An IOException occurred attempting to connect to " + openurl);
        }
        return resource;
    }
public HttpUrlConnectionCall(HttpClientHelper helper, String method, String requestUri, boolean hasEntity) throws IOException {
        super(helper, method, requestUri);
        if (requestUri.startsWith("http")) {
            URL url = new URL(requestUri);
            this.connection = (HttpURLConnection) url.openConnection();
            int majorVersionNumber = Engine.getJavaMajorVersion();
            int minorVersionNumber = Engine.getJavaMinorVersion();
            if ((majorVersionNumber > 1) || (majorVersionNumber == 1 && minorVersionNumber >= 5)) {
                this.connection.setConnectTimeout(getHelper().getConnectTimeout());
                this.connection.setReadTimeout(getHelper().getReadTimeout());
            }
            this.connection.setAllowUserInteraction(getHelper().isAllowUserInteraction());
            this.connection.setDoOutput(hasEntity);
            this.connection.setInstanceFollowRedirects(getHelper().isFollowRedirects());
            this.connection.setUseCaches(getHelper().isUseCaches());
            this.responseHeadersAdded = false;
            setConfidential(this.connection instanceof HttpsURLConnection);
        } else {
            throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
        }
    }
public LineIterator iterator() {
        LineIterator ret;
        final String charsetname;
        final Charset charset;
        final CharsetDecoder charsetDecoder;
        synchronized (this) {
            charsetname = this.charsetname;
            charset = this.charset;
            charsetDecoder = this.charsetDecoder;
        }
        try {
            if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null);
            synchronized (openedIterators) {
                openedIterators.add(ret);
            }
            return ret;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
public static synchronized String encrypt(String plaintext) throws SinaduraCoreException {
        MessageDigest md = null;
        String hash = null;
        try {
            md = MessageDigest.getInstance("SHA");
            try {
                md.update(plaintext.getBytes(CHARSET_UTF8));
            } catch (UnsupportedEncodingException e) {
                throw new SinaduraCoreException(e.getMessage(), e);
            }
            byte raw[] = md.digest();
            hash = (new BASE64Encoder()).encode(raw);
        } catch (NoSuchAlgorithmException e) {
            throw new SinaduraCoreException(e.getMessage(), e);
        }
        return hash;
    }
public ZIPSignatureService(InputStream documentInputStream, SignatureFacet signatureFacet, OutputStream documentOutputStream, RevocationDataService revocationDataService, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo signatureDigestAlgo) throws IOException {
        super(signatureDigestAlgo);
        this.temporaryDataStorage = new HttpSessionTemporaryDataStorage();
        this.documentOutputStream = documentOutputStream;
        this.tmpFile = File.createTempFile("eid-dss-", ".zip");
        FileOutputStream fileOutputStream;
        fileOutputStream = new FileOutputStream(this.tmpFile);
        IOUtils.copy(documentInputStream, fileOutputStream);
        addSignatureFacet(new ZIPSignatureFacet(this.tmpFile, signatureDigestAlgo));
        XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm());
        xadesSignatureFacet.setRole(role);
        addSignatureFacet(xadesSignatureFacet);
        addSignatureFacet(new KeyInfoSignatureFacet(true, false, false));
        addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm()));
        addSignatureFacet(signatureFacet);
        if (null != identity) {
            IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm());
            addSignatureFacet(identitySignatureFacet);
        }
    }
@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        ImagesService imgService = ImagesServiceFactory.getImagesService();
        InputStream stream = request.getInputStream();
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        int b = 0;
        while ((b = stream.read()) != -1) {
            bytes.add((byte) b);
        }
        byte img[] = new byte[bytes.size()];
        for (int i = 0; i < bytes.size(); i++) {
            img[i] = bytes.get(i);
        }
        BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        String urlBlobstore = blobstoreService.createUploadUrl("/blobstore-servlet?action=upload");
        URL url = new URL("http://localhost:8888" + urlBlobstore);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=29772313");
        OutputStream out = connection.getOutputStream();
        out.write(img);
        out.flush();
        out.close();
        System.out.println(connection.getResponseCode());
        System.out.println(connection.getResponseMessage());
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseText = "";
        String line;
        while ((line = rd.readLine()) != null) {
            responseText += line;
        }
        out.close();
        rd.close();
        response.sendRedirect("/blobstore-servlet?action=getPhoto&" + responseText);
    }
private String calculateMD5(String value) {
        String finalString = new String("");
        try {
            MessageDigest md5Alg = MessageDigest.getInstance("MD5");
            md5Alg.reset();
            md5Alg.update(value.getBytes());
            byte messageDigest[] = md5Alg.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            finalString = hexString.toString();
        } catch (NoSuchAlgorithmException exc) {
            throw new RuntimeException("Hashing error happened:", exc);
        }
        return finalString;
    }
public boolean authenticate(String user, String pass) throws IOException {
        MessageDigest hash = null;
        try {
            MessageDigest.getInstance("BrokenMD4");
        } catch (NoSuchAlgorithmException x) {
            throw new Error(x);
        }
        hash.update(new byte[4], 0, 4);
        try {
            hash.update(pass.getBytes("US-ASCII"), 0, pass.length());
            hash.update(challenge.getBytes("US-ASCII"), 0, challenge.length());
        } catch (java.io.UnsupportedEncodingException shouldNeverHappen) {
        }
        String response = Util.base64(hash.digest());
        Util.writeASCII(out, user + " " + response + '\n');
        String reply = Util.readLine(in);
        if (reply.startsWith(RSYNCD_OK)) {
            authReqd = false;
            return true;
        }
        connected = false;
        error = reply;
        return false;
    }
public void updateShoppingBean(String userId) {
        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(this.jdbcURL);
            connection.setAutoCommit(false);
            String preparedQuery = "INSERT INTO dbComputerShopping.order(name,product_id,quantity,date,status)VALUES(?,?,?,?,?)";
            preparedStatement1 = connection.prepareStatement(preparedQuery);
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String orderDate = format.format(date);
            Iterator iterator = this.cart.iterator();
            Object[] shoppingInfo = null;
            while (iterator.hasNext()) {
                shoppingInfo = (Object[]) iterator.next();
                ProductBean product = (ProductBean) shoppingInfo[0];
                int quantity = (Integer) shoppingInfo[1];
                preparedStatement1.setString(1, userId);
                preparedStatement1.setInt(2, product.getId());
                preparedStatement1.setInt(3, quantity);
                preparedStatement1.setString(4, orderDate);
                preparedStatement1.setString(5, "confirmed");
                preparedStatement1.executeUpdate();
            }
            Object[] cartInfo = null;
            preparedQuery = "UPDATE components SET quantity=quantity-? WHERE comp_id=?";
            preparedStatement2 = connection.prepareStatement(preparedQuery);
            for (Iterator i = this.cart.iterator(); i.hasNext(); ) {
                cartInfo = (Object[]) i.next();
                ProductBean product = (ProductBean) cartInfo[0];
                int quantity = (Integer) cartInfo[1];
                ProductListBean productList = new ProductListBean(jdbcURL);
                ArrayList components = productList.getComponents(product.getId());
                for (Iterator j = components.iterator(); j.hasNext(); ) {
                    ComponentBean component = (ComponentBean) j.next();
                    preparedStatement2.setInt(1, quantity);
                    preparedStatement2.setInt(2, component.getId());
                    preparedStatement2.executeUpdate();
                }
            }
            connection.commit();
        } catch (Exception ex) {
            try {
                connection.rollback();
            } catch (SQLException e) {
            }
        } finally {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
            try {
                preparedStatement1.close();
            } catch (SQLException ex) {
            }
            try {
                preparedStatement2.close();
            } catch (SQLException ex) {
            }
        }
    }
private void init() {
        synchronized (cachedProperties) {
            if (firstTime) {
                try {
                    Enumeration<URL> configFiles;
                    configFiles = classloader.getResources(CONFIG_LOCATION);
                    if (configFiles == null) {
                        logger.info("No configuration file ({}) found in the classpath.", CONFIG_LOCATION);
                        return;
                    }
                    firstTime = false;
                    boolean alreadyLoaded = false;
                    while (configFiles.hasMoreElements()) {
                        final URL url = configFiles.nextElement();
                        if (!alreadyLoaded) {
                            final InputStream is = url.openStream();
                            cachedProperties.load(is);
                            is.close();
                            logger.info("XmlFieldFactory configuration loaded from the file {}", url);
                        } else {
                            logger.info("An other XmlFieldFactory configuration file is found in the classpath. This file won't be loaded {}", url);
                        }
                    }
                } catch (IOException e) {
                    logger.error("An error occur during the XmlFieldFActory initialization", e);
                }
            }
        }
    }
public String postXmlRequest(String url, String data) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        StringBuffer responseStr = new StringBuffer();
        try {
            System.out.println(data);
            Log4j.logger.info("Request:\n" + data);
            StringEntity reqEntity = new StringEntity(data, "UTF-8");
            reqEntity.setContentType("text/xml");
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            this.setPostSatus(response.getStatusLine().getStatusCode());
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                responseStr.append(line + "\n");
            }
            if (entity != null) {
                entity.consumeContent();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println(responseStr);
        Log4j.logger.info("Response:\n" + responseStr);
        return responseStr.toString();
    }
public static String md5(String text) {
        String hashed = "";
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(text.getBytes(), 0, text.length());
            hashed = new BigInteger(1, digest.digest()).toString(16);
        } catch (Exception e) {
            Log.e(ctGlobal.tag, "ctCommon.md5: " + e.toString());
        }
        return hashed;
    }