semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
public static Map getFile(DispatchContext dctx, Map context) {
        String localFilename = (String) context.get("localFilename");
        OutputStream localFile = null;
        try {
            localFile = new FileOutputStream(localFilename);
        } catch (IOException ioe) {
            Debug.logError(ioe, "[getFile] Problem opening local file", module);
            return ServiceUtil.returnError("ERROR: Could not open local file");
        }
        List errorList = new ArrayList();
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect((String) context.get("hostname"));
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                errorList.add("Server refused connection");
            } else {
                String username = (String) context.get("username");
                String password = (String) context.get("password");
                if (!ftp.login(username, password)) {
                    errorList.add("Login failed (" + username + ", " + password + ")");
                } else {
                    Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                    boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                    if (binary) {
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    }
                    Boolean passiveMode = (Boolean) context.get("passiveMode");
                    boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
                    if (passive) {
                        ftp.enterLocalPassiveMode();
                    }
                    if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
                        errorList.add("File not received succesfully: " + ftp.getReplyString());
                    }
                }
                ftp.logout();
            }
        } catch (IOException ioe) {
            errorList.add("Problem with FTP transfer: " + ioe.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException dce) {
                    Debug.logWarning(dce, "[getFile] Problem with FTP disconnect", module);
                }
            }
        }
        try {
            localFile.close();
        } catch (IOException ce) {
            Debug.logWarning(ce, "[getFile] Problem closing local file", module);
        }
        if (errorList.size() > 0) {
            Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module);
            return ServiceUtil.returnError(errorList);
        }
        return ServiceUtil.returnSuccess();
    }
public void insertRight(final String right) throws IOException {
        try {
            Connection conn = null;
            boolean autoCommit = false;
            try {
                conn = pool.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(true);
                final PreparedStatement insert = conn.prepareStatement("insert into rights (name) values (?)");
                insert.setString(1, right);
                insert.executeUpdate();
            } catch (Throwable t) {
                if (conn != null) conn.rollback();
                throw new SQLException(t.toString());
            } finally {
                if (conn != null) {
                    conn.setAutoCommit(autoCommit);
                    conn.close();
                }
            }
        } catch (final SQLException sqle) {
            log.log(Level.SEVERE, sqle.toString(), sqle);
            throw new IOException(sqle.toString());
        }
    }
private void updateSystem() throws IOException {
          String stringUrl="http://code.google.com/p/senai-pe-cronos/downloads/list";
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
        InputStream is = url.openStream();   
InputStreamReader isr = new InputStreamReader(is);   
BufferedReader br = new BufferedReader(isr);   
  
String linha = br.readLine();  
  
while (linha != null) { 
    linha = br.readLine();  
   
   if(linha.contains("/files/updateCronos-0-")){
   String[] s=linha.split("-");
   String[] v=s[4].split(".exe");
   versao=v[0];
   println("----"+versao);
  
  break;
}   

}
      
stringUrl="http://senai-pe-cronos.googlecode.com/files/updateCronos-0-"+versao+".exe";
UpdateCronos update=new UpdateCronos();
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }       
System.out.println("versão:"+versao);
         if(Integer.parseInt(versao)>version){
              
             File f = update.gravaArquivoDeURL(url,System.getProperty("user.dir"),String.valueOf(version),versao);
            
             
            
             if(update.isS()) {
                 Runtime.getRuntime().exec(location+"\\update.exe");
                 System.exit(0);
         }
         }

          
    }
public static boolean copyFile(String src, String dst) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(new File(src)).getChannel();
            outChannel = new FileOutputStream(new File(dst)).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst);
            return false;
        } catch (IOException e) {
            MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst);
            return false;
        } finally {
            try {
                if (inChannel != null) inChannel.close();
                if (outChannel != null) outChannel.close();
            } catch (IOException e) {
                MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst);
                return false;
            }
        }
        return true;
    }
public static String sha1(String in) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] data = new byte[40];
        try {
            md.update(in.getBytes("iso-8859-1"), 0, in.length());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        data = md.digest();
        return HexidecimalUtilities.convertFromByteArrayToHex(data);
    }
public static String encrypt(String unencryptedString) {
        if (StringUtils.isBlank(unencryptedString)) {
            throw new IllegalArgumentException("Cannot encrypt a null or empty string");
        }
        MessageDigest md = null;
        String encryptionAlgorithm = Environment.getValue(Environment.PROP_ENCRYPTION_ALGORITHM);
        try {
            md = MessageDigest.getInstance(encryptionAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            logger.warn("JDK does not support the " + encryptionAlgorithm + " encryption algorithm.  Weaker encryption will be attempted.");
        }
        if (md == null) {
            try {
                md = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new UnsupportedOperationException("JDK does not support the SHA-1 or SHA-512 encryption algorithms");
            }
            Environment.setValue(Environment.PROP_ENCRYPTION_ALGORITHM, "SHA-1");
            try {
                Environment.saveConfiguration();
            } catch (WikiException e) {
                logger.info("Failure while saving encryption algorithm property", e);
            }
        }
        try {
            md.update(unencryptedString.getBytes("UTF-8"));
            byte raw[] = md.digest();
            return encrypt64(raw);
        } catch (GeneralSecurityException e) {
            logger.error("Encryption failure", e);
            throw new IllegalStateException("Failure while encrypting value");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Unsupporting encoding UTF-8");
        }
    }
public String getData(DefaultHttpClient httpclient) {
        try {
            HttpGet get = new HttpGet("http://3dforandroid.appspot.com/api/v1/note");
            get.setHeader("Content-Type", "application/json");
            get.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            responseMessage = read(instream);
            if (instream != null) instream.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }
public String deleteData(String id, DefaultHttpClient httpclient) {
        try {
            HttpDelete del = new HttpDelete("http://3dforandroid.appspot.com/api/v1/note/delete/" + id);
            del.setHeader("Content-Type", "application/json");
            del.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(del);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }
public String putData(String id, String updatedNote, DefaultHttpClient httpclient) {
        try {
            HttpPut put = new HttpPut("http://3dforandroid.appspot.com/api/v1/note/update/" + id);
            StringEntity se = new StringEntity(updatedNote);
            se.setContentEncoding(HTTP.UTF_8);
            se.setContentType("application/json");
            put.setEntity(se);
            put.setHeader("Content-Type", "application/json");
            put.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(put);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }
public String postData(String result, DefaultHttpClient httpclient) {
        try {
            HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create");
            StringEntity se = new StringEntity(result);
            se.setContentEncoding(HTTP.UTF_8);
            se.setContentType("application/json");
            post.setEntity(se);
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }
public static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException {
        httprequest.setHeader("Accept", "application/json");
        httprequest.setHeader("Content-type", "application/json");
        String result = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httprequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            result += line + "\n";
        }
        return result;
    }
public Long createSite(Site site, List<String> hosts) {
        if (log.isDebugEnabled()) {
            log.debug("site: " + site);
            if (site != null) {
                log.debug("    language: " + site.getDefLanguage());
                log.debug("    country: " + site.getDefCountry());
                log.debug("    variant: " + site.getDefVariant());
                log.debug("    companyId: " + site.getCompanyId());
            }
        }
        PreparedStatement ps = null;
        DatabaseAdapter dbDyn = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            CustomSequenceType seq = new CustomSequenceType();
            seq.setSequenceName("seq_WM_PORTAL_LIST_SITE");
            seq.setTableName("WM_PORTAL_LIST_SITE");
            seq.setColumnName("ID_SITE");
            Long siteId = dbDyn.getSequenceNextValue(seq);
            ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : ""));
            int num = 1;
            RsetTools.setLong(ps, num++, siteId);
            RsetTools.setLong(ps, num++, site.getCompanyId());
            ps.setString(num++, site.getDefLanguage());
            ps.setString(num++, site.getDefCountry());
            ps.setString(num++, site.getDefVariant());
            ps.setString(num++, site.getSiteName());
            ps.setString(num++, site.getAdminEmail());
            ps.setInt(num++, site.getCssDynamic() ? 1 : 0);
            ps.setString(num++, site.getCssFile());
            ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0);
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1);
            if (hosts != null) {
                for (String s : hosts) {
                    VirtualHost host = new VirtualHostBean(null, siteId, s);
                    InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host);
                }
            }
            dbDyn.commit();
            return siteId;
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error add new site";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }
protected static boolean copyFile(File src, File dest) {
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileInputStream fis = new FileInputStream(src);
            FileOutputStream fos = new FileOutputStream(dest);
            byte[] temp = new byte[1024 * 8];
            int readSize = 0;
            do {
                readSize = fis.read(temp);
                fos.write(temp, 0, readSize);
            } while (readSize == temp.length);
            temp = null;
            fis.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) {
        ConvResult[] convs = acr.getConvResults();
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(nwbConvGraph));
            writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph));
            String line = null;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("id*int")) {
                    writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n");
                } else if (line.matches(NODE_LINE)) {
                    String[] parts = line.split(" ");
                    String rawConvName = parts[1];
                    String convName = rawConvName.replaceAll("\"", "");
                    boolean wroteAttributes = false;
                    for (int ii = 0; ii < convs.length; ii++) {
                        ConvResult cr = convs[ii];
                        if (cr.getShortName().equals(convName)) {
                            int trusted;
                            if (cr.isTrusted()) {
                                trusted = 1;
                            } else {
                                trusted = 0;
                            }
                            writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n");
                            wroteAttributes = true;
                            break;
                        }
                    }
                    if (!wroteAttributes) {
                        writer.write(line + " 1 100.0 0" + "\r\n");
                    }
                } else {
                    writer.write(line + "\r\n");
                }
            }
        } catch (IOException e) {
            this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e);
            try {
                if (reader != null) reader.close();
            } catch (IOException e2) {
                this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e);
            }
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e);
                e.printStackTrace();
            }
        }
    }
@Override
    public void createCopy(File sourceFile, File destinnationFile) throws IOException {
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destinnationFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }
public void testRegisterFactory() throws Exception {
        try {
            new URL("classpath:/");
            fail("MalformedURLException expected");
        } catch (MalformedURLException e) {
            assertTrue(true);
        }
        ClasspathURLConnection.registerFactory();
        URL url = new URL("classpath:/dummy.txt");
        try {
            url.openStream();
            fail("IOException expected");
        } catch (IOException e) {
            assertTrue(true);
        }
        ClasspathURLConnection.registerFactory();
        url = new URL("classpath:/net/sf/alster/xsl/alster.xml");
        InputStream in = url.openStream();
        assertEquals('<', in.read());
        in.close();
    }
public static String doCrypt(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("UTF-8"), 0, text.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
public byte[] getByteCode() throws IOException {
        InputStream in = null;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
        try {
            in = url.openStream();
            int b = in.read();
            while (b != -1) {
                buf.write(b);
                b = in.read();
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        return buf.toByteArray();
    }
public Object mapRow(ResultSet rs, int i) throws SQLException {
            try {
                BLOB blob = (BLOB) rs.getBlob(1);
                OutputStream outputStream = blob.setBinaryStream(0L);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();
                inputStream.close();
            } catch (Exception e) {
                throw new SQLException(e.getMessage());
            }
            return null;
        }
public boolean connect() {
        try {
            int reply;
            ftp.connect(server, port);
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                if (ftp.login(username, password)) {
                    ftp.enterLocalPassiveMode();
                    return true;
                }
            } else {
                ftp.disconnect();
                System.out.println("FTP server refused connection.");
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
            System.out.println("Could not connect to server.");
        }
        return false;
    }
public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException {
        try {
            URL url = new URL(uri.toString());
            final URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("PUT");
                return new FilterOutputStream(urlConnection.getOutputStream()) {

                    @Override
                    public void close() throws IOException {
                        super.close();
                        int responseCode = httpURLConnection.getResponseCode();
                        switch(responseCode) {
                            case HttpURLConnection.HTTP_OK:
                            case HttpURLConnection.HTTP_CREATED:
                            case HttpURLConnection.HTTP_NO_CONTENT:
                                {
                                    break;
                                }
                            default:
                                {
                                    throw new IOException("PUT failed with HTTP response code " + responseCode);
                                }
                        }
                    }
                };
            } else {
                OutputStream result = urlConnection.getOutputStream();
                final Map<Object, Object> response = getResponse(options);
                if (response != null) {
                    result = new FilterOutputStream(result) {

                        @Override
                        public void close() throws IOException {
                            try {
                                super.close();
                            } finally {
                                response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
                            }
                        }
                    };
                }
                return result;
            }
        } catch (RuntimeException exception) {
            throw new Resource.IOWrappedException(exception);
        }
    }