semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = {  })
    public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception {
        String jarFileName = "";
        String entry = "text.txt";
        String cts = System.getProperty("java.io.tmpdir");
        File tmpDir = new File(cts);
        File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir);
        jarFileName = jarFile.getPath();
        FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName);
        JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream));
        JarEntry jarEntry = new JarEntry(entry);
        out.putNextEntry(jarEntry);
        out.write(new byte[] { 'a', 'b', 'c' });
        out.close();
        URL url = new URL("jar:file:" + jarFileName + "!/" + entry);
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        InputStream is = conn.getInputStream();
        is.close();
        assertTrue(jarFile.delete());
    }
public TreeMap getStrainMap() {
        TreeMap strainMap = new TreeMap();
        String server = "";
        try {
            Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP);
            for (int i = 0; i < ds.length; i++) {
                if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) {
                    if (ds[i].getServer().length() == 0) {
                        Connection con = ds[i].getConnection();
                        strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con);
                        break;
                    } else {
                        server = ds[i].getServer();
                        HashMap serverUrlMap = InitXml.getInstance().getServerMap();
                        String serverUrl = (String) serverUrlMap.get(server);
                        URL url = new URL(serverUrl + servletName);
                        URLConnection uc = url.openConnection();
                        uc.setDoOutput(true);
                        OutputStream os = uc.getOutputStream();
                        StringBuffer buf = new StringBuffer();
                        buf.append("viewType=getstrains");
                        buf.append("&hHead=" + hHead);
                        buf.append("&hCheck=" + version);
                        PrintStream ps = new PrintStream(os);
                        ps.print(buf.toString());
                        ps.close();
                        ObjectInputStream ois = new ObjectInputStream(uc.getInputStream());
                        strainMap = (TreeMap) ois.readObject();
                        ois.close();
                    }
                }
            }
        } catch (Exception e) {
            log.error("strain map", e);
        }
        return strainMap;
    }
public static void extractZip(Resource zip, FileObject outputDirectory) {
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(zip.getResourceURL().openStream());
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String[] pathElements = entry.getName().split("/");
                FileObject extractDir = outputDirectory;
                for (int i = 0; i < pathElements.length - 1; i++) {
                    String pathElementName = pathElements[i];
                    FileObject pathElementFile = extractDir.resolveFile(pathElementName);
                    if (!pathElementFile.exists()) {
                        pathElementFile.createFolder();
                    }
                    extractDir = pathElementFile;
                }
                String fileName = entry.getName();
                if (fileName.endsWith("/")) {
                    fileName = fileName.substring(0, fileName.length() - 1);
                }
                if (fileName.contains("/")) {
                    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
                }
                if (entry.isDirectory()) {
                    extractDir.resolveFile(fileName).createFolder();
                } else {
                    FileObject file = extractDir.resolveFile(fileName);
                    file.createFile();
                    int size = (int) entry.getSize();
                    byte[] unpackBuffer = new byte[size];
                    zis.read(unpackBuffer, 0, size);
                    InputStream in = null;
                    OutputStream out = null;
                    try {
                        in = new ByteArrayInputStream(unpackBuffer);
                        out = file.getContent().getOutputStream();
                        IOUtils.copy(in, out);
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                }
            }
        } catch (IOException e2) {
            throw new RuntimeException(e2);
        } finally {
            IOUtils.closeQuietly(zis);
        }
    }
public void updateResult(Result result) throws UnsupportedEncodingException {
        HttpPost updateRequest = populateUpdateRequest(result);
        HttpClient client = clientProvider.getHttpClient();
        try {
            HttpResponse response = client.execute(updateRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream input = entity.getContent();
                if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                    System.out.println("Request was not accepted by the collection server. Reason:");
                    System.out.println("Status: " + response.getStatusLine().getStatusCode());
                }
                for (int c = 0; (c = input.read()) > -1; ) {
                    System.out.print((char) c);
                }
                entity.consumeContent();
            }
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        String forw = null;
        try {
            int maxUploadSize = 50000000;
            MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize);
            String descrizione = multi.getParameter("text");
            File myFile = multi.getFile("uploadfile");
            String filePath = multi.getOriginalFileName("uploadfile");
            String path = "C:\\files\\";
            try {
                FileInputStream inStream = new FileInputStream(myFile);
                FileOutputStream outStream = new FileOutputStream(path + myFile.getName());
                while (inStream.available() > 0) {
                    outStream.write(inStream.read());
                }
                inStream.close();
                outStream.close();
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            forw = "../sendDoc.jsp";
            request.setAttribute("contentType", context.getMimeType(path + myFile.getName()));
            request.setAttribute("text", descrizione);
            request.setAttribute("path", path + myFile.getName());
            request.setAttribute("size", Long.toString(myFile.length()) + " Bytes");
            RequestDispatcher rd = request.getRequestDispatcher(forw);
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
@Override
    public String baiDuHotNews() {
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://news.baidu.com/z/wise_topic_processor/wise_hotwords_list.php?bd_page_type=1&tn=wapnews_hotwords_list&type=1&index=1&pfr=3-11-bdindex-top-3--");
        String hostNews = "";
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
            String line = "";
            boolean todayNewsExist = false, firstNewExist = false;
            int newsCount = -1;
            while ((line = buffer.readLine()) != null) {
                if (todayNewsExist || line.contains("<div class=\"news_title\">")) todayNewsExist = true; else continue;
                if (firstNewExist || line.contains("<div class=\"list-item\">")) {
                    firstNewExist = true;
                    newsCount++;
                } else continue;
                if (todayNewsExist && firstNewExist && (newsCount == 1)) {
                    Pattern hrefPattern = Pattern.compile("<a.*>(.+?)</a>.*");
                    Matcher matcher = hrefPattern.matcher(line);
                    if (matcher.find()) {
                        hostNews = matcher.group(1);
                        break;
                    } else newsCount--;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return hostNews;
    }
public void xtestGetThread() throws Exception {
        GMSearchOptions options = new GMSearchOptions();
        options.setFrom(loginInfo.getUsername() + "*");
        options.setSubject("message*");
        GMSearchResponse mail = client.getMail(options);
        for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) {
            GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next();
            GMThread thread = client.getThread(threadSnapshot.getThreadID());
            log.info("Most Recent Thread: " + thread);
            for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) {
                GMMessage message = (GMMessage) iter.next();
                log.info("Message: " + message);
                Iterable<GMAttachment> attachments = message.getAttachments();
                for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) {
                    GMAttachment attachment = (GMAttachment) iterator.next();
                    String ext = FilenameUtils.getExtension(attachment.getFilename());
                    if (ext.trim().length() > 0) ext = "." + ext;
                    String base = FilenameUtils.getBaseName(attachment.getFilename());
                    File file = File.createTempFile(base, ext, new File(System.getProperty("user.home")));
                    log.info("Saving attachment: " + file.getPath());
                    InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID());
                    IOUtils.copy(attStream, new FileOutputStream(file));
                    attStream.close();
                    assertEquals(file.length(), attachment.getSize());
                    log.info("Done. Successfully saved: " + file.getPath());
                    file.delete();
                }
            }
        }
    }
private File prepareFileForUpload(File source, String s3key) throws IOException {
        File tmp = File.createTempFile("dirsync", ".tmp");
        tmp.deleteOnExit();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey()));
            IOUtils.copy(in, out);
            in.close();
            out.close();
            return tmp;
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }
private void downloadFile(File target, String s3key) throws IOException, S3ServiceException {
        InputStream in = downloadData(s3key);
        if (in == null) {
            throw new IOException("No data found");
        }
        in = new InflaterInputStream(new CryptInputStream(in, cipher, getDataEncryptionKey()));
        File temp = File.createTempFile("dirsync", null);
        FileOutputStream fout = new FileOutputStream(temp);
        try {
            IOUtils.copy(in, fout);
            if (target.exists()) {
                target.delete();
            }
            IOUtils.closeQuietly(fout);
            IOUtils.closeQuietly(in);
            FileUtils.moveFile(temp, target);
        } catch (IOException e) {
            fetchStream(in);
            throw e;
        } finally {
            IOUtils.closeQuietly(fout);
            IOUtils.closeQuietly(in);
        }
    }
private byte[] digestFile(File file, MessageDigest digest) throws IOException {
        DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest);
        IOUtils.copy(in, new NullOutputStream());
        in.close();
        return in.getMessageDigest().digest();
    }
public URL getURL(String fragment) {
        URL url = null;
        try {
            url = createURL(fragment);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (url == null) return null;
        try {
            InputStream is = url.openStream();
            if (is != null) {
                is.close();
                return url;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace(Trace.out);
        }
        return null;
    }
public static void createBackup() {
        String workspacePath = Workspace.INSTANCE.getWorkspace();
        if (workspacePath.length() == 0) return;
        workspacePath += "/";
        String backupPath = workspacePath + "Backup";
        File directory = new File(backupPath);
        if (!directory.exists()) directory.mkdirs();
        String dateString = DataUtils.DateAndTimeOfNowAsLocalString();
        dateString = dateString.replace(" ", "_");
        dateString = dateString.replace(":", "");
        backupPath += "/Backup_" + dateString + ".zip";
        ArrayList<String> backupedFiles = new ArrayList<String>();
        backupedFiles.add("Database/Database.properties");
        backupedFiles.add("Database/Database.script");
        FileInputStream in;
        byte[] data = new byte[1024];
        int read = 0;
        try {
            ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath));
            zip.setMethod(ZipOutputStream.DEFLATED);
            for (int i = 0; i < backupedFiles.size(); i++) {
                String backupedFile = backupedFiles.get(i);
                try {
                    File inFile = new File(workspacePath + backupedFile);
                    if (inFile.exists()) {
                        in = new FileInputStream(workspacePath + backupedFile);
                        if (in != null) {
                            ZipEntry entry = new ZipEntry(backupedFile);
                            zip.putNextEntry(entry);
                            while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read);
                            zip.closeEntry();
                            in.close();
                        }
                    }
                } catch (Exception e) {
                    Logger.logError(e, "Error during file backup:" + backupedFile);
                }
            }
            zip.close();
        } catch (IOException ex) {
            Logger.logError(ex, "Error during backup");
        }
    }
protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Executing request " + httpUriRequest.getURI());
        }
        HttpResponse httpResponse = httpClient.execute(httpUriRequest);
        String response = EntityUtils.toString(httpResponse.getEntity());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Reading '" + response + "' into " + clazz.getName());
        }
        T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Response object " + abstractResponse);
        }
        if (abstractResponse.getError() != null) {
            throw new TranslatorException(abstractResponse.getError());
        }
        return abstractResponse;
    }
public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException {
        boolean defaultAutoCommit = conn.getAutoCommit();
        String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?";
        String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)";
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            pstmt1 = conn.prepareStatement(sqlQuery);
            pstmt2 = conn.prepareStatement(sqlInsert);
            conn.setAutoCommit(false);
            pstmt1.setString(1, originDocumentID);
            ResultSet rs = pstmt1.executeQuery();
            while (rs.next()) {
                pstmt2.setInt(1, rs.getInt(1));
                pstmt2.setString(2, rs.getString(2));
                pstmt2.setDouble(3, rs.getDouble(3));
                pstmt2.setDouble(4, rs.getDouble(4));
                pstmt2.setDouble(5, rs.getDouble(5));
                pstmt2.setDouble(6, rs.getDouble(6));
                pstmt2.setDouble(7, rs.getDouble(7));
                pstmt2.setDouble(8, rs.getDouble(8));
                pstmt2.setString(9, destinationDocumentID);
                pstmt2.executeUpdate();
            }
            rs.close();
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
        } finally {
            conn.setAutoCommit(defaultAutoCommit);
            if (pstmt1 != null) pstmt1.close();
            if (pstmt2 != null) pstmt2.close();
        }
    }
public ArrayList<Tweet> getTimeLine() {
        try {
            HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self");
            consumer.sign(get);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
                    return null;
                }
                StringBuffer sBuf = new StringBuffer();
                String linea;
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                while ((linea = reader.readLine()) != null) {
                    sBuf.append(linea);
                }
                reader.close();
                response.getEntity().consumeContent();
                get.abort();
                SAXParserFactory spf = SAXParserFactory.newInstance();
                StringReader XMLout = new StringReader(sBuf.toString());
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                xmlParserLinkedin gwh = new xmlParserLinkedin();
                xr.setContentHandler(gwh);
                xr.parse(new InputSource(XMLout));
                return gwh.getParsedData();
            }
        } catch (UnsupportedEncodingException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (IOException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthMessageSignerException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthExpectationFailedException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthCommunicationException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (ParserConfigurationException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (SAXException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        }
        return null;
    }
public String getUser() {
        try {
            HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~");
            consumer.sign(get);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
                }
                StringBuffer sBuf = new StringBuffer();
                String linea;
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                while ((linea = reader.readLine()) != null) {
                    sBuf.append(linea);
                }
                reader.close();
                response.getEntity().consumeContent();
                get.abort();
                String salida = sBuf.toString();
                String user_firstname = salida.split("</first-name>")[0].split("<first-name>")[1];
                String user_lastname = salida.split("</last-name>")[0].split("<last-name>")[1];
                return user_firstname + " " + user_lastname;
            }
        } catch (UnsupportedEncodingException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (IOException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthMessageSignerException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthExpectationFailedException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthCommunicationException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        }
        return null;
    }