semeru/Code-Code-CloneDetection-BigCloneBench huggingface dataset:
@Override
    public byte[] read(String path) throws PersistenceException {
        path = fmtPath(path);
        try {
            S3Object fileObj = s3Service.getObject(bucketObj, path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            IOUtils.copy(fileObj.getDataInputStream(), out);
            return out.toByteArray();
        } catch (Exception e) {
            throw new PersistenceException("fail to read s3 file - " + path, e);
        }
    }
@Override
    public String fetchElectronicEdition(Publication pub) {
        final String url = pub.getEe();
        HttpMethod method = null;
        String responseBody = "";
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        try {
            if (StringUtils.isNotBlank(method.getURI().getScheme())) {
                InputStream is = null;
                StringWriter writer = new StringWriter();
                try {
                    client.executeMethod(method);
                    Header contentType = method.getResponseHeader("Content-Type");
                    if (contentType != null && StringUtils.isNotBlank(contentType.getValue()) && contentType.getValue().indexOf("text/html") >= 0) {
                        is = method.getResponseBodyAsStream();
                        IOUtils.copy(is, writer);
                        responseBody = writer.toString();
                    } else {
                        logger.info("ignoring non-text/html response from page: " + url + " content-type:" + contentType);
                    }
                } catch (HttpException he) {
                    logger.error("Http error connecting to '" + url + "'");
                    logger.error(he.getMessage());
                } catch (IOException ioe) {
                    logger.error("Unable to connect to '" + url + "'");
                } finally {
                    IOUtils.closeQuietly(is);
                    IOUtils.closeQuietly(writer);
                }
            }
        } catch (URIException e) {
            logger.error(e);
        } finally {
            method.releaseConnection();
        }
        return responseBody;
    }
public void loadSample(String uid, URL url) throws Exception {
        AudioInputStream input = AudioSystem.getAudioInputStream(url.openStream());
        Clip line = null;
        DataLine.Info info = new DataLine.Info(Clip.class, input.getFormat());
        if (!AudioSystem.isLineSupported(info)) {
            throw new javax.sound.sampled.UnsupportedAudioFileException(url.toExternalForm());
        }
        line = (Clip) AudioSystem.getLine(info);
        line.open(input);
        samples.put(uid, line);
    }
public void startStreaming(final String mediaUrl) throws IOException {
        final String TAG = "startStreaming";
        int bitrate = 56;
        sendMessage(PlayListTab.CHECKRIORITY);
        sendMessage(PlayListTab.RAISEPRIORITY);
        sendMessage(PlayListTab.START);
        try {
            url = new URL(mediaUrl);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setReadTimeout(1000 * 20);
            urlConn.setConnectTimeout(1000 * 5);
            String ctype = urlConn.getContentType();
            if (ctype == null) {
                ctype = "";
            } else {
                ctype = ctype.toLowerCase();
            }
            Log.d(TAG, "Content Type: " + ctype);
            if (ctype.contains(AUDIO_MPEG) || ctype.equals("")) {
                String temp = urlConn.getHeaderField(BITERATE_HEADER);
                Log.d(TAG, "Bitrate: " + temp);
                if (temp != null) {
                    bitrate = new Integer(temp).intValue();
                }
            } else {
                Log.e(TAG, "Does not look like we can play this audio type: " + ctype);
                Log.e(TAG, "Or we could not connect to audio");
                sendMessage(PlayListTab.TROUBLEWITHAUDIO);
                stop();
                return;
            }
        } catch (IOException ioe) {
            Log.e(TAG, "Could not connect to " + mediaUrl);
            sendMessage(PlayListTab.TROUBLEWITHAUDIO);
            stop();
            return;
        }
        if (regularStream) {
            Log.d(TAG, "Setup regular stream");
            Runnable r = new Runnable() {

                public void run() {
                    try {
                        downloadAudio(mediaUrl);
                    } catch (IOException e) {
                        Log.e(TAG, "Unable to initialize the MediaPlayer for Audio Url = " + mediaUrl, e);
                        sendMessage(PlayListTab.TROUBLEWITHAUDIO);
                        stop();
                        return;
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            Log.d(TAG, "Setup incremental stream");
            INTIAL_KB_BUFFER = bitrate * SECONDS / BIT;
            Runnable r = new Runnable() {

                public void run() {
                    try {
                        downloadAudioIncrement(mediaUrl);
                    } catch (IOException e) {
                        Log.e(TAG, "Unable to initialize the MediaPlayer for Audio Url = " + mediaUrl, e);
                        sendMessage(PlayListTab.TROUBLEWITHAUDIO);
                        stop();
                        return;
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        }
    }
private String getJSONScoreStringFromNet(URL urladdress) {
        InputStream instream = null;
        BufferedReader read = null;
        try {
            instream = urladdress.openStream();
            read = new BufferedReader(new InputStreamReader(instream));
            String s = new String("");
            String line = null;
            while ((line = read.readLine()) != null) {
                s = s + line;
            }
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                read.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
@Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
        final String url = req.getParameter("url");
        if (!isAllowed(url)) {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        final HttpClient client = new HttpClient();
        client.getParams().setVersion(HttpVersion.HTTP_1_0);
        final PostMethod method = new PostMethod(url);
        method.getParams().setVersion(HttpVersion.HTTP_1_0);
        method.setFollowRedirects(false);
        final RequestEntity entity = new InputStreamRequestEntity(req.getInputStream());
        method.setRequestEntity(entity);
        try {
            final int statusCode = client.executeMethod(method);
            if (statusCode != -1) {
                InputStream is = null;
                ServletOutputStream os = null;
                try {
                    is = method.getResponseBodyAsStream();
                    try {
                        os = resp.getOutputStream();
                        IOUtils.copy(is, os);
                    } finally {
                        if (os != null) {
                            try {
                                os.flush();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                } catch (IOException ioex) {
                    final String message = ioex.getMessage();
                    if (!"chunked stream ended unexpectedly".equals(message)) {
                        throw ioex;
                    }
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        } finally {
            method.releaseConnection();
        }
    }
public SimpleParser(String filepath) throws Exception {
        this.path = filepath;
        InputStream is = null;
        try {
            if (this.path.indexOf("http") == 0) {
                URL url = new URL(this.path);
                is = url.openStream();
            } else if (this.path.indexOf("<?xml") == 0) {
                is = new ByteArrayInputStream(filepath.getBytes(encoding));
            } else {
                File f = new File(this.path);
                if (!f.exists()) {
                    setError("File not found : " + this.path);
                } else {
                    is = new FileInputStream(f);
                }
            }
            if (is != null) {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                doc = dBuilder.parse(is);
                doc.getDocumentElement().normalize();
            }
        } catch (Exception ex) {
            Malgn.errorLog("{SimpleParser.constructor} Path:" + filepath + " " + ex.getMessage());
            setError("Parser Error : " + ex.getMessage());
        } finally {
            if (is != null) is.close();
        }
    }
private Element makeRequest(String link) {
        try {
            URL url = new URL(link);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();
            InputStream in = conn.getInputStream();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document document = builder.parse(in);
            Element element = document.getDocumentElement();
            element.normalize();
            if (checkRootTag(element)) {
                return element;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        }
    }
public void importSequences() {
        names = new ArrayList<String>();
        sequences = new ArrayList<String>();
        try {
            InputStream is = urls[urlComboBox.getSelectedIndex()].openStream();
            ImportHelper helper = new ImportHelper(new InputStreamReader(is));
            int ch = helper.read();
            while (ch != '>') {
                ch = helper.read();
            }
            do {
                String line = helper.readLine();
                StringTokenizer tokenizer = new StringTokenizer(line, " \t");
                String name = tokenizer.nextToken();
                StringBuffer seq = new StringBuffer();
                helper.readSequence(seq, ">", Integer.MAX_VALUE, "-", "?", "", null);
                ch = helper.getLastDelimiter();
                names.add(name);
                sequences.add(seq.toString());
            } while (ch == '>');
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (EOFException e) {
        } catch (IOException e) {
        }
    }
public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException {
        InputStream urlStream = url.openStream();
        AudioFileFormat fileFormat = null;
        try {
            fileFormat = getFMT(urlStream, false);
        } finally {
            urlStream.close();
        }
        return fileFormat;
    }
public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException {
        InputStream urlStream = url.openStream();
        AudioFileFormat fileFormat = null;
        try {
            fileFormat = getFMT(urlStream, false);
        } finally {
            if (fileFormat == null) {
                urlStream.close();
            }
        }
        return new AudioInputStream(urlStream, fileFormat.getFormat(), fileFormat.getFrameLength());
    }
private String getHash(String string) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.reset();
        md5.update(string.getBytes());
        byte[] result = md5.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            hexString.append(Integer.toHexString(0xFF & result[i]));
        }
        String str = hexString.toString();
        return str;
    }
public CmsSetupTestResult execute(CmsSetupBean setupBean) {
        CmsSetupTestResult testResult = new CmsSetupTestResult(this);
        String basePath = setupBean.getWebAppRfsPath();
        if (!basePath.endsWith(File.separator)) {
            basePath += File.separator;
        }
        File file1;
        Random rnd = new Random();
        do {
            file1 = new File(basePath + "test" + rnd.nextInt(1000));
        } while (file1.exists());
        boolean success = false;
        try {
            file1.createNewFile();
            FileWriter fw = new FileWriter(file1);
            fw.write("aA1");
            fw.close();
            success = true;
            FileReader fr = new FileReader(file1);
            success = success && (fr.read() == 'a');
            success = success && (fr.read() == 'A');
            success = success && (fr.read() == '1');
            success = success && (fr.read() == -1);
            fr.close();
            success = file1.delete();
            success = !file1.exists();
        } catch (Exception e) {
            success = false;
        }
        if (!success) {
            testResult.setRed();
            testResult.setInfo("OpenCms cannot be installed without read and write privileges for path " + basePath + "! Please check you are running your servlet container with the right user and privileges.");
            testResult.setHelp("Not enough permissions to create/read/write a file");
            testResult.setResult(RESULT_FAILED);
        } else {
            testResult.setGreen();
            testResult.setResult(RESULT_PASSED);
        }
        return testResult;
    }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("edit") != null) {
            try {
                User cu = (User) request.getSession().getAttribute("currentuser");
                UserDetails ud = cu.getUserDetails();
                String returnTo = "editprofile.jsp";
                if (!request.getParameter("password").equals("")) {
                    String password = request.getParameter("password");
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    md.update(new String(password).getBytes());
                    byte[] hash = md.digest();
                    String pass = new BigInteger(1, hash).toString(16);
                    cu.setClientPassword(pass);
                }
                ud.setFirstName(request.getParameter("fname"));
                ud.setLastName(request.getParameter("lname"));
                ud.setEmailAddress(request.getParameter("email"));
                ud.setAddress(request.getParameter("address"));
                ud.setZipcode(request.getParameter("zipcode"));
                ud.setTown(request.getParameter("town"));
                ud.setCountry(request.getParameter("country"));
                ud.setTrackingColor(request.getParameter("input1"));
                String vis = request.getParameter("visibility");
                if (vis.equals("self")) {
                    cu.setVisibility(0);
                } else if (vis.equals("friends")) {
                    cu.setVisibility(1);
                } else if (vis.equals("all")) {
                    cu.setVisibility(2);
                } else {
                    response.sendRedirect("error.jsp?id=8");
                }
                em.getTransaction().begin();
                em.persist(cu);
                em.getTransaction().commit();
                response.sendRedirect(returnTo);
            } catch (Throwable e) {
                e.printStackTrace();
                response.sendRedirect("error.jsp?id=5");
            }
            return;
        }
    }
public void register(URL codeBase, String filePath) throws Exception {
        Properties properties = new Properties();
        URL url = new URL(codeBase + filePath);
        properties.load(url.openStream());
        initializeContext(codeBase, properties);
    }
private void renameTo(File from, File to) {
        if (!from.exists()) return;
        if (to.exists()) to.delete();
        boolean worked = false;
        try {
            worked = from.renameTo(to);
        } catch (Exception e) {
            database.logError(this, "" + e, null);
        }
        if (!worked) {
            database.logWarning(this, "Could not rename GEDCOM to " + to.getAbsolutePath(), null);
            try {
                to.delete();
                final FileReader in = new FileReader(from);
                final FileWriter out = new FileWriter(to);
                int c;
                while ((c = in.read()) != -1) out.write(c);
                in.close();
                out.close();
                from.delete();
            } catch (Exception e) {
                database.logError(this, "" + e, null);
            }
        }
    }
public static void copy(String a, String b) throws IOException {
        File inputFile = new File(a);
        File outputFile = new File(b);
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }
public static String getStringFromURL(URL url) {
        try {
            if (url == null) {
                return null;
            }
            URLConnection conn = url.openConnection();
            conn.connect();
            if (conn instanceof HttpURLConnection) {
                int status = ((HttpURLConnection) conn).getResponseCode();
                if (status != HttpURLConnection.HTTP_OK) {
                    return null;
                }
            }
            int available = conn.getContentLength();
            InputStream is = conn.getInputStream();
            byte buffer[] = new byte[available];
            int pos = 0;
            while (available > 0) {
                int amount = is.read(buffer, pos, available);
                available -= amount;
                pos += amount;
            }
            is.close();
            String tmp = new String(buffer);
            return tmp;
        } catch (Exception ex) {
            System.out.println(ex);
            return "";
        }
    }
public static void copyZip() {
        InputStream is;
        OutputStream os;
        String javacZip = "";
        try {
            if ("windows".equalsIgnoreCase(Compilador.getSo())) {
                javacZip = "javacWin.zip";
                is = UnZip.class.getResourceAsStream("javacWin.zip");
            } else if ("linux".equalsIgnoreCase(Compilador.getSo())) {
                javacZip = "javacLinux.zip";
                is = UnZip.class.getResourceAsStream("javacLinux.zip");
            }
            is = UnZip.class.getResourceAsStream(javacZip);
            File tempZip = File.createTempFile("tempJavacJTraductor", ".zip");
            tempZip.mkdir();
            tempZip.deleteOnExit();
            os = FileUtils.openOutputStream(tempZip);
            IOUtils.copy(is, os);
            is.close();
            os.close();
            extractZip(tempZip.getPath());
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(PseutemView.mainPanel, "Error al copiar los archivos temporales necesarios para ejecutar el programa:\n\n" + ex, "Error copiando.", JOptionPane.ERROR_MESSAGE);
        }
    }
public static String genDigest(String info) {
        MessageDigest alga;
        byte[] digesta = null;
        try {
            alga = MessageDigest.getInstance("SHA-1");
            alga.update(info.getBytes());
            digesta = alga.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return byte2hex(digesta);
    }
private void mergeInDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String surl = AutoplotUtil.getProperty("autoplot.default.bookmarks", "http://www.autoplot.org/data/demos.xml");
            URL url = new URL(surl);
            Document doc = AutoplotUtil.readDoc(url.openStream());
            List<Bookmark> importBook = Bookmark.parseBookmarks(doc.getDocumentElement());
            List<Bookmark> newList = new ArrayList(model.list.size());
            for (int i = 0; i < model.list.size(); i++) {
                newList.add(i, model.list.get(i).copy());
            }
            model.mergeList(importBook, newList);
            model.setList(newList);
            formatToFile(bookmarksFile);
        } catch (SAXException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
public OAuthResponseMessage access(OAuthMessage request, net.oauth.ParameterStyle style) throws IOException {
        HttpMessage httpRequest = HttpMessage.newRequest(request, style);
        HttpResponseMessage httpResponse = http.execute(httpRequest, httpParameters);
        httpResponse = HttpMessageDecoder.decode(httpResponse);
        return new OAuthResponseMessage(httpResponse);
    }